There is a simple solution to this. Start with a working program that doesn't do what you want, and incrementally make it into the one you want.
It doesn't matter what the original program does. I cannot count how many times I started with a program that printed Hello, world and wound up with with something useful and unrelated.