refactoring and error checking