Don't calculate category length on every loop iteration
Merge pull request #2 from stuartgibson/master

Optimises loop