Solving these kinds of problems requires getting a good design by using paper and pencil before coding.
When you have a design that will work and have coded it, then you need to do some debugging to...