/*
Copyright 1990-2003 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/

#include "PYIM.h"
#include <assert.h>
#include <sys/utsname.h>

SesGuiElement* pSge[512];
SesGuiElement* pCurSge;

JINT GetNextLine(FILE* pfFile, CHAR* szBuf);

ImToXSun*  IM_trans(JINT nSesID, JINT nXKey, JINT nAsciiKey, JINT nSpecKey);
ImToXSunChar*  ConvImToXSun(ImToXSun* pIeh);
ImToXSun*      ImTrans(JINT nSesID, JINT* pKsThis, JINT nSpecKeyState);
VOID    JwordInfo(JWORD* pwJwordArray, JINT nMaxLen);
VOID    Jword2Uchar(JWORD* pwJword, UCHAR* szUch, JINT nMaxLen);
JINT    JwordValidLen(JWORD* pwJwordArray, JINT nMaxLen);
VOID    ProcFreq(SesGuiElement* pSge);
VOID    ProcUdCizu(SesGuiElement* pSge);
VOID    IM_close(JINT nSesID);

VOID    InitSge(SesGuiElement* pSgeStruct);
VOID    IehReturn(ImToXSun* pieh, JINT nCaseFlag);
JINT    IsQuitKeysym(JINT *pks);
JINT    IsQpSpSwitchKeysym(JINT *pks);
JINT    IsWantedKeysym(JINT *pks);
JINT    IsPyKeysym(JINT *pks);
JINT    IsPageKeysym(JINT *pks);
JINT    IsSelectKeysym(JINT *pks);
JWORD   GetQuanjiaoSymbol(JINT *pks, JINT IsChnPunc, JINT IsChnAscii);

VOID    ProcAllKeysym(JINT* pKsThis, SesGuiElement* pSge);
VOID    DrawImToXSun(ImToXSun* pIeh, SesGuiElement* pSge);
VOID    GetIehFromSge(ImToXSun* pIeh, SesGuiElement* pSge);
VOID    GetLookupChoiceFromCandi(ImToXSun* pIeh, JWORD* pwCandi);

/* CikuOper.c */
JINT    GetCikuData(CHAR* szSysCikuName);
JINT    WriteCikuData(CHAR* szSysCikuName, JINT nTimeStamp);
VOID    FreePckAll();
VOID    InitStructSc(SysCandi* psc);
VOID    AdjustFreq(JWORD* pwHz2244, JINT nLenThis);

/* UdCikuOper.c */
VOID	InitStructUc(UdcCandi* puc);
JINT    ReadUdcData(CHAR* szUdcName);
JINT    WriteUdcData(CHAR* szUdcName, JINT nTimeStamp);
JINT    AddUdc(JWORD* pwHz2244, JINT nLen);
JINT    DelUdc(JWORD* pwHz2244, JINT nLen);
JINT    PureUdc(VOID);
VOID    FreeUdcData();

VOID    ProcSymbIMKey(SesGuiElement* pSge, JINT nSymbType, JINT *pNextKeysym, ImToXSun *pIeh);

extern  BYTE      *pCkAll;      /* Defined in file "CikuOper.c" */
extern  UdcMemAll  udcAll;      /* Defined in file "UdCikuOper.c" */

#define PUNCTUATION_STATUS    1
#define SOFTKEYBOARD_LAYOUT   2

#define SKB_QUANPIN           0
#define SKB_SPZRM             1
#define SKB_SPCSTAR           2
#define SKB_SPABC             3

#define  SKB_SYMBSCIENT     0
#define  SKB_SERIESONE      1
#define  SKB_SERIESTWO      2
#define  SKB_SERIESTHREE    3
#define  SKB_SERIESFOUR     4
#define  SKB_GREECE         5
#define  SKB_RUSSIAN        6
#define  SKB_PYSYM          7
#define  SKB_JAPPIN         8
#define  SKB_JAPPIAN        9
#define  SKB_TABSYMB        10
#define  SKB_GBKEXTSYM1     11
#define  SKB_GBKEXTSYM2     12
#define  SKB_HALFWID        13
#define  SKB_FULLWID        14

#define  PUNCT_CHINESE      0
#define  PUNCT_ENGLISH      1

JINT      nGlobalSpMode;      /* ZRM, CStar, ABC */
/*
ImToXSunChar* Aux_SetPuncSkb(JINT nSesID, JINT nWhichBmp, JINT nBmpValue)
{
	JINT    nTmp;
	ImToXSunChar*   pImxsun;
	JINT    nPunctMode;
	
	if (pSge[nSesID] == NULL)
	{
		printf("Invalid nSesID in Aux_SetPuncSkb().\n");
		return NULL;
	}
	
	if ((nWhichBmp == PUNCTUATION_STATUS) && (nBmpValue >= 0) && (nBmpValue <= 1))
		nPunctMode = pSge[nSesID]->nPunctMode  = nBmpValue;
	else if ((nWhichBmp == SOFTKEYBOARD_LAYOUT) && (nBmpValue >= 0) && (nBmpValue <= 14))
	{
		nPunctMode = pSge[nSesID]->nPunctMode;
		if ((nBmpValue == 13) || (nBmpValue == 14))
		{
			nTmp = pSge[nSesID]->nPunctMode;
			InitSge(pSge[nSesID]);
			pSge[nSesID]->nPunctMode = nTmp;
		}
		pSge[nSesID]->nKeyLayMode = nBmpValue;
	}
	else
		printf("Invalid nWhichBmp[%d] or nBmpValue[%d]\n", nWhichBmp, nBmpValue);
	
	pImxsun = IM_trans (nSesID, (JINT)IMXK_Clear, (JINT)IMXK_Clear, 0);
	pSge[nSesID]->nPunctMode = nPunctMode;
	return (pImxsun);
}
*/

VOID IM_close (JINT nSesID)
{
	IM_trans (nSesID, (JINT)IMXK_QUIT_PYIM, (JINT)IMXK_QUIT_PYIM, 0);
}

ImToXSun* NewZY_open(JINT nSesID)
{
	static JINT    nCheckSpMode = FALSE;
	
/*	strcpy(pszModeName, "新注音\0\0");*/
	nGlobalSpMode = KEYLAYMODE_NEWPY;

	return((ImToXSun*)NewZY_trans(nSesID, (JINT)IMXK_Escape, (JINT)IMXK_Escape, 0));
}

ImToXSun* IM_trans(JINT nSesID, JINT nXKey, JINT nAsciiKey, JINT nSpecKeyState)
{
	JINT    i;
	JINT    ksThis[5];
	JINT    nSpecKey;

	for(i = 0; i < 5; i++)
		ksThis[i] = 0x00000000;
	if ((nAsciiKey >= 0x20) && (nAsciiKey <= 0x7E)) {
		ksThis[0] = nAsciiKey;
	} else
		ksThis[0] = nXKey;
	
	/* PATCH for ^p and ^n: Scott Ma: 98-04-28 */
	nSpecKey = nSpecKeyState;
	if ((nAsciiKey == 0x000e) && (nSpecKeyState == 4))
	{
		ksThis[0] = (JINT)IMXK_MOUSENEXT;
		nSpecKey  = 0;
	}
	if ((nAsciiKey == 0x0010) && (nSpecKeyState == 4))
	{
		ksThis[0] = (JINT)IMXK_MOUSEPREV;
		nSpecKey  = 0;
	}
	
	bShiftIsPressed  = (JSHORT)((nSpecKey & SPEC_KEY_SHIFT)    / SPEC_KEY_SHIFT);
	bCapsIsPressed   = (JSHORT)((nSpecKey & SPEC_KEY_CAPSLOCK) / SPEC_KEY_CAPSLOCK); /* ??? Not Certain. MXL */
	bCapsIsPressed   = (JSHORT)0;
	bCtrlIsPressed   = (JSHORT)((nSpecKey & SPEC_KEY_CONTROL)  / SPEC_KEY_CONTROL);
	bAltIsPressed    = (JSHORT)((nSpecKey & SPEC_KEY_ALT)      / SPEC_KEY_ALT);
	bAltGrIsPressed  = (JSHORT)((nSpecKey & SPEC_KEY_ALTGRAPH) / SPEC_KEY_ALTGRAPH);
	bCompIsPressed   = (JSHORT)((nSpecKey & SPEC_KEY_COMPOSE)  / SPEC_KEY_COMPOSE);  /* ??? Not Certain. MXL */
	bCompIsPressed   = (JSHORT)0;
	bMetaIsPressed   = (JSHORT)((nSpecKey & SPEC_KEY_DIAMOND)  / SPEC_KEY_DIAMOND);

	return ( ImTrans(nSesID, ksThis, nSpecKey) );
}


ImToXSun* ImTrans(JINT nSesID, JINT* pKsThis, JINT nSpecKeyState)
{
	JINT    i, nLen, nTmpRes, nTmp1, nTmp2;
	static  ImToXSun ieh;
	static  JINT     nActiveSesNum = 0;
	static  JINT     pnSesIDArray[512];
	CHAR*   pszHome;
	CHAR    szPath[128];
#if 0
	struct utsname  unstr, *un;
#else
	int     endian;
#endif
	
	JWORD   wPuncAscii;      /* For Chinese Punctation and Alpha Char */
	JINT    FlagChnPunc, FlagChnAscii;

	/* since iiim sets conversion off at first to get the status string,
	   but this cause some error in newpy. So return a special struct in 
	   this case. 
	*/

	if((nActiveSesNum == 0) && IsQuitKeysym(pKsThis)) {
		IehReturn(&ieh, QUIT_THIS_IM);
		return (&ieh);
	}

	/* 
	** 在正式版本中, 應該先讀szSysCikuBak & szUdcCikuBak, 
	** 如果失敗, 再讀szSysCiku & szUdcCiku!!      MXL 97-12-14
	*/
	if (pCkAll == NULL)
	{
#if 0
        	un = &unstr;
        	(void) uname(un);
		if(strcmp(un->machine,"i86pc") ==0)
			nArch=TRUE;
		else nArch=FALSE;
#else
		endian = 1;
		if (*(char *)&endian)
			nArch = TRUE;
		else
			nArch = FALSE;
#endif

		sprintf(szPath, "%s/%s", CIKU_DATA_PATH, szSysCiku_Big5);
		nTmpRes = GetCikuData(szPath);
		if (nTmpRes == FALSE) {
			fprintf (stderr, "IME Error: Failed to Open System Ciku < ZySysCiku.dat >\n");
			return NULL;
		}

		/* Read in UdCiku.dat Data */
		sprintf(szPath, "%s/%s", CIKU_DATA_PATH, szUdCiku_Big5);
		nTmpRes = ReadUdcData(szPath);
		if (nTmpRes == FALSE) {
			fprintf (stderr, "IME Error: Failed to Open User Defined Ciku < ZyUdCiku.dat >\n");
			return NULL;
		}
	}

	if (nActiveSesNum == 0)
	{
		for (i = 0; i < MAX_SES_NUM; i++)
			pnSesIDArray[i] = 0x0000;
	}
	
	if (pnSesIDArray[nSesID] == 0x0000)	/* New Session */
		nActiveSesNum++;
	
	if (nActiveSesNum > MAX_SES_NUM)	/* Return: Too many sessions */
	{
		nActiveSesNum--;
		IehReturn(&ieh, TOO_MANY_SESSION);
		return (&ieh);
	}

	if (pnSesIDArray[nSesID] == 0x0000)	/* New Session */
	{
		pnSesIDArray[nSesID] = (0xF000 + nSesID);
		pSge[nSesID] = (SesGuiElement*) malloc(sizeof(SesGuiElement));
		if (pSge[nSesID] == NULL)
		{
			IehReturn(&ieh, FAILED_ALLOC_MEM);    /* Failed to Alloc Memory */
			pnSesIDArray[nSesID] = 0x0000;
			nActiveSesNum--;
			return (&ieh);
		}
		pSge[nSesID]->scSysCandi.pwMhCandi  = NULL;
		pSge[nSesID]->scSysCandi.pwDhCandi  = NULL;
		pSge[nSesID]->scSysCandi.pwShCandi  = NULL;
		pSge[nSesID]->scSysCandi.pwGbkCandi = NULL;
		pSge[nSesID]->ucUdcCandi.pwUdc28Candi = NULL;
		InitSge(pSge[nSesID]);
	}
	pCurSge = pSge[nSesID];
	
	if (IsQuitKeysym(pKsThis))
	{
		/* Free Space Occupied by struct SysCandi */
		free (pSge[nSesID]->scSysCandi.pwMhCandi);
		free (pSge[nSesID]->scSysCandi.pwDhCandi);
		free (pSge[nSesID]->scSysCandi.pwShCandi);
		free (pSge[nSesID]->scSysCandi.pwGbkCandi);
		free (pSge[nSesID]->ucUdcCandi.pwUdc28Candi);

		pSge[nSesID]->scSysCandi.pwMhCandi  = NULL;
		pSge[nSesID]->scSysCandi.pwDhCandi  = NULL;
		pSge[nSesID]->scSysCandi.pwShCandi  = NULL;
		pSge[nSesID]->scSysCandi.pwGbkCandi = NULL;
		pSge[nSesID]->ucUdcCandi.pwUdc28Candi = NULL;
		
		free (pSge[nSesID]);
		pSge[nSesID] = NULL;
		pnSesIDArray[nSesID] = 0x0000;
		nActiveSesNum--;
		IehReturn(&ieh, QUIT_THIS_IM);	/* Application Quit or Switch to other IM */
		
		/*
		**  If nActiveSesNum == 0, means No any Application is still using this IM, SO,
		**  Must Write these Adjuested Ciku Data back to File!!!!
		*/
		if(nActiveSesNum == 0)
		{
			FreePckAll();
			pCkAll = NULL;
			FreeUdcData();
		}
		return (&ieh);
	}
	
	else if (IsQpSpSwitchKeysym(pKsThis))
	{
		nQpSpFlag[nSesID] = 1 - nQpSpFlag[nSesID];
		IehReturn(&ieh, SWITCH_BEWTEEN_QPSP);     /* Application Quit or Switch to other IM */
		
		/* Initialize pSge[nSesID] */
		InitSge(pSge[nSesID]);
		return (&ieh);
	}
	
	else if (IsWantedKeysym(pKsThis))
	{
		if ((pCurSge->nKeyLayMode >= 0) && (pCurSge->nKeyLayMode <= 12))
		{
			ProcSymbIMKey(pCurSge, pCurSge->nKeyLayMode, pKsThis, &ieh);
#ifdef _DRAW_IM_WIN_H
			DrawImToXSun(&ieh, pCurSge);
			if (ieh.nType == IMXSUN_TYPE_COMMITSYMBOL)
				JwordInfo(ieh.pwCommit, 256);
#endif
			return (&ieh);
		}
		
		/*
		**  Determine if this keySym is really valid for current pSge enviroment (GUI Logic).
		**  If NO, return!!
		**  Some KeySyms that is not useful during PYIM's Input GUI Logic,
		**       although that is defined in IsWantedkeysym().
		**       IMXSUN_TYPE_BOUNCEKEY 0x0002 was defined in file CmSo.h
		*/
		
		/* NULL in preedit line, enter symbol now */
		if ( (JwordValidLen(pCurSge->pwMixPeStr, UONE) == 0)  && 
			((pCurSge->nKeyLayMode == SKB_HALFWID) || (pCurSge->nKeyLayMode == SKB_FULLWID)) &&
			(((pKsThis[0] >= 0x20) && (pKsThis[0] <= 0x7E)) || (pKsThis[0] == IMXK_Clear)) )
		{
			if (pKsThis[0] == IMXK_Clear)			
			{
				nTmp1 = pCurSge->nPunctMode;
				nTmp2 = pCurSge->nKeyLayMode;
				InitSge(pCurSge);
				pCurSge->nPunctMode  = nTmp1;
				pCurSge->nKeyLayMode = nTmp2;
				
				pCurSge->nPrevKeyLayMode = pCurSge->nKeyLayMode;

				memset(&ieh, 0x00, sizeof(ImToXSun));
				ieh.nType = IMXSUN_TYPE_NORMAL;
#ifdef _DRAW_IM_WIN_H
				DrawImToXSun(&ieh, pCurSge);
#endif
				return (&ieh);
			}
				
			pCurSge->nPrevKeyLayMode = pCurSge->nKeyLayMode;
			if (pCurSge->nPunctMode == PUNCT_CHINESE)
				FlagChnPunc = TRUE;
			else 
				FlagChnPunc = FALSE;
				
			if (pCurSge->nKeyLayMode == SKB_FULLWID)
				FlagChnAscii = TRUE;
			else
				FlagChnAscii = FALSE;

			wPuncAscii = GetQuanjiaoSymbol(pKsThis, FlagChnPunc, FlagChnAscii);
			if (wPuncAscii != 0x0000)
			{
				ieh.nType = IMXSUN_TYPE_COMMIT;
				memset(ieh.pwCommit, 0x00, sizeof(JWORD) * UONE);
				ieh.pwCommit[0] = wPuncAscii;
#ifdef _DRAW_IM_WIN_H
				JwordInfo(ieh.pwCommit, 256);
#endif
				return (&ieh);
			}
		}
		
#ifndef _DRAW_IM_WIN_H
		if(   bCapsIsPressed  || bCtrlIsPressed || bAltIsPressed  ||
		      bAltGrIsPressed || bCompIsPressed || bMetaIsPressed || 
		    ( (JwordValidLen(pCurSge->pwMixPeStr, UONE) == 0) && 
		      ( (IsPageKeysym(pKsThis)) || (IsSelectKeysym(pKsThis)) || (!IsPyKeysym(pKsThis)) )
		    )
		  )
		{
			ieh.nType = IMXSUN_TYPE_BOUNCEKEY;
			return (&ieh);
		}
#endif
		
		pCurSge->nErrorCode = 0;                /* Clear All Error Message before a KeySym */
		ieh.nType   = IMXSUN_TYPE_NORMAL;
		for(i = 0; i < UONE; i++)
			pCurSge->pwCommit[i] = ieh.pwCommit[i] = 0x0000;
		
		ProcAllKeysym(pKsThis, pCurSge);
		
		/*
		**  Determine if there is any other English chars in the end of pwMixPeStr[256].
		**  If there is no char lefted, indicates all is committed, pass it to IMToXSun,
		**  and InitSge(pCurSge) again. 
		**
		**  If pwMixPeStr[nLen - 1] is ['], How to deal it???
		**
		**  To create User defined Cizu HERE!!! Only after a committment.   97.11.08 MXL
		*/
		nLen = JwordValidLen(pCurSge->pwMixPeStr, 256);
		if (pCurSge->pwMixPeStr[nLen - 1] >= 0x8140)	 /* First Char defined in GBK */
		{
			for (i = 0; i < UONE; i++)
				pCurSge->pwCommit[i] = ieh.pwCommit[i] = 0x0000;
			for (i = 0; i < nLen; i++)
			{
				/*
				** The following line was commented ONLY Because For SUN's HTT!!
				pCurSge->pwCommit[i] = pCurSge->pwMixPeStr[i];
				*/
				ieh.pwCommit[i] = pCurSge->pwMixPeStr[i];
			}
			ieh.nType = IMXSUN_TYPE_COMMIT;
			ProcFreq(pCurSge);
			ProcUdCizu(pCurSge);
			
			nTmp1 = pCurSge->nPunctMode;
			InitSge(pCurSge);
			pCurSge->nPunctMode = nTmp1;
			GetIehFromSge(&ieh, pCurSge);
		}
		else
		{
			GetIehFromSge(&ieh, pCurSge);
		}

		return (&ieh);
	}
	
	/*
	**  Bounce Other KeySym which is not in the range of above wanted key.
	*/
	else
	{
		ieh.nType = IMXSUN_TYPE_BOUNCEKEY;  /* In CmSo.h:  IMXSUN_TYPE_BOUNCEKEY 0x0002 */
		return (&ieh);
	}
}


/*
**  Process Specific case.  *** This Function is to be rearranged Later.
*/
VOID IehReturn (ImToXSun* pIeh, JINT nCaseFlag)
{
	JINT   i, j;
	
	pIeh->nType      = IMXSUN_TYPE_ERROR;
	pIeh->nErrorCode = nCaseFlag;

	if (nCaseFlag == SWITCH_BEWTEEN_QPSP)
		pIeh->nCaretPos = 0;
	else
		pIeh->nCaretPos = -1;

	for (i = 0; i < 128; i++)
		pIeh->pwPreedit[i] = 0x0000;
	for (i = 0; i < 8; i++)
		for (j = 0; j < 24; j++)
			pIeh->pwLookupChoice[i][j] = 0x0000;
	pIeh->nChoiceNum  = 0;
	pIeh->nTotalSingleHzNum  = 0;
	pIeh->nTotalPhraseNum  = 0;
	pIeh->nCandiStart  = 0;
}


/*
**  Initialize / Reset / Clear SesGuiElement Structure.
*/
VOID InitSge(SesGuiElement* pSgeStruct)
{
	JINT    i;
	
	pSgeStruct->nSpRawCaretPos    = 0;

	for (i = 0; i < 40; i++)
		pSgeStruct->pwSpRawPyStr[i]  = 0x0000;
	for (i = 0; i < UONE; i++)
		pSgeStruct->pwSpMixPeStr[i]  = 0x0000;
	for (i = 0; i < UTWO; i++)
		pSgeStruct->pwSpSlctRawPy[i] = 0x0000;
	
	for (i = 0; i < UONE; i++)
	{
		pSgeStruct->pwRawPyStr[i]    = 0x0000;
		pSgeStruct->pwMixPeStr[i]    = 0x0000;
		pSgeStruct->nPrsPyYjCode[i]  = 0;
		pSgeStruct->pwCommit[i]      = 0x0000;
	}
	
	for (i = 0; i < UTWO; i++)
	{
		pSgeStruct->pwPrsPyStr[i]    = 0x0000;
		pSgeStruct->pwPrsMixStr[i]   = 0x0000;
		pSgeStruct->pwSlctHz[i]      = 0x0000;
		pSgeStruct->pwSlctRawPy[i]   = 0x0000;
	}
	
	for (i = 0; i < UHLF; i++)
	{
		pSgeStruct->pwViewPe[i]      = 0x0000;
		pSgeStruct->pwViewCandi[i]   = 0x0000;
	}
	
	pSgeStruct->nPinyinType       = -1;
	pSgeStruct->nPrevKeyLayMode   = 13;
	pSgeStruct->nKeyLayMode       = 13;    /* SKB_HALFWID: 13 */
	pSgeStruct->nPunctMode        = 0;    /* PUNCT_CHINESE: 0 */
	
	pSgeStruct->nRawCaretPos      = 0;
	pSgeStruct->nViewCaretPos     = 0;
	pSgeStruct->nViewPage         = 0;
	pSgeStruct->nViewPeStart      = 0;
	pSgeStruct->nViewPeEnd        = 0;
	pSgeStruct->nViewCandiStart   = 0;
	pSgeStruct->nViewCandiEnd     = 0;
	pSgeStruct->nSlctSteps        = 0;

	for (i = 0; i < 16; i++)
		pSgeStruct->pwStatus[i]   = 0x0000;
	pSgeStruct->nErrorCode        = 0;

	pSgeStruct->nIconFlag = F_HALFWIDTH | F_SETUP;
	
	InitStructSc(&(pSgeStruct->scSysCandi));
	InitStructUc(&(pSgeStruct->ucUdcCandi));

	/* The following 3 items were added to Fix Bug 4165549: Scott Ma, 12/8, 1998 */
	pSgeStruct->nPrevMatchMode       = -1;
	for (i = 0; i < 9; i++)
	{
		pSgeStruct->pnCurChoiceYjNew[i] = 1;
		pSgeStruct->pnCurChoiceYjOld[i] = 0;
	}
}


/*
**  Get these Common Part of struct Ieh from struct Sge.
**  Notes that these different part is not filled in this function.
**  Include:   i)   nType          ii)    szCommittString
**             iii) szBounceKey    iv)    Error Code
*/
VOID GetIehFromSge(ImToXSun* pIeh, SesGuiElement* pSge)
{
	JINT   i, j;
	
	for (i = 0; i < 128; i++)
		pIeh->pwPreedit[i] = pSge->pwViewPe[i];
		
	pIeh->nCaretPos  = pSge->nViewCaretPos;
	
	pIeh->nChoiceNum = pSge->nViewCandiEnd - pSge->nViewCandiStart;
	for (i = 0; i < 8; i++)
		for (j = 0; j < 24; j++)
			pIeh->pwLookupChoice[i][j] = 0x0000;
	
	GetLookupChoiceFromCandi(pIeh, pSge->pwViewCandi);
	
	for (i = 0; i < 16; i++)
		pIeh->pwStatus[i] = pSge->pwStatus[i];
	
	/* Because nErrorCode was cleared before each new KeySym Process */
	if (pSge->nErrorCode != 0)
	{
		pIeh->nType = IMXSUN_TYPE_ERROR;
		pIeh->nErrorCode = pSge->nErrorCode;
	}

	pIeh->nTotalSingleHzNum = pSge->scSysCandi.nNumShCandi;
	pIeh->nCandiStart = pSge->nViewCandiStart;

	pIeh->nTotalPhraseNum = pSge->scSysCandi.nNumMhCandi + pSge->scSysCandi.nNumDhCandi  +
                                pSge->ucUdcCandi.nNumSpecCandi + pSge->ucUdcCandi.nNumUdc28Candi;
/*
	printf("pIeh->nTotalPhraseNum = %d\n", pIeh->nTotalPhraseNum);
	printf("nNumShCandi = %d\n", pSge->scSysCandi.nNumShCandi);
	printf("nViewCandiStart = %d\n", pSge->nViewCandiStart);
*/
}


VOID GetLookupChoiceFromCandi(ImToXSun* pIeh, JWORD* pwCandi)
{
	JINT    i, j, k, nLen;
	JINT    nbStartCandi;
	
	nLen = JwordValidLen(pwCandi, 128);
	
	i = j = k = nbStartCandi = 0;
	for (i = 0; i < nLen; i++)
	{
		if (pwCandi[i] >= 0x8140)	/* First Hanzi in GBK */
		{
			nbStartCandi = 1;
			pIeh->pwLookupChoice[j][k++] = pwCandi[i];
			while(pwCandi[++i] >= 0x8140)
				pIeh->pwLookupChoice[j][k++] = pwCandi[i];
			j++;
			k = 0;
			nbStartCandi = 0;
		}
	}
	pIeh->nChoiceNum = j;
}


/*
**  Convert from Struct ImToXSun to Struct ImToXSunChar
*/
ImToXSunChar* ConvImToXSun(ImToXSun* pIeh)
{
	JINT   i, j, nHz;
	JINT   nNumDollar;   /* Number of Numsign and Dollar before Caret */
	static ImToXSunChar  iehc;
	
	for (i = 0; i < 256; i++)
		iehc.szPreedit[i]   = '\0';
		
	for (i = 0; i < 10; i++)
		for (j = 0; j < 48; j++)
			iehc.szLookupChoice[i][j] = '\0';
			
	for (i = 0; i < 512; i++)
		iehc.szCommit[i]    = '\0';
		
	for (i = 0; i < 32; i++)
		iehc.szStatus[i]    = '\0';
		
	/* One Hanzi is  2 Bytes */
	nHz = 0;
	for (i = 0; (pIeh->pwPreedit[i] >= 0x8140); i++)
		nHz++;
		
	iehc.nType        = pIeh->nType;
	iehc.nErrorCode   = pIeh->nErrorCode;
	iehc.nChoiceNum   = pIeh->nChoiceNum;
	iehc.nLabelType   = LABELTYPE_1234567;
	
	nNumDollar = 0;
	j = 0;
	for (i = 0; pIeh->pwPreedit[i] != 0x0000; i++)
	{
		if ((pIeh->pwPreedit[i] != (JWORD)'#') && (pIeh->pwPreedit[i] != (JWORD)'$'))
		{
			pIeh->pwPreedit[j++] = pIeh->pwPreedit[i];
		}
		else  /* '#' and '$' before pIeh->nCaretPos should be counted!! */
		{
			if (i < pIeh->nCaretPos)
				nNumDollar ++;
		}
	}
	for (; j < 128; j++)
		pIeh->pwPreedit[j++] = 0x0000;
	
	iehc.nCaretPos    = pIeh->nCaretPos + nHz - nNumDollar;
	
	Jword2Uchar(pIeh->pwPreedit, iehc.szPreedit, 128);
	Jword2Uchar(pIeh->pwCommit,  iehc.szCommit,  256);
	Jword2Uchar(pIeh->pwStatus,  iehc.szStatus,   16);
	
	for(i = 0; i < 8; i++)
		Jword2Uchar(pIeh->pwLookupChoice[i], iehc.szLookupChoice[i],  24);
	
	return (&iehc);
}

JINT GetNextLine(FILE* pfFile, CHAR* szBuf)
{
	JINT    i = 0;
	
	do
	{
		fread (&szBuf[i], 1, 1, pfFile);
		i ++;
	} while (!feof(pfFile) && (szBuf[i-1] != 0x0A));
	
	szBuf[i-1] = '\0';
	if ((i >= 2) && (szBuf[i-2] == 0x0D))
		szBuf[i-2] = '\0';
	
	if (!feof(pfFile))
		return 1;
	else
		return 0;
}
