#include <stdio.h>
#include <fcntl.h>
/* 
#include <hzinput.h>
#include "safestring.h"
*/
hz_input_table *cur_table;
char str[80];
char key[20];
 
static void load_phr( int j, char *tt, int n )
{
  FILE *fp = cur_table->PhraseFile;
  int ofs[2], len;
  int phrno =  (int)cur_table->item[j].ch;

  fseek( fp, ( phrno + 1 ) * 4, SEEK_SET );
  fread( ofs, 4, 2, fp );
  len = ofs[1] - ofs[0];

  if (len > n) {
      fprintf(stderr, "buffer overrun: %d > %d\n", len, n);
      abort();
  }
  if ( len > 128 || len <= 0 ) {
     printf("phrase error %d\n" , len );
     strcpy( tt, "err" );
     return;
  }

  ofs[0] += ( cur_table->PhraseNum + 1 ) * 4;
   /* Add the index area length */
  fseek( fp, ofs[0], SEEK_SET );
  fread( tt, 1, len, fp );
  tt[len] = 0;
}

int main(int argc, char **argv)
{
  FILE *fd, *fw;
  int i,j,nread;
  hz_input_table *table;
  char fname[FILENAME_MAX+1], fname_cin[FILENAME_MAX+1],
       fname_tab[FILENAME_MAX+1], fname_phr[FILENAME_MAX+1];

  if (argc<=1)
  {
        printf("Enter table file name [.tab] : ");
	fgets(fname, FILENAME_MAX+1-8+1, stdin);
	strtok(fname, "\n");  /* Drop the possible final LF character */
	/* fname[] and fname_phr[] will be appended ".tab.phr" suffix */
  }
  else safe_strncpy(fname, argv[1], FILENAME_MAX+1-8);

  strcpy(fname_cin,fname);
  strcpy(fname_tab,fname);
  strcat(fname_cin,".cin");
  strcat(fname_tab,".tab");
  strcpy(fname_phr,fname_tab);
  strcat(fname_phr,".phr");

  table = (hz_input_table*)malloc(sizeof(hz_input_table));
  if (table == NULL)
    printf("load_input_method error");
  cur_table = table;

  printf("\nGenerating source *.cin file for input method %s...\n",fname_cin);

  fd = fopen(fname_tab, "r");
  if (fd == NULL)
  {
    //error("error: Cannot open input method %s", filename); 
    fclose(fd);
    free(table);
    return 1;
  }

  nread = fread(table, sizeof(hz_input_table),1,fd);
  if (nread != 1)
  {
    //error("error: cannot read file header %s", filename);
    return 1;
  }

  if( strcmp(MAGIC_NUMBER, table->magic_number) )
  {
        printf("is not a valid tab file\n\n");
        return 1;
  }
  
  table->item = (ITEM *)malloc(sizeof(ITEM ) * table->TotalChar); 
  if ( table->item == NULL ) 
  {
        printf("Gosh, can't malloc enough memory");
        return 1;
  }

  nread = fread(table->item, sizeof(ITEM), table->TotalChar,fd );
  if (nread < table->TotalChar)
  {
      printf("Not enough TotalChar Items!\n");
      exit(1);
  }

  fclose( fd );
  
  table->PhraseFile = fopen( fname_phr, "r" );
  
  if (table->PhraseFile == NULL ) 
  {
     printf("Open phrase file error!\n");
     exit(1);
  }

  /*
  for(i = 0;  i<table->TotalChar;i++)
  {
     if (i%10 != 0) continue;
    index = table->item[i].ch;
    printf("No %d: Key1=%08X Key2=%08X Char=0x%04X(%d) ",
         i,table->item[i].key1,table->item[i].key2, index,index);
    if (index < 0xA1A1)
     {
       load_phr(i, str, sizeof(str));
       printf("Phrase=%s\n",str);
      }
      else printf("%c%c\n",table->item[i].ch/ 256,table->item[i].ch % 256);
  }
  */

  if ((fw=fopen(fname_cin,"w"))==NULL) 
  {
        printf("Cannot create");
   }
   
   fprintf(fw,"%%ename %s\n",table->ename);
   fprintf(fw,"%%prompt %s\n",table->cname);
   fprintf(fw,"%%selkey %s\n",table->selkey);
   fprintf(fw,"%%dupsel %d\n",table->MaxDupSel);

   fprintf(fw,"%%keyname begin\n");
   for(i = 1; i < table->TotalKey; i++)
    fprintf(fw,"%c %c\n",table->KeyName[i],table->KeyName[i]);
   fprintf(fw,"%%keyname end\n");

   for(i = 0; i< table->TotalChar; i++)
   {
     for(j = 0; j < 5; j++)
     {
       key[j] = (table->item[i].key1 >> (24 - 6 * j)) & 0x3f;
       key[5+j] = (table->item[i].key2 >> (24 - 6 * j)) & 0x3f;
     }
     for(j = 0; j < 10; j++)
     {
       if (key[j] < 0 || key[j] > 60) printf("Error Key index!\n");
       key[j] = table->KeyName[key[j]];
    }
     key[10] = '\0';

     //printf("Index = %d, KeyName=%s\n",i,key);
 
     if (table->item[i].ch < 0xA1A1)
         load_phr( i, str, sizeof(str));
      else
      {
          memcpy(str, &table->item[i].ch,2 );
          str[2] = '\0';
       }
      fprintf(fw,"%s %s\n",key,str);
    }

  fclose(fw);  

  return 0;
}
