refactor writefile()