I am not going to read through all of your code to try and make sense of it. Please narrow down to what specific lines of code are relevant and also explain why you are having a hard time.
There are only 10 types of people in the world, those who understand binary and those who don't.