Lots of refactoring and new tests.