Fixed sort function