Rewrite the counting logic.
Merge branch 'tuning'