#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "chinese.h"
static char pbuf[1024];
InputHead head;

main(int argc,char *argv[])
{
  FILE *infile,*outfile;
  int i,kk;
  char c;

  if (argc < 2)
    {
      printf("Usage : mkmulti <def file> <tbl file>\n");
      exit(-1);
    }
  
  infile = fopen(argv[1],"r");
  outfile = fopen(argv[2],"wb");
  if (infile == NULL)
    {
      printf("Definition file %s not exist\n",argv[1]);
      exit(-1);
    }
  if (outfile == NULL)
    {
      printf("Can't open %s table file\n",argv[2]);
      exit(-1);
    }
  /* section 1 */
  while(!feof(infile))
    {
      fgets(pbuf,1024,infile);
      if (strncmp(pbuf,"%%",2) == 0)
	break;
      else if (strncmp(pbuf,"bell",4) == 0)
	head.bell = 1;
      else if (strncmp(pbuf,"full",4) == 0)
	head.full = 1;
      else if (strncmp(pbuf,"mark",4) == 0)
	{
	  char *bb = strchr(pbuf,'[');
	  char *be = strchr(bb,']');
	  *be = 0;
	  strncpy(head.mark,bb,6);
	}
      else
	{
	  printf("Line is invalid\n");
	  printf(pbuf);
	}
    }
  /* section 2 */
  memset(head.cmap.chkey,0,512);    
  memset(head.keymap,255,256);
  memset(head.mapkey,255,256);
  while(fgets(pbuf,1024,infile))
    {
      if (strncmp(pbuf,"%%",2)==0)
	break;
      kk = 0;
      while(pbuf[kk]!=' '&& pbuf[kk] != '\t' && pbuf[kk] && pbuf[kk] != '\n' ) 
	kk++;
      memcpy(&head.cmap.CHKEY[*pbuf],pbuf+1,kk-1);
    }
  kk = 0;
  for(i=0;i<256;i++)
    {
      while(head.cmap.CHKEY[kk] == 0 && kk < 256) kk++;
      if (kk == 256)
	break;
      head.keymap[i] = kk;
      head.mapkey[tolower(kk)]=i;
      head.mapkey[toupper(kk)]=i;
      head.cmap.CHKEY[i] = head.cmap.CHKEY[kk];
      kk++;
    }
  for(;i<256;i++)
    head.cmap.CHKEY[i] = 0;
  for(i=0;i<256;i++)
    {
      c=head.cmap.chkey[i*2];
      head.cmap.chkey[i*2] = head.cmap.chkey[i*2+1];
      head.cmap.chkey[i*2+1]=c;
    }
  fwrite((char *)&head,sizeof(InputHead),1,outfile);
  /* section 3 */
  while(fgets(pbuf,1024,infile))
    {
      WordMap mm;
      if (strncmp(pbuf,"%%",2) == 0)
	break;
      /* If the first char in a line is blank,we think it as comment */
      if (isspace(*pbuf))
	continue;
      memset(mm.seqs,255,4);
      for(i=0;i<4;i++)
	{
	  if (pbuf[i]!= ' ')
	    mm.seqs[i] = head.mapkey[pbuf[i]];
	  else
	    break;
	  
	}
      while(pbuf[i] == ' ') i++;
      mm.word.code[1] = pbuf[i];
      mm.word.code[0] = pbuf[i+1];
      fwrite(&mm,sizeof(WordMap),1,outfile);
      printf("%2s ---> {%d,%d,%d,%d}\n",mm.word.code,
	     mm.seqs[0],
	     mm.seqs[1],
	     mm.seqs[2],
	     mm.seqs[3]);
      
    }
  fclose(infile);
  fclose(outfile);
}
	  
	  
	  





