moved filewrite into function