Cleaned up statistics code, and also grouped some queries