Minor refactoring and some input validation