Refactoring and error checking