Looking through the code, I think that it needs to be rewritten. It's very hard to look at it and just understand what's happening with it. You use a lot of ifs that are unnecessary in my opinion. Also, it doesn't hurt to have some comments in your program, especially if you want others to troubleshoot it.