More refactoring and some minor fixes