cleaned up sort function