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