I don't see any comments in the code that describes the steps the code is trying to take to solve the problem.
Can you add some comments saying what the different parts of the code are trying to do?