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