fixed file write logic