code refactoring and error checking