Add tests and minor refactoring.