Changed some function names and added a tailrec optimization.