Removed recursion, rewriten in loop