So the first thing I can recommend for you to try is to write out, line by line, in plain text what you expect the program to do at that point in the program and what the current state is of the program at that point.
You're making some code idioms that are more complex than they should be which is likely leading to the mismatch in your expectation vs. actual program execution. Simplify those bits, use more temporary variables. Very likely your read loops are not doing what you think they should be doing.