Refactoring and some error handling