Made various error checks more robust.