Refined sorting code.