Refactored code to deal with errors.