// DivFilter.cpp : DLL ̏[`łB
//

#include "stdafx.h"
#include "DivFilter.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 "Divergence Filter"

//
//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
//

// CDivFilterApp

BEGIN_MESSAGE_MAP(CDivFilterApp, CWinApp)
END_MESSAGE_MAP()


// CDivFilterApp RXgNV

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

	// p[^[̏
	ucomp = 0;
	vcomp = 0;
	wcomp = 0;

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


// B CDivFilterApp IuWFNgłB

CDivFilterApp theApp;


// CDivFilterApp 

BOOL CDivFilterApp::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.
					int n;
					if (name == "U") {
						if (Int32::TryParse(xml_reader->Value, n)) theApp.ucomp = n;
					} else if (name == "V") {
						if (Int32::TryParse(xml_reader->Value, n)) theApp.vcomp = n;
					} else if (name == "W") {
						if (Int32::TryParse(xml_reader->Value, n)) theApp.wcomp = n;
					}
#ifdef DEBUG
Console::WriteLine (" U component = {0}", theApp.ucomp);
Console::WriteLine (" V component = {0}", theApp.vcomp);
Console::WriteLine (" W component = {0}", theApp.wcomp);
#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 CDivFilterApp::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()
{

	xp_long i;
	int ncomp, ndim;
	char labels[100][MAX_LABEL_SIZE];

	/* get number of components */
	if (MAget_node_ncomp(&ncomp) != MAERROR) {
		/* support components < 100 */
		if (ncomp > 100) {
			MessageBox(NULL, _T("This filter is not supported for over 100 components."), _T(MODULE_NAME), MB_OK|MB_ICONERROR);
			return 0;
		}
		if (ncomp < 3) {
			MessageBox(theApp.m_pDlg->m_pParent->GetSafeHwnd(), _T("This filter needs 3-vector node components."), _T(MODULE_NAME), MB_OK|MB_ICONERROR);
			return 0;
		}
	} else {
		MessageBox(NULL, _T("Cannot get number of node components."), _T(MODULE_NAME), MB_OK|MB_ICONERROR); 
		return 0;
	}
	/* Field ̏ꍇ ndim `FbN */
	if (MAget_ndim(&ndim) != MAERROR) {
		if (ndim < 3) {
			MessageBox(NULL, _T("This filter only support for ndim = 3."), _T(MODULE_NAME), MB_OK|MB_ICONERROR); 
			return 0;
		}
	}

	// _CAO
	if (theApp.visible) {

		/* get and set labels */
		memset(labels, 0, sizeof(labels));
		for (i = 0; i < ncomp; i++) {
			MAget_node_data_label(i, labels[i]);
			/* Set Dialog initial value */
			theApp.m_pDlg->SetCombo1(labels[i]);
			theApp.m_pDlg->SetCombo2(labels[i]);
			theApp.m_pDlg->SetCombo3(labels[i]);
		}

		/* 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 */
		theApp.ucomp = theApp.m_pDlg->m_iCmb1;
		theApp.vcomp = theApp.m_pDlg->m_iCmb2;
		theApp.wcomp = theApp.m_pDlg->m_iCmb3;

	}
	// _CAOȂ
	// Init  xml t@CŐݒ

	int stat;
	xp_long size;
	int type;
	char* uvw_data[3];	/* input uvw */
	char* divergence;	/* output divergence */
	int veclen = 3;
	int null_flag = 0;
	double null_value = 0.0;
	char* mesh_info = NULL;

	for (i = 0; i < 3; i ++) uvw_data[i] = NULL;
	if ((MAget_node_data(theApp.ucomp, &uvw_data[0], &size, &type) == MASUCCESS) &&
		(MAget_node_data(theApp.vcomp, &uvw_data[1], &size, &type) == MASUCCESS) &&
		(MAget_node_data(theApp.wcomp, &uvw_data[2], &size, &type) == MASUCCESS)) {

		// new data
		// divergence is a scalar
		divergence = (char *)MAalloc(type, size);
		if (divergence == NULL) {
			MessageBox(NULL, _T("Error: allocation failed."), _T(MODULE_NAME), MB_OK|MB_ICONERROR); 
			for (i = 0; i < 3; i ++) {
				if (uvw_data[i] != NULL) MAfree(uvw_data[i]);
			}
			return 0;
		}

		// Calc divergence value
		xp_long dsize = MAtype_size(type)*size;
		stat = MAdivergence(uvw_data[0], uvw_data[1], uvw_data[2], size, type, divergence);
		if (stat != 1) {
			MessageBox(NULL, _T("Error in the divergence function."), _T(MODULE_NAME), MB_OK|MB_ICONERROR); 
			for (i = 0; i < 3; i ++) {
				if (uvw_data[i] != NULL) MAfree(uvw_data[i]);
			}
			if (divergence != NULL) MAfree(divergence);
			return 0;
		}

		// set data label
		memset(labels, 0, sizeof(labels));
		strcpy(labels[0], "Divergence");

		// Add divergence value
		MAadd_node_data(1, divergence, size, type, labels);
		for (i = 0; i < 3; i ++) {
			if (uvw_data[i] != NULL) MAfree(uvw_data[i]);
		}
		if (divergence != NULL) MAfree(divergence);

	}
	else {
		// Error cannot get uvw data
		MessageBox(NULL, _T("Cannot get uvw data."), _T(MODULE_NAME), MB_OK|MB_ICONERROR); 
		for (i = 0; i < 3; i ++) {
			if (uvw_data[i] != NULL) MAfree(uvw_data[i]);
		}
		return 0;
	}

	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);
}

