Replaced while loop with tail recursive function