#include "mex.h"
#include "matrix.h"
#include <stdlib.h>
#include <float.h>
#include <math.h>
#define INDEX(j, i, n2) ((i)+(j)*(n2))
#define Idx2(j, i, ps2) ((j*(ps2)) + (i))
#define ABS(x) ((x) >= 0 ? (x) : -(x))
#define MAX(x, y) (((x)>(y)) ? (x):(y))
#define MIN(x, y) (((x)<(y)) ? (x):(y))

double lamda1;




void onlySearch(double *Img, int overlap, int bksize, double *Rs1, int ncol, int nrow, int m2, int n2) {
    double mse1, mse2, mse3, mse3temp;

    int i, j, b, a, c, f, adv;
    int ps2 = bksize * bksize;
    int idx_x, idx_y;
 
    
    
    // Step 1: Compute the distance between the input patch and texture patches
    adv = bksize - overlap;
    
    mse2 = 99999999999;
    mse3temp = 0;
    f=0;
     for (j=0; j<n2-bksize+1; j+=adv) {
        for (i=0; i<m2-bksize+1; i+=adv) {
       
            
            
           
            for (a=i; a<i+bksize; a++){
                for (b=j; b<j+bksize; b++){
                    Rs1[f] = Img[INDEX(a, b, m2)];
                    f++;
                }
            }
           nrow = i+bksize-1;
            ncol = j+bksize-1;
        }
    }
    
}
void mexFunction(
        int nargout, mxArray *pargout [ ],
        int nargin, const mxArray *pargin [ ]
        ) {
    double *Img, *Rs1;
    int i, n, n2, m2, k, patchSize, overlap, nrow, ncol;
   

    n = (int)mxGetM(pargin[0]);
    n2 = (int)mxGetN(pargin[0]);
    
//      mexPrintf("the n2 and m2 values are %d, %d and %d\n", n, n2, m2) ;
    Img = mxGetPr(pargin[0]);
    patchSize = (int)mxGetScalar(pargin[1]) ;
    overlap = (int)mxGetScalar(pargin[2]) ;
   
    //mexPrintf("the lamda1 and prvCheck values are %f, %d\n", (float)lamda1,prvCheck) ;
    
    /* create output B */
    m2 = ((n-(overlap-1)) / (patchSize-overlap)) * ((n2-(overlap-1)) / (patchSize-overlap));
    //mexPrintf("m2= %f\n", (float)m2 ) ;
    pargout[0] = mxCreateDoubleMatrix(m2*patchSize*patchSize, 1, mxREAL) ;
    Rs1 = mxGetPr(pargout[0]) ;
 
    onlySearch(Img, overlap, patchSize, Rs1, ncol, nrow, n, n2);
    
 
    
}