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