/* 
* 
* Copyright (C) 2013 UMPC
* 
* This file is part of CLaRiNet.
*  
* CLaRiNet 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, either version 3 of the License, or
* (at your option) any later version.
* 
* CLaRiNet 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 CLaRiNet.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stddef.h>
#include "esriheader.h"
#include "Erreur.h"
#include <math.h>
#include <cstring>

#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

void xy2RC ( esriheader * Header , double x , double y , int * nr, int * nc )
{
        double xll,yll,cellsize;

        xll = Header->xll - 0.5*(double)(1-(Header->LL)) ;
        yll = Header->yll - 0.5*(double)(1-(Header->LL)) ;
        cellsize = Header->cellsize ;

	(*nc)=(int)(floor((x-xll)/cellsize+0.5));
	(*nr)=(int)(floor((y-yll)/cellsize+0.5));
	(*nr)=(Header->nrows)-1-(*nr);

	if((*nr)<0 || (*nr)>=(Header->nrows) || (*nc)<0 || (*nc)>=(Header->ncols) )
        {
            (*nr) = -1;
            (*nc) = -1;
        }
}

void xy2rec ( esriheader * Header , double x , double y , int * irec )
{
        double xll,yll,cellsize;
        int nc,nr;

        xll = Header->xll - 0.5*(double)(1-(Header->LL)) ;
        yll = Header->yll - 0.5*(double)(1-(Header->LL)) ;
        cellsize = Header->cellsize ;

	nc=(int)(floor((x-xll)/cellsize+0.5));
	nr=(int)(floor((y-yll)/cellsize+0.5));
	nr=(Header->nrows)-1-nr;
        
	if(nr>=0 && nr<(Header->nrows) && nc >=0 && nc<(Header->ncols) )
		(*irec)=nc+nr*(Header->ncols);
	else
		(*irec)=-1;
}

void c2rec ( esriheader * Header , complex<double> & Z , int * _irec )
{
	double x,y;

        x=Z.real();
	y=Z.imag();

        (void)  xy2rec ( Header , x , y , _irec );
}

void RC2xy ( esriheader * Header , int nr , int nc , double * x , double * y )
{

}

void rec2xy ( esriheader * Header , int irec , double * x , double * y )
{

}

void rec2c ( esriheader * Header , int irec , complex<double> & Z )
{

}

void rec2RC ( esriheader * Header , int * irec , int * nr, int * nc )
{
    *nc = (*irec)%(Header->ncols);
    *nr = ((*irec) - (*nc))/(Header->ncols);
}

int ReadHeaderFromFile (    char hdrfile[200] ,
                            int * _ncols ,
                            int * _nrows ,
                            double * _xll ,
                            double * _yll ,
                            double * _cellsize ,
                            float * _NODATA_value ,
                            int * _LL ,
                            char * _LSBFIRST
                        )
{
    string str_tmp,BYTEORDER;
    bool missing_ncols, missing_nrows, missing_cellsize, missing_xll, missing_yll, missing_NODATA_value , missing_BYTEORDER;

    ifstream hdr (hdrfile, ios::in);

    if (!hdr)
    {
        SetErreur("ReadHeaderFromFile : could not open header file\n");
        return(-1);
    }

    // Initialisation des bascules

    missing_ncols = true;
    missing_nrows = true;
    missing_cellsize = true;
    missing_xll = true;
    missing_yll = true;
    missing_NODATA_value = true;
    missing_BYTEORDER = true;

    // Parcours du fichier

    while ( hdr >> str_tmp )
    {

        std::transform(str_tmp.begin(), str_tmp.end(),str_tmp.begin(), ::tolower);

        if ( strcmp(str_tmp.c_str(),"ncols") == 0)
        {
                if ( ! (hdr >> (*_ncols) ) )
                {
                    SetErreur("ReadHeaderFromFile (%s) : could not read \"ncols\" value\n",hdrfile);
                    return(-1);
                }
                else
                    missing_ncols = false;
        }

        if ( strcmp(str_tmp.c_str(),"nrows") == 0 )
        {
                if ( ! (hdr >> (*_nrows) ) )
                {
                    SetErreur("ReadHeaderFromFile (%s) : could not read \"nrows\" value\n",hdrfile);
                    return(-1);
                }
                else
                    missing_nrows = false;
        }

        if ( strcmp(str_tmp.c_str(),"xllcorner") == 0 )
        {
            (*_LL) = 0;

                if ( ! (hdr >> (*_xll) ) )
                {
                    SetErreur("ReadHeaderFromFile (%s) : could not read \"xllcorner\" value\n",hdrfile);
                    return(-1);
                }
                else

                    missing_xll = false;
        }

        if ( strcmp(str_tmp.c_str(),"xllcenter") == 0 )
        {
             (*_LL) = 1;
            
                if ( ! (hdr >> (*_xll) ) )
                {
                    SetErreur("ReadHeaderFromFile (%s) : could not read \"xllcenter\" value\n",hdrfile);
                    return(-1);
                }
                else

                    missing_xll = false;
        }

        if ( strcmp(str_tmp.c_str(),"yllcorner") == 0 )
        {
                if ( ! (hdr >> (*_yll) ) )
                {
                    SetErreur("ReadHeaderFromFile (%s) : could not read \"yllcorner\" value\n",hdrfile);
                    return(-1);
                }
                else
                    missing_yll = false;
        }

        if ( strcmp(str_tmp.c_str(),"yllcenter") == 0 )
        {
                if ( ! (hdr >> (*_yll) ) )
                {
                    SetErreur("ReadHeaderFromFile (%s) : could not read \"yllcenter\" value\n",hdrfile);
                    return(-1);
                }
                else
                    missing_yll = false;
        }

        if ( strcmp(str_tmp.c_str(),"cellsize") == 0 )
        {
                if ( ! (hdr >> (*_cellsize) ) )
                {
                    SetErreur("ReadHeaderFromFile (%s) : could not read \"cellsize\" value\n",hdrfile);
                    return(-1);
                }
                else
                    missing_cellsize = false;
        }

        if ( strcmp(str_tmp.c_str(),"nodata_value") == 0)
        {
                if ( ! (hdr >> (*_NODATA_value) ) )
                {
                    SetErreur("ReadHeaderFromFile (%s) : could not read \"NODATA_value\" value\n",hdrfile);
                    return(-1);
                }
                else
                    missing_NODATA_value = false;
        }

        if ( strcmp(str_tmp.c_str(),"byteorder") == 0 )
        {
                if ( ! (hdr >> BYTEORDER ) )
                {
                    SetErreur("ReadHeaderFromFile (%s) : could not read \"BYTEORDER\" value\n",hdrfile);
                    return(-1);
                }
                else
                    missing_BYTEORDER = false;
        }

    }

    hdr.close () ;

    // Vérification que tous les champs requis ont été lus

    if ( missing_ncols )
    {
        SetErreur("ReadHeaderFromFile (%s) : \"ncols\" field missing\n",hdrfile);
        return(-1);
    }

    if ( missing_nrows )
    {
        SetErreur("ReadHeaderFromFile (%s) : \"nrows\" field missing\n",hdrfile);
        return(-1);
    }

    if ( missing_cellsize )
    {
        SetErreur("ReadHeaderFromFile (%s) : \"cellsize\" field missing\n",hdrfile);
        return(-1);
    }

    if ( missing_xll )
    {
        SetErreur("ReadHeaderFromFile (%s) : \"xllcorner\" ou \"xllcenter\" field missing\n",hdrfile);
        return(-1);
    }

    if ( missing_yll )
    {
        SetErreur("ReadHeaderFromFile (%s) : \"yllcorner\" ou \"yllcenter\" field missing\n",hdrfile);
        return(-1);
    }

    if ( missing_NODATA_value )
    {
        SetErreur("ReadHeaderFromFile (%s) : \"NODATA_value\" field missing\n",hdrfile);
        return(-1);
    }

    if ( missing_BYTEORDER )
    {
        SetErreur("ReadHeaderFromFile (%s) : \"BYTEORDER\" field missing\n",hdrfile);
        return(-1);
    }

    std::transform(BYTEORDER.begin(), BYTEORDER.end(),BYTEORDER.begin(), ::toupper);

    if ( strcmp(BYTEORDER.c_str(),"LSBFIRST") == 0 )
        (*_LSBFIRST) = 1;
    else
    {
        if ( strcmp(BYTEORDER.c_str(),"MSBFIRST") == 0 )
            (*_LSBFIRST) = 0;
        else
        {
            SetErreur("ReadHeaderFromFile : invalid BYTEORDER value (must be: LSBFIRST or MSBFIRST)\n");
            return(-1);
        }
    }

    return(0);
}


void GetNeighborhood ( esriheader * Header , int * _nr , int * _nc ,
                                    int * _Drmin ,
                                    int * _Drmax ,
                                    int * _Dcmin ,
                                    int * _Dcmax )
{
    if( (*_nr) == 0 )
        *_Drmin = 0;
    else
        *_Drmin = -1;

    if( (*_nr) == (Header->nrows) -1 )
        *_Drmax = 0;
    else
        *_Drmax = 1;

    if( (*_nc) == 0 )
        *_Dcmin = 0;
    else
        *_Dcmin = -1;

    if( (*_nc) == (Header->ncols) -1 )
        *_Dcmax = 0;
    else
        *_Dcmax=1;
}

int CheckSameHeader( esriheader * Header1 , esriheader * Header2 )
{
    int ncols,nrows;
    double D,cellsize,cellsize1,cellsize2,crit,xll1,yll1,xll2,yll2;

    if ( Header1->ncols != Header2->ncols )
    {
        SetErreur("CheckSameHeader : column dimension does not match\n");
        return(-1);
    }

    if ( Header1->nrows != Header2->nrows )
    {
        SetErreur("CheckSameHeader : row dimension does not match\n");
        return(-1);
    }

    cellsize1 = Header1->cellsize;
    cellsize2 = Header2->cellsize;
    cellsize = 0.5*(cellsize1+cellsize2);

    ncols = Header1->ncols;
    nrows = Header1->nrows;

    D = (double)(ncols*ncols+nrows*nrows);

    crit = sqrt(D)*abs(cellsize1-cellsize2)/cellsize;  /* Rapport ecart diagonales / taille de cellule */

    if ( crit > 0.01 )
    {
        SetErreur("CheckSameHeader : cell size does not match\n");
        return(-1);
    }

    xll1 = Header1->xll;
    yll1 = Header1->yll;
    xll2 = Header2->xll;
    yll2 = Header2->yll;

    crit = abs(xll1 - xll2)/cellsize;

    if ( crit > 0.01 )
    {
        SetErreur("CheckSameHeader : xll reference does not match\n");
        return(-1);
    }

    crit = abs(yll1 - yll2)/cellsize;

    if ( crit > 0.01 )
    {
        SetErreur("CheckSameHeader : yll reference does not match\n");
        return(-1);
    }

    return(0);

}

void d2rec ( esriheader * Header , int * irec1 ,int * irec2 , int * _d2)
{
    int nr1,nr2,nc1,nc2;

    nc1 = (*irec1)%(Header->ncols);
    nr1 = ((*irec1) - (nc1))/(Header->ncols);

    nc2 = (*irec2)%(Header->ncols);
    nr2 = ((*irec2) - (nc2))/(Header->ncols);

    (*_d2) = (nc1-nc2)*(nc1-nc2) + (nr1-nr2)*(nr1-nr2);

}
