Have you stepped through this with a debugger, or at least added some print lines, to help you figure out the flow of the program? Why are they going where they're going? Where do you want them to be...