refactored recursion to a while