some code refactoring and fixups