Better sorting function