Better error-handling and refactoring