added stack overflow prevention