7bb00b7180b1ac1d3ca450d67185d6308e83d029
[idzebra-moved-to-github.git] / index / extract.c
1 /* $Id: extract.c,v 1.122 2002-08-29 08:47:08 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002
3    Index Data Aps
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23
24 #include <stdio.h>
25 #include <assert.h>
26 #ifdef WIN32
27 #include <io.h>
28 #else
29 #include <unistd.h>
30 #endif
31 #include <fcntl.h>
32
33 #include "index.h"
34 #include <direntz.h>
35 #include <charmap.h>
36
37 #if _FILE_OFFSET_BITS == 64
38 #define PRINTF_OFF_T "%Ld"
39 #else
40 #define PRINTF_OFF_T "%ld"
41 #endif
42
43 #define USE_SHELLSORT 0
44
45 #if USE_SHELLSORT
46 static void shellsort(void *ar, int r, size_t s,
47                       int (*cmp)(const void *a, const void *b))
48 {
49     char *a = ar;
50     char v[100];
51     int h, i, j, k;
52     static const int incs[16] = { 1391376, 463792, 198768, 86961, 33936,
53                                   13776, 4592, 1968, 861, 336, 
54                                   112, 48, 21, 7, 3, 1 };
55     for ( k = 0; k < 16; k++)
56         for (h = incs[k], i = h; i < r; i++)
57         { 
58             memcpy (v, a+s*i, s);
59             j = i;
60             while (j > h && (*cmp)(a + s*(j-h), v) > 0)
61             {
62                 memcpy (a + s*j, a + s*(j-h), s);
63                 j -= h;
64             }
65             memcpy (a+s*j, v, s);
66         } 
67 }
68 #endif
69
70 static void logRecord (ZebraHandle zh)
71 {
72     ++zh->records_processed;
73     if (!(zh->records_processed % 1000))
74     {
75         logf (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
76               zh->records_processed, zh->records_inserted, zh->records_updated,
77               zh->records_deleted);
78     }
79 }
80
81 static void extract_init (struct recExtractCtrl *p, RecWord *w)
82 {
83     w->zebra_maps = p->zebra_maps;
84     w->seqno = 1;
85     w->attrSet = VAL_BIB1;
86     w->attrUse = 1016;
87     w->reg_type = 'w';
88     w->extractCtrl = p;
89 }
90
91 static const char **searchRecordKey (ZebraHandle zh,
92                                      struct recKeys *reckeys,
93                                      int attrSetS, int attrUseS)
94 {
95     static const char *ws[32];
96     int off = 0;
97     int startSeq = -1;
98     int i;
99     int seqno = 0;
100 #if SU_SCHEME
101     int chS, ch;
102 #else
103     short attrUse;
104     char attrSet;
105 #endif
106
107     for (i = 0; i<32; i++)
108         ws[i] = NULL;
109
110 #if SU_SCHEME
111     chS = zebraExplain_lookupSU (zh->reg->zei, attrSetS, attrUseS);
112     if (chS < 0)
113         return ws;
114 #endif
115     while (off < reckeys->buf_used)
116     {
117
118         const char *src = reckeys->buf + off;
119         const char *wstart;
120         int lead;
121     
122         lead = *src++;
123 #if SU_SCHEME
124         if ((lead & 3)<3)
125         {
126             memcpy (&ch, src, sizeof(ch));
127             src += sizeof(ch);
128         }
129 #else
130         if (!(lead & 1))
131         {
132             memcpy (&attrSet, src, sizeof(attrSet));
133             src += sizeof(attrSet);
134         }
135         if (!(lead & 2))
136         {
137             memcpy (&attrUse, src, sizeof(attrUse));
138             src += sizeof(attrUse);
139         }
140 #endif
141         wstart = src;
142         while (*src++)
143             ;
144         if (lead & 60)
145             seqno += ((lead>>2) & 15)-1;
146         else
147         {
148             memcpy (&seqno, src, sizeof(seqno));
149             src += sizeof(seqno);
150         }
151         if (
152 #if SU_SCHEME
153             ch == chS
154 #else
155             attrUseS == attrUse && attrSetS == attrSet
156 #endif
157             )
158         {
159             int woff;
160
161
162             if (startSeq == -1)
163                 startSeq = seqno;
164             woff = seqno - startSeq;
165             if (woff >= 0 && woff < 31)
166                 ws[woff] = wstart;
167         }
168
169         off = src - reckeys->buf;
170     }
171     assert (off == reckeys->buf_used);
172     return ws;
173 }
174
175 struct file_read_info {
176     off_t file_max;         /* maximum offset so far */
177     off_t file_offset;      /* current offset */
178     off_t file_moffset;     /* offset of rec/rec boundary */
179     int file_more;
180     int fd;
181     char *sdrbuf;
182     int sdrmax;
183 };
184
185 static struct file_read_info *file_read_start (int fd)
186 {
187     struct file_read_info *fi = (struct file_read_info *)
188         xmalloc (sizeof(*fi));
189
190     fi->fd = fd;
191     fi->file_max = 0;
192     fi->file_moffset = 0;
193     fi->sdrbuf = 0;
194     fi->sdrmax = 0;
195     return fi;
196 }
197
198 static void file_read_stop (struct file_read_info *fi)
199 {
200     xfree (fi);
201 }
202
203 static off_t file_seek (void *handle, off_t offset)
204 {
205     struct file_read_info *p = (struct file_read_info *) handle;
206     p->file_offset = offset;
207     if (p->sdrbuf)
208         return offset;
209     return lseek (p->fd, offset, SEEK_SET);
210 }
211
212 static off_t file_tell (void *handle)
213 {
214     struct file_read_info *p = (struct file_read_info *) handle;
215     return p->file_offset;
216 }
217
218 static int file_read (void *handle, char *buf, size_t count)
219 {
220     struct file_read_info *p = (struct file_read_info *) handle;
221     int fd = p->fd;
222     int r;
223     if (p->sdrbuf)
224     {
225         r = count;
226         if (r > p->sdrmax - p->file_offset)
227             r = p->sdrmax - p->file_offset;
228         if (r)
229             memcpy (buf, p->sdrbuf + p->file_offset, r);
230     }
231     else
232         r = read (fd, buf, count);
233     if (r > 0)
234     {
235         p->file_offset += r;
236         if (p->file_offset > p->file_max)
237             p->file_max = p->file_offset;
238     }
239     return r;
240 }
241
242 static void file_begin (void *handle)
243 {
244     struct file_read_info *p = (struct file_read_info *) handle;
245
246     p->file_offset = p->file_moffset;
247     if (!p->sdrbuf && p->file_moffset)
248         lseek (p->fd, p->file_moffset, SEEK_SET);
249     p->file_more = 0;
250 }
251
252 static void file_end (void *handle, off_t offset)
253 {
254     struct file_read_info *p = (struct file_read_info *) handle;
255
256     assert (p->file_more == 0);
257     p->file_more = 1;
258     p->file_moffset = offset;
259 }
260
261 static char *fileMatchStr (ZebraHandle zh,
262                            struct recKeys *reckeys, struct recordGroup *rGroup,
263                            const char *fname, const char *spec)
264 {
265     static char dstBuf[2048];      /* static here ??? */
266     char *dst = dstBuf;
267     const char *s = spec;
268     static const char **w;
269
270     while (1)
271     {
272         while (*s == ' ' || *s == '\t')
273             s++;
274         if (!*s)
275             break;
276         if (*s == '(')
277         {
278             char attset_str[64], attname_str[64];
279             data1_attset *attset;
280             int i;
281             char matchFlag[32];
282             int attSet = 1, attUse = 1;
283             int first = 1;
284
285             s++;
286             for (i = 0; *s && *s != ',' && *s != ')'; s++)
287                 if (i < 63)
288                     attset_str[i++] = *s;
289             attset_str[i] = '\0';
290
291             if (*s == ',')
292             {
293                 s++;
294                 for (i = 0; *s && *s != ')'; s++)
295                     if (i < 63)
296                         attname_str[i++] = *s;
297                 attname_str[i] = '\0';
298             }
299             
300             if ((attset = data1_get_attset (zh->reg->dh, attset_str)))
301             {
302                 data1_att *att;
303                 attSet = attset->reference;
304                 att = data1_getattbyname(zh->reg->dh, attset, attname_str);
305                 if (att)
306                     attUse = att->value;
307                 else
308                     attUse = atoi (attname_str);
309             }
310             w = searchRecordKey (zh, reckeys, attSet, attUse);
311             assert (w);
312
313             if (*s == ')')
314             {
315                 for (i = 0; i<32; i++)
316                     matchFlag[i] = 1;
317             }
318             else
319             {
320                 logf (LOG_WARN, "Missing ) in match criteria %s in group %s",
321                       spec, rGroup->groupName ? rGroup->groupName : "none");
322                 return NULL;
323             }
324             s++;
325
326             for (i = 0; i<32; i++)
327                 if (matchFlag[i] && w[i])
328                 {
329                     if (first)
330                     {
331                         *dst++ = ' ';
332                         first = 0;
333                     }
334                     strcpy (dst, w[i]);
335                     dst += strlen(w[i]);
336                 }
337             if (first)
338             {
339                 logf (LOG_WARN, "Record didn't contain match"
340                       " fields in (%s,%s)", attset_str, attname_str);
341                 return NULL;
342             }
343         }
344         else if (*s == '$')
345         {
346             int spec_len;
347             char special[64];
348             const char *spec_src = NULL;
349             const char *s1 = ++s;
350             while (*s1 && *s1 != ' ' && *s1 != '\t')
351                 s1++;
352
353             spec_len = s1 - s;
354             if (spec_len > 63)
355                 spec_len = 63;
356             memcpy (special, s, spec_len);
357             special[spec_len] = '\0';
358             s = s1;
359
360             if (!strcmp (special, "group"))
361                 spec_src = rGroup->groupName;
362             else if (!strcmp (special, "database"))
363                 spec_src = rGroup->databaseName;
364             else if (!strcmp (special, "filename"))
365                 spec_src = fname;
366             else if (!strcmp (special, "type"))
367                 spec_src = rGroup->recordType;
368             else 
369                 spec_src = NULL;
370             if (spec_src)
371             {
372                 strcpy (dst, spec_src);
373                 dst += strlen (spec_src);
374             }
375         }
376         else if (*s == '\"' || *s == '\'')
377         {
378             int stopMarker = *s++;
379             char tmpString[64];
380             int i = 0;
381
382             while (*s && *s != stopMarker)
383             {
384                 if (i < 63)
385                     tmpString[i++] = *s++;
386             }
387             if (*s)
388                 s++;
389             tmpString[i] = '\0';
390             strcpy (dst, tmpString);
391             dst += strlen (tmpString);
392         }
393         else
394         {
395             logf (LOG_WARN, "Syntax error in match criteria %s in group %s",
396                   spec, rGroup->groupName ? rGroup->groupName : "none");
397             return NULL;
398         }
399         *dst++ = 1;
400     }
401     if (dst == dstBuf)
402     {
403         logf (LOG_WARN, "No match criteria for record %s in group %s",
404               fname, rGroup->groupName ? rGroup->groupName : "none");
405         return NULL;
406     }
407     *dst = '\0';
408     return dstBuf;
409 }
410
411 struct recordLogInfo {
412     const char *fname;
413     int recordOffset;
414     struct recordGroup *rGroup;
415 };
416      
417 static void recordLogPreamble (int level, const char *msg, void *info)
418 {
419     struct recordLogInfo *p = (struct recordLogInfo *) info;
420     FILE *outf = yaz_log_file ();
421
422     if (level & LOG_LOG)
423         return ;
424     fprintf (outf, "File %s, offset %d, type %s\n",
425              p->fname, p->recordOffset, p->rGroup->recordType);
426     log_event_start (NULL, NULL);
427 }
428
429
430 static int recordExtract (ZebraHandle zh,
431                           SYSNO *sysno, const char *fname,
432                           struct recordGroup *rGroup, int deleteFlag,
433                           struct file_read_info *fi,
434                           RecType recType, char *subType, void *clientData)
435 {
436     RecordAttr *recordAttr;
437     int r;
438     char *matchStr;
439     SYSNO sysnotmp;
440     Record rec;
441     struct recordLogInfo logInfo;
442     off_t recordOffset = 0;
443
444     if (fi->fd != -1)
445     {
446         struct recExtractCtrl extractCtrl;
447
448         /* we are going to read from a file, so prepare the extraction */
449         int i;
450
451         zh->reg->keys.buf_used = 0;
452         zh->reg->keys.prevAttrUse = -1;
453         zh->reg->keys.prevAttrSet = -1;
454         zh->reg->keys.prevSeqNo = 0;
455         zh->reg->sortKeys = 0;
456         
457         recordOffset = fi->file_moffset;
458         extractCtrl.offset = fi->file_moffset;
459         extractCtrl.readf = file_read;
460         extractCtrl.seekf = file_seek;
461         extractCtrl.tellf = file_tell;
462         extractCtrl.endf = file_end;
463         extractCtrl.fh = fi;
464         extractCtrl.subType = subType;
465         extractCtrl.init = extract_init;
466         extractCtrl.tokenAdd = extract_token_add;
467         extractCtrl.schemaAdd = extract_schema_add;
468         extractCtrl.dh = zh->reg->dh;
469         extractCtrl.handle = zh;
470         for (i = 0; i<256; i++)
471         {
472             if (zebra_maps_is_positioned(zh->reg->zebra_maps, i))
473                 extractCtrl.seqno[i] = 1;
474             else
475                 extractCtrl.seqno[i] = 0;
476         }
477         extractCtrl.zebra_maps = zh->reg->zebra_maps;
478         extractCtrl.flagShowRecords = !rGroup->flagRw;
479
480         if (!rGroup->flagRw)
481             printf ("File: %s " PRINTF_OFF_T "\n", fname, recordOffset);
482
483         logInfo.fname = fname;
484         logInfo.recordOffset = recordOffset;
485         logInfo.rGroup = rGroup;
486         log_event_start (recordLogPreamble, &logInfo);
487
488         r = (*recType->extract)(clientData, &extractCtrl);
489
490         log_event_start (NULL, NULL);
491
492         if (r == RECCTRL_EXTRACT_EOF)
493             return 0;
494         else if (r == RECCTRL_EXTRACT_ERROR_GENERIC)
495         {
496             /* error occured during extraction ... */
497             if (rGroup->flagRw &&
498                 zh->records_processed < rGroup->fileVerboseLimit)
499             {
500                 logf (LOG_WARN, "fail %s %s " PRINTF_OFF_T, rGroup->recordType,
501                       fname, recordOffset);
502             }
503             return 0;
504         }
505         else if (r == RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER)
506         {
507             /* error occured during extraction ... */
508             if (rGroup->flagRw &&
509                 zh->records_processed < rGroup->fileVerboseLimit)
510             {
511                 logf (LOG_WARN, "no filter for %s %s " 
512                       PRINTF_OFF_T, rGroup->recordType,
513                       fname, recordOffset);
514             }
515             return 0;
516         }
517         if (zh->reg->keys.buf_used == 0)
518         {
519             /* the extraction process returned no information - the record
520                is probably empty - unless flagShowRecords is in use */
521             if (!rGroup->flagRw)
522                 return 1;
523             
524             logf (LOG_WARN, "empty %s %s " PRINTF_OFF_T, rGroup->recordType,
525                   fname, recordOffset);
526             return 1;
527         }
528     }
529
530     /* perform match if sysno not known and if match criteria is specified */
531        
532     matchStr = NULL;
533     if (!sysno) 
534     {
535         sysnotmp = 0;
536         sysno = &sysnotmp;
537         if (rGroup->recordId && *rGroup->recordId)
538         {
539             char *rinfo;
540         
541             matchStr = fileMatchStr (zh, &zh->reg->keys, rGroup, fname, 
542                                      rGroup->recordId);
543             if (matchStr)
544             {
545                 rinfo = dict_lookup (zh->reg->matchDict, matchStr);
546                 if (rinfo)
547                     memcpy (sysno, rinfo+1, sizeof(*sysno));
548             }
549             else
550             {
551                 logf (LOG_WARN, "Bad match criteria");
552                 return 0;
553             }
554         }
555     }
556
557     if (! *sysno)
558     {
559         /* new record */
560         if (deleteFlag)
561         {
562             logf (LOG_LOG, "delete %s %s " PRINTF_OFF_T, rGroup->recordType,
563                   fname, recordOffset);
564             logf (LOG_WARN, "cannot delete record above (seems new)");
565             return 1;
566         }
567         if (zh->records_processed < rGroup->fileVerboseLimit)
568             logf (LOG_LOG, "add %s %s " PRINTF_OFF_T, rGroup->recordType,
569                   fname, recordOffset);
570         rec = rec_new (zh->reg->records);
571
572         *sysno = rec->sysno;
573
574         recordAttr = rec_init_attr (zh->reg->zei, rec);
575
576         if (matchStr)
577         {
578             dict_insert (zh->reg->matchDict, matchStr, sizeof(*sysno), sysno);
579         }
580         extract_flushRecordKeys (zh, *sysno, 1, &zh->reg->keys);
581         extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
582
583         zh->records_inserted++;
584     }
585     else
586     {
587         /* record already exists */
588         struct recKeys delkeys;
589
590         rec = rec_get (zh->reg->records, *sysno);
591         assert (rec);
592         
593         recordAttr = rec_init_attr (zh->reg->zei, rec);
594
595         if (recordAttr->runNumber ==
596             zebraExplain_runNumberIncrement (zh->reg->zei, 0))
597         {
598             yaz_log (LOG_LOG, "run number = %d", recordAttr->runNumber);
599             yaz_log (LOG_LOG, "skipped %s %s " PRINTF_OFF_T,
600                      rGroup->recordType, fname, recordOffset);
601             extract_flushSortKeys (zh, *sysno, -1, &zh->reg->sortKeys);
602             rec_rm (&rec);
603             logRecord (zh);
604             return 1;
605         }
606         delkeys.buf_used = rec->size[recInfo_delKeys];
607         delkeys.buf = rec->info[recInfo_delKeys];
608         extract_flushSortKeys (zh, *sysno, 0, &zh->reg->sortKeys);
609         extract_flushRecordKeys (zh, *sysno, 0, &delkeys);
610         if (deleteFlag)
611         {
612             /* record going to be deleted */
613             if (!delkeys.buf_used)
614             {
615                 logf (LOG_LOG, "delete %s %s " PRINTF_OFF_T,
616                       rGroup->recordType, fname, recordOffset);
617                 logf (LOG_WARN, "cannot delete file above, storeKeys false");
618             }
619             else
620             {
621                 if (zh->records_processed < rGroup->fileVerboseLimit)
622                     logf (LOG_LOG, "delete %s %s " PRINTF_OFF_T,
623                          rGroup->recordType, fname, recordOffset);
624                 zh->records_deleted++;
625                 if (matchStr)
626                     dict_delete (zh->reg->matchDict, matchStr);
627                 rec_del (zh->reg->records, &rec);
628             }
629             rec_rm (&rec);
630             logRecord (zh);
631             return 1;
632         }
633         else
634         {
635             /* record going to be updated */
636             if (!delkeys.buf_used)
637             {
638                 logf (LOG_LOG, "update %s %s " PRINTF_OFF_T,
639                       rGroup->recordType, fname, recordOffset);
640                 logf (LOG_WARN, "cannot update file above, storeKeys false");
641             }
642             else
643             {
644                 if (zh->records_processed < rGroup->fileVerboseLimit)
645                     logf (LOG_LOG, "update %s %s " PRINTF_OFF_T,
646                         rGroup->recordType, fname, recordOffset);
647                 extract_flushRecordKeys (zh, *sysno, 1, &zh->reg->keys);
648                 zh->records_updated++;
649             }
650         }
651     }
652     /* update file type */
653     xfree (rec->info[recInfo_fileType]);
654     rec->info[recInfo_fileType] =
655         rec_strdup (rGroup->recordType, &rec->size[recInfo_fileType]);
656
657     /* update filename */
658     xfree (rec->info[recInfo_filename]);
659     rec->info[recInfo_filename] =
660         rec_strdup (fname, &rec->size[recInfo_filename]);
661
662     /* update delete keys */
663     xfree (rec->info[recInfo_delKeys]);
664     if (zh->reg->keys.buf_used > 0 && rGroup->flagStoreKeys == 1)
665     {
666 #if 1
667         rec->size[recInfo_delKeys] = zh->reg->keys.buf_used;
668         rec->info[recInfo_delKeys] = zh->reg->keys.buf;
669         zh->reg->keys.buf = NULL;
670         zh->reg->keys.buf_max = 0;
671 #else
672         rec->info[recInfo_delKeys] = xmalloc (reckeys.buf_used);
673         rec->size[recInfo_delKeys] = reckeys.buf_used;
674         memcpy (rec->info[recInfo_delKeys], reckeys.buf,
675                 rec->size[recInfo_delKeys]);
676 #endif
677     }
678     else
679     {
680         rec->info[recInfo_delKeys] = NULL;
681         rec->size[recInfo_delKeys] = 0;
682     }
683
684     /* save file size of original record */
685     zebraExplain_recordBytesIncrement (zh->reg->zei,
686                                        - recordAttr->recordSize);
687     recordAttr->recordSize = fi->file_moffset - recordOffset;
688     if (!recordAttr->recordSize)
689         recordAttr->recordSize = fi->file_max - recordOffset;
690     zebraExplain_recordBytesIncrement (zh->reg->zei,
691                                        recordAttr->recordSize);
692
693     /* set run-number for this record */
694     recordAttr->runNumber = zebraExplain_runNumberIncrement (zh->reg->zei,
695                                                              0);
696
697     /* update store data */
698     xfree (rec->info[recInfo_storeData]);
699     if (rGroup->flagStoreData == 1)
700     {
701         rec->size[recInfo_storeData] = recordAttr->recordSize;
702         rec->info[recInfo_storeData] = (char *)
703             xmalloc (recordAttr->recordSize);
704         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
705         {
706             logf (LOG_ERRNO|LOG_FATAL, "seek to " PRINTF_OFF_T " in %s",
707                   recordOffset, fname);
708             exit (1);
709         }
710         if (read (fi->fd, rec->info[recInfo_storeData], recordAttr->recordSize)
711             < recordAttr->recordSize)
712         {
713             logf (LOG_ERRNO|LOG_FATAL, "read %d bytes of %s",
714                   recordAttr->recordSize, fname);
715             exit (1);
716         }
717     }
718     else
719     {
720         rec->info[recInfo_storeData] = NULL;
721         rec->size[recInfo_storeData] = 0;
722     }
723     /* update database name */
724     xfree (rec->info[recInfo_databaseName]);
725     rec->info[recInfo_databaseName] =
726         rec_strdup (rGroup->databaseName, &rec->size[recInfo_databaseName]); 
727
728     /* update offset */
729     recordAttr->recordOffset = recordOffset;
730     
731     /* commit this record */
732     rec_put (zh->reg->records, &rec);
733     logRecord (zh);
734     return 1;
735 }
736
737 int fileExtract (ZebraHandle zh, SYSNO *sysno, const char *fname, 
738                  const struct recordGroup *rGroupP, int deleteFlag)
739 {
740     int r, i, fd;
741     char gprefix[128];
742     char ext[128];
743     char ext_res[128];
744     char subType[128];
745     RecType recType;
746     struct recordGroup rGroupM;
747     struct recordGroup *rGroup = &rGroupM;
748     struct file_read_info *fi;
749     void *clientData;
750
751     memcpy (rGroup, rGroupP, sizeof(*rGroupP));
752    
753     if (!rGroup->groupName || !*rGroup->groupName)
754         *gprefix = '\0';
755     else
756         sprintf (gprefix, "%s.", rGroup->groupName);
757
758     logf (LOG_DEBUG, "fileExtract %s", fname);
759
760     /* determine file extension */
761     *ext = '\0';
762     for (i = strlen(fname); --i >= 0; )
763         if (fname[i] == '/')
764             break;
765         else if (fname[i] == '.')
766         {
767             strcpy (ext, fname+i+1);
768             break;
769         }
770     /* determine file type - depending on extension */
771     if (!rGroup->recordType)
772     {
773         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
774         if (!(rGroup->recordType = res_get (zh->res, ext_res)))
775         {
776             sprintf (ext_res, "%srecordType", gprefix);
777             rGroup->recordType = res_get (zh->res, ext_res);
778         }
779     }
780     if (!rGroup->recordType)
781     {
782         if (zh->records_processed < rGroup->fileVerboseLimit)
783             logf (LOG_LOG, "? %s", fname);
784         return 0;
785     }
786     if (!*rGroup->recordType)
787         return 0;
788     if (!(recType =
789           recType_byName (zh->reg->recTypes, rGroup->recordType, subType,
790                           &clientData)))
791     {
792         logf (LOG_WARN, "No such record type: %s", rGroup->recordType);
793         return 0;
794     }
795
796     /* determine match criteria */
797     if (!rGroup->recordId)
798     {
799         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
800         rGroup->recordId = res_get (zh->res, ext_res);
801     }
802
803     /* determine database name */
804     if (!rGroup->databaseName)
805     {
806         sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
807         if (!(rGroup->databaseName = res_get (zh->res, ext_res)))
808         {
809             sprintf (ext_res, "%sdatabase", gprefix);
810             rGroup->databaseName = res_get (zh->res, ext_res);
811         }
812     }
813     if (!rGroup->databaseName)
814         rGroup->databaseName = "Default";
815
816     /* determine if explain database */
817     
818     sprintf (ext_res, "%sexplainDatabase", gprefix);
819     rGroup->explainDatabase =
820         atoi (res_get_def (zh->res, ext_res, "0"));
821
822     /* announce database */
823     if (zebraExplain_curDatabase (zh->reg->zei, rGroup->databaseName))
824     {
825         if (zebraExplain_newDatabase (zh->reg->zei, rGroup->databaseName,
826                                       rGroup->explainDatabase))
827             return 0;
828     }
829
830     if (rGroup->flagStoreData == -1)
831     {
832         const char *sval;
833         sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
834         if (!(sval = res_get (zh->res, ext_res)))
835         {
836             sprintf (ext_res, "%sstoreData", gprefix);
837             sval = res_get (zh->res, ext_res);
838         }
839         if (sval)
840             rGroup->flagStoreData = atoi (sval);
841     }
842     if (rGroup->flagStoreData == -1)
843         rGroup->flagStoreData = 0;
844
845     if (rGroup->flagStoreKeys == -1)
846     {
847         const char *sval;
848
849         sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
850         sval = res_get (zh->res, ext_res);
851         if (!sval)
852         {
853             sprintf (ext_res, "%sstoreKeys", gprefix);
854             sval = res_get (zh->res, ext_res);
855         }
856         if (!sval)
857             sval = res_get (zh->res, "storeKeys");
858         if (sval)
859             rGroup->flagStoreKeys = atoi (sval);
860     }
861     if (rGroup->flagStoreKeys == -1)
862         rGroup->flagStoreKeys = 0;
863
864     if (sysno && deleteFlag)
865         fd = -1;
866     else
867     {
868         char full_rep[1024];
869
870         if (zh->path_reg && !yaz_is_abspath (fname))
871         {
872             strcpy (full_rep, zh->path_reg);
873             strcat (full_rep, "/");
874             strcat (full_rep, fname);
875         }
876         else
877             strcpy (full_rep, fname);
878         
879
880         if ((fd = open (full_rep, O_BINARY|O_RDONLY)) == -1)
881         {
882             logf (LOG_WARN|LOG_ERRNO, "open %s", full_rep);
883             return 0;
884         }
885     }
886     fi = file_read_start (fd);
887     do
888     {
889         file_begin (fi);
890         r = recordExtract (zh, sysno, fname, rGroup, deleteFlag, fi,
891                            recType, subType, clientData);
892     } while (r && !sysno && fi->file_more);
893     file_read_stop (fi);
894     if (fd != -1)
895         close (fd);
896     return r;
897 }
898
899
900 int extract_rec_in_mem (ZebraHandle zh, const char *recordType,
901                         const char *buf, size_t buf_size,
902                         const char *databaseName, int delete_flag,
903                         int test_mode, int *sysno,
904                         int store_keys, int store_data,
905                         const char *match_criteria)
906 {
907     RecordAttr *recordAttr;
908     struct recExtractCtrl extractCtrl;
909     int i, r;
910     char *matchStr = 0;
911     RecType recType;
912     char subType[1024];
913     void *clientData;
914     const char *fname = "<no file>";
915     Record rec;
916     long recordOffset = 0;
917     struct zebra_fetch_control fc;
918
919     fc.fd = -1;
920     fc.record_int_buf = buf;
921     fc.record_int_len = buf_size;
922     fc.record_int_pos = 0;
923     fc.offset_end = 0;
924     fc.record_offset = 0;
925
926     extractCtrl.offset = 0;
927     extractCtrl.readf = zebra_record_int_read;
928     extractCtrl.seekf = zebra_record_int_seek;
929     extractCtrl.tellf = zebra_record_int_tell;
930     extractCtrl.endf = zebra_record_int_end;
931     extractCtrl.fh = &fc;
932
933     /* announce database */
934     if (zebraExplain_curDatabase (zh->reg->zei, databaseName))
935     {
936         if (zebraExplain_newDatabase (zh->reg->zei, databaseName, 0))
937             return 0;
938     }
939     if (!(recType =
940           recType_byName (zh->reg->recTypes, recordType, subType,
941                           &clientData)))
942     {
943         logf (LOG_WARN, "No such record type: %s", recordType);
944         return 0;
945     }
946
947     zh->reg->keys.buf_used = 0;
948     zh->reg->keys.prevAttrUse = -1;
949     zh->reg->keys.prevAttrSet = -1;
950     zh->reg->keys.prevSeqNo = 0;
951     zh->reg->sortKeys = 0;
952
953     extractCtrl.subType = subType;
954     extractCtrl.init = extract_init;
955     extractCtrl.tokenAdd = extract_token_add;
956     extractCtrl.schemaAdd = extract_schema_add;
957     extractCtrl.dh = zh->reg->dh;
958     extractCtrl.handle = zh;
959     extractCtrl.zebra_maps = zh->reg->zebra_maps;
960     extractCtrl.flagShowRecords = 0;
961     for (i = 0; i<256; i++)
962     {
963         if (zebra_maps_is_positioned(zh->reg->zebra_maps, i))
964             extractCtrl.seqno[i] = 1;
965         else
966             extractCtrl.seqno[i] = 0;
967     }
968
969     r = (*recType->extract)(clientData, &extractCtrl);
970
971     if (r == RECCTRL_EXTRACT_EOF)
972         return 0;
973     else if (r == RECCTRL_EXTRACT_ERROR_GENERIC)
974     {
975         /* error occured during extraction ... */
976         yaz_log (LOG_WARN, "extract error: generic");
977         return 0;
978     }
979     else if (r == RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER)
980     {
981         /* error occured during extraction ... */
982         yaz_log (LOG_WARN, "extract error: no such filter");
983         return 0;
984     }
985     if (zh->reg->keys.buf_used == 0)
986     {
987         /* the extraction process returned no information - the record
988            is probably empty - unless flagShowRecords is in use */
989         if (test_mode)
990             return 1;
991         logf (LOG_WARN, "No keys generated for record");
992         logf (LOG_WARN, " The file is probably empty");
993         return 1;
994     }
995     /* match criteria */
996
997     if (! *sysno)
998     {
999         /* new record */
1000         if (delete_flag)
1001         {
1002             logf (LOG_LOG, "delete %s %s %ld", recordType,
1003                   fname, (long) recordOffset);
1004             logf (LOG_WARN, "cannot delete record above (seems new)");
1005             return 1;
1006         }
1007         logf (LOG_LOG, "add %s %s %ld", recordType, fname,
1008               (long) recordOffset);
1009         rec = rec_new (zh->reg->records);
1010
1011         *sysno = rec->sysno;
1012
1013         recordAttr = rec_init_attr (zh->reg->zei, rec);
1014
1015         if (matchStr)
1016         {
1017             dict_insert (zh->reg->matchDict, matchStr,
1018                          sizeof(*sysno), sysno);
1019         }
1020         extract_flushRecordKeys (zh, *sysno, 1, &zh->reg->keys);
1021         extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
1022     }
1023     else
1024     {
1025         /* record already exists */
1026         struct recKeys delkeys;
1027
1028         rec = rec_get (zh->reg->records, *sysno);
1029         assert (rec);
1030         
1031         recordAttr = rec_init_attr (zh->reg->zei, rec);
1032
1033         if (recordAttr->runNumber ==
1034             zebraExplain_runNumberIncrement (zh->reg->zei, 0))
1035         {
1036             logf (LOG_LOG, "skipped %s %s %ld", recordType,
1037                   fname, (long) recordOffset);
1038             rec_rm (&rec);
1039             return 1;
1040         }
1041         delkeys.buf_used = rec->size[recInfo_delKeys];
1042         delkeys.buf = rec->info[recInfo_delKeys];
1043         extract_flushSortKeys (zh, *sysno, 0, &zh->reg->sortKeys);
1044         extract_flushRecordKeys (zh, *sysno, 0, &delkeys);
1045         if (delete_flag)
1046         {
1047             /* record going to be deleted */
1048             if (!delkeys.buf_used)
1049             {
1050                 logf (LOG_LOG, "delete %s %s %ld", recordType,
1051                       fname, (long) recordOffset);
1052                 logf (LOG_WARN, "cannot delete file above, storeKeys false");
1053             }
1054             else
1055             {
1056                 logf (LOG_LOG, "delete %s %s %ld", recordType,
1057                       fname, (long) recordOffset);
1058 #if 0
1059                 if (matchStr)
1060                     dict_delete (matchDict, matchStr);
1061 #endif
1062                 rec_del (zh->reg->records, &rec);
1063             }
1064             rec_rm (&rec);
1065             return 1;
1066         }
1067         else
1068         {
1069             /* record going to be updated */
1070             if (!delkeys.buf_used)
1071             {
1072                 logf (LOG_LOG, "update %s %s %ld", recordType,
1073                       fname, (long) recordOffset);
1074                 logf (LOG_WARN, "cannot update file above, storeKeys false");
1075             }
1076             else
1077             {
1078                 logf (LOG_LOG, "update %s %s %ld", recordType,
1079                       fname, (long) recordOffset);
1080                 extract_flushRecordKeys (zh, *sysno, 1, &zh->reg->keys);
1081             }
1082         }
1083     }
1084     /* update file type */
1085     xfree (rec->info[recInfo_fileType]);
1086     rec->info[recInfo_fileType] =
1087         rec_strdup (recordType, &rec->size[recInfo_fileType]);
1088
1089     /* update filename */
1090     xfree (rec->info[recInfo_filename]);
1091     rec->info[recInfo_filename] =
1092         rec_strdup (fname, &rec->size[recInfo_filename]);
1093
1094     /* update delete keys */
1095     xfree (rec->info[recInfo_delKeys]);
1096     if (zh->reg->keys.buf_used > 0 && store_keys == 1)
1097     {
1098         rec->size[recInfo_delKeys] = zh->reg->keys.buf_used;
1099         rec->info[recInfo_delKeys] = zh->reg->keys.buf;
1100         zh->reg->keys.buf = NULL;
1101         zh->reg->keys.buf_max = 0;
1102     }
1103     else
1104     {
1105         rec->info[recInfo_delKeys] = NULL;
1106         rec->size[recInfo_delKeys] = 0;
1107     }
1108
1109     /* save file size of original record */
1110     zebraExplain_recordBytesIncrement (zh->reg->zei,
1111                                        - recordAttr->recordSize);
1112 #if 0
1113     recordAttr->recordSize = fi->file_moffset - recordOffset;
1114     if (!recordAttr->recordSize)
1115         recordAttr->recordSize = fi->file_max - recordOffset;
1116 #else
1117     recordAttr->recordSize = buf_size;
1118 #endif
1119     zebraExplain_recordBytesIncrement (zh->reg->zei,
1120                                        recordAttr->recordSize);
1121
1122     /* set run-number for this record */
1123     recordAttr->runNumber =
1124         zebraExplain_runNumberIncrement (zh->reg->zei, 0);
1125
1126     /* update store data */
1127     xfree (rec->info[recInfo_storeData]);
1128     if (store_data == 1)
1129     {
1130         rec->size[recInfo_storeData] = recordAttr->recordSize;
1131         rec->info[recInfo_storeData] = (char *)
1132             xmalloc (recordAttr->recordSize);
1133 #if 1
1134         memcpy (rec->info[recInfo_storeData], buf, recordAttr->recordSize);
1135 #else
1136         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
1137         {
1138             logf (LOG_ERRNO|LOG_FATAL, "seek to %ld in %s",
1139                   (long) recordOffset, fname);
1140             exit (1);
1141         }
1142         if (read (fi->fd, rec->info[recInfo_storeData], recordAttr->recordSize)
1143             < recordAttr->recordSize)
1144         {
1145             logf (LOG_ERRNO|LOG_FATAL, "read %d bytes of %s",
1146                   recordAttr->recordSize, fname);
1147             exit (1);
1148         }
1149 #endif
1150     }
1151     else
1152     {
1153         rec->info[recInfo_storeData] = NULL;
1154         rec->size[recInfo_storeData] = 0;
1155     }
1156     /* update database name */
1157     xfree (rec->info[recInfo_databaseName]);
1158     rec->info[recInfo_databaseName] =
1159         rec_strdup (databaseName, &rec->size[recInfo_databaseName]); 
1160
1161     /* update offset */
1162     recordAttr->recordOffset = recordOffset;
1163     
1164     /* commit this record */
1165     rec_put (zh->reg->records, &rec);
1166
1167     return 0;
1168 }
1169
1170 int explain_extract (void *handle, Record rec, data1_node *n)
1171 {
1172     ZebraHandle zh = (ZebraHandle) handle;
1173     struct recExtractCtrl extractCtrl;
1174     int i;
1175
1176     if (zebraExplain_curDatabase (zh->reg->zei,
1177                                   rec->info[recInfo_databaseName]))
1178     {
1179         abort();
1180         if (zebraExplain_newDatabase (zh->reg->zei,
1181                                       rec->info[recInfo_databaseName], 0))
1182             abort ();
1183     }
1184
1185     zh->reg->keys.buf_used = 0;
1186     zh->reg->keys.prevAttrUse = -1;
1187     zh->reg->keys.prevAttrSet = -1;
1188     zh->reg->keys.prevSeqNo = 0;
1189     zh->reg->sortKeys = 0;
1190     
1191     extractCtrl.init = extract_init;
1192     extractCtrl.tokenAdd = extract_token_add;
1193     extractCtrl.schemaAdd = extract_schema_add;
1194     extractCtrl.dh = zh->reg->dh;
1195     for (i = 0; i<256; i++)
1196         extractCtrl.seqno[i] = 0;
1197     extractCtrl.zebra_maps = zh->reg->zebra_maps;
1198     extractCtrl.flagShowRecords = 0;
1199     extractCtrl.handle = handle;
1200     
1201     grs_extract_tree(&extractCtrl, n);
1202
1203     if (rec->size[recInfo_delKeys])
1204     {
1205         struct recKeys delkeys;
1206         struct sortKey *sortKeys = 0;
1207
1208         delkeys.buf_used = rec->size[recInfo_delKeys];
1209         delkeys.buf = rec->info[recInfo_delKeys];
1210         extract_flushSortKeys (zh, rec->sysno, 0, &sortKeys);
1211         extract_flushRecordKeys (zh, rec->sysno, 0, &delkeys);
1212     }
1213     extract_flushRecordKeys (zh, rec->sysno, 1, &zh->reg->keys);
1214     extract_flushSortKeys (zh, rec->sysno, 1, &zh->reg->sortKeys);
1215
1216     xfree (rec->info[recInfo_delKeys]);
1217     rec->size[recInfo_delKeys] = zh->reg->keys.buf_used;
1218     rec->info[recInfo_delKeys] = zh->reg->keys.buf;
1219     zh->reg->keys.buf = NULL;
1220     zh->reg->keys.buf_max = 0;
1221     return 0;
1222 }
1223
1224 void extract_flushRecordKeys (ZebraHandle zh, SYSNO sysno,
1225                               int cmd, struct recKeys *reckeys)
1226 {
1227 #if SU_SCHEME
1228 #else
1229     unsigned char attrSet = (unsigned char) -1;
1230     unsigned short attrUse = (unsigned short) -1;
1231 #endif
1232     int seqno = 0;
1233     int off = 0;
1234     int ch = 0;
1235     ZebraExplainInfo zei = zh->reg->zei;
1236
1237     if (!zh->reg->key_buf)
1238     {
1239         int mem = 8*1024*1024;
1240         zh->reg->key_buf = (char**) xmalloc (mem);
1241         zh->reg->ptr_top = mem/sizeof(char*);
1242         zh->reg->ptr_i = 0;
1243         zh->reg->key_buf_used = 0;
1244         zh->reg->key_file_no = 0;
1245     }
1246     zebraExplain_recordCountIncrement (zei, cmd ? 1 : -1);
1247     while (off < reckeys->buf_used)
1248     {
1249         const char *src = reckeys->buf + off;
1250         struct it_key key;
1251         int lead;
1252     
1253         lead = *src++;
1254
1255 #if SU_SCHEME
1256         if ((lead & 3) < 3)
1257         {
1258             memcpy (&ch, src, sizeof(ch));
1259             src += sizeof(ch);
1260         }
1261 #else
1262         if (!(lead & 1))
1263         {
1264             memcpy (&attrSet, src, sizeof(attrSet));
1265             src += sizeof(attrSet);
1266         }
1267         if (!(lead & 2))
1268         {
1269             memcpy (&attrUse, src, sizeof(attrUse));
1270             src += sizeof(attrUse);
1271         }
1272 #endif
1273         if (zh->reg->key_buf_used + 1024 > 
1274             (zh->reg->ptr_top -zh->reg->ptr_i)*sizeof(char*))
1275             extract_flushWriteKeys (zh);
1276         ++(zh->reg->ptr_i);
1277         (zh->reg->key_buf)[zh->reg->ptr_top - zh->reg->ptr_i] =
1278             (char*)zh->reg->key_buf + zh->reg->key_buf_used;
1279 #if SU_SCHEME
1280 #else
1281         ch = zebraExplain_lookupSU (zei, attrSet, attrUse);
1282         if (ch < 0)
1283             ch = zebraExplain_addSU (zei, attrSet, attrUse);
1284 #endif
1285         assert (ch > 0);
1286         zh->reg->key_buf_used +=
1287             key_SU_encode (ch,((char*)zh->reg->key_buf) +
1288                            zh->reg->key_buf_used);
1289
1290         while (*src)
1291             ((char*)zh->reg->key_buf) [(zh->reg->key_buf_used)++] = *src++;
1292         src++;
1293         ((char*)(zh->reg->key_buf))[(zh->reg->key_buf_used)++] = '\0';
1294         ((char*)(zh->reg->key_buf))[(zh->reg->key_buf_used)++] = cmd;
1295
1296         if (lead & 60)
1297             seqno += ((lead>>2) & 15)-1;
1298         else
1299         {
1300             memcpy (&seqno, src, sizeof(seqno));
1301             src += sizeof(seqno);
1302         }
1303         key.seqno = seqno;
1304         key.sysno = sysno;
1305         memcpy ((char*)zh->reg->key_buf + zh->reg->key_buf_used, &key, sizeof(key));
1306         (zh->reg->key_buf_used) += sizeof(key);
1307         off = src - reckeys->buf;
1308     }
1309     assert (off == reckeys->buf_used);
1310 }
1311
1312 void extract_flushWriteKeys (ZebraHandle zh)
1313 {
1314     FILE *outf;
1315     char out_fname[200];
1316     char *prevcp, *cp;
1317     struct encode_info encode_info;
1318     int ptr_i = zh->reg->ptr_i;
1319 #if SORT_EXTRA
1320     int i;
1321 #endif
1322     if (!zh->reg->key_buf || ptr_i <= 0)
1323         return;
1324
1325     (zh->reg->key_file_no)++;
1326     logf (LOG_LOG, "sorting section %d", (zh->reg->key_file_no));
1327 #if !SORT_EXTRA
1328     qsort (zh->reg->key_buf + zh->reg->ptr_top - ptr_i, ptr_i,
1329                sizeof(char*), key_qsort_compare);
1330     extract_get_fname_tmp (zh, out_fname, zh->reg->key_file_no);
1331
1332     if (!(outf = fopen (out_fname, "wb")))
1333     {
1334         logf (LOG_FATAL|LOG_ERRNO, "fopen %s", out_fname);
1335         exit (1);
1336     }
1337     logf (LOG_LOG, "writing section %d", zh->reg->key_file_no);
1338     prevcp = cp = (zh->reg->key_buf)[zh->reg->ptr_top - ptr_i];
1339     
1340     encode_key_init (&encode_info);
1341     encode_key_write (cp, &encode_info, outf);
1342     
1343     while (--ptr_i > 0)
1344     {
1345         cp = (zh->reg->key_buf)[zh->reg->ptr_top - ptr_i];
1346         if (strcmp (cp, prevcp))
1347         {
1348             encode_key_init (&encode_info);
1349             encode_key_write (cp, &encode_info, outf);
1350             prevcp = cp;
1351         }
1352         else
1353             encode_key_write (cp + strlen(cp), &encode_info, outf);
1354     }
1355 #else
1356     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_x_compare);
1357     extract_get_fname_tmp (out_fname, key_file_no);
1358
1359     if (!(outf = fopen (out_fname, "wb")))
1360     {
1361         logf (LOG_FATAL|LOG_ERRNO, "fopen %s", out_fname);
1362         exit (1);
1363     }
1364     logf (LOG_LOG, "writing section %d", key_file_no);
1365     i = ptr_i;
1366     prevcp =  key_buf[ptr_top-i];
1367     while (1)
1368         if (!--i || strcmp (prevcp, key_buf[ptr_top-i]))
1369         {
1370             key_y_len = strlen(prevcp)+1;
1371 #if 0
1372             logf (LOG_LOG, "key_y_len: %2d %02x %02x %s",
1373                       key_y_len, prevcp[0], prevcp[1], 2+prevcp);
1374 #endif
1375             qsort (key_buf + ptr_top-ptr_i, ptr_i - i,
1376                                    sizeof(char*), key_y_compare);
1377             cp = key_buf[ptr_top-ptr_i];
1378             --key_y_len;
1379             encode_key_init (&encode_info);
1380             encode_key_write (cp, &encode_info, outf);
1381             while (--ptr_i > i)
1382             {
1383                 cp = key_buf[ptr_top-ptr_i];
1384                 encode_key_write (cp+key_y_len, &encode_info, outf);
1385             }
1386             if (!i)
1387                 break;
1388             prevcp = key_buf[ptr_top-ptr_i];
1389         }
1390 #endif
1391     if (fclose (outf))
1392     {
1393         logf (LOG_FATAL|LOG_ERRNO, "fclose %s", out_fname);
1394         exit (1);
1395     }
1396     logf (LOG_LOG, "finished section %d", zh->reg->key_file_no);
1397     zh->reg->ptr_i = 0;
1398     zh->reg->key_buf_used = 0;
1399 }
1400
1401 void extract_add_index_string (RecWord *p, const char *string,
1402                                int length)
1403 {
1404     char *dst;
1405     unsigned char attrSet;
1406     unsigned short attrUse;
1407     int lead = 0;
1408     int diff = 0;
1409     int *pseqno = &p->seqno;
1410     ZebraHandle zh = p->extractCtrl->handle;
1411     ZebraExplainInfo zei = zh->reg->zei;
1412     struct recKeys *keys = &zh->reg->keys;
1413     
1414     if (keys->buf_used+1024 > keys->buf_max)
1415     {
1416         char *b;
1417
1418         b = (char *) xmalloc (keys->buf_max += 128000);
1419         if (keys->buf_used > 0)
1420             memcpy (b, keys->buf, keys->buf_used);
1421         xfree (keys->buf);
1422         keys->buf = b;
1423     }
1424     dst = keys->buf + keys->buf_used;
1425
1426     attrSet = p->attrSet;
1427     if (keys->buf_used > 0 && keys->prevAttrSet == attrSet)
1428         lead |= 1;
1429     else
1430         keys->prevAttrSet = attrSet;
1431     attrUse = p->attrUse;
1432     if (keys->buf_used > 0 && keys->prevAttrUse == attrUse)
1433         lead |= 2;
1434     else
1435         keys->prevAttrUse = attrUse;
1436 #if 1
1437     diff = 1 + *pseqno - keys->prevSeqNo;
1438     if (diff >= 1 && diff <= 15)
1439         lead |= (diff << 2);
1440     else
1441         diff = 0;
1442 #endif
1443     keys->prevSeqNo = *pseqno;
1444     
1445     *dst++ = lead;
1446
1447 #if SU_SCHEME
1448     if ((lead & 3) < 3)
1449     {
1450         int ch = zebraExplain_lookupSU (zei, attrSet, attrUse);
1451         if (ch < 0)
1452         {
1453             ch = zebraExplain_addSU (zei, attrSet, attrUse);
1454             yaz_log (LOG_DEBUG, "addSU set=%d use=%d SU=%d",
1455                      attrSet, attrUse, ch);
1456         }
1457         assert (ch > 0);
1458         memcpy (dst, &ch, sizeof(ch));
1459         dst += sizeof(ch);
1460     }
1461 #else
1462     if (!(lead & 1))
1463     {
1464         memcpy (dst, &attrSet, sizeof(attrSet));
1465         dst += sizeof(attrSet);
1466     }
1467     if (!(lead & 2))
1468     {
1469         memcpy (dst, &attrUse, sizeof(attrUse));
1470         dst += sizeof(attrUse);
1471     }
1472 #endif
1473     *dst++ = p->reg_type;
1474     memcpy (dst, string, length);
1475     dst += length;
1476     *dst++ = '\0';
1477
1478     if (!diff)
1479     {
1480         memcpy (dst, pseqno, sizeof(*pseqno));
1481         dst += sizeof(*pseqno);
1482     }
1483     keys->buf_used = dst - keys->buf;
1484 }
1485
1486 static void extract_add_sort_string (RecWord *p, const char *string,
1487                                      int length)
1488 {
1489     struct sortKey *sk;
1490     ZebraHandle zh = p->extractCtrl->handle;
1491
1492     for (sk = zh->reg->sortKeys; sk; sk = sk->next)
1493         if (sk->attrSet == p->attrSet && sk->attrUse == p->attrUse)
1494             return;
1495
1496     sk = (struct sortKey *) xmalloc (sizeof(*sk));
1497     sk->next = zh->reg->sortKeys;
1498     zh->reg->sortKeys = sk;
1499
1500     sk->string = (char *) xmalloc (length);
1501     sk->length = length;
1502     memcpy (sk->string, string, length);
1503
1504     sk->attrSet = p->attrSet;
1505     sk->attrUse = p->attrUse;
1506 }
1507
1508 void extract_add_string (RecWord *p, const char *string, int length)
1509 {
1510     assert (length > 0);
1511     if (zebra_maps_is_sort (p->zebra_maps, p->reg_type))
1512         extract_add_sort_string (p, string, length);
1513     else
1514         extract_add_index_string (p, string, length);
1515 }
1516
1517 static void extract_add_incomplete_field (RecWord *p)
1518 {
1519     const char *b = p->string;
1520     int remain = p->length;
1521     const char **map = 0;
1522
1523     if (remain > 0)
1524         map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
1525
1526     while (map)
1527     {
1528         char buf[IT_MAX_WORD+1];
1529         int i, remain;
1530
1531         /* Skip spaces */
1532         while (map && *map && **map == *CHR_SPACE)
1533         {
1534             remain = p->length - (b - p->string);
1535             if (remain > 0)
1536                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
1537             else
1538                 map = 0;
1539         }
1540         if (!map)
1541             break;
1542         i = 0;
1543         while (map && *map && **map != *CHR_SPACE)
1544         {
1545             const char *cp = *map;
1546
1547             while (i < IT_MAX_WORD && *cp)
1548                 buf[i++] = *(cp++);
1549             remain = p->length - (b - p->string);
1550             if (remain > 0)
1551                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
1552             else
1553                 map = 0;
1554         }
1555         if (!i)
1556             return;
1557         extract_add_string (p, buf, i);
1558         p->seqno++;
1559     }
1560 }
1561
1562 static void extract_add_complete_field (RecWord *p)
1563 {
1564     const char *b = p->string;
1565     char buf[IT_MAX_WORD+1];
1566     const char **map = 0;
1567     int i = 0, remain = p->length;
1568
1569     if (remain > 0)
1570         map = zebra_maps_input (p->zebra_maps, p->reg_type, &b, remain);
1571
1572     while (remain > 0 && i < IT_MAX_WORD)
1573     {
1574         while (map && *map && **map == *CHR_SPACE)
1575         {
1576             remain = p->length - (b - p->string);
1577             if (remain > 0)
1578                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
1579             else
1580                 map = 0;
1581         }
1582         if (!map)
1583             break;
1584
1585         if (i && i < IT_MAX_WORD)
1586             buf[i++] = *CHR_SPACE;
1587         while (map && *map && **map != *CHR_SPACE)
1588         {
1589             const char *cp = *map;
1590
1591             if (i >= IT_MAX_WORD)
1592                 break;
1593             while (i < IT_MAX_WORD && *cp)
1594                 buf[i++] = *(cp++);
1595             remain = p->length  - (b - p->string);
1596             if (remain > 0)
1597                 map = zebra_maps_input (p->zebra_maps, p->reg_type, &b,
1598                                         remain);
1599             else
1600                 map = 0;
1601         }
1602     }
1603     if (!i)
1604         return;
1605     extract_add_string (p, buf, i);
1606 }
1607
1608 void extract_token_add (RecWord *p)
1609 {
1610     WRBUF wrbuf;
1611     if ((wrbuf = zebra_replace(p->zebra_maps, p->reg_type, 0,
1612                                p->string, p->length)))
1613     {
1614         p->string = wrbuf_buf(wrbuf);
1615         p->length = wrbuf_len(wrbuf);
1616     }
1617     if (zebra_maps_is_complete (p->zebra_maps, p->reg_type))
1618         extract_add_complete_field (p);
1619     else
1620         extract_add_incomplete_field(p);
1621 }
1622
1623 void extract_schema_add (struct recExtractCtrl *p, Odr_oid *oid)
1624 {
1625     ZebraHandle zh = (ZebraHandle) (p->handle);
1626     zebraExplain_addSchema (zh->reg->zei, oid);
1627 }
1628
1629 void extract_flushSortKeys (ZebraHandle zh, SYSNO sysno,
1630                             int cmd, struct sortKey **skp)
1631 {
1632     struct sortKey *sk = *skp;
1633     SortIdx sortIdx = zh->reg->sortIdx;
1634
1635     sortIdx_sysno (sortIdx, sysno);
1636     while (sk)
1637     {
1638         struct sortKey *sk_next = sk->next;
1639         sortIdx_type (sortIdx, sk->attrUse);
1640         sortIdx_add (sortIdx, sk->string, sk->length);
1641         xfree (sk->string);
1642         xfree (sk);
1643         sk = sk_next;
1644     }
1645     *skp = 0;
1646 }
1647
1648 void encode_key_init (struct encode_info *i)
1649 {
1650     i->sysno = 0;
1651     i->seqno = 0;
1652     i->cmd = -1;
1653 }
1654
1655 char *encode_key_int (int d, char *bp)
1656 {
1657     if (d <= 63)
1658         *bp++ = d;
1659     else if (d <= 16383)
1660     {
1661         *bp++ = 64 + (d>>8);
1662         *bp++ = d  & 255;
1663     }
1664     else if (d <= 4194303)
1665     {
1666         *bp++ = 128 + (d>>16);
1667         *bp++ = (d>>8) & 255;
1668         *bp++ = d & 255;
1669     }
1670     else
1671     {
1672         *bp++ = 192 + (d>>24);
1673         *bp++ = (d>>16) & 255;
1674         *bp++ = (d>>8) & 255;
1675         *bp++ = d & 255;
1676     }
1677     return bp;
1678 }
1679
1680 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
1681 {
1682     struct it_key key;
1683     char *bp = i->buf;
1684
1685     while ((*bp++ = *k++))
1686         ;
1687     memcpy (&key, k+1, sizeof(struct it_key));
1688     bp = encode_key_int ( (key.sysno - i->sysno) * 2 + *k, bp);
1689     if (i->sysno != key.sysno)
1690     {
1691         i->sysno = key.sysno;
1692         i->seqno = 0;
1693     }
1694     else if (!i->seqno && !key.seqno && i->cmd == *k)
1695         return;
1696     bp = encode_key_int (key.seqno - i->seqno, bp);
1697     i->seqno = key.seqno;
1698     i->cmd = *k;
1699     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
1700     {
1701         logf (LOG_FATAL|LOG_ERRNO, "fwrite");
1702         exit (1);
1703     }
1704 }
1705