Rewrite recursion to while loop in expandToTermTree and resolveCtx

Fixes #208