some refactoring and extra error handling