More refactoring and tests