Looks like you have a logic error if your code doesn't work the way you want it to.
First you need to get a design for how the code is supposed to work. Perhaps as pseudo code that describes in...