Don't assume that every problem is software related.
I cannot help you with software, I am a hardware guy. I have seen too many instances of faults caused by erratic hardware.
Have you observed every output pulse from the micro-controller on an oscilloscope?
If the timing in the micro-controller is written in software, your output pulses may be dirty and causing erratic behaviour. If you can try generating the same pulses in hardware it may confirm your micro-controller is working properly.
I am not saying it will cure your problem; it will eliminate external factors.