Refactor function write