Modified sort function