Replaced fold with tail recursive function.