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