#include "mex.h"
#include "threshold.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	//Fetch the variable T
	double T = mxGetScalar(prhs[1]);

	//Fetch the dimensions of img
	const int *pSize;
	pSize = mxGetDimensions(prhs[0]);
	const int IMG_H = pSize[0];
	const int IMG_W = pSize[1];

	//Allocate space to the input image
	double **img;
	img = new double*[IMG_H];
	for (int i = 0; i < IMG_H;	i++)
	{
		img[i] = new double[IMG_W];
	}

	//Fetch the input image
	double *pData; /* pointer to input image */
	pData = mxGetPr(prhs[0]);

	for (int j = 0; j < IMG_W; j++)
	{
		for (int i = 0; i < IMG_H; i++)
		{
			img[i][j] = pData[i + j*IMG_H];
			//mexPrintf("I(%d,%d) = %f\n", i, j, img[i][j]);
		}
	}

	//Allocate space to the output image
	double **imgBinary;
	imgBinary = new double*[IMG_H];
	for (int i = 0; i < IMG_H;	i++)
	{
		imgBinary[i] = new double[IMG_W];
	}

	//Apply thresholding to the input image
	threshold(imgBinary, img, T, IMG_H, IMG_W);

	//Output thresholded image
	plhs[0] = mxCreateDoubleMatrix(IMG_H, IMG_W, mxREAL);
	double *outputMatrix = mxGetPr(plhs[0]);
	for (int j = 0; j < IMG_W;	j++)
	{
		for (int i = 0; i < IMG_H; i++)
		{
			outputMatrix[i + j*IMG_H] = imgBinary[i][j];
		}
	}

}