Replace do-loop with recursion