made key functions tail recursive