#!/usr/bin/env python

import os
import sys

class MemData(object):
    def __init__(self, line):
        data = line.split()
        
        self.liveBytes =int(data[3])
        self.liveObjects = int(data[4])
        self.allocatedBytes = int(data[5])
        self.allocatedObjects = int(data[6])
        self.trace = int(data[7])
        self.type = data[8]
    def add(self, other):
        self.liveBytes += other.liveBytes
        self.liveObjects += other.liveObjects
        self.allocatedBytes += other.allocatedBytes
        self.allocatedObjects += other.allocatedObjects

def compareMemData(a,b):
    if a.allocatedBytes == b.allocatedBytes:
        return 0
    elif  a.allocatedBytes < b.allocatedBytes:
        return 1
    else:
        return -1



def main():

    traces = {}
    
    if len(sys.argv) != 2:
        print "Usage: sumTypes.py <hprof-sites-file>\n"
        sys.exit(1)
        
    file = open(sys.argv[1])
    
    while file.readline() != "--------\n":
        pass    

    inTrace = False
    
#    print "after header"

    while 1:
        line = file.readline()
        if line.startswith("SITES BEGIN"):
            break
        if inTrace and not line.startswith("\t"):
            inTrace = False    
            if svensonTrace:
                traces[nr] = trace
        if line.startswith("TRACE "):
            nr = int( line[6:-2] )
            inTrace = True
            svensonTrace = False
            trace = []
        else:    
            if inTrace:
                if line.find("svenson") >= 0:
                    svensonTrace = True
                trace.append(line)

    # skip two lines
    file.readline()
    file.readline()

    types = {}

    while 1:
        line = file.readline()
        if line == "SITES END\n":
            break
        data = MemData(line)

            

        if traces.has_key(data.trace):    
            if data.type == "java.lang.reflect.Method[]":
                print "java.lang.reflect.Method[] allocation on\n%s" % "".join(traces[data.trace])

            if types.has_key(data.type):
                existing = types[data.type]
                existing.add(data)
            else:
                types[data.type] = data
        
    list = types.values()
    list.sort(compareMemData)
    
    liveSum = 0
    allocatedSum = 0

    count = 1
    for data in list:
        if count <= 10:
                  print "%40s : %12d %12d %12d %12d" % (data.type, data.liveBytes, data.liveObjects, data.allocatedBytes, data.allocatedObjects)
        count += 1
        liveSum += data.liveBytes
        allocatedSum += data.allocatedBytes

    print "                                     Sum : %12d              %12d" % (liveSum, allocatedSum)
    
if __name__ == "__main__":
    main()


