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