Added some checking for stack overflow