Add sort keys, fix a bug, add tests.