Add unit tests and fix problems identified by tests.