Add sanity check to sort function