some refactoring and error handling