Improved version using tail recursion