It's very tough to make head or tails of this function. You are trying to do too much in 1 function. A function should do one thing, and do it well. You have this function trying to do several different things. I am not trying to critisize, but you'll find it much easier to debug if you break things down to more specifc uses.
Also, keep your comments inside the function to a bare minmum. Sorry to be critical, just trying to help. And this is part of your problem, it's making it difficult for you to see what your doing.
I can't see exactly where the problem pops up, but you have a recursive funtion, it's calling itself in your while statement, I am sure that is the root of the problem. You need to be very careful with recursive functions.
If you break up the function, you should be able to avoid the problem.
It's better practice to have a function return a variable and then echo it, rather than have the function echo the variable itself.