replaced while loop with recursion