Change recursive call to while-loop to fix the stack overflow error