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