More refactoring and unit tests