Have you tried playing computer with your code by manually stepping thru it step by step and seeing why it does what it does?
You must go slow and carefully check what each statement does.

What...