Replace vars and while loops with tail-recursive functions