#include <QtCore/QCoreApplication>

/*
 * TemplateMatching 1.0
 *
 * @author 	  Nashruddin Amin <me@nashruddin.com>
 * @version   1.0
 * @website	  http://www.nashruddin.com
 */

#include <stdio.h>
#include <cv.h>
#include <highgui.h>


#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>
#include <ctime>
#include <sys/time.h>
#include <time.h>
#include <QStringList>
#include <QString>

#include <QTime>



using namespace std;

CvPoint find( IplImage	*img, IplImage	*tpl)
{
        if( tpl == 0 || img == 0 ) {
                fprintf( stderr, "Nejsou nacteny vstupni obrazy %s!\n");
        }


        IplImage	*res;
        CvPoint		minloc, maxloc;
        double		minval, maxval;
        int			img_width, img_height;
        int			tpl_width, tpl_height;
        int			res_width, res_height;

        img_width  = img->width;
        img_height = img->height;
        tpl_width  = tpl->width;
        tpl_height = tpl->height;
        res_width  = img_width - tpl_width + 1;
        res_height = img_height - tpl_height + 1;

        res = cvCreateImage( cvSize( res_width, res_height ), IPL_DEPTH_32F, 1 );

        /* choose template matching method to be used */
        cvMatchTemplate( img, tpl, res, CV_TM_SQDIFF );
        //cvMatchTemplate( img, tpl, res, CV_TM_SQDIFF_NORMED );
        //cvMatchTemplate( img, tpl, res, CV_TM_CCORR );
        //cvMatchTemplate( img, tpl, res, CV_TM_CCORR_NORMED );
        //cvMatchTemplate( img, tpl, res, CV_TM_CCOEFF );
        //cvMatchTemplate( img, tpl, res, CV_TM_CCOEFF_NORMED );

        cvMinMaxLoc( res, &minval, &maxval, &minloc, &maxloc, 0 );


        cvRectangle( img,
                                 cvPoint( minloc.x, minloc.y ),
                                 cvPoint( minloc.x + tpl_width, minloc.y + tpl_height ),
                                 cvScalar( 0, 0, 255, 0 ), 1, 0, 0 );


        //cvNamedWindow( "reference", CV_WINDOW_AUTOSIZE );
       // cvNamedWindow( "template", CV_WINDOW_AUTOSIZE );
       // cvShowImage( "reference", img );
        //cvShowImage( "template", tpl );


        //cvWaitKey( 0 );

        cvReleaseImage( &res );
        minloc.x=minloc.x+tpl_width/2;
        minloc.y=minloc.y+tpl_height/2;
        return minloc;
}


int getdir (string dir, vector<string> &files)
{
    DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(dir.c_str())) == NULL) {
        cout << "Error(" << errno << ") opening " << dir << endl;
        return errno;
    }

    while ((dirp = readdir(dp)) != NULL) {
        files.push_back(string(dirp->d_name));
    }
    closedir(dp);
    return 0;
}


void  Parse_Headr(string vstup,int *x,int *y){
//    QStringList split=foldr.split("/");
//    line=line.replace(QRegExp("\\..*$"),"");
    QString line = QString::fromUtf8(vstup.c_str());
    QStringList cisla;
    QString zk;

    int stav_hledani=0;
    for(int i=0;i<line.length();i++){
        if(line.at(i)=='-' || (line.at(i)>='0' && line.at(i)<='9') ){
            if(stav_hledani==0){
                cisla.append("");
                zk="";
            }
            cisla.last()+=line.at(i);
            zk+=line.at(i);
            //cislo=cislo+line.at(i);
            stav_hledani=1;
        }else{
            stav_hledani=0;
        }
    }

    if(cisla.length()!=3){
        //QMessageBox::critical(this, tr("QMessageBox::critical()"),"Chyba parseru, koncim");
        std::cout<<"Chyba parseru, koncim\n"<<std::endl;
    }

    zk=cisla.at(0);
    *x=zk.toInt();
    zk=cisla.at(1);
    *y=zk.toInt();

    return ;
}

int main( int argc, char** argv ){

        /* check for arguments */
       /* if( argc < 3 ) {
                fprintf( stderr, "Usage: template_match <reference> <template>\n" );
                return 1;
        }*/



        IplImage	*img;
        IplImage	*pom;
        IplImage	*tpl;

        img = cvLoadImage( "1.png", CV_LOAD_IMAGE_COLOR );
        pom = cvLoadImage( "1.png", CV_LOAD_IMAGE_COLOR );
        /*tpl = cvLoadImage( argv[2], CV_LOAD_IMAGE_COLOR );

//*/
        if(img==0){
                cout<<"nebyl nacten snimke , koncim";
        return 0;
                }

        QTime time;

        CvPoint point;

    string dir = string("obrazy/");
    vector<string> files = vector<string>();

    getdir(dir,files);

char buf[300];
double dif;

cout<<"snimek ma rozmery"<<pom->width<<"x"<<pom->height<<"\n";
int pozice_x,pozice_y;


    for (unsigned int i = 0;i < files.size();i++) {
                if(files[i]=="."||files[i]=="..")
                        continue;

                files[i]=dir+files[i];

                tpl = cvLoadImage( (char *)files[i].c_str() , CV_LOAD_IMAGE_COLOR );
                cvCopy(img,pom,NULL);
                if(tpl==0){
                        cout<<"nebyl nacta sablona, koncim \n";
                        return 0;
                }
                        time.start();
                point=find(pom,tpl);

                int p1=(pom->width/2)-point.x;
                int p2=(pom->height/2)-point.y;

                Parse_Headr(files.at(i),&pozice_x,&pozice_y);
                cout<<"*"<<time.elapsed()<<"*"<<p1<<"*"<<p2<<"*"<<pozice_x+p1<<"*"<<pozice_y+p2<<"*"<<std::endl;
               // cout<<"pozice\t"<<point.x<<"\t"<<point.y<<"\n\n";


                cvReleaseImage( &tpl );



    }



        cvDestroyWindow( "reference" );
        cvDestroyWindow( "template" );
        cvReleaseImage( &img );
return 0;
        }
