#!/usr/bin/python

import os
import sys
import cPickle

dbfile = "/home/jason/gentoo/bug-database"
txtfile = "/home/jason/gentoo/bug-report"

if os.path.exists(dbfile):
	db = cPickle.Unpickler(open(dbfile, "r")).load()
	bugtitles = db["bugtitles"]
	bugcounts = db["bugcounts"]
else:
	bugtitles = {}
	bugcounts = {}

lines = sys.stdin.readlines()
for line in lines:
	if not line.startswith("Subject:"):
		continue
	subject = line[9:]
	bugnumber = int(subject.split(" ")[1].split("]")[0])
	bugtitle = " ".join("]".join(subject.split("]")[1:]).strip().split(" "))
	if bugtitle.startswith("New: "):
		bugtitle = bugtitle[5:]
	bugtitles[bugnumber] = bugtitle
	if bugnumber in bugcounts:
		bugcounts[bugnumber] += 1
	else:
		bugcounts[bugnumber] = 1

db = {"bugtitles":bugtitles, "bugcounts":bugcounts}
cPickle.dump(db, open(dbfile, "w"), -1)

counts = {}

for number in bugcounts:
	count = bugcounts[number]
	if count in counts:
		counts[count] += [number]
	else:
		counts[count] = [number]

keys = counts.keys()
keys.sort()
keys.reverse()

txt = open(txtfile, "w")
for key in keys:
	if key == 1:
		txt.write(str(key) + " CHANGE\n")
	else:
		txt.write(str(key) + " CHANGES\n")
	counts[key].sort()
	counts[key].reverse()
	for number in counts[key]:
		txt.write((" "*(6-len(str(number))))+str(number)+"    "+bugtitles[number]+"\n")
	txt.write("\n")

txt.close()
