Refactored error checking slightly.