
#define COBJMACROS
#include <stdio.h>
#include <wchar.h>
#include "CAO.h"
#include "CAO_i.c"

void Run();

void main()
{
	CoInitialize(0);

	Run();

	CoUninitialize();
}

void Run()
{
	HRESULT hr = S_OK;
	ICaoEngine* pIEng = NULL;
	ICaoWorkspaces* pIWss = NULL;
	ICaoWorkspace* pIWs = NULL;
	ICaoController* pICtrl = NULL;
	ICaoVariable* pIVar = NULL;

	VARIANT vntID;
	VARIANT vntVal;
	BSTR bstrCtrlName = NULL;
	BSTR bstrProv = NULL;
	BSTR bstrMachine = NULL;
	BSTR bstrOption = NULL;
	BSTR bstrVarName = NULL;
	wchar_t wcsBuf[256];

	// CaoEngineの生成
	hr = CoCreateInstance(&CLSID_CaoEngine, NULL, CLSCTX_LOCAL_SERVER, &IID_ICaoEngine, (void**)&pIEng);
	if (FAILED(hr)) {
		goto EndProc;
	}

	// Workespaceコレクションの取得
	hr = ICaoEngine_get_Workspaces(pIEng, &pIWss);
	if (FAILED(hr)) {
		goto EndProc;
	}

	// Workspaceの取得
	VariantInit(&vntID);
	vntID.vt = VT_I4;
	vntID.lVal = 0;
	hr = ICaoWorkspaces_Item(pIWss, vntID, &pIWs);
	if (FAILED(hr)) {
		goto EndProc;
	}
	

	// Controllerの生成
	bstrCtrlName = SysAllocString(L"RC1");
	bstrProv = SysAllocString(L"CaoProv.Dummy");
	bstrMachine = SysAllocString(L"");
	bstrOption = SysAllocString(L"");
	hr = ICaoWorkspace_AddController(pIWs, bstrCtrlName, bstrProv, bstrMachine, bstrOption, &pICtrl);
	if (FAILED(hr)) {
		goto EndProc;
	}

	// Variableの生成
	bstrVarName = SysAllocString(L"S11");
	hr = ICaoController_AddVariable(pICtrl, bstrVarName, bstrOption, &pIVar);
	if (FAILED(hr)) {
		goto EndProc;
	}

	// 値の設定
	wprintf(L"Input data : ");
#if _MSC_VER <  1400
	_getws(wcsBuf);
#else
	_getws_s(wcsBuf, sizeof(wcsBuf)/sizeof(wchar_t));
#endif

	VariantInit(&vntVal);
	vntVal.vt = VT_BSTR;
	vntVal.bstrVal = SysAllocString(wcsBuf);
	hr = ICaoVariable_put_Value(pIVar, vntVal);
	if (FAILED(hr)) {
		wprintf(L"Failed CaoVariable::put_Value.");
		goto EndProc;
	}

	// 値の取得
	VariantClear(&vntVal);
	hr = ICaoVariable_get_Value(pIVar, &vntVal);
	if (FAILED(hr)) {
		wprintf(L"Failed CaoVariable::get_Value.");
		goto EndProc;
	}

	wprintf(L"Output data : %s\r\n", vntVal.bstrVal);
	wprintf(L"Press any key.");
	getwchar();

EndProc:
	// 解放処理
	if (pIVar)	ICaoVariable_Release(pIVar);
	if (pICtrl)	ICaoController_Release(pICtrl);
	if (pIWs)	ICaoWorkspace_Release(pIWs);
	if (pIWss)	ICaoWorkspaces_Release(pIWss);
	if (pIEng)	ICaoEngine_Release(pIEng);

	VariantClear(&vntID);
	VariantClear(&vntVal);
	if (bstrCtrlName)	SysFreeString(bstrCtrlName);
	if (bstrProv)		SysFreeString(bstrProv);
	if (bstrMachine)	SysFreeString(bstrMachine);
	if (bstrOption)		SysFreeString(bstrOption);

}