/*
  Copyright 2002-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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "codetable.h"
#include "ctfile.h"
#include "encode.h"

#define	MAX_CHAR_NUM_PER_LINE	80
#define	MAX_WORD_NUM_PER_LINE	30

CodeTableStruct hzCodeTable;

tableNode *nodeList;		/* all Nodes will be linearized to put here */
unsigned char *hzList;		/* all HZ codes will be put here */

unsigned int clen = 0;
unsigned char keystack[80];

char comment[MAX_COMMENT_LEN];
keyPrompt keyprompt[MAX_USEDCODES_NUM];
functionKey functionkey[MAX_FUNCTIONKEY_NUM];

typedef struct _str_int {
  char  *string;
  int   value;
} string_value_pair;

string_value_pair selectkeymode_str_val[] = {
  { NUMBER_MODE_STR, NUMBER_MODE },
  { LOWER_MODE_STR,  LOWER_MODE },
  { UPPER_MODE_STR,  UPPER_MODE },
  { NULL,            NUMBER_MODE }
};

int str2val(string_value_pair *str_val, char *str)
{
  while (str_val->string) {
    /*
      printf("%d: %s\n", str_val->value, str_val->string);
    */
    if (!strncasecmp (str_val->string, str, strlen(str_val->string)))
      return (str_val->value);
    str_val++;
  }
  return (str_val->value);
}

char *val2str(string_value_pair *str_val, int value)
{
  while (str_val->string) {
    /*
      printf("%d: %s\n", str_val->value, str_val->string);
    */
    if (str_val->value == value)
      return (str_val->string);
    str_val++;
  }
  return (str_val->string);
}

void PrintNodeList()
{
  int i;

  for (i=0; i<hzCodeTable.sizeNodeList; i++)
    {
      printf("id :%d\n", i);
      printf("key: %c\n", nodeList[i].key);
      printf("num_NextKeys: %d\n", nodeList[i].num_NextKeys);
      printf("num_HZchoice: %d\n", nodeList[i].num_HZchoice);
      printf("pos_NextKey: %d\n", nodeList[i].pos_NextKey);
      printf("pos_HZidx: %d\n", nodeList[i].pos_HZidx);
      printf("\n");
    }
}

void PrintTableInfo()
{
  int i;

  printf("Lname:%s\n", hzCodeTable.Lname);
  printf("Cname:%s\n", hzCodeTable.Cname);
  printf("WildChar:%s\n", hzCodeTable.WildChar);
  printf("UsedCodes:%s\n", hzCodeTable.UsedCodes);
  printf("MaxCodes:%d\n", hzCodeTable.MaxCodes);
  printf("Encode:%d\n", hzCodeTable.Encode);
  printf("sizeNodeList:%d\n", hzCodeTable.sizeNodeList);
  printf("sizeHZList:%d\n", hzCodeTable.sizeHZList);

  printf("key_prompt\n");
  for (i=0; i<MAX_USEDCODES_NUM; i++)
    {
      if (keyprompt[i].prompt[0])
	printf("%c:  %s\n", i, keyprompt[i].prompt);
    }

  printf("function_key\n");
  for (i=0; i<MAX_FUNCTIONKEY_NUM; i++)
    {
      if (functionkey[i].keylist[0])
	printf("%d:  %d\n", i, functionkey[i].keylist[0]);
    }

  comment[clen] = '\0';
  printf("comment is \n%s\n", comment);
}

/*
 * ReadInput -- read and parse input codetable binary format file
 */
static void ReadInput(ifile)
     FILE *ifile;
{
  char ctFlag[256];
  int  ver;

  /* Read CodeTable File Flag */
  if (fread (ctFlag, strlen(CODETABLE_FLAG), 1, ifile) != 1)
    {
      fprintf (stderr, "File read Error\n");
      exit(1);
    }

  if (strncmp (ctFlag, CODETABLE_FLAG, strlen(CODETABLE_FLAG)) != 0) {
    fprintf (stderr, "File is not in CodeTable format\n");
    exit(1);
  }

  /* Read CodeTable Version Flag */
  if (fread ((char *)(&ver), sizeof (int), 1, ifile) != 1) 
    {
      fprintf (stderr, "File read Error\n");
      exit(1);
    }

  if (ver != CODETABLE_VERSION)
    {
      fprintf (stderr, "File is not in correct Version Number\n");
      exit(1);
    }


  /* Read CodeTable Header Structure */
  if (fread (&hzCodeTable, sizeof(CodeTableStruct), 1, ifile) == 0) {
    fprintf (stderr, "File read Error\n");
    exit(1);
  }

  /* Read Node List and HanZi List */
  nodeList = (tableNode *) calloc(hzCodeTable.sizeNodeList,sizeof(tableNode));
  hzList = (unsigned char *) calloc(hzCodeTable.sizeHZList, sizeof(unsigned char));
  if ((! nodeList) || (! hzList)) {
    perror ("Memory allocation");
    exit (1);
  }

  if ((fread (nodeList, sizeof(tableNode), hzCodeTable.sizeNodeList, ifile)
       != hzCodeTable.sizeNodeList) ||
      (fread (hzList, sizeof(unsigned char), hzCodeTable.sizeHZList, ifile)
       != hzCodeTable.sizeHZList))
    {
      fprintf (stderr, "File Read Error\n");
      exit (1);
    }

  /* Read Key Prompt List */
  if (GETBIT(hzCodeTable.bSectionsFlag, KEYPROMPT_SECTION))
    {
      if ((fread ((char *)(&(keyprompt[0])), MAX_USEDCODES_NUM, sizeof(keyPrompt), ifile)) 
	  != sizeof(keyPrompt)) 
	{
	  fprintf (stderr, "File Read Error\n");
	  exit (1);
	}
    }

  /* Read Function Key List */
  if (GETBIT(hzCodeTable.bSectionsFlag, FUNCTIONKEY_SECTION))
    {
      if ((fread ((char *)(&(functionkey[0])), MAX_FUNCTIONKEY_NUM, sizeof(functionKey), ifile)) 
	  != sizeof(functionKey)) 
	{
	  fprintf (stderr, "File Read Error\n");
	  exit (1);
	}
    }

  /* Read Comment */
  if (GETBIT(hzCodeTable.bSectionsFlag, COMMENT_SECTION))
    {
      if ((fread ((char *)(&clen), sizeof (unsigned int), 1, ifile) != 1) ||
	  (fread (comment, 1, clen, ifile) != clen))
	{
	  clen = 0;
	}
      if (clen > MAX_COMMENT_LEN)
	clen = MAX_COMMENT_LEN;
    }
}

int check_if_duplicate(unsigned char *hzstr, int hzlen, 
		       unsigned char *whole_str, int word_num, int encode)
{
  int i, str_len;
  unsigned char *phz;

  phz = whole_str;
  for (i=0; i<word_num; i++) {
    if (*phz == HZ_PHRASE_TAG) {
      /* phrase */
      str_len = *(phz+1);
      phz += 2;
      if (str_len == hzlen) {
	if(!strncmp((char *)hzstr, (char *)phz, hzlen))
	  return(1);
      }
    } else {
      /* hanzi */
      str_len = get_char_len_by_encodeid(encode, phz);
      if (str_len == hzlen) {
	if(!strncmp((char *)hzstr, (char *)phz, hzlen))
	  return(1);
      }
    }

    phz += str_len;
  }

  return(0);
}

/* output line by line while traveling the tableNodes */
static void LineOut (top, nodeIdx, mode, ofile)
     int top;
     unsigned int nodeIdx;
     int mode;
     FILE *ofile;
{
  register tableNode *tnptr = &nodeList[nodeIdx];
  unsigned char *phz;
  int i, j, hzlen, encode, cnt, nSingle, nPhrase;
  int num;   /* number of choices under the key sequence in stack */
  int max_char_num, bDup, newline;

  keystack[top] = tnptr->key;
  num = tnptr->num_HZchoice;
  encode = hzCodeTable.Encode;

  /*
    printf("top:%d, key:%c, num_NextKeys:%d, num:%d\n", top, tnptr->key, tnptr->num_NextKeys, num);
  */
  /* if there are strings in this node */
  if (num > 0){
    /* there are HZs exclusively under the keys, or no more input keys */
		
    /* compute the Single HZ num and Phrase num in this string */
    nSingle = 0; 
    nPhrase = 0;
    phz = &hzList[tnptr->pos_HZidx];
    for ( i = 0; i < num; i++ )
      {
	if (*phz == HZ_PHRASE_TAG) {
	  phz += *(phz+1) + 2;
	  nPhrase ++;
	} else {
	  hzlen = get_char_len_by_encodeid(encode, phz);
	  phz += hzlen;
	  nSingle ++;
	}
      }

    if (mode == SINGLE_SECTION && nSingle == 0) return;
    if (mode == PHRASE_SECTION && nPhrase == 0) return;
 
    /* print Single HZ string or Phrase string */
    if (mode == SINGLE_SECTION)
      max_char_num = MAX_WORD_NUM_PER_LINE;
    else 
      max_char_num = MAX_CHAR_NUM_PER_LINE;

    cnt = 0;
    newline = 1;
    phz = &hzList[tnptr->pos_HZidx];
    for (i = 0; i < num; i++) {
      /* begin a new line */
      if (cnt >= max_char_num) {
	cnt = 0;
	newline = 1;
      }
      if (newline == 1) {
	register int j;

	/* print external code */
	(void) putc ('\n', ofile);
	for (j = 1; j <= top; j++) {
	  (void) putc (keystack[j], ofile);
	}
	(void) putc ('\t', ofile);
	newline = 0;
      }

      if (*phz == HZ_PHRASE_TAG) {
	/* phrase */
	hzlen = *(phz+1);
	phz += 2;
	if (mode == PHRASE_SECTION) {
	  bDup = check_if_duplicate(phz, hzlen, phz+hzlen, num-i-1, encode);
	  if(!bDup){
	    for (j = 0; j < hzlen; j++) {
	      (void) putc (*(phz+j), ofile);
	    }
	    (void) putc (' ', ofile);
	    cnt += hzlen;
	  }
	}
      } else {
	/* hanzi */
	hzlen = get_char_len_by_encodeid(encode, phz);

	if (mode == SINGLE_SECTION) {
	  bDup = check_if_duplicate(phz, hzlen, phz+hzlen, num-i-1, encode);
	  if(!bDup){
	    for (j = 0; j < hzlen; j++) {
	      (void) putc (*(phz+j), ofile);
	    }
	    cnt ++;
	  }
	}
      }
      phz += hzlen;
    }
  }

  for (i = 0; i < tnptr->num_NextKeys; i++)
    LineOut (top + 1, tnptr->pos_NextKey + i, mode, ofile);
}

/* convert key value to "^A" format or normal visible character */
static int Putc (ch, ofile)
     unsigned char ch;
     FILE *ofile;
{
  /*
    printf("ch:  0x%x, 0x%x, %c\n", ch, ch & 0x7f, ch & 0x7f);
  */

  if (ch & 0x80) {
    fprintf (ofile, " ^%c", ch & 0x7f);
  } else {
    (void) putc (ch, ofile);
  }
  return (1);
}

static void Output (ofile)
     FILE *ofile;
{
  int i;

  fprintf (ofile, "## HANZI codetable input table\n");

  /* description section */
  fprintf (ofile, "\n[ %s ]\n", DESCRIPTION_STR);
  fprintf (ofile, "%s\t\t%s\n", LOCALE_STR, hzCodeTable.Lname);
  fprintf (ofile, "%s\t\t%s\n", NAME_STR, hzCodeTable.Cname);
  fprintf (ofile, "%s\t\t%s\n", ENCODE_STR, (char *)get_name_from_encodeid(hzCodeTable.Encode));
  fprintf (ofile, "%s\t%s\n", USEDCODES_STR, hzCodeTable.UsedCodes);
  fprintf (ofile, "%s\t%s\n", WILDCHAR_STR, hzCodeTable.WildChar);
  fprintf (ofile, "%s\t%d\n", MAXCODES_STR, hzCodeTable.MaxCodes);
	
  /* Key_Prompt section */
  if (GETBIT(hzCodeTable.bSectionsFlag, KEYPROMPT_SECTION))
    {
      fprintf (ofile, "\n[ %s ]\n", KEYPROMPT_STR);
      for (i=0; i<MAX_USEDCODES_NUM; i++)
	{
	  if (keyprompt[i].prompt[0] != 0)
	    fprintf (ofile, "%c\t%s\n", i, keyprompt[i].prompt);
	}
    }

  /* Function_Key section */
  if (GETBIT(hzCodeTable.bSectionsFlag, FUNCTIONKEY_SECTION))
    {
      fprintf (ofile, "\n[ %s ]\n", FUNCTIONKEY_STR);
      if (functionkey[PAGEUP_KEY_ID].keylist[0] != 0)
	{
	  fprintf(ofile, "%s\t\t", PAGEUP_KEY_STR);
	  for (i=0; i<strlen(functionkey[PAGEUP_KEY_ID].keylist); i++)
	    Putc(functionkey[PAGEUP_KEY_ID].keylist[i], ofile);
	  fprintf(ofile, "\n");
	}

      if (functionkey[PAGEDOWN_KEY_ID].keylist[0] != 0)
	{
	  fprintf(ofile, "%s\t", PAGEDOWN_KEY_STR);
	  for (i=0; i<strlen(functionkey[PAGEDOWN_KEY_ID].keylist); i++)
	    Putc(functionkey[PAGEDOWN_KEY_ID].keylist[i], ofile);
	  fprintf(ofile, "\n");
	}

      if (functionkey[BACKSPACE_KEY_ID].keylist[0] != 0)
	{
	  fprintf(ofile, "%s\t", BACKSPACE_KEY_STR);
	  for (i=0; i<strlen(functionkey[BACKSPACE_KEY_ID].keylist); i++)
	    Putc(functionkey[BACKSPACE_KEY_ID].keylist[i],ofile);
	  fprintf(ofile, "\n");
	}

      if (functionkey[CLEARALL_KEY_ID].keylist[0] != 0)
	{
	  fprintf(ofile, "%s\t", CLEARALL_KEY_STR);
	  for (i=0; i<strlen(functionkey[CLEARALL_KEY_ID].keylist); i++)
	    Putc(functionkey[CLEARALL_KEY_ID].keylist[i],ofile);
	  fprintf(ofile, "\n");
	}
    }

  /* Options section */
  if (GETBIT(hzCodeTable.bSectionsFlag, OPTIONS_SECTION))
    {
      fprintf (ofile, "\n[ %s ]\n", OPTIONS_STR);
      if (hzCodeTable.nKeyByKeyMode)
	fprintf(ofile, "%s\t\t%s\n", KEYBYKEY_MODE_STR, OPTION_OPEN_STR);
      else
	fprintf(ofile, "%s\t\t%s\n", KEYBYKEY_MODE_STR, OPTION_CLOSE_STR);

      if (hzCodeTable.nHelpInfoMode)
	fprintf(ofile, "%s\t\t%s\n", HELPINFO_MODE_STR, OPTION_OPEN_STR);
      else
	fprintf(ofile, "%s\t\t%s\n", HELPINFO_MODE_STR, OPTION_CLOSE_STR);

      if (hzCodeTable.nAutoSelectMode)
	fprintf(ofile, "%s\t%s\n", AUTOSELECT_MODE_STR, OPTION_OPEN_STR);
      else
	fprintf(ofile, "%s\t%s\n", AUTOSELECT_MODE_STR, OPTION_CLOSE_STR);

      if (hzCodeTable.nKeyPromptMode)
	fprintf(ofile, "%s\t\t%s\n", KEYPROMPT_MODE_STR, OPTION_OPEN_STR);
      else
	fprintf(ofile, "%s\t\t%s\n", KEYPROMPT_MODE_STR, OPTION_CLOSE_STR);
      /*
	if (hzCodeTable.nDisplayOnSpotMode)
	fprintf(ofile, "%s\t%s\n", DISPLAYONSPOT_MODE_STR, OPTION_OPEN_STR);
	else
	fprintf(ofile, "%s\t%s\n", DISPLAYONSPOT_MODE_STR, OPTION_CLOSE_STR);
      */
      fprintf(ofile, "%s\t\t%s\n", SELECTKEY_MODE_STR, val2str(selectkeymode_str_val, hzCodeTable.nSelectKeyMode));
    }

  /* comment section */
  if (GETBIT(hzCodeTable.bSectionsFlag, COMMENT_SECTION))
    {
      if (clen > 0)
	{
	  fprintf (ofile, "\n[ %s ]\n", COMMENT_STR);
	  fprintf (ofile, "%s\n", comment);
	}
    }

  /* single hanzi section */
  if (GETBIT(hzCodeTable.bSectionsFlag, SINGLE_SECTION))
    {
      fprintf (ofile, "\n[ %s ]", SINGLE_STR);
      LineOut(0, 0, SINGLE_SECTION, ofile);
      fprintf (ofile, "\n");
    }

  /* phrase section */
  if (GETBIT(hzCodeTable.bSectionsFlag, PHRASE_SECTION))
    {
      fprintf (ofile, "\n[ %s ]", PHRASE_STR);
      LineOut(0, 0, PHRASE_SECTION, ofile);
      fprintf (ofile, "\n");
    }
}

int main(argc, argv)
     int argc;
     char *argv[];
{
  FILE *ifile, *ofile;
  char *inputfile_name = "wbtest.txt";
  char *outputfile_name = "test.data";

  if (argc != 3)
    {
      printf("%s inputfile outputfile\n", argv[0]);
      exit(0);
    }

  inputfile_name = argv[1];
  outputfile_name = argv[2];

  /*
    printf("Begin converting from binary file to text file:\n");
    printf("Binary file:%s\nText file:%s\n",inputfile_name, outputfile_name);
  */

  ifile = fopen(inputfile_name, "r");
  if (! ifile) 
    {
      perror(inputfile_name);
      exit(1);
    }

  ofile = fopen(outputfile_name, "w+");
  if (! ofile) 
    {
      fclose(ifile);
      exit(1);
    }

  ReadInput(ifile);
  fclose(ifile);

  /*
    PrintTableInfo();
    PrintNodeList();
  */

  Output(ofile);
  fclose(ofile);

  /*
    printf("Completed converting from binary file to text file\n");
  */
  exit(0);
}

