/*
 *  	$Id: ac_prep.c,v 1.1 2011/02/14 05:45:02 rec Exp $
 *
 * Implementation of the Aho-Corasick algorithm.
 *
 * This file is public domain.
 */

#include <stdio.h>
#include "ac.h"
/*
 * ac_prep
 *
 * Compute the failure and output links for the keyword tree.
 *
 * Parameters:  node  -  an AC_Struct structure
 *
 * Returns: non-zero on success, zero on error.
 */
int 
ac_prep(AC_Handle node)
{
  char x;
  AC_priv_tree v, vprime, 
    w, wprime, 
    root, 
    front, back, 
    child;

  if (node->errorflag)
    return 0;

  /*
   * The failure link and output link computation requires a breadth-first
   * traversal of the keyword tree.  And, to do that, we need a queue of
   * the nodes yet to be processed.
   *
   * The `faillink' fields will be used as the pointers for the queue
   * of nodes to be computed (since the failure link is only set after
   * the node is removed from the queue).
   * 
   * The `outlink' fields will be used as the pointers to a node's parent
   * for nodes in the queue (since the output link is also only set after
   * the node is removed from the queue).
   */
  root = node->tree;

  front = back = root;
  front->faillink = NULL;
  front->outlink = NULL;

  while (front != NULL) {
    v = front;
    x = v->ch;
    vprime = v->outlink;

    /*
     * Add the node's children to the queue.
     */
    for (child=v->children; child != NULL; child=child->sibling) {
      child->outlink = v;
      back->faillink = child;
      back = child;
    }
    back->faillink = NULL;

    front = front->faillink;
    v->faillink = v->outlink = NULL;
    
    /*
     * Set the failure and output links.
     */
    if (v == root)
      ;
    else if (vprime == root)
      v->faillink = root;
    else {
      /*
       * Find the find link in the failure link chain which has a child
       * labeled with x.
       */
      wprime = NULL;
      w = vprime->faillink;

      while (1) {
        wprime = w->children;
        while (wprime != NULL && wprime->ch < x)
          wprime = wprime->sibling;

        if ((wprime != NULL && wprime->ch == x) || w == root)
          break;

        w = w->faillink;

        node->prep_fail_compares++;
      }
      node->prep_fail_compares++;

      if (wprime != NULL && wprime->ch == x)
        v->faillink = wprime;
      else
        v->faillink = root;

      if (v->matchid != 0) {
        if (v->faillink->matchid != 0)
          v->outlink = v->faillink;
        else
          v->outlink = v->faillink->outlink;
      }
    }
  }

  node->ispreprocessed = 1;
  node->initflag = 0;

  return 1;
}
