Remove loop and replace with recursive function