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