Made buffer handling more robust under various error conditions