Add tests. Fix bugs discovered by tests.