Marlin modification

hello, I'm reviving this old CNC plotter, it only has two axis and an electromagnet that pulls down the pen to the paper. I've hooked up the electromagnet to RAMPS 1.4 D9 pin and are now able to trick the plotter in to activating the electromagnet by replacing Z0.000 with M106 ( this way he thinks that he turns on the heatbed) and all the Z0.5000 with M107 (turns off the heat bed). however I've only the knowledge to do this by manually finding and replacing inside the gcode via ctrl+f :)

so my question would be: is there any way to alter the marlin firmware so that it would automatically use M106 instead of G1 Z0.000 and M107 instead of G1 Z0.500?

If anyone has ever done something like similar then maybe you could suggest an alternative method?

Thank You