Refactoring and better error handling