Refactor index generation/sorting.