Correct sorting order, add tests