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