Your first input file doesn't have the same as the input data you have given.

If your conditions are as simple as you given in the original post, i think you are over-complicating the algorithm. I...