Add test coverage and fix bugs revealed by tests.