Write data to file properly