Yet more tests and some refactoring.