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