Refactor build_index