Make output file handling more robust