Sorry. I just don't see anything wrong with the sub routine. I
wouldn't have written it that way, but it doesn't look like it should
loop endlessly.
Try commenting out every line and run the script. If the problem
stops, try adding them back in one line at a time. Each time you add
a new line in, run your program. Eventually, you may isolate the
offending line and get a better grasp of the problem.