Refactor of I/O code

Inspired by cpg