/*
 * Copyright (C) 2012-2026 MotionSystems
 * 
 * This file is part of ForceSeatMI SDK.
 *
 * www.motionsystems.eu
 *
 */

#include <Windows.h>
#include "mex.h"

#define BUFFER_SIZE (MAX_PATH*2)

void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
#ifdef _M_X64
	static const wchar_t* const LIBRARY_DLL_NAME = L"ForceSeatMI64.dll";
	static const wchar_t* const REG_PATH         = L"SOFTWARE\\Wow6432Node\\MotionSystems\\ForceSeatPM";
#else
	static const wchar_t* const LIBRARY_DLL_NAME = L"ForceSeatMI32.dll";
	static const wchar_t* const REG_PATH         = L"SOFTWARE\\MotionSystems\\ForceSeatPM";
#endif

	wchar_t buffer[BUFFER_SIZE];
	memset(buffer, 0, sizeof(buffer));

	HKEY hKey = NULL;
	if (ERROR_SUCCESS == RegOpenKeyW(HKEY_LOCAL_MACHINE, REG_PATH, &hKey))
	{
		DWORD dwBufSize = sizeof(buffer);
		DWORD dwType = REG_SZ;

		if (ERROR_SUCCESS == RegQueryValueExW(hKey, L"InstallationPath", 0, &dwType, (BYTE*)buffer, &dwBufSize))
		{
			wcscat_s(buffer, BUFFER_SIZE, L"\\");
			wcscat_s(buffer, BUFFER_SIZE, LIBRARY_DLL_NAME);
		}

		RegCloseKey(hKey);
	}

	mwSize dims[] = { BUFFER_SIZE };
	mxArray* charArray = mxCreateCharArray(1, (const mwSize*)dims);
	mxChar* charData  = (mxChar*)mxGetData(charArray);

	for (int i = 0; i < BUFFER_SIZE; ++i)
	{
		charData[i] = (mxChar)buffer[i];
	}

	plhs[0] = mxCreateString(mxArrayToString(charArray));
}
