Make counting records more efficient. Fix #523