Fix ugly bug, add missing tests.