Fixes for infinite loops and excessive call stack size