Added some unit testing.
Fixed some bugs revealed by the tests.