Rework code generation + bug fixes