Sorting out the sort optimisation
I have a first implementation of the sort optimisation. I didn't have time to test it thoroughly, so I am not quite sure whether there won't be some hidden problems. But it is too late today to do the testing. I will leave this for tomorrow.