When posting code, please use code tags so that the code is readable. Before posting, the code needs to be formatted properly. Go Advanced, select the formatted code and click '#'.

What debugging of the code have you done using the debugger? In cases like this, it is usually necessary to use the debugger to trace through the code and see the execution trace and to watch the value of the various variables to see why the program execution deviates from that expected from the design.