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