Add a functional test.

And fix a couple bugs.