/*
 * CoordTransform: mesh a domain using an .exp file
 */

#include "./CoordTransform.h"
#define ACCEPT_USE_OF_DEPRECATED_PROJ_API_H
#include <proj_api.h>

void CoordTransformUsage(void){/*{{{*/
	_printf_(" type help CoordTransform\n");
}/*}}}*/
WRAPPER(CoordTransform_python){
	
	/*intermediary: */
	double *xin     = NULL;
   double *yin     = NULL;
   char   *projin  = NULL;
   char   *projout = NULL;
   int     M,N;
   int     test1,test2;

	printf("%i %i %i %i\n",NLHS,nlhs,NRHS,nrhs);

	/*Boot module: */
	MODULEBOOT();

	/*checks on arguments: */
	CHECKARGUMENTS(NLHS,NRHS,&CoordTransformUsage);

	/*Fetch data needed for meshing: */
	FetchData(&xin,&M,&N,XIN);
   FetchData(&yin,&test1,&test2,YIN);
   if(!M*N)     _error_("no coordinate provided");
   if(test1!=M) _error_("x and y do not have the same size");
   if(test2!=N) _error_("x and y do not have the same size");
   FetchData(&projin,PROJIN);
   FetchData(&projout,PROJOUT);

	/*Initialize output*/
	double* xout = xNew<double>(M*N);
	double* yout = xNew<double>(M*N);

	/*Initialize projections*/
	projPJ pj_src = pj_init_plus(projin);
	projPJ pj_dst = pj_init_plus(projout);
	if(!pj_src) _error_("Failed to initialize PROJ with source projection\n");
	if(!pj_dst) _error_("Failed to initialize PROJ with destination projection\n");

	/*Transform coordinates*/
	int p = pj_transform(pj_src,pj_dst,M*N,1,xout,yout,NULL);
	if(p!=0){
		_error_("PROJ failed with error code: "<<p);
	}

	/*write outputs: */
	WriteData(XOUT,xout,M,N);
	WriteData(YOUT,yout,M,N);

	/*Clean-up and return*/
   mxFree(projin);
   mxFree(projout);
	xDelete<double>(xin);
	xDelete<double>(yin);
	xDelete<double>(xout);
	xDelete<double>(yout);
	xDelete<char>(projin);
	xDelete<char>(projout);

	/*end module: */
	MODULEEND();
}
