fixed write_file function