Refactoring to make function tail recursive