More index rewritings and some refactoring.

For details see commits.