Replace tail-end recursion with more efficient while loop