/**
    \file ModifiedDijkstra.cpp
    Implementation of ModifiedDijkstra distance transform class which, given
    and input binary image, calculates the corresponding distance transform.

    \author George J. Grevera, Ph.D., ggrevera@sju.edu

    Copyright (C) 2002, George J. Grevera

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
    USA or from http://www.gnu.org/licenses/gpl.txt.

    This General Public License does not permit incorporating this
    code into proprietary programs.  (So a hypothetical company such
    as GH (Generally Hectic) should NOT incorporate this code into
    their proprietary programs.)
 */
/*
     no OUT OF BOUNDS checks!
*/
#include <stdlib.h>
#include "ModifiedDijkstra.h"

using namespace std;
//----------------------------------------------------------------------
void ModifiedDijkstra::init ( const unsigned char* const I, double*& d,
    SetElement*& se, set< const SetElement*, ltSetElement > &s )
{
    borderCheck(I);
    cleanUp();
    d = (double*)malloc( ySize*xSize*sizeof(double)   );
    assert( d!=NULL );

    this->p = (P*)malloc( ySize*xSize*sizeof(P) );
    assert( this->p!=NULL );

    se = (SetElement*)malloc( ySize*xSize*sizeof(SetElement) );
    assert(se!=NULL);
    int y;
    for (y=0; y<ySize; y++) {
        for (int x=0; x<xSize; x++) {
            const int i=sub(x,y);
            d[i] = DistanceTransform::FloatInfinity;
            this->p[i].x = this->p[i].y = -1;  //parent location
        }
    }

    //initialize immediate interior & exterior elements
    for (y=1; y<ySize-1; y++) {
        for (int x=1; x<xSize-1; x++) {
            const int c=sub(x,y);
            if (I[sub(x-1,y)] != I[c] || I[sub(x+1,y)] != I[c] ||
                I[sub(x,y-1)] != I[c] || I[sub(x,y+1)] != I[c]) {
                d[c] = 0;
                this->p[c].x = x;
                this->p[c].y = y;
                //s.insert( new SetElement(0.0, x, y) );
                //distance & location
                se[c].d = 0.0;    se[c].x = x;    se[c].y = y;
                s.insert( &se[c] );
            }
        }
    }
}
//----------------------------------------------------------------------
void ModifiedDijkstra::modifiedDijkstra ( const unsigned char* const I ) {
    double*      d;
    SetElement*  se;
    set< const SetElement*, ltSetElement >  s;

    init(I, d, se, s);

    set< const SetElement*, ltSetElement >::iterator  it;
    for (it=s.begin(); it!=s.end(); it=s.begin()) {
        const SetElement* const  v = *it;
        // cout << v->d << ", " << v->x << ", " << v->y << endl;
        //propagate distance to neighbors of v
        const int c = sub(v->x, v->y);

        #define _check(X,Y,D)                                               \
            if (v->X >=0 && v->X < xSize && v->Y >=0 && v->Y < xSize) {     \
                const int n=sub(v->X, v->Y);                                \
                if (d[c]+D < d[n]) {                                        \
                    /*SetElement* nse = new SetElement(d[n], v->X, v->Y);*/ \
                    se[n].d = d[n];    se[n].x = v->X;    se[n].y = v->Y;   \
                    SetElement* nse = &se[n];                               \
                    /* remove it (if it already exists with a higher */     \
                    /*  distance value) */                                  \
                    s.erase(nse);                                           \
                    d[n] = nse->d = d[c]+D;  /*new, better distance value*/ \
                    this->p[n].x = this->p[c].x;  /*new, better parent*/    \
                    this->p[n].y = this->p[c].y;                            \
                    s.insert(nse);                                          \
                }                                                           \
            }

        _check(x+1, y,   1.0);
        _check(x-1, y,   1.0);
        _check(x,   y+1, 1.0);
        _check(x,   y-1, 1.0);

        _check(x+1, y+1, M_SQRT2);
        _check(x+1, y-1, M_SQRT2);
        _check(x-1, y+1, M_SQRT2);
        _check(x-1, y-1, M_SQRT2);

        #undef _check

        s.erase(v);  //"pop" the first element
    }

    finish(I, d);
    free(se);    se=NULL;
}
//----------------------------------------------------------------------
void ModifiedDijkstra::modifiedDijkstra_DeadReckoning (
    const unsigned char* const I )
{
    double*      d;
    SetElement*  se;
    set< const SetElement*, ltSetElement >  s;

    init(I, d, se, s);

    set< const SetElement*, ltSetElement >::iterator  it;
    for (it=s.begin(); it!=s.end(); it=s.begin()) {
        const SetElement* const  v = *it;
        // cout << v->d << ", " << v->x << ", " << v->y << endl;
        //propagate distance to neighbors of v
        const int c = sub(v->x, v->y);

        #define _check(X,Y,D)                                               \
            if (v->X >=0 && v->X < xSize && v->Y >=0 && v->Y < xSize) {     \
                const int n=sub(v->X, v->Y);                                \
                if (d[c]+D < d[n]) {                                        \
		            /*SetElement* nse = new SetElement(d[n], v->X, v->Y);*/ \
                    se[n].d = d[n];    se[n].x = v->X;    se[n].y = v->Y;   \
                    SetElement* nse = &se[n];                               \
		            /* remove it (if it already exists with a higher */     \
		            /*  distance value) */                                  \
                    s.erase(nse);                                           \
		            d[n] = nse->d = d[c]+D;  /*new, better distance value*/ \
		            this->p[n].x = this->p[c].x;  /*new, better parent*/    \
                    this->p[n].y = this->p[c].y;                            \
                    d[n] = nse->d = sqrt(                                   \
                        (v->X - this->p[n].x)*(v->X - this->p[n].x) +       \
                        (v->Y - this->p[n].y)*(v->Y - this->p[n].y) );      \
		            s.insert(nse);                                          \
                }                                                           \
            }

        _check(x+1, y,   1.0);
        _check(x-1, y,   1.0);
        _check(x,   y+1, 1.0);
        _check(x,   y-1, 1.0);

        _check(x+1, y+1, M_SQRT2);
        _check(x+1, y-1, M_SQRT2);
        _check(x-1, y+1, M_SQRT2);
        _check(x-1, y-1, M_SQRT2);

        #undef _check

        s.erase(v);  //"pop" the first element
    }
    /*
    for (it=s.begin(); it!=s.end(); it++) {
        const SetElement* const  v = *it;
        cout << v->d << ", " << v->x << ", " << v->y << endl;
    }
    */

    finish(I, d);
    free(se);    se=NULL;
}
//----------------------------------------------------------------------
void ModifiedDijkstra::modifiedDijkstra_ModifiedDeadReckoning (
    const unsigned char* const I )
{
    double*      d;
    SetElement*  se;
    set< const SetElement*, ltSetElement >  s;

    init(I, d, se, s);

    //cout << "here" << endl;
    set< const SetElement*, ltSetElement >::iterator  it;
    for (it=s.begin(); it!=s.end(); it=s.begin()) {
        const SetElement* const  v = *it;
        //cout << v->d << ", " << v->x << ", " << v->y << endl;
        //propagate distance to neighbors of v
        const int c = sub(v->x, v->y);

        //checking the 4-connected neighbors is sufficient
        check( d, c, v->x+1, v->y,   se, s );
        check( d, c, v->x-1, v->y,   se, s );
        check( d, c, v->x,   v->y+1, se, s );
        check( d, c, v->x,   v->y-1, se, s );

        s.erase(v);  //"pop" the first element
    }

    finish(I, d);
    free(se);    se=NULL;
}
//----------------------------------------------------------------------
void ModifiedDijkstra::check ( double* d, const int center, const int X,
    const int Y, SetElement*  se, set< const SetElement*, ltSetElement >  &s )
{
    //bounds check
    if (X<0 || X>=xSize || Y<0 || Y>=ySize)    return;
    //calculate the distance from the neighbor to the parent's border point
    const double D = sqrt( (X - this->p[center].x)*(X - this->p[center].x) +
                           (Y - this->p[center].y)*(Y - this->p[center].y) );
    const int n=sub(X, Y);
    //better?
    if (D < d[n]) {
        //better
        se[n].d = d[n];    se[n].x = X;    se[n].y = Y;
        SetElement* nse = &se[n];
        //remove it (if it already exists with a higher distance value)
        s.erase(nse);
        d[n] = nse->d = D;                 //new, better distance value
        this->p[n].x = this->p[center].x;  //new, better parent
        this->p[n].y = this->p[center].y;
        s.insert(nse);
    } else if (D == d[n] && this->p[n].x != this->p[center].x &&
        this->p[n].y != this->p[center].y) {
        //the same
#if 0
        cout << "eq: " << D << "  parent: ("
             << this->p[n].x << "," << this->p[n].y
             << "), other possible parent: (" << this->p[center].x << ","
             << this->p[center].y << ")" << endl;
#endif
    }
}
//----------------------------------------------------------------------

