Fixed bug in file writing