Some refactoring and error handling