refactoring and some sanity checks