Solved #286: Very slow response during pagination for large datasets
Moves count() code to its own function.