made inner function tail recursive