// DM2SkCmdList.cpp: CDM2SkCmdList クラスのインプリメンテーション
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "dm2gded.h"
#include "DM2SkCmdList.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

namespace
{

LPCSTR g_pszSkTextCmdTbl[DM2SKCMD_MAX_CMD] = {
	"AT",
	"BZ",
	"CM",
	"DM",
	"EX",
	"HN",
	"LV",
	"NC",
	"PA",
	"PB",
	"RP",
	"SD",
	"SK",
	"ST",
	"TA",
	"TR",
};

};

//////////////////////////////////////////////////////////////////////
// CDM2SkCmdList

CDM2SkCmdList::CDM2SkCmdList()
{
	ZeroMemory(nVal, sizeof(nVal));
}

LPCSTR CDM2SkCmdList::GetName(UINT i)
{
	if (i < DM2SKCMD_MAX_CMD) return g_pszSkTextCmdTbl[i];

	return "";
}

int CDM2SkCmdList::LookUpName(LPCSTR pszPos, LPCSTR pszEnd)
{
	int n = pszEnd - pszPos;
	for (UINT i = 0; i < DM2SKCMD_MAX_CMD; i++) {
		if (memcmp(GetName(i), pszPos, n) == 0) return i;
	}
	return -1;
}

bool CDM2SkCmdList::Parse(LPCSTR pszPos)
{
	LPCSTR pszBegin = pszPos;
	LPCSTR pszEnd = strchr(pszBegin, '\0');
	if ((pszPos = strchr(pszPos, ':')) == NULL)
		return false;
	strName = CString(pszBegin, pszPos - pszBegin);
	pszPos++;
	LPCSTR pszOrg;
	while (pszPos < pszEnd) {
		pszOrg = pszPos;
		pszPos += 2;
		int iCmd = LookUpName(pszOrg, pszPos);
		if (iCmd >= 0) {
			pszOrg = pszPos;
			int x;
			if (ReadInt(pszPos, pszEnd, x)) {
				nVal[iCmd] = x;
			} else {
				pszPos = pszOrg;
			}
		}
	}
	return true;
}

bool CDM2SkCmdList::ReadInt(LPCSTR &pszPos, LPCSTR pszEnd, int &x)
{
	int i = 0;
	int s = 1;
	x = 0;
	if (*pszPos == '-') {
		s = -s;
		pszPos++;
	}
	while (pszPos < pszEnd && isdigit((BYTE)*pszPos)) {
		x = x * 10 + (*pszPos - '0');
		i++;
		pszPos++;
	}
	if (i == 0)
		return false;
	x = x * s;
	return true;
}

CString CDM2SkCmdList::Mk()
{
	CString strRet = strName + ":";

	CString strText;
	for (int i = 0; i < DM2SKCMD_MAX_CMD; i++) {
		if (nVal[i] != 0) {
			strText.Format("%s%d", GetName(i), nVal[i]);
			strRet += strText;
		}
	}

	return strRet;
}

//////////////////////////////////////////////////////////////////////
// CDM2SkCmdDesc

void CDM2SkCmdDesc::RemoveAll()
{
	for (UINT i = 0; i < DM2SKCMD_MAX_CMD; i++) strDesc[i].Empty();
}

void CDM2SkCmdDesc::LoadFrom(LPCTSTR pszFileIn)
{
	for (UINT i = 0; i < DM2SKCMD_MAX_CMD; i++) {
		CString strText;
		LoadProfileStringFrom("DM2PC_CommandTextDesc", CDM2SkCmdList::GetName(i), strText, "", pszFileIn);
		strDesc[i] = strText;
	}
}

LPCTSTR CDM2SkCmdDesc::GetDesc(UINT i) const
{
	if (i < DM2SKCMD_MAX_CMD)
		return strDesc[i];
	return NULL;
}
