Add tests, and minor bugfixes found while writing tests.