Fixed stack overflow error by converting tail-recursion to a flat-stack loop