Refactoring to reduce recursion, and minimize the number of Context.typeOf calls. Also removed the Task-based CPS style, for simplicity.