Safer method for writing data to file, fixing #6