Fixed code to write to file