Added error handling and instant write to output file