#!/usr/bin/env python


import sys
import fileinput
import math

import numpy as np
import pylab

from matplotlib import mlab
from matplotlib import pyplot as plot
from matplotlib.ticker import FuncFormatter


fig_width_cm = 29.7
fig_height_cm = 21
inches_per_cm = 1 / 2.58


def format_time(value, position):
    return '%0.3f' % (value / 1000000.0)

def format_mem(value, position):
    return '%0.3f' % (value / 1024.0)


if __name__ == '__main__':
    header = None
    lineno = 0
    rows = []
    for line in fileinput.input():
        lineno += 1
        if line.startswith('!!!!!'):
            line = line[5:].strip().split('\t')
            if not header:
                header = line
                header.append('lineno')
            else:
                line = (int(line[0]),
                        int(line[1]),
                        int(line[2]),
                        str(lineno) + ' (' + (str(line[3]) if len(line)==4 else '') + ')')
                rows.append(line)
    data = np.rec.fromrecords(rows, names=header,
                              formats=['f8', 'i4', 'i4', 'a50'])

    fig_width = fig_width_cm * inches_per_cm
    fig_height = fig_height_cm * inches_per_cm
    fig_size = [fig_width, fig_height] 
    figure = plot.figure('GTK+ Memory Usage', figsize=fig_size)

    axes = figure.add_subplot(211, title='Working set')
    axes.xaxis.set_major_formatter(FuncFormatter(format_time))  
    axes.yaxis.set_major_formatter(FuncFormatter(format_mem))  
    lines = axes.plot(data.time, data.workingset, 'o-', picker=5)
#    for record in data:
#        axes.annotate('{}'.format(record[3]),
#                      xy=(record[0], record[1]),
#                      xytext=(-5, 5),
#                      ha='center',
#                      va='bottom',
#                      rotation=90,
#                      textcoords='offset points')

    axes = figure.add_subplot(212, title='Private')
    axes.xaxis.set_major_formatter(FuncFormatter(format_time))  
    axes.yaxis.set_major_formatter(FuncFormatter(format_mem))  
    lines = axes.plot(data.time, data.private, 'o-', picker=5)
#    for record in data:
#        axes.annotate('{}'.format(record[3]),
#                      xy=(record[0], record[2]),
#                      xytext=(-5, 5),
#                      ha='center',
#                      va='bottom',
#                      rotation=90,
#                      textcoords='offset points')

    plot.show()
