/*
 * Copyright (C) 2002 Red Hat, Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

/*
 * Written by Yukihiro Nakai <ynakai@redhat.com>
 */

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>

#define BUFSIZE 4096

char* zen2han[][2] = {
  {"¡Ý", "-"},
  {"¡Ê", "("},
  {"¡Ë", ")"},
  {"£°", "0"},
  {"£±", "1"},
  {"£²", "2"},
  {"£³", "3"},
  {"£´", "4"},
  {"£µ", "5"},
  {"£¶", "6"},
  {"£·", "7"},
  {"£¸", "8"},
  {"£¹", "9"}
};

int main(int argc, char** argv) {
  FILE* fp;
  unsigned char buf[BUFSIZE];

  setlocale(LC_ALL, "ja_JP.eucJP");

  if( argc != 2 ) {
    fprintf(stderr, "Usage: zennum2han file \n");
    exit(0);
  }
  bzero(buf, BUFSIZE);

  fp = fopen(argv[1], "r");
  while(fgets(buf, BUFSIZE, fp) != NULL ) {
    int idx = 0;
    char* buf2 = malloc(sizeof(char)*(strlen(buf)+1));
    bzero(buf2, sizeof(char)*(strlen(buf)+1));
    while(strlen(buf+idx)>0 ) {
      int ret = mblen(buf+idx, MB_CUR_MAX);
      if( ret <= 0 ) {
        fprintf(stderr, "Illegal sequence found.\n");
        exit(0);
      }
      if( ret > 1 ) {
        int i;
        int flag = 0;
        for( i=0;i<sizeof(zen2han)/sizeof(zen2han[0]);i++) {
          if( strncmp(zen2han[i][0], buf+idx, ret) == 0 ) {
            strncat(buf2, zen2han[i][1], strlen(zen2han[i][1]));
            flag = 1;
            break;
          }
        }
        if( *(buf+idx) == 0xa3 && *(buf+idx+1) >= 0xc1
            && *(buf+idx+1) <= 0xda ) {
          char c = *(buf+idx+1) - 0xc1 + 'A';
          strncat(buf2, &c, 1);
          flag = 1;
        } else if( *(buf+idx) == 0xa3 && *(buf+idx+1) >= 0xe1
            && *(buf+idx+1) <= 0xfa ) {
          char c = *(buf+idx+1) - 0xfa + 'a';
          strncat(buf2, &c, 1);
          flag = 1;
        }
        if( flag == 0 ) {
          strncat(buf2, buf+idx, ret);
        }
      } else {
        strncat(buf2, buf+idx, ret);
      }
      idx += ret;
    }
    bzero(buf, BUFSIZE);
    printf("%s", buf2);
  }
  fclose(fp);
  
  return 0;
}
