Big refactoring with many added tests.