File: kdtree.cpp

package info (click to toggle)
tesseract 2.04-2%2Bsqueeze1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 7,336 kB
  • ctags: 6,860
  • sloc: cpp: 81,388; sh: 3,446; java: 1,220; makefile: 376
file content (884 lines) | stat: -rw-r--r-- 27,799 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
/******************************************************************************
 **	Filename:	kdtree.c
 **	Purpose:	Routines for managing K-D search trees
 **	Author:		Dan Johnson
 **	History:	3/10/89, DSJ, Created.
 **			5/23/89, DSJ, Added circular feature capability.
 **			7/13/89, DSJ, Made tree nodes invisible to outside.
 **
 **	(c) Copyright Hewlett-Packard Company, 1988.
 ** Licensed under the Apache License, Version 2.0 (the "License");
 ** you may not use this file except in compliance with the License.
 ** You may obtain a copy of the License at
 ** http://www.apache.org/licenses/LICENSE-2.0
 ** Unless required by applicable law or agreed to in writing, software
 ** distributed under the License is distributed on an "AS IS" BASIS,
 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 ******************************************************************************/

/**----------------------------------------------------------------------------
          Include Files and Type Defines
----------------------------------------------------------------------------**/
#include "kdtree.h"
#include "const.h"
#include "emalloc.h"
#include "freelist.h"
#include <stdio.h>
#include <math.h>
#include <setjmp.h>

#define Magnitude(X)    ((X) < 0 ? -(X) : (X))
#define MIN(A,B)    ((A) < (B) ? (A) : (B))
#define NodeFound(N,K,D)  (( (N)->Key == (K) ) && ( (N)->Data == (D) ))

/**----------------------------------------------------------------------------
        Global Data Definitions and Declarations
----------------------------------------------------------------------------**/
#define MINSEARCH -MAX_FLOAT32
#define MAXSEARCH MAX_FLOAT32

static int NumberOfNeighbors;
static inT16 N;                  /* number of dimensions in the kd tree */

static FLOAT32 *QueryPoint;
static int MaxNeighbors;
static FLOAT32 Radius;
static int Furthest;
static char **Neighbor;
static FLOAT32 *Distance;

static int MaxDimension = 0;
static FLOAT32 *SBMin;
static FLOAT32 *SBMax;
static FLOAT32 *LBMin;
static FLOAT32 *LBMax;

static PARAM_DESC *KeyDesc;

static jmp_buf QuickExit;

static void_proc WalkAction;

// Helper function to find the next essential dimension in a cycle.
static int NextLevel(int level) {
  do {
    ++level;
    if (level >= N)
      level = 0;
  } while (KeyDesc[level].NonEssential);
  return level;
}

// Helper function to find the previous essential dimension in a cycle.
static int PrevLevel(int level) {
  do {
    --level;
    if (level < 0)
      level = N - 1;
  } while (KeyDesc[level].NonEssential);
  return level;
}

/**----------------------------------------------------------------------------
              Public Code
----------------------------------------------------------------------------**/
/*---------------------------------------------------------------------------*/
KDTREE *
MakeKDTree (inT16 KeySize, PARAM_DESC KeyDesc[]) {
/*
 **	Parameters:
 **		KeySize		# of dimensions in the K-D tree
 **		KeyDesc		array of params to describe key dimensions
 **	Globals:
 **		MaxDimension	largest # of dimensions in any K-D tree
 **		SBMin		small search region box
 **		SBMax
 **		LBMin		large search region box
 **		LBMax
 **		Key		description of key dimensions
 **	Operation:
 **		This routine allocates and returns a new K-D tree data
 **		structure.  It also reallocates the small and large
 **		search region boxes if they are not large enough to
 **		accomodate the size of the new K-D tree.  KeyDesc is
 **		an array of key descriptors that indicate which dimensions
 **		are circular and, if they are circular, what the range is.
 **	Return:
 **		Pointer to new K-D tree
 **	Exceptions:
 **		None
 **	History:
 **		3/13/89, DSJ, Created.
 */
  int i;
  void *NewMemory;
  KDTREE *KDTree;

  if (KeySize > MaxDimension) {
    NewMemory = Emalloc (KeySize * 4 * sizeof (FLOAT32));
    if (MaxDimension > 0) {
      memfree ((char *) SBMin);
      memfree ((char *) SBMax);
      memfree ((char *) LBMin);
      memfree ((char *) LBMax);
    }
    SBMin = (FLOAT32 *) NewMemory;
    SBMax = SBMin + KeySize;
    LBMin = SBMax + KeySize;
    LBMax = LBMin + KeySize;
  }

  KDTree =
    (KDTREE *) Emalloc (sizeof (KDTREE) +
    (KeySize - 1) * sizeof (PARAM_DESC));
  for (i = 0; i < KeySize; i++) {
    KDTree->KeyDesc[i].NonEssential = KeyDesc[i].NonEssential;
    KDTree->KeyDesc[i].Circular = KeyDesc[i].Circular;
    if (KeyDesc[i].Circular) {
      KDTree->KeyDesc[i].Min = KeyDesc[i].Min;
      KDTree->KeyDesc[i].Max = KeyDesc[i].Max;
      KDTree->KeyDesc[i].Range = KeyDesc[i].Max - KeyDesc[i].Min;
      KDTree->KeyDesc[i].HalfRange = KDTree->KeyDesc[i].Range / 2;
      KDTree->KeyDesc[i].MidRange = (KeyDesc[i].Max + KeyDesc[i].Min) / 2;
    }
    else {
      KDTree->KeyDesc[i].Min = MINSEARCH;
      KDTree->KeyDesc[i].Max = MAXSEARCH;
    }
  }
  KDTree->KeySize = KeySize;
  KDTree->Root.Left = NULL;
  KDTree->Root.Right = NULL;
  return (KDTree);
}                                /* MakeKDTree */


/*---------------------------------------------------------------------------*/
void KDStore(KDTREE *Tree, FLOAT32 *Key, void *Data) {
/*
 **	Parameters:
 **		Tree		K-D tree in which data is to be stored
 **		Key		ptr to key by which data can be retrieved
 **		Data		ptr to data to be stored in the tree
 **	Globals:
 **		N		dimension of the K-D tree
 **		KeyDesc		descriptions of tree dimensions
 **		StoreCount	debug variables for performance tests
 **		StoreUniqueCount
 **		StoreProbeCount
 **	Operation:
 **		This routine stores Data in the K-D tree specified by Tree
 **		using Key as an access key.
 **	Return: none
 **	Exceptions: none
 **	History:	3/10/89, DSJ, Created.
 **			7/13/89, DSJ, Changed return to void.
 */
  int Level;
  KDNODE *Node;
  KDNODE **PtrToNode;

  N = Tree->KeySize;
  KeyDesc = &(Tree->KeyDesc[0]);
  PtrToNode = &(Tree->Root.Left);
  Node = *PtrToNode;
  Level = NextLevel(-1);
  while (Node != NULL) {
    if (Key[Level] < Node->BranchPoint) {
      PtrToNode = &(Node->Left);
      if (Key[Level] > Node->LeftBranch)
        Node->LeftBranch = Key[Level];
    }
    else {
      PtrToNode = &(Node->Right);
      if (Key[Level] < Node->RightBranch)
        Node->RightBranch = Key[Level];
    }
    Level = NextLevel(Level);
    Node = *PtrToNode;
  }

  *PtrToNode = MakeKDNode (Key, (char *) Data, Level);
}                                /* KDStore */


/*---------------------------------------------------------------------------*/
void
KDDelete (KDTREE * Tree, FLOAT32 Key[], void *Data) {
/*
 **	Parameters:
 **		Tree		K-D tree to delete node from
 **		Key		key of node to be deleted
 **		Data		data contents of node to be deleted
 **	Globals:
 **		N		dimension of the K-D tree
 **		KeyDesc		description of each dimension
 **		DeleteCount	debug variables for performance tests
 **		DeleteProbeCount
 **	Operation:
 **		This routine deletes a node from Tree.  The node to be
 **		deleted is specified by the Key for the node and the Data
 **		contents of the node.  These two pointers must be identical
 **		to the pointers that were used for the node when it was
 **		originally stored in the tree.  A node will be deleted from
 **		the tree only if its key and data pointers are identical
 **		to Key and Data respectively.  The empty space left in the tree
 **		is filled by pulling a leaf up from the bottom of one of
 **		the subtrees of the node being deleted.  The leaf node will
 **		be pulled from left subtrees whenever possible (this was
 **		an arbitrary decision).  No attempt is made to pull the leaf
 **		from the deepest subtree (to minimize length).  The branch
 **		point for the replacement node is changed to be the same as
 **		the branch point of the deleted node.  This keeps us from
 **		having to rearrange the tree every time we delete a node.
 **		Also, the LeftBranch and RightBranch numbers of the
 **		replacement node are set to be the same as the deleted node.
 **		The makes the delete easier and more efficient, but it may
 **		make searches in the tree less efficient after many nodes are
 **		deleted.  If the node specified by Key and Data does not
 **		exist in the tree, then nothing is done.
 **	Return: none
 **		None
 **	Exceptions: none
 **		None
 **	History:	3/13/89, DSJ, Created.
 **			7/13/89, DSJ, Specify node indirectly by key and data.
 */
  int Level;
  KDNODE *Current;
  KDNODE *Father;
  KDNODE *Replacement;
  KDNODE *FatherReplacement;

  /* initialize search at root of tree */
  N = Tree->KeySize;
  KeyDesc = &(Tree->KeyDesc[0]);
  Father = &(Tree->Root);
  Current = Father->Left;
  Level = NextLevel(-1);

  /* search tree for node to be deleted */
  while ((Current != NULL) && (!NodeFound (Current, Key, Data))) {
    Father = Current;
    if (Key[Level] < Current->BranchPoint)
      Current = Current->Left;
    else
      Current = Current->Right;

    Level = NextLevel(Level);
  }

  if (Current != NULL) {         /* if node to be deleted was found */
    Replacement = Current;
    FatherReplacement = Father;

    /* search for replacement node (a leaf under node to be deleted */
    while (TRUE) {
      if (Replacement->Left != NULL) {
        FatherReplacement = Replacement;
        Replacement = Replacement->Left;
      }
      else if (Replacement->Right != NULL) {
        FatherReplacement = Replacement;
        Replacement = Replacement->Right;
      }
      else
        break;

      Level = NextLevel(Level);
    }

    /* compute level of replacement node's father */
    Level = PrevLevel(Level);

    /* disconnect replacement node from it's father */
    if (FatherReplacement->Left == Replacement) {
      FatherReplacement->Left = NULL;
      FatherReplacement->LeftBranch = KeyDesc[Level].Min;
    }
    else {
      FatherReplacement->Right = NULL;
      FatherReplacement->RightBranch = KeyDesc[Level].Max;
    }

    /* replace deleted node with replacement (unless they are the same) */
    if (Replacement != Current) {
      Replacement->BranchPoint = Current->BranchPoint;
      Replacement->LeftBranch = Current->LeftBranch;
      Replacement->RightBranch = Current->RightBranch;
      Replacement->Left = Current->Left;
      Replacement->Right = Current->Right;

      if (Father->Left == Current)
        Father->Left = Replacement;
      else
        Father->Right = Replacement;
    }
    FreeKDNode(Current);
  }
}                                /* KDDelete */


/*---------------------------------------------------------------------------*/
int
KDNearestNeighborSearch (KDTREE * Tree,
FLOAT32 Query[],
int QuerySize,
FLOAT32 MaxDistance,
void *NBuffer, FLOAT32 DBuffer[]) {
/*
 **	Parameters:
 **		Tree		ptr to K-D tree to be searched
 **		Query		ptr to query key (point in D-space)
 **		QuerySize	number of nearest neighbors to be found
 **		MaxDistance	all neighbors must be within this distance
 **		NBuffer		ptr to QuerySize buffer to hold nearest neighbors
 **		DBuffer		ptr to QuerySize buffer to hold distances
 **					from nearest neighbor to query point
 **	Globals:
 **		NumberOfNeighbors	# of neighbors found so far
 **		N			# of features in each key
 **		KeyDesc			description of tree dimensions
 **		QueryPoint		point in D-space to find neighbors of
 **		MaxNeighbors		maximum # of neighbors to find
 **		Radius			current distance of furthest neighbor
 **		Furthest		index of furthest neighbor
 **		Neighbor		buffer of current neighbors
 **		Distance		buffer of neighbor distances
 **		SBMin			lower extent of small search region
 **		SBMax			upper extent of small search region
 **		LBMin			lower extent of large search region
 **		LBMax			upper extent of large search region
 **		QuickExit		quick exit from recursive search
 **	Operation:
 **		This routine searches the K-D tree specified by Tree and
 **		finds the QuerySize nearest neighbors of Query.  All neighbors
 **		must be within MaxDistance of Query.  The data contents of
 **		the nearest neighbors
 **		are placed in NBuffer and their distances from Query are
 **		placed in DBuffer.
 **	Return: Number of nearest neighbors actually found
 **	Exceptions: none
 **	History:
 **		3/10/89, DSJ, Created.
 **		7/13/89, DSJ, Return contents of node instead of node itself.
 */
  int i;

  NumberOfNeighbors = 0;
  N = Tree->KeySize;
  KeyDesc = &(Tree->KeyDesc[0]);
  QueryPoint = Query;
  MaxNeighbors = QuerySize;
  Radius = MaxDistance;
  Furthest = 0;
  Neighbor = (char **) NBuffer;
  Distance = DBuffer;

  for (i = 0; i < N; i++) {
    SBMin[i] = KeyDesc[i].Min;
    SBMax[i] = KeyDesc[i].Max;
    LBMin[i] = KeyDesc[i].Min;
    LBMax[i] = KeyDesc[i].Max;
  }

  if (Tree->Root.Left != NULL) {
    if (setjmp (QuickExit) == 0)
      Search (0, Tree->Root.Left);
  }
  return (NumberOfNeighbors);
}                                /* KDNearestNeighborSearch */


/*---------------------------------------------------------------------------*/
void KDWalk(KDTREE *Tree, void_proc Action) {
/*
 **	Parameters:
 **		Tree	ptr to K-D tree to be walked
 **		Action	ptr to function to be executed at each node
 **	Globals:
 **		WalkAction	action to be performed at every node
 **	Operation:
 **		This routine stores the desired action in a global
 **		variable and starts a recursive walk of Tree.  The walk
 **		is started at the root node.
 **	Return:
 **		None
 **	Exceptions:
 **		None
 **	History:
 **		3/13/89, DSJ, Created.
 */
  WalkAction = Action;
  if (Tree->Root.Left != NULL)
    Walk (Tree->Root.Left, NextLevel(-1));
}                                /* KDWalk */


/*---------------------------------------------------------------------------*/
void FreeKDTree(KDTREE *Tree) {
/*
 **	Parameters:
 **		Tree	tree data structure to be released
 **	Globals: none
 **	Operation:
 **		This routine frees all memory which is allocated to the
 **		specified KD-tree.  This includes the data structure for
 **		the kd-tree itself plus the data structures for each node
 **		in the tree.  It does not include the Key and Data items
 **		which are pointed to by the nodes.  This memory is left
 **		untouched.
 **	Return: none
 **	Exceptions: none
 **	History:
 **		5/26/89, DSJ, Created.
 */
  FreeSubTree (Tree->Root.Left);
  memfree(Tree);
}                                /* FreeKDTree */


/**----------------------------------------------------------------------------
              Private Code
----------------------------------------------------------------------------**/
/*---------------------------------------------------------------------------*/
int
Equal (FLOAT32 Key1[], FLOAT32 Key2[]) {
/*
 **	Parameters:
 **		Key1,Key2	search keys to be compared for equality
 **	Globals:
 **		N		number of parameters per key
 **	Operation:
 **		This routine returns TRUE if Key1 = Key2.
 **	Return:
 **		TRUE if Key1 = Key2, else FALSE.
 **	Exceptions:
 **		None
 **	History:
 **		3/11/89, DSJ, Created.
 */
  int i;

  for (i = N; i > 0; i--, Key1++, Key2++)
    if (*Key1 != *Key2)
      return (FALSE);
  return (TRUE);
}                                /* Equal */


/*---------------------------------------------------------------------------*/
KDNODE *
MakeKDNode (FLOAT32 Key[], char *Data, int Index) {
/*
 **	Parameters:
 **		Key	Access key for new node in KD tree
 **		Data	ptr to data to be stored in new node
 **		Index	index of Key to branch on
 **	Globals:
 **		KeyDesc	descriptions of key dimensions
 **	Operation:
 **		This routine allocates memory for a new K-D tree node
 **		and places the specified Key and Data into it.  The
 **		left and right subtree pointers for the node are
 **		initialized to empty subtrees.
 **	Return:
 **		pointer to new K-D tree node
 **	Exceptions:
 **		None
 **	History:
 **		3/11/89, DSJ, Created.
 */
  KDNODE *NewNode;

  NewNode = (KDNODE *) Emalloc (sizeof (KDNODE));

  NewNode->Key = Key;
  NewNode->Data = Data;
  NewNode->BranchPoint = Key[Index];
  NewNode->LeftBranch = KeyDesc[Index].Min;
  NewNode->RightBranch = KeyDesc[Index].Max;
  NewNode->Left = NULL;
  NewNode->Right = NULL;

  return (NewNode);
}                                /* MakeKDNode */


/*---------------------------------------------------------------------------*/
void FreeKDNode(KDNODE *Node) {
/*
 **	Parameters:
 **		Node	ptr to node data structure to be freed
 **	Globals:
 **		None
 **	Operation:
 **		This routine frees up the memory allocated to Node.
 **	Return:
 **		None
 **	Exceptions:
 **		None
 **	History:
 **		3/13/89, DSJ, Created.
 */
  memfree ((char *) Node);
}                                /* FreeKDNode */


/*---------------------------------------------------------------------------*/
void Search(int Level, KDNODE *SubTree) {
/*
 **	Parameters:
 **		Level		level in tree of sub-tree to be searched
 **		SubTree		sub-tree to be searched
 **	Globals:
 **		NumberOfNeighbors	# of neighbors found so far
 **		N			# of features in each key
 **		KeyDesc			description of key dimensions
 **		QueryPoint		point in D-space to find neighbors of
 **		MaxNeighbors		maximum # of neighbors to find
 **		Radius			current distance of furthest neighbor
 **		Furthest		index of furthest neighbor
 **		Neighbor		buffer of current neighbors
 **		Distance		buffer of neighbor distances
 **		SBMin			lower extent of small search region
 **		SBMax			upper extent of small search region
 **		LBMin			lower extent of large search region
 **		LBMax			upper extent of large search region
 **		QuickExit		quick exit from recursive search
 **	Operation:
 **		This routine searches SubTree for those entries which are
 **		possibly among the MaxNeighbors nearest neighbors of the
 **		QueryPoint and places their data in the Neighbor buffer and
 **		their distances from QueryPoint in the Distance buffer.
 **	Return: none
 **	Exceptions: none
 **	History:
 **		3/11/89, DSJ, Created.
 **		7/13/89, DSJ, Save node contents, not node, in neighbor buffer
 */
  FLOAT32 d;
  FLOAT32 OldSBoxEdge;
  FLOAT32 OldLBoxEdge;

  if (Level >= N)
    Level = 0;

  d = ComputeDistance (N, KeyDesc, QueryPoint, SubTree->Key);
  if (d < Radius) {
    if (NumberOfNeighbors < MaxNeighbors) {
      Neighbor[NumberOfNeighbors] = SubTree->Data;
      Distance[NumberOfNeighbors] = d;
      NumberOfNeighbors++;
      if (NumberOfNeighbors == MaxNeighbors)
        FindMaxDistance();
    }
    else {
      Neighbor[Furthest] = SubTree->Data;
      Distance[Furthest] = d;
      FindMaxDistance();
    }
  }
  if (QueryPoint[Level] < SubTree->BranchPoint) {
    OldSBoxEdge = SBMax[Level];
    SBMax[Level] = SubTree->LeftBranch;
    OldLBoxEdge = LBMax[Level];
    LBMax[Level] = SubTree->RightBranch;
    if (SubTree->Left != NULL)
      Search (NextLevel(Level), SubTree->Left);
    SBMax[Level] = OldSBoxEdge;
    LBMax[Level] = OldLBoxEdge;
    OldSBoxEdge = SBMin[Level];
    SBMin[Level] = SubTree->RightBranch;
    OldLBoxEdge = LBMin[Level];
    LBMin[Level] = SubTree->LeftBranch;
    if ((SubTree->Right != NULL) && QueryIntersectsSearch ())
      Search (NextLevel(Level), SubTree->Right);
    SBMin[Level] = OldSBoxEdge;
    LBMin[Level] = OldLBoxEdge;
  }
  else {
    OldSBoxEdge = SBMin[Level];
    SBMin[Level] = SubTree->RightBranch;
    OldLBoxEdge = LBMin[Level];
    LBMin[Level] = SubTree->LeftBranch;
    if (SubTree->Right != NULL)
      Search (NextLevel(Level), SubTree->Right);
    SBMin[Level] = OldSBoxEdge;
    LBMin[Level] = OldLBoxEdge;
    OldSBoxEdge = SBMax[Level];
    SBMax[Level] = SubTree->LeftBranch;
    OldLBoxEdge = LBMax[Level];
    LBMax[Level] = SubTree->RightBranch;
    if ((SubTree->Left != NULL) && QueryIntersectsSearch ())
      Search (NextLevel(Level), SubTree->Left);
    SBMax[Level] = OldSBoxEdge;
    LBMax[Level] = OldLBoxEdge;
  }
  if (QueryInSearch ())
    longjmp (QuickExit, 1);
}                                /* Search */


/*---------------------------------------------------------------------------*/
FLOAT32
ComputeDistance (register int N,
register PARAM_DESC Dim[],
register FLOAT32 p1[], register FLOAT32 p2[]) {
/*
 **	Parameters:
 **		N		number of dimensions in K-D space
 **		Dim		descriptions of each dimension
 **		p1,p2		two different points in K-D space
 **	Globals:
 **		None
 **	Operation:
 **		This routine computes the euclidian distance
 **		between p1 and p2 in K-D space (an N dimensional space).
 **	Return:
 **		Distance between p1 and p2.
 **	Exceptions:
 **		None
 **	History:
 **		3/11/89, DSJ, Created.
 */
  register FLOAT32 TotalDistance;
  register FLOAT32 DimensionDistance;
  FLOAT32 WrapDistance;

  TotalDistance = 0;
  for (; N > 0; N--, p1++, p2++, Dim++) {
    if (Dim->NonEssential)
      continue;

    DimensionDistance = *p1 - *p2;

    /* if this dimension is circular - check wraparound distance */
    if (Dim->Circular) {
      DimensionDistance = Magnitude (DimensionDistance);
      WrapDistance = Dim->Max - Dim->Min - DimensionDistance;
      DimensionDistance = MIN (DimensionDistance, WrapDistance);
    }

    TotalDistance += DimensionDistance * DimensionDistance;
  }
  return ((FLOAT32) sqrt ((FLOAT64) TotalDistance));
}                                /* ComputeDistance */


/*---------------------------------------------------------------------------*/
void FindMaxDistance() {
/*
 **	Parameters:
 **		None
 **	Globals:
 **		MaxNeighbors		maximum # of neighbors to find
 **		Radius			current distance of furthest neighbor
 **		Furthest		index of furthest neighbor
 **		Distance		buffer of neighbor distances
 **	Operation:
 **		This routine searches the Distance buffer for the maximum
 **		distance, places this distance in Radius, and places the
 **		index of this distance in Furthest.
 **	Return:
 **		None
 **	Exceptions:
 **		None
 **	History:
 **		3/11/89, DSJ, Created.
 */
  int i;

  Radius = Distance[Furthest];
  for (i = 0; i < MaxNeighbors; i++) {
    if (Distance[i] > Radius) {
      Radius = Distance[i];
      Furthest = i;
    }
  }
}                                /* FindMaxDistance */


/*---------------------------------------------------------------------------*/
int QueryIntersectsSearch() {
/*
 **	Parameters:
 **		None
 **	Globals:
 **		N			# of features in each key
 **		KeyDesc			descriptions of each dimension
 **		QueryPoint		point in D-space to find neighbors of
 **		Radius			current distance of furthest neighbor
 **		SBMin			lower extent of small search region
 **		SBMax			upper extent of small search region
 **	Operation:
 **		This routine returns TRUE if the query region intersects
 **		the current smallest search region.  The query region is
 **		the circle of radius Radius centered at QueryPoint.
 **		The smallest search region is the box (in N dimensions)
 **		whose edges in each dimension are specified by SBMin and SBMax.
 **		In the case of circular dimensions, we must also check the
 **		point which is one wrap-distance away from the query to
 **		see if it would intersect the search region.
 **	Return:
 **		TRUE if query region intersects search region, else FALSE
 **	Exceptions:
 **		None
 **	History:
 **		3/11/89, DSJ, Created.
 */
  register int i;
  register FLOAT32 *Query;
  register FLOAT32 *Lower;
  register FLOAT32 *Upper;
  register FLOAT64 TotalDistance;
  register FLOAT32 DimensionDistance;
  register FLOAT64 RadiusSquared;
  register PARAM_DESC *Dim;
  register FLOAT32 WrapDistance;

  RadiusSquared = Radius * Radius;
  Query = QueryPoint;
  Lower = SBMin;
  Upper = SBMax;
  TotalDistance = 0.0;
  Dim = KeyDesc;
  for (i = N; i > 0; i--, Dim++, Query++, Lower++, Upper++) {
    if (Dim->NonEssential)
      continue;

    if (*Query < *Lower)
      DimensionDistance = *Lower - *Query;
    else if (*Query > *Upper)
      DimensionDistance = *Query - *Upper;
    else
      DimensionDistance = 0;

    /* if this dimension is circular - check wraparound distance */
    if (Dim->Circular) {
      if (*Query < *Lower)
        WrapDistance = *Query + Dim->Max - Dim->Min - *Upper;
      else if (*Query > *Upper)
        WrapDistance = *Lower - (*Query - (Dim->Max - Dim->Min));
      else
        WrapDistance = MAX_FLOAT32;

      DimensionDistance = MIN (DimensionDistance, WrapDistance);
    }

    TotalDistance += DimensionDistance * DimensionDistance;
    if (TotalDistance >= RadiusSquared)
      return (FALSE);
  }
  return (TRUE);
}                                /* QueryIntersectsSearch */


/*---------------------------------------------------------------------------*/
int QueryInSearch() {
/*
 **	Parameters:
 **		None
 **	Globals:
 **		N			# of features in each key
 **		KeyDesc			descriptions of each dimension
 **		QueryPoint		point in D-space to find neighbors of
 **		Radius			current distance of furthest neighbor
 **		LBMin			lower extent of large search region
 **		LBMax			upper extent of large search region
 **	Operation:
 **		This routine returns TRUE if the current query region is
 **		totally contained in the current largest search region.
 **		The query region is the circle of
 **		radius Radius centered at QueryPoint.  The search region is
 **		the box (in N dimensions) whose edges in each
 **		dimension are specified by LBMin and LBMax.
 **	Return:
 **		TRUE if query region is inside search region, else FALSE
 **	Exceptions:
 **		None
 **	History:
 **		3/11/89, DSJ, Created.
 */
  register int i;
  register FLOAT32 *Query;
  register FLOAT32 *Lower;
  register FLOAT32 *Upper;
  register PARAM_DESC *Dim;

  Query = QueryPoint;
  Lower = LBMin;
  Upper = LBMax;
  Dim = KeyDesc;

  for (i = N - 1; i >= 0; i--, Dim++, Query++, Lower++, Upper++) {
    if (Dim->NonEssential)
      continue;

    if ((*Query < *Lower + Radius) || (*Query > *Upper - Radius))
      return (FALSE);
  }
  return (TRUE);
}                                /* QueryInSearch */


/*---------------------------------------------------------------------------*/
void Walk(KDNODE *SubTree, inT32 Level) {
/*
 **	Parameters:
 **		SubTree		ptr to root of subtree to be walked
 **		Level		current level in the tree for this node
 **	Globals:
 **		WalkAction	action to be performed at every node
 **	Operation:
 **		This routine walks thru the specified SubTree and invokes
 **		WalkAction at each node.  WalkAction is invoked with three
 **		arguments as follows:
 **			WalkAction( NodeData, Order, Level )
 **		Data is the data contents of the node being visited,
 **		Order is either preorder,
 **		postorder, endorder, or leaf depending on whether this is
 **		the 1st, 2nd, or 3rd time a node has been visited, or
 **		whether the node is a leaf.  Level is the level of the node in
 **		the tree with the root being level 0.
 **	Return: none
 **	Exceptions: none
 **	History:
 **		3/13/89, DSJ, Created.
 **		7/13/89, DSJ, Pass node contents, not node, to WalkAction().
 */
  if ((SubTree->Left == NULL) && (SubTree->Right == NULL))
    (*WalkAction) (SubTree->Data, leaf, Level);
  else {
    (*WalkAction) (SubTree->Data, preorder, Level);
    if (SubTree->Left != NULL)
      Walk (SubTree->Left, NextLevel(Level));
    (*WalkAction) (SubTree->Data, postorder, Level);
    if (SubTree->Right != NULL)
      Walk (SubTree->Right, NextLevel(Level));
    (*WalkAction) (SubTree->Data, endorder, Level);
  }
}                                /* Walk */


/*---------------------------------------------------------------------------*/
void FreeSubTree(KDNODE *SubTree) {
/*
 **	Parameters:
 **		SubTree		ptr to root node of sub-tree to be freed
 **	Globals: none
 **	Operation:
 **		This routine recursively frees the memory allocated to
 **		to the specified subtree.
 **	Return: none
 **	Exceptions: none
 **	History: 7/13/89, DSJ, Created.
 */
  if (SubTree != NULL) {
    FreeSubTree (SubTree->Left);
    FreeSubTree (SubTree->Right);
    memfree(SubTree);
  }
}                                /* FreeSubTree */