#!/bin/env python

import sys

def parse_type_usage(file):
    stats = {}
    for line in file:
        try:
            line = line.replace('GLib-GObject-Message:', '')
            data = [x.strip() for x in line.split('|')]
            name = data.pop(0)
            data = dict(x.split() for x in data)
            max_population = int(data['max-population'])
            num_created = int(data['created'])
            num_destroyed = int(data['destroyed'])
            stats[name] = (max_population, num_created, num_destroyed)
        except:
            continue  # If anything goes wrong, move on.
    return stats

# Sort by:
#   Max Population (descending)
#   # Created (descending)
#   Instance Type (ascending)
def default_ordering(a, b):
    a_name, a_data = a
    b_name, b_data = b
    if a_data[0] != b_data[0]:
        return cmp(a_data[0], b_data[0]) * -1
    elif a_data[1] != b_data[1]:
        return cmp(a_data[1], b_data[1]) * -1
    else:
        return cmp(a_name, b_name)

def report_type_usage(stats, cmp_func=default_ordering):
    sep = '  '
    name_width = max(len(x) for x in stats.keys())
    fields = ('Instance Type'.ljust(name_width),
              'Max Population', '# Created', '# Destroyed')
    widths = tuple(len(x) for x in fields)
    print sep.join(fields)
    print sep.join('-' * x for x in widths)
    for name, data in sorted(stats.items(), cmp=cmp_func):
        print sep.join((name.ljust(name_width),) +
              tuple(str(value).rjust(width) for value, width in
              zip(data, widths[1:])))

if __name__ == '__main__':
    stats = parse_type_usage(sys.stdin)
    report_type_usage(stats)
