fix sorting

Needs a test case that demonstrates that the problem is fixed.