Move writing logic out to write