More refactoring and fixes