Pull uses of count() out of for() loops

To speed them up, per #138.