#include <origin.h>
#include <GetNBox.h>
#include <xfutils.h>
#include <GetNBox.h>

//put additional include files here
#include <fft_utils.h>
#include <fftEx_utils.h>
///////////////////////////////////////////////////////////////////////////////
// This function computes the mean and standard deviation of the data in 
// the matrix and then sets the display range of the matrix to be between
// (mean - sd) and (mean + sd)
//
//enum {
	//ERR_INVALID_MATRIXOBJECT = XF_LOCAL_ERR_BEGIN,	
//};

//2006-5-19 Sandy will move to Matrix.c in the near future
static void set_display_range_with_in_SD(Matrix& matM)
{
	bool bret;
	//vector<double> vMat;
	//bret = matM.GetAsVector(vMat);
	//Dataset ds(vMat);
	//BasicStats bStat;
	//bret = Data_sum(&ds, &bStat);
	MatrixStats ms;
	MatrixBasicStats(matM, ms);
	//bret = matM.SetZRange(bStat.mean - bStat.sd, bStat.mean + bStat.sd);	
	bret = matM.SetZRange(ms.dMean - ms.dSD, ms.dMean + ms.dSD);	
}
//
//static void _set_noused_output_optional(TreeNode& trGetN)
//{
	////if(!trGetN.ga.nVal)
	////{
		//trGetN.amo.strVal = "<optional>";
	////}
	//
	////if(!trGetN.gp.nVal)
	////{
		//trGetN.pmo.strVal = "<optional>";
	////}
	////
	////if(!trGetN.gw.nVal)
	////{
		//trGetN.wmo.strVal = "<optional>";
	////}
//}

//static void _init_generate_matrix_name(TreeNode& trGetN, bool bga, bool bgp, bool bgw)
//{
	//if(trGetN.ga.nVal && bga)
	//{
		//trGetN.amo.strVal = "[<new>]<new name:=Amplitude>!";			
	//}
	//
	//if(trGetN.gp.nVal && bgp)
	//{
		//trGetN.pmo.strVal = "[<new>]<new name:=Phase>!";	
	//}
	//
	//if(trGetN.gw.nVal && bgw)
	//{
		//trGetN.wmo.strVal = "[<new>]<new name:=Power>!";
	//}
//}

///Sandy 2008-6-11 check input err function
static bool _check_input_error(TreeNode trGetN, string& strErrMsg)
{
	strErrMsg = "";
	MatrixObject im;
	if(!okxf_resolve_string_get_origin_object(trGetN.im.strVal, &im)||!im.HasData(false))
	{
		///Sophy 6/24/2010 ORG-322-P1 BETTER_ERR_MSG_INFORM_CVT_IMAGE_TO_DATA
		//strErrMsg = CER_INVALID_MATOBJ;
		if ( !im.IsValid() )
			strErrMsg = CER_INVALID_MATOBJ;
		else
		{
			strErrMsg = CER_NEED_CVT_TO_DATA;
		}
		///end BETTER_ERR_MSG_INFORM_CVT_IMAGE_TO_DATA
		return false;
	}
	
	
	int  nComplex,nAmp,nPhase,nPower;
	
	trGetN.ocm.GetAttribute(STR_ATTRIB_DYNACONTROL_USE_CHECK, nComplex);
	trGetN.oam.GetAttribute(STR_ATTRIB_DYNACONTROL_USE_CHECK, nAmp);
	trGetN.opm.GetAttribute(STR_ATTRIB_DYNACONTROL_USE_CHECK, nPhase);
	trGetN.owm.GetAttribute(STR_ATTRIB_DYNACONTROL_USE_CHECK, nPower);
	if(!nComplex&&!nAmp&&!nPhase&&!nPower)
	{
		strErrMsg = XFERR_NO_MATOBJ_NEED_TO_OUPUT;
		return false;
	}
	
	return true;
}


void fft2(const MatrixObject& im, const int& norm, const int& sc, MatrixObject& ocm, MatrixObject& oam, MatrixObject& opm, MatrixObject& owm)
{
	waitCursor junk;
	/**
	Two-dimensional discrete fast Fourier transform.
	Parameters:
		im = [input] The input matrixobject or the layer of a multi-layer matrix.
		out = [output] The output complex matrixobject.
		dir = [input] FFT direction: FFT_FORWARD or FFT_BACKWARD.
		amp = [input] Generate amplitude or not.
		phase = [input] Generate phase or not.
		center_dc = [input] If checked, zero frequency displays at center of matrix rather than four corners.
		norm = [input] Normalize the generated amplitude matrix.
	Examples:
	1. fft2
		Perform forward two-dimensional Fourier transform. Amplitude and phase matrices will be generated.
	2. fft2 -d 1 -a 1 -p 1 -n 1
		Perform inverse two-dimensional Fourier transform. Normalized amplitude and phase matrices will be generated.				
	*/
	if( !im.IsValid() )
	{
		XF_THROW(XFERR_INVALID_MATOBJ);
	}
	//if( !check_matrix_has_data(mi) )
		//return;
									
	int nRows = im.GetNumRows();
	int nCols = im.GetNumCols();
	
	if( nRows <= 1 || nCols <= 1 )
	{
		XF_THROW(-1);
	}
	
	/// Fisher	07/29/09	QA80-14034 SET_2DFFT_FREQUENCY_DOMAIN
	double dx, dy;
	get_sampling_interval_2d(im, dx, dy);
	/// end SET_2DFFT_FREQUENCY_DOMAIN
	
	bool bValid = false;
	if(bValid = ocm.IsValid())
	{
		ocm.SetSize(nRows,nCols);
		ocm.SetInternalData(FSI_COMPLEX);
		set_frequency_domain_2d(ocm, dx, dy, sc);		/// Fisher	07/29/09 QA80-14034 SET_2DFFT_FREQUENCY_DOMAIN
	}
	
	if(bValid |= oam.IsValid())
	{
		oam.SetSize(nRows,nCols);
		set_frequency_domain_2d(oam, dx, dy, sc);		/// Fisher	07/29/09 QA80-14034 SET_2DFFT_FREQUENCY_DOMAIN
	}
	
	if(bValid |= opm.IsValid())
	{
		opm.SetSize(nRows,nCols);
		set_frequency_domain_2d(opm, dx, dy, sc);		/// Fisher	07/29/09 QA80-14034 SET_2DFFT_FREQUENCY_DOMAIN	
	}
	
	if(bValid |= owm.IsValid())
	{
		owm.SetSize(nRows,nCols);
		set_frequency_domain_2d(owm, dx, dy, sc);		/// Fisher	07/29/09 QA80-14034 SET_2DFFT_FREQUENCY_DOMAIN		
	}
	
	if(!bValid)
		XF_THROW(XFERR_NO_MATOBJ_NEED_TO_OUPUT);
	
	
	
	//Matrix<complex>& mcout = cmo.GetDataObject();
	
	matrixbase& mat = im.GetDataObject();
	matrix<complex> mc;
	mc = mat;
	
	int iRet;
	
	if (im.GetInternalData() == FSI_COMPLEX)
	{
		//if (center_dc && FFT_BACKWARD == dir)
		//{
			//if (0 != nRows%2)
				//mout.Wrap(nRows-1, 0);
			//if (0 != nCols%2)
				//mout.Wrap(0, nCols-1);
			//iRet = mout.FFTShift(mout);
			//if (-2 == iRet)
			//{
				//xf_error_out(INTERNAL_CASTING_ERROR_MSG);
				//return;
			//}
		//}
		iRet = fft_2d_complex(nRows, nCols, mc, FFT_FORWARD);
	}
	else
		iRet = fft_2d_real(nRows, nCols, mc, FFT_FORWARD);
	
	if( 0 != iRet )
	{
		//XF_THROW_EX("Xfunction failed, Code = %d", iRet);
		XF_THROW(iRet);
	} 
	
	//if (center_dc && FFT_FORWARD == dir)
	if (sc)
	{
		iRet = mc.FFTShift(mc);
		if (-2 == iRet)
		{
			//XF_THROW_EX("Xfunction failed, Code = %d", iRet);
			XF_THROW(iRet);
		}
	}
	
	
	//MatrixLayer ml;
	//cmo.GetParent(ml);
	//ml.SetName("Complex");
	//MatrixPage mp = ml.GetPage();
	
	//if (ga)
	if(ocm.IsValid())
	{
		Matrix<complex>& mComplex = ocm.GetDataObject();
		mComplex = mc;
		
	}
		
	
	if(oam.IsValid())
	{
		matrix mAmplitude;
		mc.GetAmplitude(mAmplitude);
		if (norm)
		{
			double dMax = mAmplitude.GetMax();
			mAmplitude = mAmplitude/dMax;
		}
		///-----Kit 10/26/2010 ORG-1227-P3 SUPPORT_OTHER_FFT_TOOL_SHOW_UNITS_ON_REPORT_TABLE
		else
		{
			oam.SetUnits( im.GetUnits() );
		}
		/// End SUPPORT_OTHER_FFT_TOOL_SHOW_UNITS_ON_REPORT_TABLE
	
		//MatrixLayer mlay;
		//amo.GetParent(mlay);
		//mlay.SetName("Amplitude");
		//oam.SetInternalData(FSI_DOUBLE);//sandy 2008-11-10 keep current view mode
		oam.SetInternalData(FSI_DOUBLE, true, false);
		Matrix& matAmp = oam.GetDataObject();
		matAmp = mAmplitude;
		set_display_range_with_in_SD(matAmp);
	}
	
	if (opm.IsValid())
	{
		matrix mPhase;
		mc.GetPhase(mPhase);
	
		//MatrixLayer mlay;
		//opm.GetParent(mlay);
		//mlay.SetName("Phase");
		//opm.SetInternalData(FSI_DOUBLE);//sandy 2008-11-10 keep current view mode
		opm.SetInternalData(FSI_DOUBLE, true, false);
		Matrix& matPha = opm.GetDataObject();
		matPha = mPhase;
		
		opm.SetUnits( "Rad" );///-----Kit 10/26/2010 ORG-1227-P3 SUPPORT_OTHER_FFT_TOOL_SHOW_UNITS_ON_REPORT_TABLE
		
	}
	
	if (owm.IsValid())
	{
		owm.SetSize(nRows,nCols);
		//owm.SetInternalData(FSI_COMPLEX);//sandy 2008-11-10 keep current view mode
		owm.SetInternalData(FSI_COMPLEX, true, false);
		Matrix<complex>& matPow = owm.GetDataObject();
		matPow = mc;
		matPow.Conjugate();
		matPow.DotMultiply(mc);
		
		//apply sqrt
		matrix msqrt(nRows,nCols);
		msqrt = 0.5;
		matPow.DotPower(msqrt);
		
		//owm.SetInternalData(FSI_DOUBLE);
		owm.SetInternalData(FSI_DOUBLE, true, false);//sandy 2008-11-10 keep current view mode
		 
	}
		
	//if(mp)
	//{
		//string strLabel = dir ? "Inverse FFT of " : "FFT of ";
		//string strLabel = "FFT of";
		//MatrixLayer mlIn;
		//mi.GetParent(mlIn);
		//MatrixPage mpIn = mlIn.GetPage();
		//
		//strLabel.Insert(strLabel.GetLength(), mpIn.GetName());
	//
		//mp.SetLongName(strLabel);
		//mp.TitleShow = WIN_TITLE_SHOW_BOTH;
	//}
	
}

//nEventID < 0 on event, like GETNE_ON_INIT, GETNE_ON_OK etc, >0 on change from control
//return 0 to do nothing, return PEVENT_GETN_RET_TO_CLOSE to close dialog
//dwEnables = bOKEnable, bBTN1Enable, bBTN2Enable, bBTN3Enable, , can set to false to disable OK/Apply buttons
//lpcszNodeName = the trGetN TreeNode tag name that generates the event, or is  if GETNE_ON_OK etc
//strAux = optional string for XF Wizard Bar, like DLG_NEED_CHANGE_GRID etc, it will be invalid if from internal node value change event
//strErrMsg = allowing messages to be shown
int fft2_event1(TreeNode& trGetN, int nRow, int nEventID, DWORD& dwEnables, LPCSTR lpcszNodeName, WndContainer& DynaCntrlContainer, string& strAux, string& strErrMsg)
{
	if( xf_is_extended_event(nEventID) )
		return fft2_event1_ex(trGetN, nRow, nEventID, dwEnables, lpcszNodeName, DynaCntrlContainer, strAux, strErrMsg);
	DECLARE_BUTTON_ENABLES
	
	//if(nEventID == GETNE_ON_INIT)
		//_init_generate_matrix_name(trGetN, true, true, true);
	
	//printf("now = %d\n, trGetN.norm.show = %d, trGetN.amp.Enable = %d\n", nRow, trGetN.norm.Show, trGetN.amp.nVal);
	//if (nRow == 1 || nRow < 0) // the amplitude row
	//{
		//trGetN.norm.Show = trGetN.ga.nVal;
		//trGetN.amo.Show = trGetN.ga.nVal;
		//return true;
	//}
	//if (nRow == 3 || nRow < 0) // the phase row
	//{
		//trGetN.pmo.Show = trGetN.gp.nVal;
		//return true;
	//}
	
	//if (nRow == 1 || nRow == 3 || nRow < 0) // the amplitude row
	//bool bIsChangingGA = lstrcmpi(lpcszNodeName,"ga") == 0? true:false;
	//bool bIsChangingGP = lstrcmpi(lpcszNodeName,"gp") == 0? true:false;
	//bool bIsChangingGPower = lstrcmpi(lpcszNodeName,"gw") == 0? true:false;
	//if(GETNE_ON_INIT == nEventID || bIsChangingGA || bIsChangingGP || bIsChangingGPower)
	//{
		//
		//trGetN.norm.Show = trGetN.ga.nVal;
		//trGetN.amo.Show = trGetN.ga.nVal;
		//trGetN.pmo.Show = trGetN.gp.nVal;
		//trGetN.wmo.Show = trGetN.gw.nVal;
	//
	//}
	
	///Sandy 2006-9-25 add setting <optional>
	//trGetN.norm.Show = trGetN.ga.nVal;
	//trGetN.amo.Show = trGetN.ga.nVal;
	//trGetN.pmo.Show = trGetN.gp.nVal;
	//trGetN.wmo.Show = trGetN.gw.nVal;
	
	
	///Sandy 2008-6-11 check input err function
	//Sandy 2007-7-11 add for check input
	//MatrixObject im;
	//if(!okxf_resolve_string_get_origin_object(trGetN.im.strVal, &im)||!im.HasData(false))
	//{
		//strErrMsg = CER_INVALID_MATOBJ;
		//bOKEnable = false;
		//return true;
	//}
	//
	//
	//int  nComplex,nAmp,nPhase,nPower;
	//
	//trGetN.ocm.GetAttribute(STR_ATTRIB_DYNACONTROL_USE_CHECK, nComplex);
	//trGetN.oam.GetAttribute(STR_ATTRIB_DYNACONTROL_USE_CHECK, nAmp);
	//trGetN.opm.GetAttribute(STR_ATTRIB_DYNACONTROL_USE_CHECK, nPhase);
	//trGetN.owm.GetAttribute(STR_ATTRIB_DYNACONTROL_USE_CHECK, nPower);
	//if(!nComplex&&!nAmp&&!nPhase&&!nPower)
	//{
		//strErrMsg = XFERR_NO_MATOBJ_NEED_TO_OUPUT;
		//bOKEnable = false;
		//
	//}
	bOKEnable = _check_input_error(trGetN, strErrMsg);
	
		
	
	return true;
	

}

int fft2_make_tree(TreeNode& tr, LPCSTR lpcszVarName)
{
		return false;
}
//nGetNDialog = 0,1,2, corresponding to the XF GetN dropdown, 0 = dialog is not used
//you can change nRet to be one of XFEVT_PROCEED (defualt), XFEVT_ABORT, XFEVT_PROCEED_NO_DLG or XFEVT_PROCEED_WITH_DLG(when nGetNDialog = 0)
//nGetNDialog = -1 when Ok on GetN dialog to allow handler to preocess <auto> etc variables
//dwCntrl is combination of bits
//LTXF_FROM_GUI_MENU, LTXF_FROM_GUI_PROMPT, LTXF_FROM_AUTO_UPDATE, LTXF_FROM_FUNCTION, LTXF_THEME_USED, LTXF_CHANGE_PARAM
void fft2_before_execute(TreeNode& trGetN, int nGetNDialog, int& nRet, int dwCntrl)
{
	//if(0 == nGetNDialog)
		//_set_noused_output_optional(trGetN);
		
	///Sandy 2008-6-11 check input err function
	if(0 == nGetNDialog)
	{
		string strErrMsg;
		if(!_check_input_error(trGetN, strErrMsg))
			nRet = XFEVT_PROCEED_WITH_DLG;
	}
}
//nEventID < 0 on event, like GETNE_ON_INIT, GETNE_ON_OK etc, >0 on change from control
//return 0 to do nothing, return PEVENT_GETN_RET_TO_CLOSE to close dialog
//dwEnables = bOKEnable, bBTN1Enable, bBTN2Enable, bBTN3Enable, , can set to false to disable OK/Apply buttons
//lpcszNodeName = the trGetN TreeNode tag name that generates the event, or is  if GETNE_ON_OK etc
//strAux = optional string for XF Wizard Bar, like DLG_NEED_CHANGE_GRID etc, it will be invalid if from internal node value change event
//strErrMsg = allowing messages to be shown
int fft2_event1_ex(TreeNode& trGetN, int nRow, int nEventID, DWORD& dwEnables, LPCSTR lpcszNodeName, WndContainer& DynaCntrlContainer, string& strAux, string& strErrMsg)
{
	return false;
}
