Fixed bug and made the function use a tail call