You're running into problem after problem because you're not learning enough about what your program actually does. Seriously, run the program in a debugger and step through it one line at a time.
What you're doing is like coming up with a bunch of directions about precisely what turns to take to your cab driver then going to sleep and waking up at the wrong destination. What you need to do is the equivalent of staying awake to see where he makes a wrong turn so that you can correct your directions. That equivalent change to staying awake is to use the debugger.
You step through the code one line at a time and see where it goes wrong. Tell us what programming environment you're using so we can help you to use your debugger, then you can stop programming in the dark.
Otherwise known as "Give a man a fish and he'll eat for a day; teach a man to fish and ...".
'cause I think I'm done handing out fishes for today...