Made functions tail-recursive