Refactored a loop to tail-recursion