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