Rewrite recursion to while loop in resolveCtx