1 /* Copyright (C) 2009 Edward Der-Hua Liu, Hsin-Chu, Taiwan
2  *
3  * This library is free software; you can redistribute it and/or
4  * modify it under the terms of the GNU Lesser General Public
5  * License as published by the Free Software Foundation version 2.1
6  * of the License.
7  *
8  * This library is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public
14  * License along with this library; if not, write to the Free Software
15  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
16  */
17 
18 #include <stdio.h>
19 
20 #include "hime.h"
21 
22 #include "t2s-file.h"
23 
24 static int N;
25 static FILE *fp;
26 
k_lookup(char * s,char out[])27 static int k_lookup (char *s, char out[]) {
28     unsigned int key;
29     memset (&key, 0, sizeof (key));
30 
31     u8cpy ((char *) &key, s);
32 
33     int bot = 0, top = N - 1;
34     while (bot <= top) {
35         int mid = (bot + top) / 2;
36         T2S t;
37         fseek (fp, mid * sizeof (T2S), SEEK_SET);
38         fread (&t, sizeof (T2S), 1, fp);
39 
40         if (key > t.a)
41             bot = mid + 1;
42         else if (key < t.a)
43             top = mid - 1;
44         else
45             return u8cpy (out, (char *) &t.b);
46     }
47 
48     return u8cpy (out, s);
49 }
50 
51 #include <sys/stat.h>
52 
translate(char * fname,char * str,int strN,char ** out)53 static int translate (char *fname, char *str, int strN, char **out) {
54     char fullname[128];
55 
56     get_sys_table_file_name (fname, fullname);
57 
58     if ((fp = fopen (fullname, "rb")) == NULL)
59         p_err ("cannot open %s %s", fname, fullname);
60 
61     struct stat st;
62 
63     stat (fullname, &st);
64     N = st.st_size / sizeof (T2S);
65 
66     char *p = str;
67     char *endp = str + strN;
68     int opN = 0;
69     char *op = NULL;
70 
71     while (p < endp) {
72         op = (char *) realloc (op, opN + 5);
73         opN += k_lookup (p, &op[opN]);
74         p += utf8_sz (p);
75     }
76 
77     fclose (fp);
78     *out = op;
79     if (op)
80         op[opN] = 0;
81     return opN;
82 }
83 
trad2sim(char * str,int strN,char ** out)84 int trad2sim (char *str, int strN, char **out) {
85     return translate ("t2s.dat", str, strN, out);
86 }
87 
sim2trad(char * str,int strN,char ** out)88 int sim2trad (char *str, int strN, char **out) {
89     puts (str);
90     return translate ("s2t.dat", str, strN, out);
91     puts (*out);
92 }
93