'use strict';

if(!process.addAsyncListener)
    require('async-listener');

var stack = require('./lib/stack');
var fs = require('fs');

var parent = 0;
var counter = 0;
var calls = [];
var len = 0;

/**
 * AsyncListener object
 */
var AsyncListener = {};

AsyncListener.create = function create() {
    // This always gets called in between before/after
    counter += 1;
    calls.push( {"parent":parent, "current":counter } );
    return counter;
};


AsyncListener.before = function before(context, stack) {
    parent = stack;
};


AsyncListener.error = function error(stack, err) {
};

var key = process.addAsyncListener(AsyncListener);



function printCalls(){
  console.log(calls);}

function get_tree( calls ) {
  var tree = { 0:{} }
  get_tree_helper( calls, tree[0],  0 );
  return tree;
}

function get_tree_helper(calls, tree, prevParent ) {
    for (var j = 0; j < calls.length; j++){
      call = calls[j];
      if (prevParent === call.parent ){
        tree[call.current] = {}
        get_tree_helper(calls, tree[call.current], call.current );
      }
    }
}


function tree_to_dot_code(){
  var str = "digraph {\n";
  for (var i = 0; i < len; i++){
    var parent = calls[i].parent;
    var child = calls[i].current;
    str += parent + " -> " + child +"\n";
  }
  str += "}";
  return str;
}

function create_dot_file(){
  len = calls.length;
  fs.writeFileSync( 'dotgraph', tree_to_dot_code() );
  console.log( tree_to_dot_code() );
}

process.on('exit', create_dot_file);
module.exports = key;

@@ -78,38 +78,17 @@
 var 
-stack = require('./lib/stack')
+tree = %7B%7D
 ;%0Ava
@@ -476,21 +476,20 @@
 ontext, 
-stack
+tree
 ) %7B%0A    
@@ -497,21 +497,20 @@
 arent = 
-stack
+tree
 ;%0A%7D;%0A%0A%0AA
@@ -549,13 +549,12 @@
 ror(
-stack
+tree
 , er

Rename some vars