File: xjdxgen.c

package info (click to toggle)
kdeedu 4%3A4.4.5-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 148,956 kB
  • ctags: 39,891
  • sloc: cpp: 318,170; xml: 95,032; ansic: 4,991; python: 4,483; ruby: 2,504; perl: 1,958; ml: 799; sh: 389; makefile: 106; pascal: 72
file content (400 lines) | stat: -rw-r--r-- 12,556 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/**************************************************************************
*                     X J D X G E N
*                                                   Author: Jim Breen
*           Index (.xjdx) generator program fron XJDIC
*
*		V2.3 - indexes JIS X 0212 (3-byte EUC) kanji
*		Copyright 1998 Jim Breen <jwb@csse.monash.edu.au>
***************************************************************************/
/*  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 1, 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.     */

/* Changed: ignore all rc stuff. use args 1 and 2 for input/output file.
  -- jason */

/* Heavily commented, removed the unused header file, split off the
	readDictionary function, removed unused functions and variables... cleaned
	up the code in general.	Preparing for integration to the rest of the program

	Note that this indexer has been hacked off of Jim Breen's xjdic program,
	and a lot of the things which have been removed were relevant to that
	program, but not to this one.
	--Joe
	*/

#include <config-kiten.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif

#define TRUE 1
#define FALSE 0
#define SPTAG '@'
#define TOKENLIM 40
#define INDEX_VERSION 14;		/*The last time the index structure changed was Version1.4*/

unsigned char *db;
uint32_t  *jindex;
uint32_t indlen;

/*====== prototypes=================================================*/
void jqsort(int32_t i, int32_t j);
int Kstrcmp(uint32_t lhs, uint32_t rhs);
int alphaoreuc(unsigned char x);
unsigned char* readDictionary(const char* dictName,uint32_t *filesize);
uint32_t buildIndex(unsigned char* dict, uint32_t dictLength);

/*====function to Load Dictionary and load/create index table=======*/
int  main(argc,argv)
int argc;
unsigned char **argv;
{
	const char *Dname;
	const char *JDXname;
	FILE *fp;
	uint32_t diclen;
	uint32_t indptr;

	printf("\nNOTE: running this program by itself is never necessary. Kiten will run it automatically.\n");
	printf("\nXJDXGEN V2.3 Index Table Generator for XJDIC. \n      Copyright J.W. Breen, 1998\n");

	if (argc < 3)
	{
		printf("\nUSAGE: kitengen input output.xjdx\n");
		exit(2);
	}

	Dname = argv[1]; /*Name of the dictionary being scanned */
	JDXname = argv[2]; /*Name of the output file */
	printf("Commandline request to use files %s and %s \n", Dname, JDXname);
	printf("\nWARNING!!  This program may take a long time to run .....\n");

	db = readDictionary(Dname,&diclen); /*Reads the dict, but leaves a space at the beginning*/
	diclen++; /*add one to the number of bytes considered in the file */
	db[diclen] = 10;  /*set the first and final entry in the database to 10 */
	db[0] = 10;
	printf("Dictionary size: %d bytes.\n",diclen);


	indlen = (diclen * 3)/4; /*Make a wild guess at the index file length */
	jindex = (uint32_t *)malloc(indlen); /* and allocate it */
	if(jindex == NULL)
	{
		fprintf(stderr,"malloc() for index table failed.\n");
		exit(1);
	}

	printf("Parsing.... \n");
  /*this is the dictionary parser. It places an entry in jindex for every
   kana/kanji string and every alphabetic string it finds which is >=3
   characters */
	indptr = buildIndex(db,diclen);

	printf("Index entries: %d  \nSorting (this is slow)......\n",indptr);
	jqsort((int32_t)1,indptr);

	printf("Sorted\nWriting index file ....\n");
	fp = fopen(JDXname,"wb");
	if (fp==NULL )
	{
		printf("\nCannot open %s output file\n",JDXname);
		exit(1);
	}
	jindex[0] = diclen+INDEX_VERSION; /* prepend the index file size + version # */
	fwrite(jindex,sizeof(int32_t),indptr+1,fp);
	fclose(fp);

	return 0;
}

/*=========function to parse the dict file and fill the jindex global with the index====*/
/*=========returns the size of the index file                                       ====*/
/*
	A bit of explanation on what this thing generates is probably in order.
	Essentially, it fills jindex with a large number of numbers... each number
	being an offset to a byte location inside of the dictionary file. Starting
	at position index 1 (second pos)
	In other words... feeding this thing the dict file
	"Llama X1\nJT Fred Flintstone X"
	would generate: {<unmodified>,0,6,12,17}.
	"X" is skipped because it is only 1 byte long.
	"JT" is skipped because it is only two bytes long, the J is regular ascii
		(<127), and the T is not a digit. If any of those were different, (it
		was longer than 2 bytes, was an euc (kana or kanji) character, or T was
		a digit) it would be included in the index.
*/

/*First... an ugly #define to make our code a bit more readable*/
#define INDEX_OVERFLOW_CHECK(x) {if(x > indlen/sizeof(int32_t)) { \
	printf("Index table overflow. Dictionary too large?\n"); exit(1); } }

uint32_t buildIndex(unsigned char *dict, uint32_t dictLength) {
	int nowReadingWord = FALSE; /*Boolean to track if we're mid-word in the dict */
	int currentDictCharacter;   /*Current character index in the dict */
	unsigned char c;				/*the current reading character*/
	unsigned char currstr[TOKENLIM]; /* String that we're currently getting */
	int currstrIndex = 0;
	uint32_t indptr = 1;        /* next 'slot' in the index to fill */
	int saving = FALSE;	/*is what we are doing right now slated for salvation?*/

	for (currentDictCharacter =0; currentDictCharacter < dictLength;
							currentDictCharacter++)
	{
		c = dict[currentDictCharacter]; /* Fetch the next character */

		if(!nowReadingWord) /*if we are NOT in the middle of reading a word */
		{
			if (alphaoreuc(c) || c == SPTAG) /* if character or priority entry */
			{
				nowReadingWord = TRUE;  /* Mark that we're mid word */
				jindex[indptr] = currentDictCharacter;
					/* copy the location of this character to our index structure */
				currstrIndex = 1;
					/*mark the next position in the string to copy a char into */
				currstr[0] = c;
					/*set the current string to be equal to this character so far */
				currstr[1] = '\0';
				saving = TRUE;
			}
		} else {		/*If we're in the middle of parsing a word atm */

			/*if it's alphanumeric or - or . copy it and increment where the
			  next one goes */
			if ((alphaoreuc(c))||(c == '-')||(c == '.')||((c >= '0') && (c<='9')))
			{
				currstr[currstrIndex] = c;
				if(currstrIndex < TOKENLIM-1)
					currstrIndex++;
			}
			else /* We were reading a word... and we just encountered the
					  end of the word */
			{
				currstr[currstrIndex] = '\0'; /*null terminate the string */
				nowReadingWord = FALSE;

				/*Don't save single or dual character items where the
				  first item is ascii */
				if ((strlen(currstr) <= 2) && (currstr[0] < 127))
					saving = FALSE;
				/*EXCEPT: Save anything that's two character where the second
				  is a number
					Note that this might catch single 2-byte kanji as well...
					but it might not*/
				if ((strlen(currstr) == 2) && (currstr[1] <= '9'))
					saving = TRUE;

				/* This is a latin-character string, either longer than 2 bytes
					or having an ascii digit for a second byte */
				if (saving && (currstr[0] < 127))
				{
					indptr++;
					INDEX_OVERFLOW_CHECK(indptr);

					/* If this is non-Japanese, and has a 'SPTAGn' tag, generate
						two indices */
					if ( currstr[0] == SPTAG)
					{
						/*make a separate entry pointing to
							the non-SPTAG'd entry (the next byte)*/
						jindex[indptr] = jindex[indptr-1]+1;
							/*overwrite the SPTAG marker*/
						strcpy(currstr,currstr+1);
						indptr++;
						INDEX_OVERFLOW_CHECK(indptr);
					}
				}

				/*For strings that start with non latin characters*/
				if (saving && (currstr[0] > 127))
				{
					int i;
					uint32_t possav = jindex[indptr]; /*Save the current marker*/
					indptr++;
					INDEX_OVERFLOW_CHECK(indptr);

					/* generate index for *every* kanji in key */
					i = 2;
					/*if this is a three byte kanji, ignore the 0x8f marker */
					if (currstr[0] == 0x8f)
						i++;
					/*step through... two by two*/
					for ( ;  i < strlen(currstr);  i+=2)
					{
						if((currstr[i] >= 0xb0) || (currstr[i] == 0x8f))
						{
							/*Add in a specific reference to the kanji*/
							jindex[indptr] = possav+i;
							indptr++;
							INDEX_OVERFLOW_CHECK(indptr);
						}
						/*again the check if it's a three byte kanji*/
						if(currstr[i] == 0x8f)
							i++;
					}
				}
			}
		}
	}
	indptr--; /*correct for the overshoot */
	return indptr;
}

/*===function to read the dictionary files into array, returning filesize===*/
/*Note: We leave a blank byte in the first byte of the returned dictionary, and
  allocate an extra 99 bytes at the end */
unsigned char*
readDictionary(const char* dictName,uint32_t *filesize) {
  FILE *fp;
  struct stat buf;
  unsigned char *memDictionary;
  int nodread;

  if(stat(dictName, &buf) != 0) /* if the dict file doesn't exist */
  {
	 perror(NULL);
	 printf("Cannot stat: %s \n",dictName);
	 exit(1);
  }

  *filesize = buf.st_size; /*file size in bytes*/

  puts ("\nLoading Dictionary file.  Please wait.....\n");
  fp=fopen(dictName,"rb");
  if (fp==NULL )
  {
	printf("\nCannot open dictionary file\n");
	exit(1);
  }
  /*Allocate the database index 100 bytes larger than the dict filesize*/
  memDictionary=(unsigned char*)malloc((*filesize+100)*sizeof(unsigned char));
  if(memDictionary == NULL)
  {
      fprintf(stderr,"malloc() for dictionary failed.\n");
      fclose(fp);
      exit(1);
  }

  nodread = (*filesize)/1024; /*number of kilobytes in the file */
  /*reads 1024 x nodread bytes from fp, storing in memDictionary at offset 1*/
  fread((unsigned char *)memDictionary+1, 1024, nodread, fp);
  nodread = (*filesize) % 1024; /* "leftover" bytes after the previous read */
  /*reads the remaining bytes from fp... for what filesystem is this split-read needed?*/
  fread((unsigned char *)(memDictionary+((*filesize)/1024)*1024)+1, nodread,1, fp);
  fclose(fp);

  return memDictionary;
}

/*======function to sort jindex table====================*/
/*see the index generator for information about what jindex contains
  This simply sorts that output according to the data in the dictionary*/
void jqsort(int32_t lhs, int32_t rhs)
{
	int32_t i,last,midp;
	uint32_t temp;

	if (lhs >= rhs) return;

	midp = (lhs+rhs)/2; /* calculate the midpoint */

	/*Swap (midp,lhs) */
	temp = jindex[lhs];
	jindex[lhs] = jindex[midp];
	jindex[midp] = temp;

	last = lhs;
	for (i = lhs+1;i <= rhs; i++)
		{
			if (Kstrcmp(jindex[i],jindex[lhs]) < 0)
			{
				/* Swap(++last,i);*/
				last++;
				temp = jindex[i];
				jindex[i] = jindex[last];
				jindex[last] = temp;
			}
		}

/*	Swap (lhs,last);*/
	temp = jindex[lhs];
	jindex[lhs] = jindex[last];
	jindex[last] = temp;

	jqsort(lhs,last-1);
	jqsort(last+1,rhs);
}

/*=====string comparison used by jqsort==========================*/
int Kstrcmp(uint32_t lhs, uint32_t rhs)
{
	int i,c1 = 0, c2 = 0;
/* effectively does a strnicmp on two "strings" within the dictionary,
   except it will make katakana and hirgana match (EUC A4 & A5) */

	for (i = 0; i<20 ; i++) /*Compare up to 20 chars*/
	{
		c1 = db[lhs+i];
		c2 = db[rhs+i];

		if ((i % 2) == 0) /*If we're reading the first byte*/
		{
			if (c1 == 0xA5) /*Change hiragana to katakana for */
				c1 = 0xA4;   /*The purposes of this comparison */
			if (c2 == 0xA5)
				c2 = 0xA4;
		}

		/*If this is ascii, remove the difference between capitals and small*/
		if ((c1 >= 'A') && (c1 <= 'Z')) c1 |= 0x20;
		if ((c2 >= 'A') && (c2 <= 'Z')) c2 |= 0x20;

		if (c1 != c2 ) break;
	}
	return(c1-c2);
}

/*=======function to test a character for alpha or kana/kanji====*/
int alphaoreuc(unsigned char x)
{
	int c;

	c = x & 0xff;
	if(((c >= 65) && (c <= 90)) || ((c >= 97) && (c <= 122)))
		/*ASCII alphabet*/
	{
		return (TRUE);
	}
	if ((c >= '0') && (c <= '9'))
		/*digits*/
	{
		return(TRUE);
	}
	if ((c & 0x80) > 0)
		/*EUC kanji/kana*/
	{
		return(TRUE);
	}
	return (FALSE);
}