One of the things that tends to happen to every developer is that you get get stuck with something you're working on. Your code isn't producing the result you are expecting it to.
What do you do?
Go through every line of code and write a comment about exactly what it does. Get descriptive. What data is being used, what's the intended result.
Use a debugger, or just good old
Sometimes the problem is in the expectations: The data that is really necessary is a few lines down, so reorganizing the code may help.
Sometimes the result you are getting doesn't match the result.
Walking through the code and adding comments will help clarify your thoughts and give you something solid to stand on. Try it the next time you're stuck.