#!/usr/bin/python
import re
import os


def main():
	fd = os.popen("avr-objdump -d firmware.bin")
	oldaddr=0
	lastfnname=""
	namespacedict = {}
	s="foo"
	while s:
		s=fd.readline()
		m=re.match("([0-9a-f]+) <(\w+)>:",s)
		if m:
			addr,fname=m.groups()
			addr=int(addr,16)
			size=addr-oldaddr
			oldaddr=addr
	#		print size,"\t",lastfnname
			namespace=get_namespace(lastfnname)
			try:
				namespacedict[namespace].append((lastfnname, size))
			except:
				namespacedict[namespace] = [(lastfnname, size)]
			lastfnname = fname

	print "individual sizes:"
	for k,v in namespacedict.items():
		for a,b in sorted(v):
			print "%4i  %s"%(b,a)
	print "namespace sizes:"
	for k,v in namespacedict.items():
		totalsize = sum( [ i[1] for i in v ] )
		print "%4i  %s*"%(totalsize,k)
		
def get_namespace(name):
	matchlist = [
			r"(^__)",
			r"(^\w+?_)",
			r"(\w[a-z0-9])[A-Z]"]
	for i in matchlist:
		m = re.match(i, name)
		if m:
			return m.groups()[0]
	return "<nonamespace>"


if __name__=="__main__":
	main()
