Changed recursion to a while loop. This avoids taking up too much space on the stack