General refactoring and better error handling.