#include <stdio.h>
#include <err.h>
#include "ac.h"

/* 	$Id: ac_print.c,v 1.2 2011/02/17 19:12:37 rec Exp $	 */

#ifndef lint
static char vcid[] = "$Id: ac_print.c,v 1.2 2011/02/17 19:12:37 rec Exp $";
#endif /* lint */


static void print_child(FILE *f, 
			AC_priv_tree p,
			unsigned n1, 
			unsigned *node)
{
  unsigned n2;

  if (p == NULL) 		/* if no node here, end recursion */
    return;

  n2 = *node += 1;		/* get next node number */

  if (p->matchid)		/* is this a terminal? If so, mark it */
    fprintf(f,"  %u [shape=doublecircle]\n", n2);

  fprintf(f,"  %u -> %u [label=\"%c\"]\n", /* print this edige */
	    n1, n2, p->ch);

  print_child(f,p->children, n2, node); /* print remaining kids */
  print_child(f,p->sibling, n1, node);	/* then go for siblings */
}

void ac_print(AC_Handle p, 
	      char *fname)
{
  FILE *f;			/* DOT format output file */
  unsigned node = 0;		/* incremented as nodes are processed */
  AC_priv_tree q;		/* pointer for traversal */
  /*
   * Open output file.
   * Note: If cannot open output file, print error and return.
   * Failure to create graph should not crash an application.
   */
  if ((f = fopen(fname,"w")) == NULL) {
    warn("Unable to create output file %s for GraphViz output.", fname);
    return;
  }
  /*
   * Print DOT preamble
   */
  fprintf(f,"digraph G {\n");
  fprintf(f,"  rankdir=LR;\n");
  fprintf(f,"  center=\"true\";\n");
  fprintf(f,"  size=\"7.5,10\";\n");
  fprintf(f,"  node [shape=circle];\n");
  /*
   * print root node.
   */
  fprintf(f,"  0 -> 0 [shape=circle, label=\"not {%c",p->tree->children->ch);
  for (q = p->tree->children->sibling;q;q = q->sibling)
    fprintf(f,",%c", q->ch);
  fprintf(f,"}\"]\n");
  /*
   * Print rest of state machine by recursion
   */
  print_child(f,p->tree->children,0,&node);
  /*
   * Terminate file and close
   */
  fprintf(f,"}\n");
  fclose(f);
}
