Minor refactoring and error handling