Add missing unit tests for existing code and fix a few bugs