refactoring and improved error handling