clean up and add stack size checking