Can you add some println statements to output data that shows the problem?
Add some comments to the output and post it here.