Stats cleanup

Relates to #172, don't know if it fully covers it.

Before merging *please read the comments I left* - they concern tricky bits of code that I'm not sure I faithfully translated.