#include "p_apps.h"

#ifndef CALL_MGCP

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

BOOLEAN _IsMatched(PXCHAR pEvent, PXSHORT pMap, UCHAR iNum)
{
	DCHAR i;

	for (i = 0; i < iNum; i ++)
	{
		if ((_cDigitMapMask[pEvent[i]] & pMap[i]) == 0)
		{
			return FALSE;
		}
	}
	return TRUE;
}

BOOLEAN _IsPeriodMatched(PXCHAR pEvent, UCHAR iEventNum, PXSHORT pMap, UCHAR iMapLen)
{
	DCHAR i;

	for (i = 0; i < iMapLen; i ++)
	{
		if ((_cDigitMapMask[pEvent[i]] & pMap[i]) == 0)
		{
			return FALSE;
		}
	}
	for (i = iMapLen; i < iEventNum; i ++)
	{
		if ((_cDigitMapMask[pEvent[i]] & pMap[iMapLen-1]) == 0)
			return FALSE;
	}
	return TRUE;
}

UCHAR p_matchMap(PXCHAR pEvent, UCHAR iEventNum)
{
	PXSHORT pMap;
	DCHAR i, iRtVal, iLen;

	iRtVal = DIGITMAP_NOTMATCH;
	pMap = (PXSHORT)Sdram_pDataCache;
	for (i = 0; i < Sys_iDigitMapNum; i ++)
	{
		SdramRead(MAP_SDRAM_HI, (UCHAR)(MAP_SDRAM_LO+i), SRAM_DMA_HALF_DWORD);
		iLen = X_VAL(Sdram_pDataCache, SDRAM_DATA_LENGTH);
		iLen >>= 1;
		iLen --;
		if (pMap[iLen])
		{
			//this entry has a dot in it, so it's a variable length map
			iLen --;
			if (iEventNum > iLen)
			{
				if (_cDigitMapMask[pEvent[iEventNum-1]] & pMap[iLen])
				{
					if (_IsPeriodMatched(pEvent, (UCHAR)(iEventNum - 1), pMap, iLen))
						return DIGITMAP_MATCH;
				}
				else
				{
					if (_IsPeriodMatched(pEvent, iEventNum, pMap, iLen) && iRtVal == DIGITMAP_NOTMATCH)
					{
						iRtVal = DIGITMAP_TOMATCH;
					}
				}
			}
			else if (iEventNum == iLen)
			{
				if (_IsMatched(pEvent, pMap, iEventNum) && iRtVal == DIGITMAP_NOTMATCH)
				{
					iRtVal = DIGITMAP_TOMATCH;
				}
			}
			else
			{
				if (_IsMatched(pEvent, pMap, iEventNum))
				{
					iRtVal = DIGITMAP_UNDERMATCH;
				}
			}
		}
		else
		{
			if (iEventNum < iLen)
			{
				if (_IsMatched(pEvent, pMap, iEventNum))
				{
					iRtVal = DIGITMAP_UNDERMATCH;				
				}
			}
			else if (iEventNum == iLen)
			{
				if (_IsMatched(pEvent, pMap, iEventNum))
				{
					return DIGITMAP_MATCH;
				}
			}
		}
	}
	return iRtVal;
}
#endif

