fixed file-writing logic