fix sorting bug + tests