Fix some bugs and add some tests.

This addresses the bugs pointed out on the pull request by Tom Switzer
and Alexander Altman. It also adds a basic test for some of the
functionality.

The test should be fleshed out more before the PR is merged, but I
just wanted to push what I had so far.