More refactoring and adding tests.