Bugfixes

Fix some bugs and add some test coverage.