#include "p_apps.h"

#define DIGITMAP_MASK_X		0x03ff
static CSHORT _cDigitMapMask[MAP_KEY_NUM] = 
{
	0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
	0x0100, 0x0200, 0x0400, 0x0800, 0x1000
};

void p_addEntry(PXCHAR pMapEntry)
{
	PXCHAR_D pCur;
	PXSHORT pDst;
	DCHAR i, iLen, iDotIndex;
	DSHORT iVal;

	if (Sys_iDigitMapNum >= MAP_SDRAM_NO)	return;

	iLen = 0;
	iDotIndex = 0;
	pCur = (PXCHAR)pMapEntry;
	pDst = (PXSHORT)Sdram_pDataCache;

	while (*pCur != 0)
	{
		iVal = 0;
		if (*pCur == '[')
		{
			pCur ++;
			while (*pCur != ']')
			{
				if (pCur[1] == '-')
				{
					for (i = (UCHAR)(*pCur - '0'); i <= (UCHAR)(pCur[2] - '0'); i ++)
					{
						iVal |= _cDigitMapMask[i];
					}
					pCur += 3;
				}
				else
				{
					i = p_getKeyId(pCur[0]);
					if (i != MAP_KEY_UNKNOWN)
					{
						iVal |= _cDigitMapMask[i];
					}
					pCur ++;
				}
			}
		}
		else if (*pCur == 'x' || *pCur == 'X')
		{
			iVal = DIGITMAP_MASK_X;
		}
		else if (*pCur == '.')
		{
			iDotIndex = (iLen >> 1);
			pCur ++;
			continue;
		}
		else
		{
			i = p_getKeyId(*pCur);
			if (i != MAP_KEY_UNKNOWN)
			{
				iVal = _cDigitMapMask[i];
			}
			else
			{
				pCur ++;
				continue;
			}
		}
		*pDst = iVal;
		pDst ++;
		pCur ++;
		iLen += 2;
	}

	*pDst = (USHORT)iDotIndex;
	iLen += 2;

	X_VAL(Sdram_pDataCache, SDRAM_DATA_LENGTH) = iLen;
	sdram_write(MAP_SDRAM_HI, (UCHAR)(MAP_SDRAM_LO+Sys_iDigitMapNum), SRAM_DMA_HALF_DWORD);
	Sys_iDigitMapNum ++;
}

void MapLoadMsg()
{
	XCHAR pTemp[MAP_ENTRY_LEN+1];
	XCHAR pMap[256];
	DCHAR iLen, iChar, iPos, iIndexLo;

	Sys_iDigitMapNum = 0;

	iLen = 0;
	iIndexLo = DIAL_MAP_LO;
	sdram_read(OPTIONS_SDRAM_HI, iIndexLo, SRAM_DMA_HALF_DWORD);
	p_memcpy_x2x(pMap, (PXCHAR)Sdram_pDataCache, (UCHAR)256);
	iPos = 0;
	iChar = pMap[iPos];
	while (iChar)
	{
		if (iChar == 0x0d || iChar == 0x0a)
		{
			if (iLen)
			{
				if (iLen <= MAP_ENTRY_LEN)
				{
					pTemp[iLen] = 0;
					p_addEntry(pTemp);
				}
				iLen = 0;
			}
		}
		else
		{
			pTemp[iLen] = iChar;
			iLen ++;
			if (iLen == MAP_ENTRY_LEN)	iLen = 0;
		}
		iPos ++;
		if (!iPos)
		{
			iIndexLo ++;
			if (iIndexLo >= DIAL_MAP_LO + 8)	break;
			sdram_read(OPTIONS_SDRAM_HI, iIndexLo, SRAM_DMA_HALF_DWORD);
			p_memcpy_x2x(pMap, (PXCHAR)Sdram_pDataCache, (UCHAR)256);
		}
		iChar = pMap[iPos];
	}

	SdramReadFlags();
	X_VAL(Sdram_pDataCache, FLAGS_MAP_NUMBER) = Sys_iDigitMapNum;
	SdramWriteFlags();
}
