Big refactoring, unit tests.