Time to step through this with a debugger, or at least add some print statements, to figure out what's going on. Where exactly does the code's execution differ from what you expect it to do?