hmm, it did not quite explain the problem.
At least to me.;-)
Can you please provide some data samples where the script fails and explain what outcome you'd expect from it.
Then I (or others) could try to figure out a solution.
_____________
Code for TallyGenerator