Fix several bugs found by unit testing.