/**
   @file SearchTree.h
   @author Morgan McGuire, morgan@cs.williams.edu
 */
#ifndef SEARCHTREE_H
#define SEARCHTREE_H

#include <G3D/G3DAll.h>
#include <GLG3D/GLG3D.h>
#include <ANN/ANN.h>

typedef Array<ANNcoord> FeatureVector;

/**
   Associates pixel locations with large feature vectors and then
   efficiently finds the pixel that is a best match for a feature
   vector.

   Wrapper for ANNkd_tree.  See ANN manual, page 6.  Provides log-time
   approximate nearest neighbor for high-dimensional spaces.
*/
class SearchTree {
private:
    class ANNkd_tree* tree;

    /** Each element is a pointer to a feature vector. */
    Array<ANNpoint>             pointArray; 

    /** Coordinates from which the feature vector came. */
    Array<Vector2int16>         sourceArray;

    int numDimensions;

    bool balanced;

public:

    SearchTree();

    /** Describe the features of a given pixel location in an unbalanced tree.*/
    void addPoint(const Vector2int16& v, const FeatureVector& features);

    /**
       Returns the pixel position associated with the given feature vector.  Assumes that the tree is balanced.
       @param norm2 Returns the distance squared between the desired and actual features.
     */
    Vector2int16 findNearestNeighbor(const FeatureVector& features, float& norm2) const;

    /** Call after all points are added */
    void balance();

    ~SearchTree();
};

#endif
