Added suport for EXPLAIN Proxy servers - added settings databasePath
[idzebra-moved-to-github.git] / index / extract.c
1 /*
2  * Copyright (C) 1994-1998, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: extract.c,v $
7  * Revision 1.83  1998-06-08 14:43:10  adam
8  * Added suport for EXPLAIN Proxy servers - added settings databasePath
9  * and explainDatabase to facilitate this. Increased maximum number
10  * of databases and attributes in one register.
11  *
12  * Revision 1.82  1998/05/20 10:12:15  adam
13  * Implemented automatic EXPLAIN database maintenance.
14  * Modified Zebra to work with ASN.1 compiled version of YAZ.
15  *
16  * Revision 1.81  1998/03/11 11:19:04  adam
17  * Changed the way sequence numbers are generated.
18  *
19  * Revision 1.80  1998/03/05 08:45:11  adam
20  * New result set model and modular ranking system. Moved towards
21  * descent server API. System information stored as "SGML" records.
22  *
23  * Revision 1.79  1998/02/17 10:32:52  adam
24  * Fixed bug: binary files weren't opened with flag b on NT.
25  *
26  * Revision 1.78  1998/02/10 12:03:05  adam
27  * Implemented Sort.
28  *
29  * Revision 1.77  1998/01/12 15:04:08  adam
30  * The test option (-s) only uses read-lock (and not write lock).
31  *
32  * Revision 1.76  1997/10/27 14:33:04  adam
33  * Moved towards generic character mapping depending on "structure"
34  * field in abstract syntax file. Fixed a few memory leaks. Fixed
35  * bug with negative integers when doing searches with relational
36  * operators.
37  *
38  * Revision 1.75  1997/09/17 12:19:12  adam
39  * Zebra version corresponds to YAZ version 1.4.
40  * Changed Zebra server so that it doesn't depend on global common_resource.
41  *
42  * Revision 1.74  1997/09/09 13:38:06  adam
43  * Partial port to WIN95/NT.
44  *
45  * Revision 1.73  1997/09/04 13:57:20  adam
46  * New file extract/retrieve method tellf (added).
47  * Added O_BINARY for open calls.
48  *
49  * Revision 1.72  1997/07/15 16:32:29  adam
50  * Bug fix: Match handler didn't terminate the resulting string!
51  *
52  * Revision 1.71  1997/07/15 16:28:41  adam
53  * Bug fix: storeData didn't work with files with multiple records.
54  * Bug fix: fixed memory management with records; not really well
55  *  thought through.
56  *
57  * Revision 1.70  1997/07/01 13:00:42  adam
58  * Bug fix in routine searchRecordKey: uninitialized variables.
59  *
60  * Revision 1.69  1997/04/29 09:26:03  adam
61  * Bug fix: generic recordId handling didn't work for compressed internal
62  * keys.
63  *
64  * Revision 1.68  1997/02/12 20:39:45  adam
65  * Implemented options -f <n> that limits the log to the first <n>
66  * records.
67  * Changed some log messages also.
68  *
69  * Revision 1.67  1996/11/15 15:02:14  adam
70  * Minor changes regarding logging.
71  *
72  * Revision 1.66  1996/11/14  09:52:21  adam
73  * Strings in record keys bound by IT_MAX_WORD.
74  *
75  * Revision 1.65  1996/11/14  08:57:56  adam
76  * Reduction of storeKeys area.
77  *
78  * Revision 1.64  1996/11/08 11:10:16  adam
79  * Buffers used during file match got bigger.
80  * Compressed ISAM support everywhere.
81  * Bug fixes regarding masking characters in queries.
82  * Redesigned Regexp-2 queries.
83  *
84  * Revision 1.63  1996/10/29 14:09:39  adam
85  * Use of cisam system - enabled if setting isamc is 1.
86  *
87  * Revision 1.62  1996/10/11 10:57:01  adam
88  * New module recctrl. Used to manage records (extract/retrieval).
89  * Several files have been moved to the recctrl sub directory.
90  *
91  * Revision 1.61  1996/06/06 12:08:37  quinn
92  * Added showRecord function
93  *
94  * Revision 1.60  1996/06/04  10:18:12  adam
95  * Search/scan uses character mapping module.
96  *
97  * Revision 1.59  1996/05/14  15:47:07  adam
98  * Cleanup of various buffer size entities.
99  *
100  * Revision 1.58  1996/05/14  06:16:38  adam
101  * Compact use/set bytes used in search service.
102  *
103  * Revision 1.57  1996/05/13 14:23:04  adam
104  * Work on compaction of set/use bytes in dictionary.
105  *
106  * Revision 1.56  1996/05/09  09:54:42  adam
107  * Server supports maps from one logical attributes to a list of physical
108  * attributes.
109  * The extraction process doesn't make space consuming 'any' keys.
110  *
111  * Revision 1.55  1996/05/09  07:28:55  quinn
112  * Work towards phrases and multiple registers
113  *
114  * Revision 1.54  1996/05/01  13:46:35  adam
115  * First work on multiple records in one file.
116  * New option, -offset, to the "unread" command in the filter module.
117  *
118  * Revision 1.53  1996/04/26  12:09:43  adam
119  * Added a few comments.
120  *
121  * Revision 1.52  1996/04/25  13:27:57  adam
122  * Function recordExtract modified so that files with no keys (possibly empty)
123  * are ignored.
124  *
125  * Revision 1.51  1996/03/19  11:08:42  adam
126  * Bug fix: Log preamble wasn't always turned off after recordExtract.
127  *
128  * Revision 1.50  1996/02/12  18:45:36  adam
129  * New fileVerboseFlag in record group control.
130  *
131  * Revision 1.49  1996/02/05  12:29:57  adam
132  * Logging reduced a bit.
133  * The remaining running time is estimated during register merge.
134  *
135  * Revision 1.48  1996/02/01  20:53:26  adam
136  * The temporary per-record keys are compacted a little, and duplication
137  * of the per-records keys are avoided when they are saved in the record
138  * information buffer.
139  *
140  * Revision 1.47  1996/01/17  14:57:48  adam
141  * Prototype changed for reader functions in extract/retrieve. File
142  *  is identified by 'void *' instead of 'int.
143  *
144  * Revision 1.46  1995/12/15  14:57:16  adam
145  * Bug fix.
146  *
147  * Revision 1.45  1995/12/15  12:37:41  adam
148  * In addRecordKeyAny: Writes key only when attrSet != -1.
149  *
150  * Revision 1.44  1995/12/12  16:00:54  adam
151  * System call sync(2) used after update/commit.
152  * Locking (based on fcntl) uses F_EXLCK and F_SHLCK instead of F_WRLCK
153  * and F_RDLCK.
154  *
155  * Revision 1.43  1995/12/11  09:12:46  adam
156  * The rec_get function returns NULL if record doesn't exist - will
157  * happen in the server if the result set records have been deleted since
158  * the creation of the set (i.e. the search).
159  * The server saves a result temporarily if it is 'volatile', i.e. the
160  * set is register dependent.
161  *
162  * Revision 1.42  1995/12/07  17:38:46  adam
163  * Work locking mechanisms for concurrent updates/commit.
164  *
165  * Revision 1.41  1995/12/06  16:06:42  adam
166  * Better diagnostics. Work on 'real' dictionary deletion.
167  *
168  * Revision 1.40  1995/12/05  16:57:40  adam
169  * More work on regular patterns.
170  *
171  * Revision 1.39  1995/12/05  13:20:18  adam
172  * Bug fix: file_read sometimes returned early EOF.
173  *
174  * Revision 1.38  1995/12/04  17:59:21  adam
175  * More work on regular expression conversion.
176  *
177  * Revision 1.37  1995/12/04  14:22:27  adam
178  * Extra arg to recType_byName.
179  * Started work on new regular expression parsed input to
180  * structured records.
181  *
182  * Revision 1.36  1995/11/30  08:34:29  adam
183  * Started work on commit facility.
184  * Changed a few malloc/free to xmalloc/xfree.
185  *
186  * Revision 1.35  1995/11/28  14:26:21  adam
187  * Bug fix: recordId with constant wasn't right.
188  * Bug fix: recordId dictionary entry wasn't deleted when needed.
189  *
190  * Revision 1.34  1995/11/28  09:09:38  adam
191  * Zebra config renamed.
192  * Use setting 'recordId' to identify record now.
193  * Bug fix in recindex.c: rec_release_blocks was invokeded even
194  * though the blocks were already released.
195  * File traversal properly deletes records when needed.
196  *
197  * Revision 1.33  1995/11/27  09:56:20  adam
198  * Record info elements better enumerated. Internal store of records.
199  *
200  * Revision 1.32  1995/11/25  10:24:05  adam
201  * More record fields - they are enumerated now.
202  * New options: flagStoreData flagStoreKey.
203  *
204  * Revision 1.31  1995/11/24  11:31:35  adam
205  * Commands add & del read filenames from stdin if source directory is
206  * empty.
207  * Match criteria supports 'constant' strings.
208  *
209  * Revision 1.30  1995/11/22  17:19:16  adam
210  * Record management uses the bfile system.
211  *
212  * Revision 1.29  1995/11/21  15:01:14  adam
213  * New general match criteria implemented.
214  * New feature: document groups.
215  *
216  * Revision 1.28  1995/11/21  09:20:30  adam
217  * Yet more work on record match.
218  *
219  * Revision 1.27  1995/11/20  16:59:45  adam
220  * New update method: the 'old' keys are saved for each records.
221  *
222  * Revision 1.26  1995/11/20  11:56:24  adam
223  * Work on new traversal.
224  *
225  * Revision 1.25  1995/11/16  15:34:54  adam
226  * Uses new record management system in both indexer and server.
227  *
228  * Revision 1.24  1995/11/15  19:13:08  adam
229  * Work on record management.
230  *
231  * Revision 1.23  1995/10/27  14:00:10  adam
232  * Implemented detection of database availability.
233  *
234  * Revision 1.22  1995/10/17  18:02:07  adam
235  * New feature: databases. Implemented as prefix to words in dictionary.
236  *
237  * Revision 1.21  1995/10/10  12:24:38  adam
238  * Temporary sort files are compressed.
239  *
240  * Revision 1.20  1995/10/06  13:52:05  adam
241  * Bug fixes. Handler may abort further scanning.
242  *
243  * Revision 1.19  1995/10/04  12:55:16  adam
244  * Bug fix in ranked search. Use=Any keys inserted.
245  *
246  * Revision 1.18  1995/10/04  09:37:08  quinn
247  * Fixed bug.
248  *
249  * Revision 1.17  1995/10/03  14:28:57  adam
250  * Buffered read in extract works.
251  *
252  * Revision 1.16  1995/10/03  14:28:45  adam
253  * Work on more effecient read handler in extract.
254  *
255  * Revision 1.15  1995/10/02  15:42:53  adam
256  * Extract uses file descriptors instead of FILE pointers.
257  *
258  * Revision 1.14  1995/10/02  15:29:13  adam
259  * More logging in file_extract.
260  *
261  * Revision 1.13  1995/09/29  14:01:39  adam
262  * Bug fixes.
263  *
264  * Revision 1.12  1995/09/28  14:22:56  adam
265  * Sort uses smaller temporary files.
266  *
267  * Revision 1.11  1995/09/28  12:10:31  adam
268  * Bug fixes. Field prefix used in queries.
269  *
270  * Revision 1.10  1995/09/28  09:19:41  adam
271  * xfree/xmalloc used everywhere.
272  * Extract/retrieve method seems to work for text records.
273  *
274  * Revision 1.9  1995/09/27  12:22:28  adam
275  * More work on extract in record control.
276  * Field name is not in isam keys but in prefix in dictionary words.
277  *
278  * Revision 1.8  1995/09/14  07:48:22  adam
279  * Record control management.
280  *
281  * Revision 1.7  1995/09/11  13:09:32  adam
282  * More work on relevance feedback.
283  *
284  * Revision 1.6  1995/09/08  14:52:27  adam
285  * Minor changes. Dictionary is lower case now.
286  *
287  * Revision 1.5  1995/09/06  16:11:16  adam
288  * Option: only one word key per file.
289  *
290  * Revision 1.4  1995/09/05  15:28:39  adam
291  * More work on search engine.
292  *
293  * Revision 1.3  1995/09/04  12:33:41  adam
294  * Various cleanup. YAZ util used instead.
295  *
296  * Revision 1.2  1995/09/04  09:10:34  adam
297  * More work on index add/del/update.
298  * Merge sort implemented.
299  * Initial work on z39 server.
300  *
301  * Revision 1.1  1995/09/01  14:06:35  adam
302  * Split of work into more files.
303  *
304  */
305 #include <stdio.h>
306 #include <assert.h>
307 #ifdef WINDOWS
308 #include <io.h>
309 #else
310 #include <unistd.h>
311 #endif
312 #include <fcntl.h>
313
314 #include <recctrl.h>
315 #include <charmap.h>
316 #include <sortidx.h>
317 #include "index.h"
318
319 #include "zinfo.h"
320
321 static Dict matchDict;
322
323 static Records records = NULL;
324 static SortIdx sortIdx = NULL;
325
326 static char **key_buf;
327 static size_t ptr_top;
328 static size_t ptr_i;
329 static size_t key_buf_used;
330 static int key_file_no;
331
332 static int records_inserted = 0;
333 static int records_updated = 0;
334 static int records_deleted = 0;
335 static int records_processed = 0;
336
337 static ZebraExplainInfo zti = NULL;
338
339 static void logRecord (int showFlag)
340 {
341     if (!showFlag)
342         ++records_processed;
343     if (showFlag || !(records_processed % 1000))
344     {
345         logf (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
346               records_processed, records_inserted, records_updated,
347               records_deleted);
348     }
349 }
350
351 static int explain_extract (void *handle, Record drec, data1_node *n);
352
353 int key_open (struct recordGroup *rGroup, int mem)
354 {
355     BFiles bfs = rGroup->bfs;
356     int rw = rGroup->flagRw;
357     data1_handle dh = rGroup->dh;
358     if (!mem)
359         mem = atoi(res_get_def (common_resource, "memMax", "4"))*1024*1024;
360     if (mem < 50000)
361         mem = 50000;
362     key_buf = xmalloc (mem);
363     ptr_top = mem/sizeof(char*);
364     ptr_i = 0;
365
366     key_buf_used = 0;
367     key_file_no = 0;
368
369     if (!(matchDict = dict_open (bfs, GMATCH_DICT, 50, rw)))
370     {
371         logf (LOG_FATAL, "dict_open fail of %s", GMATCH_DICT);
372         return -1;
373     }
374     assert (!records);
375     records = rec_open (bfs, rw);
376     if (!records)
377     {
378         dict_close (matchDict);
379         return -1;
380     }
381     zti = zebraExplain_open (records, dh, common_resource,
382                              rw, rGroup, explain_extract);
383     if (!zti)
384     {
385         rec_close (&records);
386         dict_close (matchDict);
387         return -1;      
388     }
389     sortIdx = sortIdx_open (bfs, 1);
390     return 0;
391 }
392
393 struct encode_info {
394     int  sysno;
395     int  seqno;
396     char buf[768];
397 };
398
399 void encode_key_init (struct encode_info *i)
400 {
401     i->sysno = 0;
402     i->seqno = 0;
403 }
404
405 char *encode_key_int (int d, char *bp)
406 {
407     if (d <= 63)
408         *bp++ = d;
409     else if (d <= 16383)
410     {
411         *bp++ = 64 + (d>>8);
412         *bp++ = d  & 255;
413     }
414     else if (d <= 4194303)
415     {
416         *bp++ = 128 + (d>>16);
417         *bp++ = (d>>8) & 255;
418         *bp++ = d & 255;
419     }
420     else
421     {
422         *bp++ = 192 + (d>>24);
423         *bp++ = (d>>16) & 255;
424         *bp++ = (d>>8) & 255;
425         *bp++ = d & 255;
426     }
427     return bp;
428 }
429
430 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
431 {
432     struct it_key key;
433     char *bp = i->buf;
434
435     while ((*bp++ = *k++))
436         ;
437     memcpy (&key, k+1, sizeof(struct it_key));
438     bp = encode_key_int ( (key.sysno - i->sysno) * 2 + *k, bp);
439     if (i->sysno != key.sysno)
440     {
441         i->sysno = key.sysno;
442         i->seqno = 0;
443     }
444     bp = encode_key_int (key.seqno - i->seqno, bp);
445     i->seqno = key.seqno;
446     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
447     {
448         logf (LOG_FATAL|LOG_ERRNO, "fwrite");
449         exit (1);
450     }
451 }
452
453 #define SORT_EXTRA 0
454
455 #if SORT_EXTRA
456 static int key_y_len;
457
458 static int key_y_compare (const void *p1, const void *p2)
459 {
460     int r;
461
462     if ((r = key_compare (*(char**) p1 + key_y_len + 1,
463                           *(char**) p2 + key_y_len + 1)))
464          return r;
465     return *(*(char**) p1 + key_y_len) - *(*(char**) p2 + key_y_len);
466 }
467
468 static int key_x_compare (const void *p1, const void *p2)
469 {
470     return strcmp (*(char**) p1, *(char**) p2);
471 }
472 #endif
473
474 void key_flush (void)
475 {
476     FILE *outf;
477     char out_fname[200];
478     char *prevcp, *cp;
479     struct encode_info encode_info;
480 #if SORT_EXTRA
481     int i;
482 #endif
483     
484     if (ptr_i <= 0)
485         return;
486
487     key_file_no++;
488     logf (LOG_LOG, "sorting section %d", key_file_no);
489 #if !SORT_EXTRA
490     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_qsort_compare);
491     getFnameTmp (out_fname, key_file_no);
492
493     if (!(outf = fopen (out_fname, "wb")))
494     {
495         logf (LOG_FATAL|LOG_ERRNO, "fopen %s", out_fname);
496         exit (1);
497     }
498     logf (LOG_LOG, "writing section %d", key_file_no);
499     prevcp = cp = key_buf[ptr_top-ptr_i];
500     
501     encode_key_init (&encode_info);
502     encode_key_write (cp, &encode_info, outf);
503     while (--ptr_i > 0)
504     {
505         cp = key_buf[ptr_top-ptr_i];
506         if (strcmp (cp, prevcp))
507         {
508             encode_key_init (&encode_info);
509             encode_key_write (cp, &encode_info, outf);
510             prevcp = cp;
511         }
512         else
513             encode_key_write (cp + strlen(cp), &encode_info, outf);
514     }
515 #else
516     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_x_compare);
517     getFnameTmp (out_fname, key_file_no);
518
519     if (!(outf = fopen (out_fname, "wb")))
520     {
521         logf (LOG_FATAL|LOG_ERRNO, "fopen %s", out_fname);
522         exit (1);
523     }
524     logf (LOG_LOG, "writing section %d", key_file_no);
525     i = ptr_i;
526     prevcp =  key_buf[ptr_top-i];
527     while (1)
528         if (!--i || strcmp (prevcp, key_buf[ptr_top-i]))
529         {
530             key_y_len = strlen(prevcp)+1;
531 #if 0
532             logf (LOG_LOG, "key_y_len: %2d %02x %02x %s",
533                       key_y_len, prevcp[0], prevcp[1], 2+prevcp);
534 #endif
535             qsort (key_buf + ptr_top-ptr_i, ptr_i - i,
536                                    sizeof(char*), key_y_compare);
537             cp = key_buf[ptr_top-ptr_i];
538             --key_y_len;
539             encode_key_init (&encode_info);
540             encode_key_write (cp, &encode_info, outf);
541             while (--ptr_i > i)
542             {
543                 cp = key_buf[ptr_top-ptr_i];
544                 encode_key_write (cp+key_y_len, &encode_info, outf);
545             }
546             if (!i)
547                 break;
548             prevcp = key_buf[ptr_top-ptr_i];
549         }
550 #endif
551     if (fclose (outf))
552     {
553         logf (LOG_FATAL|LOG_ERRNO, "fclose %s", out_fname);
554         exit (1);
555     }
556     logf (LOG_LOG, "finished section %d", key_file_no);
557     ptr_i = 0;
558     key_buf_used = 0;
559 }
560
561 int key_close (struct recordGroup *rGroup)
562 {
563     int rw = rGroup->flagRw;
564     if (rw)
565         zebraExplain_runNumberIncrement (zti, 1);
566     zebraExplain_close (zti, rw, 0);
567     key_flush ();
568     xfree (key_buf);
569     rec_close (&records);
570     dict_close (matchDict);
571     sortIdx_close (sortIdx);
572
573     logRecord (1);
574     return key_file_no;
575 }
576
577 static void wordInit (struct recExtractCtrl *p, RecWord *w)
578 {
579     w->zebra_maps = p->zebra_maps;
580     w->seqnos = p->seqno;
581     w->attrSet = VAL_BIB1;
582     w->attrUse = 1016;
583     w->reg_type = 'w';
584 }
585
586 static struct sortKey {
587     char *string;
588     int length;
589     int attrSet;
590     int attrUse;
591     struct sortKey *next;
592 } *sortKeys = NULL;
593
594 static struct recKeys {
595     int buf_used;
596     int buf_max;
597     char *buf;
598     char prevAttrSet;
599     short prevAttrUse;
600     int prevSeqNo;
601 } reckeys;
602
603 static void addIndexString (RecWord *p, const char *string, int length)
604 {
605     char *dst;
606     char attrSet;
607     short attrUse;
608     int lead = 0;
609     int diff = 0;
610     int *pseqno = &p->seqnos[p->reg_type];
611
612     if (reckeys.buf_used+1024 > reckeys.buf_max)
613     {
614         char *b;
615
616         b = xmalloc (reckeys.buf_max += 128000);
617         if (reckeys.buf_used > 0)
618             memcpy (b, reckeys.buf, reckeys.buf_used);
619         xfree (reckeys.buf);
620         reckeys.buf = b;
621     }
622     dst = reckeys.buf + reckeys.buf_used;
623
624     attrSet = p->attrSet;
625     if (reckeys.buf_used > 0 && reckeys.prevAttrSet == attrSet)
626         lead |= 1;
627     else
628         reckeys.prevAttrSet = attrSet;
629     attrUse = p->attrUse;
630     if (reckeys.buf_used > 0 && reckeys.prevAttrUse == attrUse)
631         lead |= 2;
632     else
633         reckeys.prevAttrUse = attrUse;
634 #if 1
635     diff = 1 + *pseqno - reckeys.prevSeqNo;
636     if (diff >= 1 && diff <= 15)
637         lead |= (diff << 2);
638     else
639         diff = 0;
640 #endif
641     reckeys.prevSeqNo = *pseqno;
642     
643     *dst++ = lead;
644
645     if (!(lead & 1))
646     {
647         memcpy (dst, &attrSet, sizeof(attrSet));
648         dst += sizeof(attrSet);
649     }
650     if (!(lead & 2))
651     {
652         memcpy (dst, &attrUse, sizeof(attrUse));
653         dst += sizeof(attrUse);
654     }
655     *dst++ = p->reg_type;
656     memcpy (dst, string, length);
657     dst += length;
658     *dst++ = '\0';
659
660     if (!diff)
661     {
662         memcpy (dst, pseqno, sizeof(*pseqno));
663         dst += sizeof(*pseqno);
664     }
665     reckeys.buf_used = dst - reckeys.buf;
666     (*pseqno)++;
667 }
668
669 static void addSortString (RecWord *p, const char *string, int length)
670 {
671     struct sortKey *sk;
672
673     for (sk = sortKeys; sk; sk = sk->next)
674         if (sk->attrSet == p->attrSet && sk->attrUse == p->attrUse)
675             return;
676
677     sk = xmalloc (sizeof(*sk));
678     sk->next = sortKeys;
679     sortKeys = sk;
680
681     sk->string = xmalloc (p->length);
682     sk->length = p->length;
683     memcpy (sk->string, p->string, p->length);
684     sk->attrSet = p->attrSet;
685     sk->attrUse = p->attrUse;
686 }
687
688 static void addString (RecWord *p, const char *string, int length)
689 {
690     assert (length > 0);
691     if (zebra_maps_is_sort (p->zebra_maps, p->reg_type))
692         addSortString (p, string, length);
693     else
694         addIndexString (p, string, length);
695 }
696
697 static void addIncompleteField (RecWord *p)
698 {
699     const char *b = p->string;
700     int remain = p->length;
701     const char **map = 0;
702
703     if (remain > 0)
704         map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
705
706     while (map)
707     {
708         char buf[IT_MAX_WORD+1];
709         int i, remain;
710
711         /* Skip spaces */
712         while (map && *map && **map == *CHR_SPACE)
713         {
714             remain = p->length - (b - p->string);
715             if (remain > 0)
716                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
717             else
718                 map = 0;
719         }
720         if (!map)
721             break;
722         i = 0;
723         while (map && *map && **map != *CHR_SPACE)
724         {
725             const char *cp = *map;
726
727             while (i < IT_MAX_WORD && *cp)
728                 buf[i++] = *(cp++);
729             remain = p->length - (b - p->string);
730             if (remain > 0)
731                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
732             else
733                 map = 0;
734         }
735         if (!i)
736             return;
737         addString (p, buf, i);
738     }
739 }
740
741 static void addCompleteField (RecWord *p)
742 {
743     const char *b = p->string;
744     char buf[IT_MAX_WORD+1];
745     const char **map = 0;
746     int i = 0, remain = p->length;
747
748     if (remain > 0)
749         map = zebra_maps_input (p->zebra_maps, p->reg_type, &b, remain);
750
751     while (remain > 0 && i < IT_MAX_WORD)
752     {
753         while (map && *map && **map == *CHR_SPACE)
754         {
755             remain = p->length - (b - p->string);
756             if (remain > 0)
757                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
758             else
759                 map = 0;
760         }
761         if (!map)
762             break;
763
764         if (i && i < IT_MAX_WORD)
765             buf[i++] = *CHR_SPACE;
766         while (map && *map && **map != *CHR_SPACE)
767         {
768             const char *cp = *map;
769
770             if (i >= IT_MAX_WORD)
771                 break;
772             while (i < IT_MAX_WORD && *cp)
773                 buf[i++] = *(cp++);
774             remain = p->length  - (b - p->string);
775             if (remain > 0)
776                 map = zebra_maps_input (p->zebra_maps, p->reg_type, &b,
777                                         remain);
778             else
779                 map = 0;
780         }
781     }
782     if (!i)
783         return;
784     addString (p, buf, i);
785 }
786
787 static void addRecordKey (RecWord *p)
788 {
789     if (zebra_maps_is_complete (p->zebra_maps, p->reg_type))
790         addCompleteField (p);
791     else
792         addIncompleteField(p);
793 }
794
795 static void flushSortKeys (SYSNO sysno, int cmd)
796 {
797     struct sortKey *sk = sortKeys;
798
799     sortIdx_sysno (sortIdx, sysno);
800     while (sk)
801     {
802         struct sortKey *sk_next = sk->next;
803         sortIdx_type (sortIdx, sk->attrUse);
804         sortIdx_add (sortIdx, sk->string, sk->length);
805         xfree (sk->string);
806         xfree (sk);
807         sk = sk_next;
808     }
809     sortKeys = NULL;
810 }
811
812 static void flushRecordKeys (SYSNO sysno, int cmd, struct recKeys *reckeys)
813 {
814     char attrSet = -1;
815     short attrUse = -1;
816     int seqno = 0;
817     int off = 0;
818
819     zebraExplain_recordCountIncrement (zti, cmd ? 1 : -1);
820     while (off < reckeys->buf_used)
821     {
822         const char *src = reckeys->buf + off;
823         struct it_key key;
824         int lead, ch;
825     
826         lead = *src++;
827
828         if (!(lead & 1))
829         {
830             memcpy (&attrSet, src, sizeof(attrSet));
831             src += sizeof(attrSet);
832         }
833         if (!(lead & 2))
834         {
835             memcpy (&attrUse, src, sizeof(attrUse));
836             src += sizeof(attrUse);
837         }
838         if (key_buf_used + 1024 > (ptr_top-ptr_i)*sizeof(char*))
839             key_flush ();
840         ++ptr_i;
841         key_buf[ptr_top-ptr_i] = (char*)key_buf + key_buf_used;
842
843         ch = zebraExplain_lookupSU (zti, attrSet, attrUse);
844         if (ch < 0)
845             ch = zebraExplain_addSU (zti, attrSet, attrUse);
846         assert (ch > 0);
847         key_buf_used += key_SU_code (ch, ((char*)key_buf) + key_buf_used);
848
849         while (*src)
850             ((char*)key_buf) [key_buf_used++] = *src++;
851         src++;
852         ((char*)key_buf) [key_buf_used++] = '\0';
853         ((char*) key_buf)[key_buf_used++] = cmd;
854
855         if (lead & 60)
856             seqno += ((lead>>2) & 15)-1;
857         else
858         {
859             memcpy (&seqno, src, sizeof(seqno));
860             src += sizeof(seqno);
861         }
862         key.seqno = seqno;
863         key.sysno = sysno;
864         memcpy ((char*)key_buf + key_buf_used, &key, sizeof(key));
865         key_buf_used += sizeof(key);
866         off = src - reckeys->buf;
867     }
868     assert (off == reckeys->buf_used);
869 }
870
871 static const char **searchRecordKey (struct recKeys *reckeys,
872                                      int attrSetS, int attrUseS)
873 {
874     static const char *ws[32];
875     int off = 0;
876     int startSeq = -1;
877     int i;
878     short attrUse;
879     char attrSet;
880     int seqno = 0;
881
882     for (i = 0; i<32; i++)
883         ws[i] = NULL;
884     
885     while (off < reckeys->buf_used)
886     {
887
888         const char *src = reckeys->buf + off;
889         const char *wstart;
890         int lead;
891     
892         lead = *src++;
893
894         if (!(lead & 1))
895         {
896             memcpy (&attrSet, src, sizeof(attrSet));
897             src += sizeof(attrSet);
898         }
899         if (!(lead & 2))
900         {
901             memcpy (&attrUse, src, sizeof(attrUse));
902             src += sizeof(attrUse);
903         }
904         wstart = src;
905         while (*src++)
906             ;
907         if (lead & 60)
908             seqno += ((lead>>2) & 15)-1;
909         else
910         {
911             memcpy (&seqno, src, sizeof(seqno));
912             src += sizeof(seqno);
913         }
914         if (attrUseS == attrUse && attrSetS == attrSet)
915         {
916             int woff;
917
918
919             if (startSeq == -1)
920                 startSeq = seqno;
921             woff = seqno - startSeq;
922             if (woff >= 0 && woff < 31)
923                 ws[woff] = wstart;
924         }
925
926         off = src - reckeys->buf;
927     }
928     assert (off == reckeys->buf_used);
929     return ws;
930 }
931
932 struct file_read_info {
933     off_t file_max;
934     off_t file_offset;
935     off_t file_moffset;
936     int file_more;
937     int fd;
938 };
939
940 static struct file_read_info *file_read_start (int fd)
941 {
942     struct file_read_info *fi = xmalloc (sizeof(*fi));
943
944     fi->fd = fd;
945     fi->file_max = 0;
946     fi->file_moffset = 0;
947     return fi;
948 }
949
950 static void file_read_stop (struct file_read_info *fi)
951 {
952     xfree (fi);
953 }
954
955 static off_t file_seek (void *handle, off_t offset)
956 {
957     struct file_read_info *p = handle;
958     p->file_offset = offset;
959     return lseek (p->fd, offset, SEEK_SET);
960 }
961
962 static off_t file_tell (void *handle)
963 {
964     struct file_read_info *p = handle;
965     return p->file_offset;
966 }
967
968 static int file_read (void *handle, char *buf, size_t count)
969 {
970     struct file_read_info *p = handle;
971     int fd = p->fd;
972     int r;
973     r = read (fd, buf, count);
974     if (r > 0)
975     {
976         p->file_offset += r;
977         if (p->file_offset > p->file_max)
978             p->file_max = p->file_offset;
979     }
980     return r;
981 }
982
983 static void file_begin (void *handle)
984 {
985     struct file_read_info *p = handle;
986
987     p->file_offset = p->file_moffset;
988     if (p->file_moffset)
989         lseek (p->fd, p->file_moffset, SEEK_SET);
990     p->file_more = 0;
991 }
992
993 static void file_end (void *handle, off_t offset)
994 {
995     struct file_read_info *p = handle;
996
997     assert (p->file_more == 0);
998     p->file_more = 1;
999     p->file_moffset = offset;
1000 }
1001
1002 static int atois (const char **s)
1003 {
1004     int val = 0, c;
1005     while ( (c=**s) >= '0' && c <= '9')
1006     {
1007         val = val*10 + c - '0';
1008         ++(*s);
1009     }
1010     return val;
1011 }
1012
1013 static char *fileMatchStr (struct recKeys *reckeys, struct recordGroup *rGroup,
1014                            const char *fname,
1015                            const char *spec)
1016 {
1017     static char dstBuf[2048];
1018     char *dst = dstBuf;
1019     const char *s = spec;
1020     static const char **w;
1021     int i;
1022
1023     while (1)
1024     {
1025         while (*s == ' ' || *s == '\t')
1026             s++;
1027         if (!*s)
1028             break;
1029         if (*s == '(')
1030         {
1031             char matchFlag[32];
1032             int attrSet, attrUse;
1033             int first = 1;
1034
1035             s++;
1036             attrSet = atois (&s);
1037             if (*s != ',')
1038             {
1039                 logf (LOG_WARN, "Missing , in match criteria %s in group %s",
1040                       spec, rGroup->groupName ? rGroup->groupName : "none");
1041                 return NULL;
1042             }
1043             s++;
1044             attrUse = atois (&s);
1045             w = searchRecordKey (reckeys, attrSet, attrUse);
1046             assert (w);
1047
1048             if (*s == ')')
1049             {
1050                 for (i = 0; i<32; i++)
1051                     matchFlag[i] = 1;
1052             }
1053             else
1054             {
1055                 logf (LOG_WARN, "Missing ) in match criteria %s in group %s",
1056                       spec, rGroup->groupName ? rGroup->groupName : "none");
1057                 return NULL;
1058             }
1059             s++;
1060
1061             for (i = 0; i<32; i++)
1062                 if (matchFlag[i] && w[i])
1063                 {
1064                     if (first)
1065                     {
1066                         *dst++ = ' ';
1067                         first = 0;
1068                     }
1069                     strcpy (dst, w[i]);
1070                     dst += strlen(w[i]);
1071                 }
1072             if (first)
1073             {
1074                 logf (LOG_WARN, "Record didn't contain match"
1075                       " fields in (%d,%d)", attrSet, attrUse);
1076                 return NULL;
1077             }
1078         }
1079         else if (*s == '$')
1080         {
1081             int spec_len;
1082             char special[64];
1083             const char *spec_src = NULL;
1084             const char *s1 = ++s;
1085             while (*s1 && *s1 != ' ' && *s1 != '\t')
1086                 s1++;
1087
1088             spec_len = s1 - s;
1089             if (spec_len > 63)
1090                 spec_len = 63;
1091             memcpy (special, s, spec_len);
1092             special[spec_len] = '\0';
1093             s = s1;
1094
1095             if (!strcmp (special, "group"))
1096                 spec_src = rGroup->groupName;
1097             else if (!strcmp (special, "database"))
1098                 spec_src = rGroup->databaseName;
1099             else if (!strcmp (special, "filename"))
1100                 spec_src = fname;
1101             else if (!strcmp (special, "type"))
1102                 spec_src = rGroup->recordType;
1103             else 
1104                 spec_src = NULL;
1105             if (spec_src)
1106             {
1107                 strcpy (dst, spec_src);
1108                 dst += strlen (spec_src);
1109             }
1110         }
1111         else if (*s == '\"' || *s == '\'')
1112         {
1113             int stopMarker = *s++;
1114             char tmpString[64];
1115             int i = 0;
1116
1117             while (*s && *s != stopMarker)
1118             {
1119                 if (i < 63)
1120                     tmpString[i++] = *s++;
1121             }
1122             if (*s)
1123                 s++;
1124             tmpString[i] = '\0';
1125             strcpy (dst, tmpString);
1126             dst += strlen (tmpString);
1127         }
1128         else
1129         {
1130             logf (LOG_WARN, "Syntax error in match criteria %s in group %s",
1131                   spec, rGroup->groupName ? rGroup->groupName : "none");
1132             return NULL;
1133         }
1134         *dst++ = 1;
1135     }
1136     if (dst == dstBuf)
1137     {
1138         logf (LOG_WARN, "No match criteria for record %s in group %s",
1139               fname, rGroup->groupName ? rGroup->groupName : "none");
1140         return NULL;
1141     }
1142     *dst = '\0';
1143     return dstBuf;
1144 }
1145
1146 struct recordLogInfo {
1147     const char *fname;
1148     int recordOffset;
1149     struct recordGroup *rGroup;
1150 };
1151      
1152 static void recordLogPreamble (int level, const char *msg, void *info)
1153 {
1154     struct recordLogInfo *p = info;
1155     FILE *outf = log_file ();
1156
1157     if (level & LOG_LOG)
1158         return ;
1159     fprintf (outf, "File %s, offset %d, type %s\n",
1160              p->rGroup->recordType, p->recordOffset, p->fname);
1161     log_event_start (NULL, NULL);
1162 }
1163
1164 void addSchema (struct recExtractCtrl *p, Odr_oid *oid)
1165 {
1166     zebraExplain_addSchema (zti, oid);
1167 }
1168
1169 static int recordExtract (SYSNO *sysno, const char *fname,
1170                           struct recordGroup *rGroup, int deleteFlag,
1171                           struct file_read_info *fi,
1172                           RecType recType, char *subType)
1173 {
1174     RecordAttr *recordAttr;
1175     int r;
1176     char *matchStr;
1177     SYSNO sysnotmp;
1178     Record rec;
1179     struct recordLogInfo logInfo;
1180     off_t recordOffset = 0;
1181
1182     if (fi->fd != -1)
1183     {
1184         struct recExtractCtrl extractCtrl;
1185
1186         /* we are going to read from a file, so prepare the extraction */
1187         int i;
1188
1189         reckeys.buf_used = 0;
1190         reckeys.prevAttrUse = -1;
1191         reckeys.prevAttrSet = -1;
1192         reckeys.prevSeqNo = 0;
1193         
1194         recordOffset = fi->file_moffset;
1195         extractCtrl.offset = fi->file_moffset;
1196         extractCtrl.readf = file_read;
1197         extractCtrl.seekf = file_seek;
1198         extractCtrl.tellf = file_tell;
1199         extractCtrl.endf = file_end;
1200         extractCtrl.fh = fi;
1201         extractCtrl.subType = subType;
1202         extractCtrl.init = wordInit;
1203         extractCtrl.addWord = addRecordKey;
1204         extractCtrl.addSchema = addSchema;
1205         extractCtrl.dh = rGroup->dh;
1206         for (i = 0; i<256; i++)
1207             extractCtrl.seqno[i] = 0;
1208         extractCtrl.zebra_maps = rGroup->zebra_maps;
1209         extractCtrl.flagShowRecords = !rGroup->flagRw;
1210
1211         if (!rGroup->flagRw)
1212             printf ("File: %s %ld\n", fname, (long) recordOffset);
1213
1214         logInfo.fname = fname;
1215         logInfo.recordOffset = recordOffset;
1216         logInfo.rGroup = rGroup;
1217         log_event_start (recordLogPreamble, &logInfo);
1218
1219         r = (*recType->extract)(&extractCtrl);
1220
1221         log_event_start (NULL, NULL);
1222
1223         if (r)      
1224         {
1225             /* error occured during extraction ... */
1226             if (rGroup->flagRw &&
1227                 records_processed < rGroup->fileVerboseLimit)
1228             {
1229                 logf (LOG_WARN, "fail %s %s %ld code = %d", rGroup->recordType,
1230                       fname, (long) recordOffset, r);
1231             }
1232             return 0;
1233         }
1234         if (reckeys.buf_used == 0)
1235         {
1236             /* the extraction process returned no information - the record
1237                is probably empty - unless flagShowRecords is in use */
1238             if (!rGroup->flagRw)
1239                 return 1;
1240             logf (LOG_WARN, "No keys generated for file %s", fname);
1241             logf (LOG_WARN, " The file is probably empty");
1242             return 0;
1243         }
1244     }
1245
1246     /* perform match if sysno not known and if match criteria is specified */
1247        
1248     matchStr = NULL;
1249     if (!sysno) 
1250     {
1251         sysnotmp = 0;
1252         sysno = &sysnotmp;
1253         if (rGroup->recordId && *rGroup->recordId)
1254         {
1255             char *rinfo;
1256         
1257             matchStr = fileMatchStr (&reckeys, rGroup, fname, 
1258                                      rGroup->recordId);
1259             if (matchStr)
1260             {
1261                 rinfo = dict_lookup (matchDict, matchStr);
1262                 if (rinfo)
1263                     memcpy (sysno, rinfo+1, sizeof(*sysno));
1264             }
1265             else
1266             {
1267                 logf (LOG_WARN, "Bad match criteria");
1268                 return 0;
1269             }
1270         }
1271     }
1272
1273     if (! *sysno)
1274     {
1275         /* new record */
1276         if (deleteFlag)
1277         {
1278             logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType,
1279                   fname, (long) recordOffset);
1280             logf (LOG_WARN, "cannot delete record above (seems new)");
1281             return 1;
1282         }
1283         if (records_processed < rGroup->fileVerboseLimit)
1284             logf (LOG_LOG, "add %s %s %ld", rGroup->recordType,
1285                   fname, (long) recordOffset);
1286         rec = rec_new (records);
1287
1288         *sysno = rec->sysno;
1289
1290         recordAttr = rec_init_attr (zti, rec);
1291
1292         if (matchStr)
1293         {
1294             dict_insert (matchDict, matchStr, sizeof(*sysno), sysno);
1295         }
1296         flushRecordKeys (*sysno, 1, &reckeys);
1297         flushSortKeys (*sysno, 1);
1298
1299         records_inserted++;
1300     }
1301     else
1302     {
1303         /* record already exists */
1304         struct recKeys delkeys;
1305
1306         rec = rec_get (records, *sysno);
1307         assert (rec);
1308         
1309         recordAttr = rec_init_attr (zti, rec);
1310
1311         if (recordAttr->runNumber == zebraExplain_runNumberIncrement (zti, 0))
1312         {
1313             logf (LOG_LOG, "skipped %s %s %ld", rGroup->recordType,
1314                   fname, (long) recordOffset);
1315             rec_rm (&rec);
1316             logRecord (0);
1317             return 1;
1318         }
1319         delkeys.buf_used = rec->size[recInfo_delKeys];
1320         delkeys.buf = rec->info[recInfo_delKeys];
1321         flushSortKeys (*sysno, 0);
1322         flushRecordKeys (*sysno, 0, &delkeys);
1323         if (deleteFlag)
1324         {
1325             /* record going to be deleted */
1326             if (!delkeys.buf_used)
1327             {
1328                 logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType,
1329                       fname, (long) recordOffset);
1330                 logf (LOG_WARN, "cannot delete file above, storeKeys false");
1331             }
1332             else
1333             {
1334                 if (records_processed < rGroup->fileVerboseLimit)
1335                     logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType,
1336                           fname, (long) recordOffset);
1337                 records_deleted++;
1338                 if (matchStr)
1339                     dict_delete (matchDict, matchStr);
1340                 rec_del (records, &rec);
1341             }
1342             rec_rm (&rec);
1343             logRecord (0);
1344             return 1;
1345         }
1346         else
1347         {
1348             /* record going to be updated */
1349             if (!delkeys.buf_used)
1350             {
1351                 logf (LOG_LOG, "update %s %s %ld", rGroup->recordType,
1352                       fname, (long) recordOffset);
1353                 logf (LOG_WARN, "cannot update file above, storeKeys false");
1354             }
1355             else
1356             {
1357                 if (records_processed < rGroup->fileVerboseLimit)
1358                     logf (LOG_LOG, "update %s %s %ld", rGroup->recordType,
1359                           fname, (long) recordOffset);
1360                 flushRecordKeys (*sysno, 1, &reckeys);
1361                 records_updated++;
1362             }
1363         }
1364     }
1365     /* update file type */
1366     xfree (rec->info[recInfo_fileType]);
1367     rec->info[recInfo_fileType] =
1368         rec_strdup (rGroup->recordType, &rec->size[recInfo_fileType]);
1369
1370     /* update filename */
1371     xfree (rec->info[recInfo_filename]);
1372     rec->info[recInfo_filename] =
1373         rec_strdup (fname, &rec->size[recInfo_filename]);
1374
1375     /* update delete keys */
1376     xfree (rec->info[recInfo_delKeys]);
1377     if (reckeys.buf_used > 0 && rGroup->flagStoreKeys == 1)
1378     {
1379 #if 1
1380         rec->size[recInfo_delKeys] = reckeys.buf_used;
1381         rec->info[recInfo_delKeys] = reckeys.buf;
1382         reckeys.buf = NULL;
1383         reckeys.buf_max = 0;
1384 #else
1385         rec->info[recInfo_delKeys] = xmalloc (reckeys.buf_used);
1386         rec->size[recInfo_delKeys] = reckeys.buf_used;
1387         memcpy (rec->info[recInfo_delKeys], reckeys.buf,
1388                 rec->size[recInfo_delKeys]);
1389 #endif
1390     }
1391     else
1392     {
1393         rec->info[recInfo_delKeys] = NULL;
1394         rec->size[recInfo_delKeys] = 0;
1395     }
1396
1397     /* save file size of original record */
1398     zebraExplain_recordBytesIncrement (zti, - recordAttr->recordSize);
1399     recordAttr->recordSize = fi->file_moffset - recordOffset;
1400     if (!recordAttr->recordSize)
1401         recordAttr->recordSize = fi->file_max - recordOffset;
1402     zebraExplain_recordBytesIncrement (zti, recordAttr->recordSize);
1403
1404     /* set run-number for this record */
1405     recordAttr->runNumber = zebraExplain_runNumberIncrement (zti, 0);
1406
1407     /* update store data */
1408     xfree (rec->info[recInfo_storeData]);
1409     if (rGroup->flagStoreData == 1)
1410     {
1411         rec->size[recInfo_storeData] = recordAttr->recordSize;
1412         rec->info[recInfo_storeData] = xmalloc (recordAttr->recordSize);
1413         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
1414         {
1415             logf (LOG_ERRNO|LOG_FATAL, "seek to %ld in %s", fname,
1416                   (long) recordOffset);
1417             exit (1);
1418         }
1419         if (read (fi->fd, rec->info[recInfo_storeData], recordAttr->recordSize)
1420             < recordAttr->recordSize)
1421         {
1422             logf (LOG_ERRNO|LOG_FATAL, "read %d bytes of %s",
1423                   recordAttr->recordSize, fname);
1424             exit (1);
1425         }
1426     }
1427     else
1428     {
1429         rec->info[recInfo_storeData] = NULL;
1430         rec->size[recInfo_storeData] = 0;
1431     }
1432     /* update database name */
1433     xfree (rec->info[recInfo_databaseName]);
1434     rec->info[recInfo_databaseName] =
1435         rec_strdup (rGroup->databaseName, &rec->size[recInfo_databaseName]); 
1436
1437     /* update offset */
1438     recordAttr->recordOffset = recordOffset;
1439     
1440     /* commit this record */
1441     rec_put (records, &rec);
1442     logRecord (0);
1443     return 1;
1444 }
1445
1446 int fileExtract (SYSNO *sysno, const char *fname, 
1447                  const struct recordGroup *rGroupP, int deleteFlag)
1448 {
1449     int r, i, fd;
1450     char gprefix[128];
1451     char ext[128];
1452     char ext_res[128];
1453     char subType[128];
1454     RecType recType;
1455     struct recordGroup rGroupM;
1456     struct recordGroup *rGroup = &rGroupM;
1457     struct file_read_info *fi;
1458
1459     memcpy (rGroup, rGroupP, sizeof(*rGroupP));
1460    
1461     if (!rGroup->groupName || !*rGroup->groupName)
1462         *gprefix = '\0';
1463     else
1464         sprintf (gprefix, "%s.", rGroup->groupName);
1465
1466     logf (LOG_DEBUG, "fileExtract %s", fname);
1467
1468     /* determine file extension */
1469     *ext = '\0';
1470     for (i = strlen(fname); --i >= 0; )
1471         if (fname[i] == '/')
1472             break;
1473         else if (fname[i] == '.')
1474         {
1475             strcpy (ext, fname+i+1);
1476             break;
1477         }
1478     /* determine file type - depending on extension */
1479     if (!rGroup->recordType)
1480     {
1481         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1482         if (!(rGroup->recordType = res_get (common_resource, ext_res)))
1483         {
1484             sprintf (ext_res, "%srecordType", gprefix);
1485             rGroup->recordType = res_get (common_resource, ext_res);
1486         }
1487     }
1488     if (!rGroup->recordType)
1489     {
1490         if (records_processed < rGroup->fileVerboseLimit)
1491             logf (LOG_LOG, "? %s", fname);
1492         return 0;
1493     }
1494     if (!*rGroup->recordType)
1495         return 0;
1496     if (!(recType = recType_byName (rGroup->recordType, subType)))
1497     {
1498         logf (LOG_WARN, "No such record type: %s", rGroup->recordType);
1499         return 0;
1500     }
1501
1502     /* determine match criteria */
1503     if (!rGroup->recordId)
1504     {
1505         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1506         rGroup->recordId = res_get (common_resource, ext_res);
1507     }
1508
1509     /* determine database name */
1510     if (!rGroup->databaseName)
1511     {
1512         sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1513         if (!(rGroup->databaseName = res_get (common_resource, ext_res)))
1514         {
1515             sprintf (ext_res, "%sdatabase", gprefix);
1516             rGroup->databaseName = res_get (common_resource, ext_res);
1517         }
1518     }
1519     if (!rGroup->databaseName)
1520         rGroup->databaseName = "Default";
1521
1522     /* determine if explain database */
1523     
1524     sprintf (ext_res, "%sexplainDatabase", gprefix);
1525     rGroup->explainDatabase =
1526         atoi (res_get_def (common_resource, ext_res, "0"));
1527
1528     /* announce database */
1529     if (zebraExplain_curDatabase (zti, rGroup->databaseName))
1530     {
1531         if (zebraExplain_newDatabase (zti, rGroup->databaseName,
1532                                       rGroup->explainDatabase))
1533             abort ();
1534     }
1535
1536     if (rGroup->flagStoreData == -1)
1537     {
1538         const char *sval;
1539         sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1540         if (!(sval = res_get (common_resource, ext_res)))
1541         {
1542             sprintf (ext_res, "%sstoreData", gprefix);
1543             sval = res_get (common_resource, ext_res);
1544         }
1545         if (sval)
1546             rGroup->flagStoreData = atoi (sval);
1547     }
1548     if (rGroup->flagStoreData == -1)
1549         rGroup->flagStoreData = 0;
1550
1551     if (rGroup->flagStoreKeys == -1)
1552     {
1553         const char *sval;
1554
1555         sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1556         if (!(sval = res_get (common_resource, ext_res)))
1557         {
1558             sprintf (ext_res, "%sstoreKeys", gprefix);
1559             sval = res_get (common_resource, ext_res);
1560         }
1561         if (sval)
1562             rGroup->flagStoreKeys = atoi (sval);
1563     }
1564     if (rGroup->flagStoreKeys == -1)
1565         rGroup->flagStoreKeys = 0;
1566
1567     if (sysno && deleteFlag)
1568         fd = -1;
1569     else
1570     {
1571         if ((fd = open (fname, O_BINARY|O_RDONLY)) == -1)
1572         {
1573             logf (LOG_WARN|LOG_ERRNO, "open %s", fname);
1574             return 0;
1575         }
1576     }
1577     fi = file_read_start (fd);
1578     do
1579     {
1580         file_begin (fi);
1581         r = recordExtract (sysno, fname, rGroup, deleteFlag, fi,
1582                            recType, subType);
1583     } while (r && !sysno && fi->file_more);
1584     file_read_stop (fi);
1585     if (fd != -1)
1586         close (fd);
1587     return r;
1588 }
1589
1590 static int explain_extract (void *handle, Record rec, data1_node *n)
1591 {
1592     struct recordGroup *rGroup = (struct recordGroup*) handle;
1593     struct recExtractCtrl extractCtrl;
1594     int i;
1595
1596     if (zebraExplain_curDatabase (zti, rec->info[recInfo_databaseName]))
1597     {
1598         if (zebraExplain_newDatabase (zti, rec->info[recInfo_databaseName], 0))
1599             abort ();
1600     }
1601
1602     reckeys.buf_used = 0;
1603     reckeys.prevAttrUse = -1;
1604     reckeys.prevAttrSet = -1;
1605     reckeys.prevSeqNo = 0;
1606     
1607     extractCtrl.init = wordInit;
1608     extractCtrl.addWord = addRecordKey;
1609     extractCtrl.addSchema = addSchema;
1610     extractCtrl.dh = rGroup->dh;
1611     for (i = 0; i<256; i++)
1612         extractCtrl.seqno[i] = 0;
1613     extractCtrl.zebra_maps = rGroup->zebra_maps;
1614     extractCtrl.flagShowRecords = !rGroup->flagRw;
1615     
1616     grs_extract_tree(&extractCtrl, n);
1617
1618     logf (LOG_DEBUG, "flush explain record, sysno=%d", rec->sysno);
1619
1620     if (rec->size[recInfo_delKeys])
1621     {
1622         struct recKeys delkeys;
1623
1624         delkeys.buf_used = rec->size[recInfo_delKeys];
1625         delkeys.buf = rec->info[recInfo_delKeys];
1626         flushSortKeys (rec->sysno, 0);
1627         flushRecordKeys (rec->sysno, 0, &delkeys);
1628     }
1629     flushRecordKeys (rec->sysno, 1, &reckeys);
1630     flushSortKeys (rec->sysno, 1);
1631
1632     xfree (rec->info[recInfo_delKeys]);
1633     rec->size[recInfo_delKeys] = reckeys.buf_used;
1634     rec->info[recInfo_delKeys] = reckeys.buf;
1635     reckeys.buf = NULL;
1636     reckeys.buf_max = 0;
1637
1638     return 0;
1639 }