#!/usr/bin/python
#
# example usage: dtrace -n 'profile-4999hz { @a[ustack()]=count() }' | thisthing | dot -Tsvg
# Requires graphviz
# Still needs lots of work and love.
# License: CC-BY
# Author: Domas Mituzas 
#
import sys, string

symbol=""
symbols=[]
rels=[]
count=0
counts={}
relationships={}
printed={}
child=""

for line in sys.stdin:
	line=line.strip().split("+")[0]
	if line=="":
		for symbol in symbols:
			try: counts[symbol]+=count
			except KeyError: counts[symbol]=count
		for parent,child in rels:
			if parent not in relationships: relationships[parent]={}
			if child not in relationships[parent]: relationships[parent][child]=0
			relationships[parent][child]+=count
		parent=""
		child=""
		symbols=[]
		rels=[]
		continue

	try: 
		count=string.atoi(line)
	except ValueError: 
		# line=line.split('`')[-1]
		if line.startswith("0x"): line="unresolved"
		line=line.split('(')[0]
		symbols.append(line)
		rels.append((line,child))
		child=line
	
print """digraph prof {
	node [style=filled, shape=box];
	graph [
	rankdir = "UD"
	];
	fontsize=1;
"""

for parent,children in relationships.items():
	if counts[parent]<10:
		continue
	for child,count in children.items():
		if child=="": continue
		if count>3:
			pct = count*100/counts[parent]
			if pct>10:
				print """ "%s" -> "%s" [label="%d%%"];"""%(parent,child,pct)
				printed[child]=counts[child]
				printed[parent]=counts[parent]
				
for node,count in printed.items():
	try: (ex,sym)=node.split('`')
	except: 
		ex=""
		sym=node
	print """ "%s" [label="%s\\n%s (%d)"]; """%(node,sym,ex,count);
print """ } """