Added logic for whether to sort or not