/**
* @file EMDDistanceSingle.cpp
* @brief Earth Movers Distance
* @author Erik Rodner
* @date 10/24/2007

*/

#include <iostream>

#include "vislearning/math/distances/emd.h"
#include "vislearning/math/distances/EMDDistanceSingle.h"

using namespace OBJREC;

using namespace std;
// refactor-nice.pl: check this substitution
// old: using namespace ice;
using namespace NICE;

float simple_distance(double **x, double **y)
{
    double *xx = *x;
    double *yy = *y;
   

    return fabs(xx[0]-yy[0]);
}


EMDDistanceSingle::EMDDistanceSingle()
{
}

EMDDistanceSingle::~EMDDistanceSingle()
{
}

// refactor-nice.pl: check this substitution
// old: double EMDDistanceSingle::calculate (const Vector & x, const Vector & y) const
double EMDDistanceSingle::doCalculate(const NICE::Vector & x, const NICE::Vector & y) const
{
    signature_t x_signature;
    signature_t y_signature;

    if (x.size() != y.size())
    {
        fprintf(stderr, "EMDDistanceSingle::distance: wrong dimensions: x.size()=%d, y.size()=%d\n",
                x.size(), y.size());
        exit(-1);
    }

    x_signature.n = x.size();
    y_signature.n = y.size();

    x_signature.Features = new double * [ x_signature.n ];
    x_signature.Weights  = new float    [ x_signature.n ];
    y_signature.Features = new double * [ y_signature.n ];
    y_signature.Weights  = new float    [ y_signature.n ];


    double *dataX = const_cast<double *>(x.getDataPointer());
    double *dataY = const_cast<double *>(y.getDataPointer());

    for (int i = 0; i < x_signature.n ; i++)
    {
        x_signature.Features[i] = dataX + i;
        x_signature.Weights[i]  = 1.0;
    }

    for (int i = 0; i < y_signature.n ; i++)
    {
        y_signature.Features[i] = dataY + i;
        y_signature.Weights[i]  = 1.0;
    }

    double result = emd(&x_signature, &y_signature,
                        simple_distance, 0, 0);

    delete [] x_signature.Features;
    delete [] y_signature.Features;
    delete [] x_signature.Weights;
    delete [] y_signature.Weights;

    return result;
}
