Replace move function with a tailrec function