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

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

/*
 * ac_alloc
 *
 * Creates a new AC_Struct structure and initializes its fields.
 *
 * Parameters:    none.
 *
 * Returns:  A dynamically allocated AC_Struct structure.
 */
AC_Handle 
ac_alloc(void)
{
  AC_Handle node;
  
  if ((node = malloc(sizeof(AC_Struct))) == NULL)
    return NULL;
  memset(node, 0, sizeof(AC_Struct));
  
  if ((node->tree = malloc(sizeof(AC_priv_tree_node))) == NULL) {
    free(node);
    return NULL;
  }
  memset(node->tree, 0, sizeof(AC_priv_tree_node));

  node->isstatic = 0;		/* 0 means dynamic */
  return node;
}

/*
 * ac_free
 *
 * Free up the allocated AC_Struct structure.
 *
 * Parameters:   node  -  a AC_Struct structure
 *
 * Returns:  nothing.
 */
void 
ac_free(AC_Handle node)
{
  AC_priv_tree front, back, next;

  if (node == NULL)
    return;

  if (node->isstatic != 0) 	/* ignore static state machines */
    return;

  if (node->tree != NULL) {
    front = back = node->tree;
    while (front != NULL) {
      back->sibling = front->children;
      while (back->sibling != NULL)
        back = back->sibling;

      next = front->sibling;
      free(front);
      front = next;
    }
  }

  if (node->Plengths != NULL)
    free(node->Plengths);

  free(node);
}
