Add exhaustive tests.

Fix a bunch of things that came up along the way.