There is more than one nested loop. Please add some comments to the code explaining WHERE the problem is. Which loop executes and how many times and which loop only executes once etc.