Fixed bugs and optimized for stack size