Deleted extra code and made tail-recursive