Generalize balance indexing with arbitrary script