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