Added tail recursive optimization.