minor refactoring and error checking