// CoordinateMath.cpp : DLL ̏[`łB
//
#include "stdafx.h"
#include "CoordinateMath.h"
#include "MFilterDlg.h"
#include "MAapi.h"

#using <System.xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Text;
using namespace System::IO;

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define MODULE_NAME "Coordinate Math"

//
//TODO:  DLL  MFC DLL ɑ΂ēIɃNꍇA
//		MFC ŌĂяo邱 DLL GNX|[gꂽǂ̊֐
//		֐̍ŏɒǉ AFX_MANAGE_STATE }N
//		Ȃ΂Ȃ܂B
//
//		:
//
//		extern "C" BOOL PASCAL EXPORT ExportedFunction()
//		{
//			AFX_MANAGE_STATE(AfxGetStaticModuleState());
//			// ʏ֐̖{̂͂̈ʒuɂ܂
//		}
//
//		̃}Ne֐Ɋ܂܂Ă邱ƁAMFC 
//		ǂ̌ĂяoD悷邱Ƃ͔ɏdvłB
//		͊֐̍ŏ̃Xe[ggłȂ΂ 
//		ȂƂӖ܂ARXgN^ MFC
//		DLL ւ̌Ăяos\̂ŁAIu
//		WFNgϐ̐錾OłȂ΂Ȃ܂B
//
//		ڍׂɂĂ MFC eNjJ m[g 33 
//		58 QƂĂB
//

// CCoordinateMathApp

BEGIN_MESSAGE_MAP(CCoordinateMathApp, CWinApp)
END_MESSAGE_MAP()


// CCoordinateMathApp RXgNV

CCoordinateMathApp::CCoordinateMathApp()
{
	// TODO: ̈ʒuɍ\zpR[hǉĂB
	//  InitInstance ̏dvȏׂċLqĂB

	// p[^[̏
	scale_x = 1.0f;
	scale_y = 1.0f;
	scale_z = 1.0f;
	translate_x = 0.0f;
	translate_y = 0.0f;
	translate_z = 0.0f;

	// _CAO̍쐬
	m_pDlg = new MFilterDlg(GetMainWnd());
}


// B CCoordinateMathApp IuWFNgłB

CCoordinateMathApp theApp;


// CCoordinateMathApp 

BOOL CCoordinateMathApp::InitInstance()
{

	// DLL Ɠꏊ xml t@CꍇA̐ݒlǂݍ
	TCHAR szMyPath[ _MAX_PATH ];
	TCHAR szDir[ _MAX_DIR ];
	TCHAR szDrive[ _MAX_DRIVE ];
	TCHAR szFName[ _MAX_FNAME ];
	TCHAR szExt[ _MAX_EXT ];

	// DLL ̃pX瓯O xml t@C쐬
	GetModuleFileName(m_hInstance, szMyPath, sizeof(szMyPath));
	_tsplitpath_s(szMyPath, szDrive, sizeof(szDrive), szDir, sizeof(szDir), szFName, sizeof(szFName), szExt, sizeof(szExt));
	_tmakepath_s(szMyPath, sizeof(szMyPath), szDrive, szDir, szFName, _T(".xml"));

	// xml t@C
	String^ xmlpath = gcnew String(szMyPath);
#ifdef DEBUG
Console::Write("xml filename = {0}\n", xmlpath);
#endif

	// xml ̗vf
	String^ name = "";
	String^ visible = "true";

	// xml t@C΁Al擾
	if (File::Exists(xmlpath)) {

#ifdef DEBUG
Console::Write("xml file found!\n");
#endif
		StreamReader^ stream = gcnew StreamReader(xmlpath);
		XmlReader^ xml_reader = XmlReader::Create(stream);

		// xml l擾
		while(xml_reader->Read()) {

			switch (xml_reader->NodeType) 
			{
				case XmlNodeType::Element:
					name = xml_reader->Name;
#ifdef DEBUG
Console::Write("<{0}", name);
#endif
					while (xml_reader->MoveToNextAttribute()) {
#ifdef DEBUG
Console::Write(" {0}='{1}'", xml_reader->Name, xml_reader->Value);
#endif
						if (name == "dialog" && xml_reader->Name == "visible") {
							visible = xml_reader->Value;
#ifdef DEBUG
Console::Write("  [ dialog visible = {0} ]  ", visible);
#endif
						}
					}
#ifdef DEBUG
Console::WriteLine(">");
#endif
				break;

				case XmlNodeType::Text: //Display the text in each element.
					double val;
					if (name == "xscale") {
						if (Double::TryParse(xml_reader->Value, val)) theApp.scale_x = (float)val;
					} else if (name == "yscale") {
						if (Double::TryParse(xml_reader->Value, val)) theApp.scale_y = (float)val;
					} else if (name == "zscale") {
						if (Double::TryParse(xml_reader->Value, val)) theApp.scale_z = (float)val;
					} else if (name == "xtrans") {
						if (Double::TryParse(xml_reader->Value, val)) theApp.translate_x = (float)val;
					} else if (name == "ytrans") {
						if (Double::TryParse(xml_reader->Value, val)) theApp.translate_y = (float)val;
					} else if (name == "ztrans") {
						if (Double::TryParse(xml_reader->Value, val)) theApp.translate_z = (float)val;
					}
#ifdef DEBUG
Console::WriteLine (" scale_x = {0}", theApp.scale_x);
Console::WriteLine (" scale_y = {0}", theApp.scale_y);
Console::WriteLine (" scale_z = {0}", theApp.scale_z);
Console::WriteLine (" translate_x = {0}", theApp.translate_x);
Console::WriteLine (" translate_y = {0}", theApp.translate_y);
Console::WriteLine (" translate_z = {0}", theApp.translate_z);
#endif

                break;
			
				case XmlNodeType::EndElement: //Display the end of the element.
#ifdef DEBUG
Console::Write("</{0}", xml_reader->Name);
Console::WriteLine(">");
#endif
                break;

			}
			
		}
		// check dialog visible
		if (0 == System::String::Compare(visible, _T("false"))) {
			theApp.visible = 0;
		} else {
			theApp.visible = 1;
		}

	} else {
		theApp.visible = 1;
	}

#ifdef DEBUG
Console::WriteLine("Dialog visible = {0}", theApp.visible);
#endif

	// visible ̏ꍇ̓_CAO쐬
	if (theApp.visible) {
		AfxEnableControlContainer();
		m_pDlg->Create();
	}
	CWinApp::InitInstance();

	return TRUE;
}


int CCoordinateMathApp::ExitInstance()
{
	// TODO: ɓȃR[hǉ邩A͊{NXĂяoĂB
    if(m_pDlg) {
        m_pDlg->DestroyWindow();
        delete m_pDlg;
    }
	return CWinApp::ExitInstance();
}

/**************************************************************************\
                             MAuser_function()

@F
   MAuser_function֐́AMicroAVS̃j[ł̃vOC[hꂽ
   ɃR[܂BMicroAVSŕ\f[^̕ύXsɂ́Å֐
   MicroAVSAPIR[ĂB
\**************************************************************************/
int __stdcall MAuser_function()
{

	// _CAO
	if (theApp.visible) {

		/* Set Dialog initial value */
		CString txt;
		txt.Format(_T("%f"), theApp.scale_x);
		theApp.m_pDlg->m_scale_x = txt;
		txt.Format(_T("%f"), theApp.scale_y);
		theApp.m_pDlg->m_scale_y = txt;
		txt.Format(_T("%f"), theApp.scale_z);
		theApp.m_pDlg->m_scale_z = txt;
		txt.Format(_T("%f"), theApp.translate_x);
		theApp.m_pDlg->m_translate_x = txt;
		txt.Format(_T("%f"), theApp.translate_y);
		theApp.m_pDlg->m_translate_y = txt;
		txt.Format(_T("%f"), theApp.translate_z);
		theApp.m_pDlg->m_translate_z = txt;

		/* Show Dialog */
		theApp.m_pDlg->ShowWindow(SW_SHOW);
		theApp.m_pDlg->UpdateData(FALSE);

		MSG msg;
		while(GetMessage(&msg, NULL, 0, 0))
		{
			TranslateMessage(&msg); 
			DispatchMessage(&msg);
		}

		/* After OK button, calculation and set new value */
		double val;
		val = _tcstod(theApp.m_pDlg->m_scale_x,NULL);
		if (val != 0.0) theApp.scale_x = (float)val;
		val = _tcstod(theApp.m_pDlg->m_scale_y,NULL);
		if (val != 0.0) theApp.scale_y = (float)val;
		val = _tcstod(theApp.m_pDlg->m_scale_z,NULL);
		if (val != 0.0) theApp.scale_z = (float)val;
		val = _tcstod(theApp.m_pDlg->m_translate_x,NULL);
		theApp.translate_x = (float)val;
		val = _tcstod(theApp.m_pDlg->m_translate_y,NULL);
		theApp.translate_y = (float)val;
		val = _tcstod(theApp.m_pDlg->m_translate_z,NULL);
		theApp.translate_z = (float)val;

	}

	// _CAOȂ
	// Init  xml t@CŐݒ
	/* MicroAVS */
	int   ndim    = 0;
	int	  ncomp   = 0;
	xp_long   nnodes  = 0;
	int   veclen  = 0;
	xp_long   npoints = 0;
	int   nspace  = 0;
	int   result  = 0;
	xp_long   *dims   = (xp_long *)NULL;
	xp_long    dims_size   = 0;
	xp_long    sum_dims    = 0;
	xp_long    points_size = 0;
	float *points      = (float *)NULL;
	float *new_points  = (float *)NULL;
	float *coord       = (float *)NULL;
	float *new_coord   = (float *)NULL;

	xp_long    coord_size     = 0;
	xp_long    i = 0;
	xp_long    j = 0;
	xp_long    k = 0;

	/* m[h擾 */
	result = MAget_nnodes(&nnodes);
	if(result == MAERROR)
	{
		MessageBox(NULL, _T("MAget_node_ncomp failed."), _T(MODULE_NAME), MB_OK|MB_ICONERROR);
		return(0);
	}
	/* fBW̏擾(field ̂) */
	ndim = 0;
	result = MAget_ndim(&ndim);
	if(result == MAERROR)
	{
		ndim = 0;
	}
	if( ndim > 0){
#ifdef WIN64
		dims = (xp_long *)MAalloc(MA_DTYPE_LONG, ndim);
#else
		dims = (int *)MAalloc(MA_DTYPE_INT, ndim);
#endif
		result = MAget_dims(&dims, &dims_size);
		if(result == MAERROR)
		{
			MessageBox(NULL, _T("MAget_dims failed."), _T(MODULE_NAME), MB_OK|MB_ICONERROR);
			return(0);
		}
	}

	/* \Ԃ̎擾 */
	result = MAget_nspace(&nspace);
	if(result == MAERROR)
	{
		MessageBox(NULL, _T("MAget_nspace failed."), _T(MODULE_NAME), MB_OK|MB_ICONERROR);
		return(0);
	}
	/* z̃TCY擾 */
	result = MAget_npoints(&npoints);

    if(result == MAERROR)
	{
		npoints = 0;
	}
	if( npoints != 0)
	{
		/* field is uniform or rectilinear */
		points     = (float *)MAalloc(MA_DTYPE_FLOAT, (npoints * nspace));
		new_points = (float *)MAalloc(MA_DTYPE_FLOAT, (npoints * nspace));		
		result     = MAget_points( &points, &points_size );

		if(result == MAERROR)
		{
			MessageBox(NULL, _T("MAget_points failed."), _T(MODULE_NAME), MB_OK|MB_ICONERROR);
			return 0;
		}

		if( npoints == 2 ){
			/* field is uniform */
			switch(nspace){
			case 1:
				new_points[0] = (points[0] * theApp.scale_x) + theApp.translate_x;
				new_points[1] = (points[1] * theApp.scale_x) + theApp.translate_x;
			break;
			case 2:
				new_points[0] = (points[0] * theApp.scale_x) + theApp.translate_x;
				new_points[1] = (points[1] * theApp.scale_y) + theApp.translate_y;
				new_points[2] = (points[2] * theApp.scale_x) + theApp.translate_x;
				new_points[3] = (points[3] * theApp.scale_y) + theApp.translate_y;
			break;
			case 3:
				new_points[0] = (points[0] * theApp.scale_x) + theApp.translate_x;
				new_points[1] = (points[1] * theApp.scale_y) + theApp.translate_y;
				new_points[2] = (points[2] * theApp.scale_z) + theApp.translate_z;
				new_points[3] = (points[3] * theApp.scale_x) + theApp.translate_x;
				new_points[4] = (points[4] * theApp.scale_y) + theApp.translate_y;
				new_points[5] = (points[5] * theApp.scale_z) + theApp.translate_z;
			break;
			default:
			break;
			}
		} else {
			/* field is rectiliniaer */
			sum_dims = 0;
			for(i=0;i<ndim;i++){
				sum_dims = sum_dims + dims[i];
			}
			switch(nspace){
			case 1:
				for(i=0;i<sum_dims;i++){
					new_points[i] = (points[i] * theApp.scale_x) + theApp.translate_x;
				}
			break;
			case 2:
				for(i=0;i<sum_dims;i++){
					new_points[i*2  ] = (points[i*2  ] * theApp.scale_x) + theApp.translate_x;
					new_points[i*2+1] = (points[i*2+1] * theApp.scale_y) + theApp.translate_y;
				}
			break;
			case 3:
				for(i=0;i<sum_dims;i++){
					new_points[i*3  ] = (points[i*3  ] * theApp.scale_x) + theApp.translate_x;
					new_points[i*3+1] = (points[i*3+1] * theApp.scale_y) + theApp.translate_y;
					new_points[i*3+2] = (points[i*3+2] * theApp.scale_z) + theApp.translate_z;
				}
			break;
			default:
			break;
			}
		}
		result = MAset_points(new_points ,points_size);
		if(result == MAERROR)
		{
			MessageBox(NULL, _T("MAset_points failed."), _T(MODULE_NAME), MB_OK|MB_ICONERROR);
			return 0;
		}
	} else {
		/* field is irregluar */
		coord = (float *)MAalloc(MA_DTYPE_FLOAT, (nnodes * nspace) );
		new_coord = (float *)MAalloc(MA_DTYPE_FLOAT, (nnodes * nspace) );
		result = MAget_coordinates(&coord, &coord_size);
		if(result == MAERROR)
		{
			MessageBox(NULL, _T("MAget_coordinates failed."), _T(MODULE_NAME), MB_OK|MB_ICONERROR);
			return 0;
		}		
		switch(nspace)
		{
		case 1:
			for(i=0;i<nnodes;i++){
				new_coord[i] = (coord[i] * theApp.scale_x) + theApp.translate_x;
			}
		break;
		case 2:
			for(i=0;i<nnodes;i++){
				new_coord[i*2  ] = (coord[i*2  ] * theApp.scale_x) + theApp.translate_x;
				new_coord[i*2+1] = (coord[i*2+1] * theApp.scale_y) + theApp.translate_y;
			}
		break;
		case 3:
			for(i=0;i<nnodes;i++){
				new_coord[i*3  ] = (coord[i*3  ] * theApp.scale_x) + theApp.translate_x;
				new_coord[i*3+1] = (coord[i*3+1] * theApp.scale_y) + theApp.translate_y;
				new_coord[i*3+2] = (coord[i*3+2] * theApp.scale_z) + theApp.translate_z;
			}
		break;
		default:
		break;
		}

		result = MAset_coordinates( new_coord, coord_size);
		if(result == MAERROR)
		{
			MessageBox(NULL, _T("MAset_coordinates failed."), _T(MODULE_NAME), MB_OK|MB_ICONERROR);
			return(0);
		}
	}

	if(dims != NULL) MAfree(dims);
	if(points != NULL) MAfree(points);
	if(new_points != NULL) MAfree(new_points);
	if(coord != NULL) MAfree(coord);
	if(new_coord != NULL) MAfree(new_coord);

	return(1);	
}

/**************************************************************************\
                             MAuser_function_name()

@F
   MAuser_function_name֐́AMicroAVS̋NɁAvOC̃j[
   \镶ݒ肵܂B
\**************************************************************************/
void __stdcall MAuser_function_name(char* szFilterName)
{
	strcpy(szFilterName, MODULE_NAME);
}

