/*
 *  	$Id: ac_search.c,v 1.2 2011/02/18 18:47:29 rec Exp rec $
 *
 * Implementation of the Aho-Corasick algorithm.
 *
 * This file is public domain.
 */

#include <stdio.h>		/* for fprintf(3) */
#include <stdlib.h>		/* for malloc(3) */
#include <string.h>		/* for memset(3) */
#include <err.h>		/* for warnx(3) */
#include "ac.h"			/* for data structures */

/*
 * ac_search_init
 *
 * Initializes the variables used during an Aho-Corasick search.
 * See ac_search for an example of how it should be used.
 *
 * Parameters:  node  -  an AC_Struct structure
 *              T     -  the sequence to be searched
 *              N     -  the length of the sequence (or 0 to call strlen(3))
 *
 * Returns:  nothing.
 */
void 
ac_search_init(AC_Handle node, 
	       char *T, 
	       unsigned int N)
{
  /*
   * Make sure we're set up to run.
   *
   * Specifically, no error flag and we've been preprocessed.
   */
  if (node->errorflag)
    return;
  if (!node->ispreprocessed) {
    if (!ac_prep(node)) {
      warnx("Error in Aho-Corasic search init: Preprocessing fails.");
      return;
    }
  }
  /*
   * As a convenience, allow length N to be 0 to cause us to run
   * strlen(3) for you.
   */
  if (N == 0)
    N = strlen(T);
  /*
   * Set up initial variables
   */
  node->T = T - 1;          /* Shift to make sequence be T[1],...,T[N] */
  node->N = N;
  node->c = 1;
  node->w = node->tree;
  node->output = NULL;
  node->initflag = 1;
  node->endflag = 0;
}


/*
 * ac_search
 *
 * Scans a text to look for the next occurrence of one of the patterns
 * in the text.  An example of how this search should be used is the
 * following:
 *
 *    s = T;
 *    len = N; 
 *    contflag = 0;
 *    ac_search_init(node, T, N);
 *    while (ac_search(node, &s, &matchlen, &matchid)) {
 *      >>> Pattern `matchid' matched from `s' to `s + matchlen - 1'. <<<
 *    }
 *
 * where `node', `T' and `N' are assumed to be initialized appropriately.
 *
 * Parameters:  node           -  a preprocessed AC_Struct structure
 *              length_out     -  where to store the new match's length
 *              id_out         -  where to store the identifier of the
 *                                pattern that matched
 *
 * Returns:  0 if no more matches.
 *           's' is the left end of the text that matches a pattern, or NULL
 *           if no match occurs.  It also stores values in `*length_out',
 *           and `*id_out' giving the match's length and pattern identifier.
 */
int
ac_search(AC_Handle node, 
	  char **s,
	  unsigned int *length_out, 
	  unsigned int *id_out)
{
  int c, N, id;
  char *T;
  AC_priv_tree w, wprime, root;

  if (node->errorflag)
    return 0;
  if (!node->ispreprocessed) {
    fprintf(stderr, "Error in Aho-Corasick search.  The preprocessing "
            "has not been completed.\n");
    return 0;
  }
  if (!node->initflag) {
    warnx("Error in Aho-Corasick search: ac_search_init was not "
            "called.");
    return 0;
  }
  if (node->endflag)
    return 0;

  T = node->T;
  N = node->N;
  c = node->c;
  w = node->w;
  root = node->tree;

  /*
   * If the last call to ac_search returned a match, check for another
   * match ending at the same right endpoint (denoted by a non-NULL
   * output link).
   */
  if (node->output != NULL) {
    node->output = node->output->outlink;
    node->outlinks_traversed++;
    
    if (node->output != NULL) {
      id = node->output->matchid;
      if (id_out)
        *id_out = id;
      if (length_out)
        *length_out = node->Plengths[id];
      *s = &T[c] - node->Plengths[id];
      return 1;
    }
  }

  /*
   * Run the search algorithm, stopping at the first position where a
   * match to one of the patterns occurs.
   */
  while (c <= N) {
    /*
     * Try to match the next input character to a child in the tree.
     */
    wprime = w->children;
    while (wprime != NULL && wprime->ch != T[c])
      wprime = wprime->sibling;

    node->num_compares++;

    /*
     * If the match fails, then either use the failure link (if not
     * at the root), or move to the next character since no prefix
     * of any pattern ends with character T[c].
     */
    if (wprime == NULL) {
      if (w == root)                
        c++;
      else {
        w = w->faillink;
        node->num_failures++;
      }
    }
    else {
      /*
       * If we could match the input, move down the tree and to the
       * next input character, and see if that match completes the
       * match to a pattern (when matchid != 0 or outlink != NULL).
       */
      c++;
      w = wprime;
      node->edges_traversed++;

      if (w->matchid != 0)
        node->output = w;
      else if (w->outlink != NULL) {
        node->output = w->outlink;
        node->outlinks_traversed++;
      }

      if (node->output != NULL) {
        id = node->output->matchid;
        if (id_out)
          *id_out = id;
        if (length_out)
          *length_out = node->Plengths[id];

        node->w = w;
        node->c = c;
	*s = &T[c] - node->Plengths[id];
        return 1;
      }
    }
  }

  node->c = c;
  node->endflag = 1;

  return 0;
}

/*
 * ac_match
 *
 * Scans a text to look for the next occurrence of one of the patterns
 * in the text.  An example of how this search should be used is the
 * following:
 *
 *    s = T;
 *    len = N; 
 *    contflag = 0;
 *    ac_search_init(node, T, N);
 *    while (ac_match(node, &s, &matchlen, &matchid)) {
 *      >>> Pattern `matchid' matched from `s' to `s + matchlen - 1'. <<<
 *    }
 *
 * where `node', `T' and `N' are assumed to be initialized appropriately.
 *
 * Parameters:  node           -  a preprocessed AC_Struct structure
 *              length_out     -  where to store the new match's length
 *              id_out         -  where to store the identifier of the
 *                                pattern that matched
 *
 * Returns:  0 if no more matches.
 *           's' is the left end of the text that matches a pattern, or NULL
 *           if no match occurs.  It also stores values in `*length_out',
 *           and `*id_out' giving the match's length and pattern identifier.
 */
int
ac_match(AC_Handle node, 
	 char **s,
	 unsigned int *length_out, 
	 unsigned int *id_out)
{
  int c, N, id;
  char *T;
  AC_priv_tree w, wprime, root;

  if (node->errorflag)
    return 0;
  if (!node->ispreprocessed) {
    fprintf(stderr, "Error in Aho-Corasick search.  The preprocessing "
            "has not been completed.\n");
    return 0;
  }
  if (!node->initflag) {
    warnx("Error in Aho-Corasick search: ac_search_init was not "
            "called.");
    return 0;
  }
  if (node->endflag)
    return 0;

  T = node->T;
  N = node->N;
  c = node->c;
  w = node->w;
  root = node->tree;

  /*
   * If the last call to ac_match returned a match, check for another
   * match ending at the same right endpoint (denoted by a non-NULL
   * output link).
   */
  if (node->output != NULL) {
    node->output = node->output->outlink;
    node->outlinks_traversed++;
    
    if (node->output != NULL) {
      id = node->output->matchid;
      if (id_out)
        *id_out = id;
      if (length_out)
        *length_out = node->Plengths[id];
      *s = &T[c] - node->Plengths[id];
      return 1;
    }
  }

  /*
   * Run the search algorithm, stopping at the first position where a
   * match to one of the patterns occurs.
   */
  while (c <= N) {
    /*
     * Try to match the next input character to a child in the tree.
     */
    wprime = w->children;
    while (wprime != NULL && wprime->ch != T[c])
      wprime = wprime->sibling;

    node->num_compares++;

    /*
     * If the match fails, then either use the failure link (if not
     * at the root), or move to the next character since no prefix
     * of any pattern ends with character T[c].
     *
     * So, we quit here.
     */
    if (wprime == NULL) {
      if (w == root) 
        return 0;
      else {
        w = w->faillink;
        node->num_failures++;
      }
    }
    else {
      /*
       * If we could match the input, move down the tree and to the
       * next input character, and see if that match completes the
       * match to a pattern (when matchid != 0 or outlink != NULL).
       */
      c++;
      w = wprime;
      node->edges_traversed++;

      if (w->matchid != 0)
        node->output = w;
      else if (w->outlink != NULL) {
        node->output = w->outlink;
        node->outlinks_traversed++;
      }

      if (node->output != NULL) {
        id = node->output->matchid;
        if (id_out)
          *id_out = id;
        if (length_out)
          *length_out = node->Plengths[id];

        node->w = w;
        node->c = c;
	*s = &T[c] - node->Plengths[id];
        return 1;
      }
    }
  }

  node->c = c;
  node->endflag = 1;

  return 0;
}

