core/sm_trie.cpp
author David Anderson <dvander@alliedmods.net>
Fri Feb 16 04:16:31 2007 +0000 (2007-02-16)
changeset 502 4530ea065a8b
parent 370 d3a484f98f6d
child 604 f373aaca29db
permissions -rw-r--r--
fixed a serious potential bug with swapping plugins to debug mode, leaving stale function pointers without plugin removal
     1 /**
     2  * ===============================================================
     3  * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     4  * ===============================================================
     5  *
     6  * This file is not open source and may not be copied without explicit
     7  * written permission of AlliedModders LLC.  This file may not be redistributed 
     8  * in whole or significant part.
     9  * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
    10  *
    11  * Version: $Id$
    12  */
    13 
    14 #include <string.h>
    15 #include <stdlib.h>
    16 #include <assert.h>
    17 #include "sm_trie.h"
    18 
    19 /**
    20  * Double Array Trie algorithm, based on:
    21  * An Efficient Implementation of Trie Structures, by
    22  *  Jun-ichi Aoe and Katsushi Maromoto, and Takashi Sato
    23  * from Sofiware - Practice and Experience, Vol. 22(9), 695-721 (September 1992)
    24  *
    25  *  A Trie is a simple data structure which stores strings as DFAs, with each 
    26  * transition state being a string entry.  For example, observe the following strings:
    27  *
    28  * BAILOPAN, BAT, BACON, BACK
    29  *  These transition as the follow production rules:
    30  *  B -> ...                  B
    31  *       A -> ...             BA
    32  *            I -> ...        BAI
    33  *                 LOPAN      BAILOPAN
    34  *            T -> ...        BAT
    35  *            C ->            BAC
    36  *                 O -> ...   BACO
    37  *                      N     BACON
    38  *                 K          BACK
    39  *
    40  *  The standard implementation for this - using lists - gives a slow linear lookup, somewhere between
    41  * O(N+M) or O(log n).  A faster implementation is proposed in the paper above, which is based on compacting
    42  * the transition states into two arrays.  In the paper's implementation, two arrays are used, and thus it is
    43  * called the "Double Array" algorithm.  However, the CHECK array's size is maintained the same as BASE, 
    44  * so they can be combined into one structure.  The array seems complex at first, but is very simple: it is a
    45  * tree structure flattened out into a single vector.  I am calling this implementation the Flat Array Trie.
    46  *
    47  *  BASE[] is an array where each member is a node in the Trie.  The node can either be UNUSED (empty), an ARC
    48  * (containing an offset to the next set of ARCs), or a TERMINATOR (contains the rest of a string).
    49  * Each node has an index which must be interpeted based on the node type.  If the node is a TERMINATOR, then the
    50  * index is an index into a string table, to find the rest of the string.  
    51  *  If the node is an ARC, the index is another index into BASE.  For each possible token that can follow the
    52  * current token, the value of those tokens can be added to the index given in the ARC.  Thus, given a current
    53  * position and the next desired token, the current arc will jump to another arc which can contain either:
    54  *   1) An invalid production (collision, no entry exists)
    55  *   2) An empty production (no entry exists)
    56  *   3) Another arc label (the string ends here or continues into more productions)
    57  *   4) A TERMINATOR (the string ends here and contains an unused set of productions)
    58  * 
    59  *  So, given current offset N (starting at N=1), jumping to token C means the next offset will be:
    60  *      offs = BASE[n] + C
    61  *  Thus, the next node will be at:
    62  *      BASE[BASE[n] + C]
    63  * 
    64  *  This allows each ARC to specify the base offset for any of its ARC children, like a tree.  Each node specifies
    65  * its parent ARC -- so if an invalid offset is specified, the parent will not match, and thus no such derived 
    66  * string exists.
    67  *
    68  *  This means that arrays can be laid out "sparsely," maximizing their usage.  Note that N need not be related to
    69  * the range of tokens (1-256).  I.e., a base index does not have to be at 1, 256, 512, et cetera.  This is because
    70  * insertion comes with a small deal of complexity.  To insert a new set of tokens T, the algorithm finds a new 
    71  * BASE index N such that BASE[N+T[i]] is unused for each T[i].  Thus, indirection is not necessarily linear; 
    72  * traversing a chain of ARC nodes can _and will_ jump around BASE.
    73  *
    74  *  Of course, given this level of flexibility in the array organization, there are collisions.  This is largely 
    75  * where insertions become slow, as the old chain must be relocated before the new one is used.  Relocation means 
    76  * finding one or more new base indexes, and this means traversing BASE until an acceptable index is found, such 
    77  * that each offset is unused (see description in previous paragraph).
    78  *
    79  *  However, it is not insertion time we are concerned about.  The "trie" name comes from reTRIEval.  We are only
    80  * concerned with lookup and deletion.  Both lookup and deletion are O(k), where k is relative to the length of the 
    81  * input string.  Note that it is best case O(1) and worst case O(k).  Deleting the entire trie is always O(1).
    82  */
    83 
    84 /**
    85  * Optimization ideas for the future:
    86  * 1) Store a reference count for each arc, with the count of sub-children.
    87  *    This could let us break out of "children searches" for case 4 easily.
    88  * 2) Use a 'free list' so we can easily search the trie for free points.
    89  *    This would drastically speed up x_check*
    90  */
    91 
    92 enum NodeType
    93 {
    94 	Node_Unused = 0,		/* Node is not being used (sparse) */
    95 	Node_Arc,				/* Node is part of an arc and does not terminate */
    96 	Node_Term,				/* Node is a terminator */
    97 };
    98 
    99 struct TrieNode
   100 {
   101 	/**
   102 	 * For Node_Arc, this index stores the 'base' offset to the next arc chain.
   103 	 *   I.e. to jump from this arc to character C, it will be at base[idx+C].
   104 	 * For Node_Term, this is an index into the string table.
   105 	 */
   106 	unsigned int idx;
   107 
   108 	/**
   109 	 * This contains the prior arc that we must have come from.
   110 	 * For example, if arc 63 has a base jump of index 12, and we want to see if
   111 	 * there is a valid character C, the parent of 12+C must be 63.
   112 	 */
   113 	unsigned int parent;
   114 
   115 	void *value;			/* Value associated with this node */
   116 	NodeType mode;			/* Current usage type of the node */
   117 	bool valset;			/* Whether or not a value is set */
   118 };
   119 
   120 struct Trie
   121 {
   122 	TrieNode *base;			/* Base array for the sparse tables */
   123 	char *stringtab;		/* String table pointer */
   124 	unsigned int baseSize;	/* Size of the base array, in members */
   125 	unsigned int stSize;	/* Size of the string table, in bytes */
   126 	unsigned int tail;		/* Current unused offset into the string table */
   127 };
   128 
   129 inline unsigned char charval(char c)
   130 {
   131 	return (unsigned char)c;
   132 }
   133 
   134 bool sm_trie_grow(Trie *trie)
   135 {
   136 	/* The current # of nodes in the tree is trie->baseSize + 1 */
   137 	unsigned int curSize = trie->baseSize;
   138 	unsigned int newSize = curSize * 2;
   139 
   140 	//:TODO: Make functions calling this return failure if this fails 
   141 	trie->base = (TrieNode *)realloc(trie->base, (newSize + 1) * sizeof(TrieNode));
   142 	if (!trie->base)
   143 	{
   144 		return false;
   145 	}
   146 
   147 	memset(&trie->base[curSize+1], 0, (newSize - curSize) * sizeof(TrieNode));
   148 	trie->baseSize = newSize;
   149 
   150 	return true;
   151 }
   152 
   153 unsigned int x_check(Trie *trie, char c, unsigned int start=1)
   154 {
   155 	TrieNode *base = trie->base;
   156 	unsigned char _c = charval(c);
   157 	unsigned int to_check = trie->baseSize - _c;
   158 	for (unsigned int i=start; i<=to_check; i++)
   159 	{
   160 		if (base[i+_c].mode == Node_Unused)
   161 		{
   162 			return i;
   163 		}
   164 	}
   165 
   166 	sm_trie_grow(trie);
   167 
   168 	return x_check(trie, c, to_check+1);
   169 }
   170 
   171 unsigned int x_check2(Trie *trie, char c1, char c2, unsigned int start=1)
   172 {
   173 	TrieNode *base = trie->base;
   174 	unsigned char _c1 = charval(c1);
   175 	unsigned char _c2 = charval(c2);
   176 	unsigned int to_check = trie->baseSize - (_c1 > _c2 ? _c1 : _c2);
   177 	for (unsigned int i=start; i<=to_check; i++)
   178 	{
   179 		if (base[i+_c1].mode == Node_Unused
   180 			&& base[i+_c2].mode == Node_Unused)
   181 		{
   182 			return i;
   183 		}
   184 	}
   185 
   186 	sm_trie_grow(trie);
   187 
   188 	return x_check2(trie, c1, c2, to_check+1);
   189 }
   190 
   191 unsigned int x_check_multi(Trie *trie, 
   192 							unsigned int offsets[], 
   193 							unsigned int count,
   194 							unsigned int start=1)
   195 {
   196 	TrieNode *base = trie->base;
   197 	TrieNode *cur;
   198 	unsigned int to_check = trie->baseSize;
   199 	unsigned int highest = 0;
   200 
   201 	for (unsigned int i=0; i<count; i++)
   202 	{
   203 		if (offsets[i] > highest)
   204 		{
   205 			highest = offsets[i];
   206 		}
   207 	}
   208 
   209 	to_check -= highest;
   210 
   211 	for (unsigned int i=start; i<=to_check; i++)
   212 	{
   213 		bool okay = true;
   214 		for (unsigned int j=0; j<count; j++)
   215 		{
   216 			cur = &base[i+offsets[j]];
   217 			if (cur->mode != Node_Unused)
   218 			{
   219 				okay = false;
   220 				break;
   221 			}
   222 		}
   223 		if (okay)
   224 		{
   225 			return i;
   226 		}
   227 	}
   228 
   229 	sm_trie_grow(trie);
   230 
   231 	return x_check_multi(trie, offsets, count, to_check+1);
   232 }
   233 
   234 unsigned int x_addstring(Trie *trie, const char *ptr)
   235 {
   236 	size_t len = strlen(ptr) + 1;
   237 
   238 	if (trie->tail + len >= trie->stSize)
   239 	{		
   240 		while (trie->tail + len >= trie->stSize)
   241 		{
   242 			trie->stSize *= 2;
   243 		}
   244 		trie->stringtab = (char *)realloc(trie->stringtab, trie->stSize);
   245 	}
   246 
   247 	unsigned int tail = trie->tail;
   248 	strcpy(&trie->stringtab[tail], ptr);
   249 	trie->tail += len;
   250 
   251 	return tail;
   252 }
   253 
   254 Trie *sm_trie_create()
   255 {
   256 	Trie *t = new Trie;
   257 
   258 	t->base = (TrieNode *)malloc(sizeof(TrieNode) * (256 + 1));
   259 	t->stringtab = (char *)malloc(sizeof(char) * 256);
   260 	t->baseSize = 256;
   261 	t->stSize = 256;
   262 
   263 	sm_trie_clear(t);
   264 
   265 	return t;
   266 }
   267 
   268 void sm_trie_clear(Trie *trie)
   269 {
   270 	trie->tail = 0;
   271 
   272 	memset(trie->base, 0, sizeof(TrieNode) * (trie->baseSize + 1));
   273 	memset(trie->stringtab, 0, sizeof(char) * trie->stSize);
   274 
   275 	/* Sentinel root node */
   276 	trie->base[1].idx = 1;
   277 	trie->base[1].mode = Node_Arc;
   278 	trie->base[1].parent = 1;
   279 }
   280 
   281 void sm_trie_destroy(Trie *trie)
   282 {
   283 	free(trie->base);
   284 	free(trie->stringtab);
   285 	delete trie;
   286 }
   287 
   288 bool sm_trie_delete(Trie *trie, const char *key)
   289 {
   290 	unsigned int lastidx = 1;		/* the last node index */
   291 	unsigned int curidx;			/* current node index */
   292 	const char *keyptr = key;		/* input stream at current token */
   293 	TrieNode *node = NULL;			/* current node being processed */
   294 	TrieNode *base = trie->base;
   295 
   296 	if (!*key)
   297 	{
   298 		return false;
   299 	}
   300 
   301 	/* Start traversing at the root node */
   302 	do
   303 	{
   304 		/* Find where the next character is, then advance */
   305 		curidx = base[lastidx].idx;
   306 		node = &base[curidx];
   307 		curidx += charval(*keyptr);
   308 		node = &base[curidx];
   309 		keyptr++;
   310 
   311 		/* Check if this slot is supposed to be empty or is a collision */
   312 		if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
   313 		{
   314 			return false;
   315 		} else if (node->mode == Node_Term) {
   316 			char *term = &trie->stringtab[node->idx];
   317 			if (strcmp(keyptr, term) == 0)
   318 			{
   319 				break;
   320 			}
   321 		}
   322 		lastidx = curidx;
   323 	} while (*keyptr != '\0');
   324 
   325 	assert(node != NULL);
   326 
   327 	if (!node->valset)
   328 	{
   329 		return false;
   330 	}
   331 
   332 	node->valset = false;
   333 	node->value = NULL;
   334 
   335 	return true;
   336 }
   337 
   338 bool sm_trie_retrieve(Trie *trie, const char *key, void **value)
   339 {
   340 	unsigned int lastidx = 1;		/* the last node index */
   341 	unsigned int curidx;			/* current node index */
   342 	const char *keyptr = key;		/* input stream at current token */
   343 	TrieNode *node = NULL;			/* current node being processed */
   344 	TrieNode *base = trie->base;
   345 
   346 	if (!*key)
   347 	{
   348 		return false;
   349 	}
   350 
   351 	/* Start traversing at the root node */
   352 	do
   353 	{
   354 		/* Find where the next character is, then advance */
   355 		curidx = base[lastidx].idx;
   356 		node = &base[curidx];
   357 		curidx += charval(*keyptr);
   358 		node = &base[curidx];
   359 		keyptr++;
   360 
   361 		/* Check if this slot is supposed to be empty or is a collision */
   362 		if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
   363 		{
   364 			return false;
   365 		} else if (node->mode == Node_Term) {
   366 			char *term = &trie->stringtab[node->idx];
   367 			if (strcmp(keyptr, term) == 0)
   368 			{
   369 				break;
   370 			}
   371 		}
   372 		lastidx = curidx;
   373 	} while (*keyptr != '\0');
   374 
   375 	assert(node != NULL);
   376 
   377 	if (!node->valset)
   378 	{
   379 		return false;
   380 	}
   381 
   382 	if (value)
   383 	{
   384 		*value = node->value;
   385 	}
   386 
   387 	return true;
   388 }
   389 
   390 bool sm_trie_insert(Trie *trie, const char *key, void *value)
   391 {
   392 	unsigned int lastidx = 1;		/* the last node index */
   393 	unsigned int curidx;			/* current node index */
   394 	const char *keyptr = key;		/* input stream at current token */
   395 	TrieNode *node = NULL;			/* current node being processed */
   396 	TrieNode *basenode = NULL;		/* current base node being processed */
   397 	unsigned int q;					/* temporary var for x_check results */
   398 	TrieNode *base = trie->base;
   399 	unsigned int curoffs;			/* current offset */
   400 
   401 	/* Do not handle empty strings for simplicity */
   402 	if (!*key)
   403 	{
   404 		return false;
   405 	}
   406 
   407 	/* Start traversing at the root node (1) */
   408 	do
   409 	{
   410 		/* Find where the next character is, then advance */
   411 		curidx = base[lastidx].idx;
   412 		basenode = &base[curidx];
   413 		curoffs = charval(*keyptr);
   414 		curidx += curoffs;
   415 		node = &base[curidx];
   416 		keyptr++;
   417 
   418 		/* Check if this slot is supposed to be empty.  If so, we need to handle CASES 1/2:
   419 		 * Insertion without collisions
   420 		 */
   421 		if ( (curidx > trie->baseSize) || (node->mode == Node_Unused) )
   422 		{
   423 			if (curidx > trie->baseSize)
   424 			{
   425 				if (!sm_trie_grow(trie))
   426 				{
   427 					return false;
   428 				}
   429 				node = &trie->base[curidx];
   430 			}
   431 			node->parent = lastidx;
   432 			if (*keyptr == '\0')
   433 			{
   434 				node->mode = Node_Arc;
   435 			} else {
   436 				node->idx = x_addstring(trie, keyptr);
   437 				node->mode = Node_Term;
   438 			}
   439 			node->valset = true;
   440 			node->value = value;
   441 			
   442 			return true;
   443 		} else if (node->parent != lastidx) {
   444 			/* Collision! We have to split up the tree here.  CASE 4:
   445 			 * Insertion when a new word is inserted with a collision.
   446 			 * NOTE: This is the hardest case to handle.  All below examples are based on:
   447 			 * BACHELOR, BADGE, inserting BABY.
   448 			 * The problematic production here is A -> B, where B is already being used.
   449 			 *
   450 			 * This process has to rotate one half of the 'A' arc.  We generate two lists:
   451 			 *  Outgoing Arcs - Anything leaving this 'A'
   452 			 *  Incoming Arcs - Anything going to this 'A'
   453 			 * Whichever list is smaller will be moved.  Note that this works because the intersection
   454 			 * affects both arc chains, and moving one will make the slot available to either.
   455 			 */
   456 			TrieNode *cur;
   457 			
   458 			/* Find every node arcing from the last node.
   459 			 * I.e. for BACHELOR, BADGE, BABY,
   460 			 * The arcs leaving A will be C and D, but our current node is B -> *.
   461 			 * Thus, we use the last index (A) to find the base for arcs leaving A.
   462 			 */
   463 			unsigned int outgoing_base = base[lastidx].idx;
   464 			unsigned int outgoing_list[256];
   465 			unsigned int outgoing_count = 0;	/* count the current index here */
   466 			cur = &base[outgoing_base] + 1;
   467 			unsigned int outgoing_limit = 255;
   468 
   469 			if (outgoing_base + outgoing_limit > trie->baseSize)
   470 			{
   471 				outgoing_limit = trie->baseSize - outgoing_base;
   472 			}
   473 
   474 			for (unsigned int i=1; i<=outgoing_limit; i++,cur++)
   475 			{
   476 				if (cur->mode == Node_Unused || cur->parent != lastidx)
   477 				{
   478 					continue;
   479 				}
   480 				outgoing_list[outgoing_count++] = i;
   481 			}
   482 			outgoing_list[outgoing_count++] = curidx - outgoing_base;
   483 
   484 			/* Now we need to find all the arcs leaving our parent...
   485 			 * Note: the inconsistency is the base of our parent.  
   486 			 */
   487 			assert(base[node->parent].mode == Node_Arc);
   488 			unsigned int incoming_list[256];
   489 			unsigned int incoming_base = base[node->parent].idx;
   490 			unsigned int incoming_count = 0;
   491 			unsigned int incoming_limit = 255;
   492 			cur = &base[incoming_base] + 1;
   493 
   494 			if (incoming_base + incoming_limit > trie->baseSize)
   495 			{
   496 				incoming_limit = trie->baseSize - incoming_base;
   497 			}
   498 
   499 			assert(incoming_limit > 0 && incoming_limit <= 255);
   500 
   501 			for (unsigned int i=1; i<=255; i++,cur++)
   502 			{
   503 				if (cur->mode == Node_Arc || cur->mode == Node_Term)
   504 				{
   505 					if (cur->parent == node->parent)
   506 					{
   507 						incoming_list[incoming_count++] = i;
   508 					}
   509 				}
   510 			}
   511 
   512 			if (incoming_count < outgoing_count + 1)
   513 			{
   514 				unsigned int q = x_check_multi(trie, incoming_list, incoming_count);
   515 
   516 				base = trie->base;
   517 				node = &base[curidx];
   518 
   519 				/* If we're incoming, we need to modify our parent */
   520 				base[node->parent].idx = q;
   521 
   522 				/* For each node in the "to move" list,
   523 				 * Relocate the node's info to the new position.
   524 				 */
   525 				unsigned int idx, newidx, oldidx;
   526 				for (unsigned int i=0; i<incoming_count; i++)
   527 				{
   528 					idx = incoming_list[i];
   529 					newidx = q + idx;
   530 					oldidx = incoming_base + idx;
   531 					if (oldidx == lastidx)
   532 					{
   533 						/* Important! Make sure we're not invalidating our sacred lastidx */
   534 						lastidx = newidx;
   535 					}
   536 					base[newidx] = base[oldidx];
   537 					assert(base[base[newidx].parent].mode == Node_Arc);
   538 					memset(&base[oldidx], 0, sizeof(TrieNode));
   539 					/* If we are not a terminator, we have children we must take care of */
   540 					if (base[newidx].mode == Node_Arc)
   541 					{
   542 						TrieNode *check_base = &base[base[newidx].idx] + 1;
   543 						for (unsigned int j=1; j<=255; j++, check_base++)
   544 						{
   545 							if (check_base->parent == oldidx)
   546 							{
   547 								check_base->parent = newidx;
   548 							}
   549 						}
   550 					}
   551 				}
   552 			} else {
   553 				unsigned int q = x_check_multi(trie, outgoing_list, outgoing_count);
   554 
   555 				base = trie->base;
   556 				node = &base[curidx];
   557 
   558 				/* If we're outgoing, we need to modify our own base */
   559 				base[lastidx].idx = q;
   560 
   561 				/* Take the last index (curidx) out of the list.  Technically we are not moving this,
   562 				 * since it's already being used by something else.  
   563 				 */
   564 				outgoing_count--;
   565 
   566 				/* For each node in the "to move" list,
   567 				 * Relocate the node's info to the new position.
   568 				 */
   569 				unsigned int idx, newidx, oldidx;
   570 				for (unsigned int i=0; i<outgoing_count; i++)
   571 				{
   572 					idx = outgoing_list[i];
   573 					newidx = q + idx;
   574 					oldidx = outgoing_base + idx;
   575 					if (oldidx == lastidx)
   576 					{
   577 						/* Important! Make sure we're not invalidating our sacred lastidx */
   578 						lastidx = newidx;
   579 					}
   580 					base[newidx] = base[oldidx];
   581 					assert(base[base[newidx].parent].mode == Node_Arc);
   582 					memset(&base[oldidx], 0, sizeof(TrieNode));
   583 					/* If we are not a terminator, we have children we must take care of */
   584 					if (base[newidx].mode == Node_Arc)
   585 					{
   586 						TrieNode *check_base = &base[base[newidx].idx] + 1;
   587 						for (unsigned int j=1; j<=255; j++, check_base++)
   588 						{
   589 							if (check_base->parent == oldidx)
   590 							{
   591 								check_base->parent = newidx;
   592 							}
   593 						}
   594 					}
   595 				}
   596 
   597 				/* Take the invisible node and use it as our new node */
   598 				node = &base[q + outgoing_list[outgoing_count]];
   599 			}
   600 
   601 			/* We're finally done! */
   602 			node->parent = lastidx;
   603 			if (*keyptr == '\0')
   604 			{
   605 				node->mode = Node_Arc;
   606 			} else {
   607 				node->idx = x_addstring(trie, keyptr);
   608 				node->mode = Node_Term;
   609 			}
   610 			node->valset = true;
   611 			node->value = value;
   612 
   613 			return true;
   614 		} else {
   615 			/* See what's in the next node - special case if terminator! */
   616 			if (node->mode == Node_Term)
   617 			{
   618 				/* If we're a terminator, we need to handle CASE 3:
   619 				 * Insertion when a terminating collision occurs
   620 				 */
   621 				char *term = &trie->stringtab[node->idx];
   622 				/* Do an initial browsing to make sure they're not the same string */
   623 				if (strcmp(keyptr, term) == 0)
   624 				{
   625 					if (!node->valset)
   626 					{
   627 						node->valset = true;
   628 						node->value = value;
   629 						return true;
   630 					}
   631 					/* Same string.  We can't insert. */
   632 					return false;
   633 				}
   634 				/* For each matching character pair, we need to disband the terminator.
   635 				 * This splits the similar prefix into a single arc path.
   636 				 * First, save the old values so we can move them to a new node.
   637 				 * Next, for each loop:
   638 				 *  Take the current (invalid) node, and point it to the next arc base.
   639 				 *  Set the current node to the node at the next arc.
   640 				 */
   641 				void *oldvalue = node->value;
   642 				bool oldvalset = node->valset;
   643 				if (*term == *keyptr)
   644 				{
   645 				while (*term == *keyptr)
   646 				{
   647 					/* Find the next free slot in the check array.
   648 					 * This is the "vector base" essentially
   649 					 */
   650 					q = x_check(trie, *term);
   651 						base = trie->base;
   652 						node = &base[curidx];
   653 					/* Point the node to the next new base */
   654 					node->idx = q;
   655 					node->mode = Node_Arc;
   656 					node->valset = false;
   657 					/* Advance the input stream and local variables */
   658 					lastidx = curidx;
   659 					curidx = q + charval(*term);
   660 					node = &base[curidx];
   661 					/* Make sure the new current node has its parent set. */
   662 					node->parent = lastidx;
   663 					node->mode = Node_Arc;	/* Just in case we run x_check again */
   664 					*term = '\0';	/* Unmark the string table here */
   665 					term++;
   666 					keyptr++;
   667 					}
   668 				} else {
   669 					node->valset = false;
   670 				}
   671 				/* We're done inserting new pairs.  If one of them is exhausted,
   672 				 * we take special shortcuts.
   673 				 */
   674 				if (*term == '\0')				//EX: BADGERHOUSE added over B -> ADGER.  
   675 				{
   676 					/* First backpatch the current node - it ends the newly split terminator.
   677 					 * In the example, this would mean the node is the production from R -> ?
   678 					 * This node ends the old BADGER, so we set it here.
   679 					 */
   680 					node->valset = oldvalset;
   681 					node->value = oldvalue;
   682 
   683 					/* The terminator was split up, but pieces of keyptr remain.
   684 					 * We need to generate a new production, in this example, R -> H,
   685 					 * with H being a terminator to OUSE.  Thus we get:
   686 					 * B,A,D,G,E,R*,H*->OUSE (* = value set).
   687 					 * NOTE: parent was last set at the end of the while loop.
   688 					 */
   689 					/* Get the new base and apply re-basing */
   690 					q = x_check(trie, *keyptr);
   691 					base = trie->base;
   692 					node = &base[curidx];
   693 
   694 					node->idx = q;
   695 					node->mode = Node_Arc;
   696 					lastidx = curidx;
   697 					/* Finish the final node */
   698 					curidx = q + charval(*keyptr);
   699 					node = &trie->base[curidx];
   700 					keyptr++;
   701 					/* Optimize - don't add to string table if there's nothing more to eat */
   702 					if (*keyptr == '\0')
   703 					{
   704 						node->mode = Node_Arc;
   705 					} else {
   706 						node->idx = x_addstring(trie, keyptr);
   707 						node->mode = Node_Term;
   708 					}
   709 					node->parent = lastidx;
   710 					node->valset = true;
   711 					node->value = value;
   712 				} else if (*keyptr == '\0') {	//EX: BADGER added over B -> ADGERHOUSE
   713 					/* First backpatch the current node - it ends newly split input string.
   714 					 * This is the exact opposite of the above procedure.
   715 					 */
   716 					node->valset = true;
   717 					node->value = value;
   718 
   719 					/* Get the new base and apply re-basing */
   720 					q = x_check(trie, *term);
   721 					base = trie->base;
   722 					node = &base[curidx];
   723 
   724 					node->idx = q;
   725 					node->mode = Node_Arc;
   726 					lastidx = curidx;
   727 					/* Finish the final node */
   728 					curidx = q + charval(*term);
   729 					node = &trie->base[curidx];
   730 					term++;
   731 					/* Optimize - don't add to string table if there's nothing more to eat */
   732 					if (*term == '\0')
   733 					{
   734 						node->mode = Node_Arc;
   735 					} else {
   736 						node->idx = (term - trie->stringtab); /* Already in the string table! */
   737 						node->mode = Node_Term;
   738 					}
   739 					node->parent = lastidx;
   740 					node->valset = oldvalset;
   741 					node->value = oldvalue;
   742 				} else {
   743 					/* Finally, we have to create two new nodes instead of just one. */
   744 					node->mode = Node_Arc;
   745 					
   746 					/* Get the new base and apply re-basing */
   747 					q = x_check2(trie, *keyptr, *term);
   748 					base = trie->base;
   749 					node = &base[curidx];
   750 
   751 					node->idx = q;
   752 					lastidx = curidx;
   753 
   754 					/* Re-create the old terminated node */
   755 					curidx = q + charval(*term);
   756 					node = &trie->base[curidx];
   757 					term++;
   758 					node->valset = oldvalset;
   759 					node->value = oldvalue;
   760 					node->parent = lastidx;
   761 					if (*term == '\0')
   762 					{
   763 						node->mode = Node_Arc;
   764 					} else {
   765 						node->mode = Node_Term;
   766 						node->idx = (term - trie->stringtab); /* Already in the string table! */
   767 					}
   768 
   769 					/* Create the new keyed input node */
   770 					curidx = q + charval(*keyptr);
   771 					node = &trie->base[curidx];
   772 					keyptr++;
   773 					node->valset = true;
   774 					node->value = value;
   775 					node->parent = lastidx;
   776 					if (*keyptr == '\0')
   777 					{
   778 						node->mode = Node_Arc;
   779 					} else {
   780 						node->mode = Node_Term;
   781 						node->idx = x_addstring(trie, keyptr);
   782 					}
   783 				}
   784 
   785 				/* Phew! */
   786 				return true;
   787 			} else {
   788 				assert(node->mode == Node_Arc);
   789 			}
   790 		}
   791 		lastidx = curidx;
   792 	} while (*keyptr != '\0');
   793 
   794 	assert(node);
   795 
   796 	/* If we've exhausted the string and we have a valid reached node,
   797 	 * the production rule already existed.  Make sure it's valid to set first.
   798 	 */
   799 
   800 	/* We have to be an Arc.  If the last result was anything else, we would have returned a new 
   801 	 * production earlier.
   802 	 */
   803 	assert(node->mode == Node_Arc);
   804 
   805 	/* Furthermore, if this is the last arc label in an arc, we should have a value set. */
   806 	if (node->idx == 0)
   807 	{
   808 		assert(node->valset == true);
   809 	}
   810 
   811 	if (!node->valset)
   812 	{
   813 		/* Insert is only possible if we have no production */
   814 		node->valset = true;
   815 		node->value = value;
   816 		return true;
   817 	}
   818 
   819 	return false;
   820 }