Some refactoring plus start on unit tests.