#include "page1.h"

BOOLEAN _CheckInnerLine()
{
	DCHAR iLen;

	if (!Sys_iInnerLine)	return FALSE;	// option 0[disable]

	iLen = p_strlen_x(Sys_pInnerLinePrefix);		// nonlocal prefix is empty, means disable inner line too
	if (!iLen)	return FALSE;

	if (p_memcmp_x2x(Sys_pInnerLinePrefix, Key_pBuf, iLen))	return FALSE;	// mismatch

	if (Sys_iInnerLine == INNER_LINE_OMIT_PREFIX)
	{
		p_memcpy_x2x_0(Sys_pRemoteNumber, (PXCHAR)(Key_pBuf + iLen), DIALED_MAX_LEN);
	}
	else
	{
		// option 1 [enable]
		p_memcpy_x2x_0(Sys_pRemoteNumber, Key_pBuf, DIALED_MAX_LEN);
	}

	return TRUE;
}

void DialPlanBuildNumber()
{
	DCHAR iLen;
	XCHAR pDialBuf[MAX_KEYBUF_LEN];

	// set REMOTE_NUMBER_SDRAM_LO data length to 0
	SdramWriteData(OPTIONS_SDRAM_POS+REMOTE_NUMBER_SDRAM_LO, 0);

	// copy first for no dialplan settings
	p_memcpy_x2x_0(Sys_pRemoteNumber, Key_pBuf, DIALED_MAX_LEN);

	// no dialplan for inner line
	if (_CheckInnerLine())	return;

	if (!Sys_iUseDialPlan || Sys_iUseDialPlan == DIALPLAN_HOTLINE)		return;
	
	// If the first dialed key is "#" or "*", return directly
	if (Sys_pRemoteNumber[0] == '*' || Sys_pRemoteNumber[0] == '#')		return;

	if (Sys_iScrollType <= CALL_TYPE_MISSED)		// missed, answered
	{
		p_strcpy_x2x((PXCHAR)Sdram_pDataCache, Key_pBuf);
		p_strcpy_x2x(Key_pBuf, Sys_pIntlPrefix);
		p_strcat_x2x(Key_pBuf, (PXCHAR)Sdram_pDataCache);
	}

	if (Sys_iUseDialPlan == DIALPLAN_DIALNUM)
	{
		p_strcpy_x2x(pDialBuf, Sys_pDialNumber);
	}
	else
	{
		pDialBuf[0] = 0;
	}

	iLen = p_strlen_x(Sys_pIntlPrefix);
	if (!p_memcmp_x2x(Sys_pIntlPrefix, Key_pBuf, iLen))
	{
		p_strcat_x2x(pDialBuf, (PXCHAR)(Key_pBuf+iLen));

	}
	else
	{
		iLen = p_strlen_x(Sys_pLongPrefix);
		if (!p_memcmp_x2x(Sys_pLongPrefix, Key_pBuf, iLen))
		{
			p_strcat_x2x(pDialBuf, Sys_pCountryCode);
			p_strcat_x2x(pDialBuf, (PXCHAR)(Key_pBuf+iLen));
		}
		else
		{
			p_strcat_x2x(pDialBuf, Sys_pCountryCode);
			p_strcat_x2x(pDialBuf, Sys_pAreaCode);
			p_strcat_x2x(pDialBuf, Key_pBuf);
		}
	}
	p_memcpy_x2x_0(Sys_pRemoteNumber, pDialBuf, DIALED_MAX_LEN);

	if (Sys_iUseDialPlan == DIALPLAN_PREFIX)
	{
		p_strcpy_x2x((PXCHAR)Sdram_pDataCache, Sys_pAccount);
		p_strcat_x2x((PXCHAR)Sdram_pDataCache, Sys_pPin);
		p_strcat_x2x((PXCHAR)Sdram_pDataCache, Sys_pRemoteNumber);
		p_strcat_char2x((PXCHAR)Sdram_pDataCache, '#');
		SdramWriteData(OPTIONS_SDRAM_POS+REMOTE_NUMBER_SDRAM_LO, p_strlen_x((PXCHAR)Sdram_pDataCache));

		if (p_strlen_x(Sys_pDialNumber))
		{
			p_strcpy_x2x(Sys_pRemoteNumber, Sys_pDialNumber);
		}
	}
}

