Refactor global state into global state object
Generate correct write/writeln function