The while loop has me stumped too. Looks useless in my opinion. What I see here is an all too common problem. Writing code to solve the problem.
Instead write a solution to the problem, and then...