I suggest that you start with a bigger thread, seems to me that an M4 tap may be quite flimsy by the time you have ground off 2 or 3 of the rows of teeth. Also it won't give you much clearance in an M4 tapping hole. You do of course need to use a tap with the same pitch as the thread you want which is limiting. I was lucky using a modified tap as I wanted an M14 x 1 thread and had an M8 x 1 tap.

As for the code, I suggest you look at Richard's wizard that I linked to in an earlier post as an example for comparison.