To debug your problem, just start adding print statements throughout your code. Then you can verify if each variable contains what you expect it to contain. If you end up in an infinite while loop, and get too much info scrolling quickly by your screen, just exit out of it.
You should have also posted a very short sample (10 lines) of your input file.