Add a state parameter for the comparator.

Use it at all call sites.
Merge branch 'comparator-with-state'.