Fixed method for writing to file