Codegen: partial refactor with contexts