Since a lot of your code is missing, the only thing I can suggest is to add some print statements to your code to display variables as they change and to trace execution flow.