#!/usr/bin/env python3

import sys
import json

with open(sys.argv[1], 'r') as f:
    data = json.load(f)

totals = {}
    
for context in data['memory']['contexts']:
    if 'name' in context:
        name = context['name']
    else:
        name = '<unknown>'
    inuse = int(context['inuse'])
    malloced = int(context['malloced'])

    if name[0:3] == 'res':
        name = 'res'

    if name[0:4] == 'loop':
        name = 'loop'
        
    if name in totals:
        totals[name]['inuse'] += inuse
        totals[name]['malloced'] += malloced
    else:
        totals[name] = {'inuse': inuse, 'malloced': malloced}

sum = {'inuse': 0, 'malloced': 0}

def human_fmt(num, suffix="B"):
    for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
        if abs(num) < 1024.0:
            return f"{num:3.1f}{unit}{suffix}"
        num /= 1024.0
    return f"{num:.1f}Yi{suffix}"

def fmt(num):
    o = None
    s = f"{num}"
    while len(s) > 3:
        if o is None:
            o = f"{s[-3:]}"
        else:
            o = f"{s[-3:]}.{o}"
        s = s[:-3]
    if len(s) > 0:
        if o is None:
            o = f"{s[-3:]}"
        else:
            o = f"{s[-3:]}.{o}"
    return o

for name in totals:
    inuse = totals[name]['inuse']
    malloced = totals[name]['malloced']

    sum['inuse'] += inuse
    sum['malloced'] += malloced
    
    print(f'{name}: {human_fmt(inuse)} {human_fmt(malloced)}')

inuse = int(data['memory']['InUse'])
malloced = int(data['memory']['Malloced'])


print("SUMMARY")
print(f"INUSE: {human_fmt(sum['inuse'])} == {human_fmt(inuse)}")
print(f"MALLOCED: {human_fmt(sum['malloced'])} == {human_fmt(malloced)}")
