Refactored code and error handling