Add tests, fix bugs uncovered by tests