Factor out write_code and read_code