Fix logic in sort_terms function which was ignoring terms without a sort order.