Integrate factory into code gen

Produce right code immediately instead of patching code afterwards and overwriting file