b08d3bb21a8fa43164036ed20928db66810b01b1
[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.111 2002-02-20 23:07:54 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         
430         recordOffset = fi->file_moffset;
431         extractCtrl.offset = fi->file_moffset;
432         extractCtrl.readf = file_read;
433         extractCtrl.seekf = file_seek;
434         extractCtrl.tellf = file_tell;
435         extractCtrl.endf = file_end;
436         extractCtrl.fh = fi;
437         extractCtrl.subType = subType;
438         extractCtrl.init = extract_init;
439         extractCtrl.tokenAdd = extract_token_add;
440         extractCtrl.schemaAdd = extract_schema_add;
441         extractCtrl.dh = zh->service->dh;
442         extractCtrl.handle = zh;
443         for (i = 0; i<256; i++)
444         {
445             if (zebra_maps_is_positioned(zh->service->zebra_maps, i))
446                 extractCtrl.seqno[i] = 1;
447             else
448                 extractCtrl.seqno[i] = 0;
449         }
450         extractCtrl.zebra_maps = zh->service->zebra_maps;
451         extractCtrl.flagShowRecords = !rGroup->flagRw;
452
453         if (!rGroup->flagRw)
454             printf ("File: %s " PRINTF_OFF_T "\n", fname, recordOffset);
455
456         logInfo.fname = fname;
457         logInfo.recordOffset = recordOffset;
458         logInfo.rGroup = rGroup;
459         log_event_start (recordLogPreamble, &logInfo);
460
461         r = (*recType->extract)(clientData, &extractCtrl);
462
463         log_event_start (NULL, NULL);
464
465         if (r == RECCTRL_EXTRACT_EOF)
466             return 0;
467         else if (r == RECCTRL_EXTRACT_ERROR)
468         {
469             /* error occured during extraction ... */
470             if (rGroup->flagRw &&
471                 records_processed < rGroup->fileVerboseLimit)
472             {
473                 logf (LOG_WARN, "fail %s %s " PRINTF_OFF_T, rGroup->recordType,
474                       fname, recordOffset);
475             }
476             return 0;
477         }
478         if (zh->keys.buf_used == 0)
479         {
480             /* the extraction process returned no information - the record
481                is probably empty - unless flagShowRecords is in use */
482             if (!rGroup->flagRw)
483                 return 1;
484             
485             logf (LOG_WARN, "empty %s %s " PRINTF_OFF_T, rGroup->recordType,
486                   fname, recordOffset);
487             return 1;
488         }
489     }
490
491     /* perform match if sysno not known and if match criteria is specified */
492        
493     matchStr = NULL;
494     if (!sysno) 
495     {
496         sysnotmp = 0;
497         sysno = &sysnotmp;
498         if (rGroup->recordId && *rGroup->recordId)
499         {
500             char *rinfo;
501         
502             matchStr = fileMatchStr (zh, &zh->keys, rGroup, fname, 
503                                      rGroup->recordId);
504             if (matchStr)
505             {
506                 rinfo = dict_lookup (zh->service->matchDict, matchStr);
507                 if (rinfo)
508                     memcpy (sysno, rinfo+1, sizeof(*sysno));
509             }
510             else
511             {
512                 logf (LOG_WARN, "Bad match criteria");
513                 return 0;
514             }
515         }
516     }
517
518     if (! *sysno)
519     {
520         /* new record */
521         if (deleteFlag)
522         {
523             logf (LOG_LOG, "delete %s %s " PRINTF_OFF_T, rGroup->recordType,
524                   fname, recordOffset);
525             logf (LOG_WARN, "cannot delete record above (seems new)");
526             return 1;
527         }
528         if (records_processed < rGroup->fileVerboseLimit)
529             logf (LOG_LOG, "add %s %s " PRINTF_OFF_T, rGroup->recordType,
530                   fname, recordOffset);
531         rec = rec_new (zh->service->records);
532
533         *sysno = rec->sysno;
534
535         recordAttr = rec_init_attr (zh->service->zei, rec);
536
537         if (matchStr)
538         {
539             dict_insert (zh->service->matchDict, matchStr, sizeof(*sysno), sysno);
540         }
541         extract_flushRecordKeys (zh, *sysno, 1, &zh->keys);
542         extract_flushSortKeys (zh, *sysno, 1, &zh->sortKeys);
543
544         records_inserted++;
545     }
546     else
547     {
548         /* record already exists */
549         struct recKeys delkeys;
550
551         rec = rec_get (zh->service->records, *sysno);
552         assert (rec);
553         
554         recordAttr = rec_init_attr (zh->service->zei, rec);
555
556         if (recordAttr->runNumber ==
557             zebraExplain_runNumberIncrement (zh->service->zei, 0))
558         {
559             logf (LOG_LOG, "skipped %s %s " PRINTF_OFF_T, rGroup->recordType,
560                   fname, recordOffset);
561             extract_flushSortKeys (zh, *sysno, -1, &zh->sortKeys);
562             rec_rm (&rec);
563             logRecord (0);
564             return 1;
565         }
566         delkeys.buf_used = rec->size[recInfo_delKeys];
567         delkeys.buf = rec->info[recInfo_delKeys];
568         extract_flushSortKeys (zh, *sysno, 0, &zh->sortKeys);
569         extract_flushRecordKeys (zh, *sysno, 0, &delkeys);
570         if (deleteFlag)
571         {
572             /* record going to be deleted */
573             if (!delkeys.buf_used)
574             {
575                 logf (LOG_LOG, "delete %s %s " PRINTF_OFF_T,
576                       rGroup->recordType, fname, recordOffset);
577                 logf (LOG_WARN, "cannot delete file above, storeKeys false");
578             }
579             else
580             {
581                 if (records_processed < rGroup->fileVerboseLimit)
582                     logf (LOG_LOG, "delete %s %s " PRINTF_OFF_T,
583                          rGroup->recordType, fname, recordOffset);
584                 records_deleted++;
585                 if (matchStr)
586                     dict_delete (zh->service->matchDict, matchStr);
587                 rec_del (zh->service->records, &rec);
588             }
589             rec_rm (&rec);
590             logRecord (0);
591             return 1;
592         }
593         else
594         {
595             /* record going to be updated */
596             if (!delkeys.buf_used)
597             {
598                 logf (LOG_LOG, "update %s %s " PRINTF_OFF_T,
599                       rGroup->recordType, fname, recordOffset);
600                 logf (LOG_WARN, "cannot update file above, storeKeys false");
601             }
602             else
603             {
604                 if (records_processed < rGroup->fileVerboseLimit)
605                     logf (LOG_LOG, "update %s %s " PRINTF_OFF_T,
606                         rGroup->recordType, fname, recordOffset);
607                 extract_flushRecordKeys (zh, *sysno, 1, &zh->keys);
608                 records_updated++;
609             }
610         }
611     }
612     /* update file type */
613     xfree (rec->info[recInfo_fileType]);
614     rec->info[recInfo_fileType] =
615         rec_strdup (rGroup->recordType, &rec->size[recInfo_fileType]);
616
617     /* update filename */
618     xfree (rec->info[recInfo_filename]);
619     rec->info[recInfo_filename] =
620         rec_strdup (fname, &rec->size[recInfo_filename]);
621
622     /* update delete keys */
623     xfree (rec->info[recInfo_delKeys]);
624     if (zh->keys.buf_used > 0 && rGroup->flagStoreKeys == 1)
625     {
626 #if 1
627         rec->size[recInfo_delKeys] = zh->keys.buf_used;
628         rec->info[recInfo_delKeys] = zh->keys.buf;
629         zh->keys.buf = NULL;
630         zh->keys.buf_max = 0;
631 #else
632         rec->info[recInfo_delKeys] = xmalloc (reckeys.buf_used);
633         rec->size[recInfo_delKeys] = reckeys.buf_used;
634         memcpy (rec->info[recInfo_delKeys], reckeys.buf,
635                 rec->size[recInfo_delKeys]);
636 #endif
637     }
638     else
639     {
640         rec->info[recInfo_delKeys] = NULL;
641         rec->size[recInfo_delKeys] = 0;
642     }
643
644     /* save file size of original record */
645     zebraExplain_recordBytesIncrement (zh->service->zei,
646                                        - recordAttr->recordSize);
647     recordAttr->recordSize = fi->file_moffset - recordOffset;
648     if (!recordAttr->recordSize)
649         recordAttr->recordSize = fi->file_max - recordOffset;
650     zebraExplain_recordBytesIncrement (zh->service->zei,
651                                        recordAttr->recordSize);
652
653     /* set run-number for this record */
654     recordAttr->runNumber = zebraExplain_runNumberIncrement (zh->service->zei,
655                                                              0);
656
657     /* update store data */
658     xfree (rec->info[recInfo_storeData]);
659     if (rGroup->flagStoreData == 1)
660     {
661         rec->size[recInfo_storeData] = recordAttr->recordSize;
662         rec->info[recInfo_storeData] = (char *)
663             xmalloc (recordAttr->recordSize);
664         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
665         {
666             logf (LOG_ERRNO|LOG_FATAL, "seek to " PRINTF_OFF_T " in %s",
667                   recordOffset, fname);
668             exit (1);
669         }
670         if (read (fi->fd, rec->info[recInfo_storeData], recordAttr->recordSize)
671             < recordAttr->recordSize)
672         {
673             logf (LOG_ERRNO|LOG_FATAL, "read %d bytes of %s",
674                   recordAttr->recordSize, fname);
675             exit (1);
676         }
677     }
678     else
679     {
680         rec->info[recInfo_storeData] = NULL;
681         rec->size[recInfo_storeData] = 0;
682     }
683     /* update database name */
684     xfree (rec->info[recInfo_databaseName]);
685     rec->info[recInfo_databaseName] =
686         rec_strdup (rGroup->databaseName, &rec->size[recInfo_databaseName]); 
687
688     /* update offset */
689     recordAttr->recordOffset = recordOffset;
690     
691     /* commit this record */
692     rec_put (zh->service->records, &rec);
693     logRecord (0);
694     return 1;
695 }
696
697 int fileExtract (ZebraHandle zh, SYSNO *sysno, const char *fname, 
698                  const struct recordGroup *rGroupP, int deleteFlag)
699 {
700     int r, i, fd;
701     char gprefix[128];
702     char ext[128];
703     char ext_res[128];
704     char subType[128];
705     RecType recType;
706     struct recordGroup rGroupM;
707     struct recordGroup *rGroup = &rGroupM;
708     struct file_read_info *fi;
709     void *clientData;
710
711     memcpy (rGroup, rGroupP, sizeof(*rGroupP));
712    
713     if (!rGroup->groupName || !*rGroup->groupName)
714         *gprefix = '\0';
715     else
716         sprintf (gprefix, "%s.", rGroup->groupName);
717
718     logf (LOG_DEBUG, "fileExtract %s", fname);
719
720     /* determine file extension */
721     *ext = '\0';
722     for (i = strlen(fname); --i >= 0; )
723         if (fname[i] == '/')
724             break;
725         else if (fname[i] == '.')
726         {
727             strcpy (ext, fname+i+1);
728             break;
729         }
730     /* determine file type - depending on extension */
731     if (!rGroup->recordType)
732     {
733         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
734         if (!(rGroup->recordType = res_get (zh->service->res, ext_res)))
735         {
736             sprintf (ext_res, "%srecordType", gprefix);
737             rGroup->recordType = res_get (zh->service->res, ext_res);
738         }
739     }
740     if (!rGroup->recordType)
741     {
742         if (records_processed < rGroup->fileVerboseLimit)
743             logf (LOG_LOG, "? %s", fname);
744         return 0;
745     }
746     if (!*rGroup->recordType)
747         return 0;
748     if (!(recType =
749           recType_byName (zh->service->recTypes, rGroup->recordType, subType,
750                           &clientData)))
751     {
752         logf (LOG_WARN, "No such record type: %s", rGroup->recordType);
753         return 0;
754     }
755
756     /* determine match criteria */
757     if (!rGroup->recordId)
758     {
759         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
760         rGroup->recordId = res_get (zh->service->res, ext_res);
761     }
762
763     /* determine database name */
764     if (!rGroup->databaseName)
765     {
766         sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
767         if (!(rGroup->databaseName = res_get (zh->service->res, ext_res)))
768         {
769             sprintf (ext_res, "%sdatabase", gprefix);
770             rGroup->databaseName = res_get (zh->service->res, ext_res);
771         }
772     }
773     if (!rGroup->databaseName)
774         rGroup->databaseName = "Default";
775
776     /* determine if explain database */
777     
778     sprintf (ext_res, "%sexplainDatabase", gprefix);
779     rGroup->explainDatabase =
780         atoi (res_get_def (zh->service->res, ext_res, "0"));
781
782     /* announce database */
783     if (zebraExplain_curDatabase (zh->service->zei, rGroup->databaseName))
784     {
785         if (zebraExplain_newDatabase (zh->service->zei, rGroup->databaseName,
786                                       rGroup->explainDatabase))
787             return 0;
788     }
789
790     if (rGroup->flagStoreData == -1)
791     {
792         const char *sval;
793         sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
794         if (!(sval = res_get (zh->service->res, ext_res)))
795         {
796             sprintf (ext_res, "%sstoreData", gprefix);
797             sval = res_get (zh->service->res, ext_res);
798         }
799         if (sval)
800             rGroup->flagStoreData = atoi (sval);
801     }
802     if (rGroup->flagStoreData == -1)
803         rGroup->flagStoreData = 0;
804
805     if (rGroup->flagStoreKeys == -1)
806     {
807         const char *sval;
808
809         sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
810         sval = res_get (zh->service->res, ext_res);
811         if (!sval)
812         {
813             sprintf (ext_res, "%sstoreKeys", gprefix);
814             sval = res_get (zh->service->res, ext_res);
815         }
816         if (!sval)
817             sval = res_get (zh->service->res, "storeKeys");
818         if (sval)
819             rGroup->flagStoreKeys = atoi (sval);
820     }
821     if (rGroup->flagStoreKeys == -1)
822         rGroup->flagStoreKeys = 0;
823
824     if (sysno && deleteFlag)
825         fd = -1;
826     else
827     {
828         if ((fd = open (fname, O_BINARY|O_RDONLY)) == -1)
829         {
830             logf (LOG_WARN|LOG_ERRNO, "open %s", fname);
831             return 0;
832         }
833     }
834     fi = file_read_start (fd);
835     do
836     {
837         file_begin (fi);
838         r = recordExtract (zh, sysno, fname, rGroup, deleteFlag, fi,
839                            recType, subType, clientData);
840     } while (r && !sysno && fi->file_more);
841     file_read_stop (fi);
842     if (fd != -1)
843         close (fd);
844     return r;
845 }
846
847
848 int extract_rec_in_mem (ZebraHandle zh, const char *recordType,
849                         const char *buf, size_t buf_size,
850                         const char *databaseName, int delete_flag,
851                         int test_mode, int *sysno,
852                         int store_keys, int store_data,
853                         const char *match_criteria)
854 {
855     RecordAttr *recordAttr;
856     struct recExtractCtrl extractCtrl;
857     int i, r;
858     char *matchStr;
859     RecType recType;
860     char subType[1024];
861     void *clientData;
862     const char *fname = "<no file>";
863     Record rec;
864     long recordOffset = 0;
865     struct zebra_fetch_control fc;
866
867     fc.fd = -1;
868     fc.record_int_buf = buf;
869     fc.record_int_len = buf_size;
870     fc.record_int_pos = 0;
871     fc.offset_end = 0;
872     fc.record_offset = 0;
873
874     extractCtrl.offset = 0;
875     extractCtrl.readf = zebra_record_int_read;
876     extractCtrl.seekf = zebra_record_int_seek;
877     extractCtrl.tellf = zebra_record_int_tell;
878     extractCtrl.endf = zebra_record_int_end;
879     extractCtrl.fh = &fc;
880
881     /* announce database */
882     if (zebraExplain_curDatabase (zh->service->zei, databaseName))
883     {
884         if (zebraExplain_newDatabase (zh->service->zei, databaseName, 0))
885             return 0;
886     }
887     if (!(recType =
888           recType_byName (zh->service->recTypes, recordType, subType,
889                           &clientData)))
890     {
891         logf (LOG_WARN, "No such record type: %s", recordType);
892         return 0;
893     }
894
895     zh->keys.buf_used = 0;
896     zh->keys.prevAttrUse = -1;
897     zh->keys.prevAttrSet = -1;
898     zh->keys.prevSeqNo = 0;
899     zh->sortKeys = 0;
900
901     extractCtrl.subType = subType;
902     extractCtrl.init = extract_init;
903     extractCtrl.tokenAdd = extract_token_add;
904     extractCtrl.schemaAdd = extract_schema_add;
905     extractCtrl.dh = zh->service->dh;
906     extractCtrl.handle = zh;
907     extractCtrl.zebra_maps = zh->service->zebra_maps;
908     extractCtrl.flagShowRecords = 0;
909     for (i = 0; i<256; i++)
910     {
911         if (zebra_maps_is_positioned(zh->service->zebra_maps, i))
912             extractCtrl.seqno[i] = 1;
913         else
914             extractCtrl.seqno[i] = 0;
915     }
916
917     r = (*recType->extract)(clientData, &extractCtrl);
918
919     if (r == RECCTRL_EXTRACT_EOF)
920         return 0;
921     else if (r == RECCTRL_EXTRACT_ERROR)
922     {
923         /* error occured during extraction ... */
924 #if 1
925         yaz_log (LOG_WARN, "extract error");
926 #else
927         if (rGroup->flagRw &&
928             records_processed < rGroup->fileVerboseLimit)
929         {
930             logf (LOG_WARN, "fail %s %s %ld", rGroup->recordType,
931                   fname, (long) recordOffset);
932         }
933 #endif
934         return 0;
935     }
936     if (zh->keys.buf_used == 0)
937     {
938         /* the extraction process returned no information - the record
939            is probably empty - unless flagShowRecords is in use */
940         if (test_mode)
941             return 1;
942         logf (LOG_WARN, "No keys generated for record");
943         logf (LOG_WARN, " The file is probably empty");
944         return 1;
945     }
946     /* match criteria */
947
948     if (! *sysno)
949     {
950         /* new record */
951         if (delete_flag)
952         {
953             logf (LOG_LOG, "delete %s %s %ld", recordType,
954                   fname, (long) recordOffset);
955             logf (LOG_WARN, "cannot delete record above (seems new)");
956             return 1;
957         }
958         logf (LOG_LOG, "add %s %s %ld", recordType, fname,
959               (long) recordOffset);
960         rec = rec_new (zh->service->records);
961
962         *sysno = rec->sysno;
963
964         recordAttr = rec_init_attr (zh->service->zei, rec);
965
966         if (matchStr)
967         {
968             dict_insert (zh->service->matchDict, matchStr,
969                          sizeof(*sysno), sysno);
970         }
971         extract_flushRecordKeys (zh, *sysno, 1, &zh->keys);
972         extract_flushSortKeys (zh, *sysno, 1, &zh->sortKeys);
973     }
974     else
975     {
976         /* record already exists */
977         struct recKeys delkeys;
978
979         rec = rec_get (zh->service->records, *sysno);
980         assert (rec);
981         
982         recordAttr = rec_init_attr (zh->service->zei, rec);
983
984         if (recordAttr->runNumber ==
985             zebraExplain_runNumberIncrement (zh->service->zei, 0))
986         {
987             logf (LOG_LOG, "skipped %s %s %ld", recordType,
988                   fname, (long) recordOffset);
989             rec_rm (&rec);
990             return 1;
991         }
992         delkeys.buf_used = rec->size[recInfo_delKeys];
993         delkeys.buf = rec->info[recInfo_delKeys];
994         extract_flushSortKeys (zh, *sysno, 0, &zh->sortKeys);
995         extract_flushRecordKeys (zh, *sysno, 0, &delkeys);
996         if (delete_flag)
997         {
998             /* record going to be deleted */
999             if (!delkeys.buf_used)
1000             {
1001                 logf (LOG_LOG, "delete %s %s %ld", recordType,
1002                       fname, (long) recordOffset);
1003                 logf (LOG_WARN, "cannot delete file above, storeKeys false");
1004             }
1005             else
1006             {
1007                 logf (LOG_LOG, "delete %s %s %ld", recordType,
1008                       fname, (long) recordOffset);
1009 #if 0
1010                 if (matchStr)
1011                     dict_delete (matchDict, matchStr);
1012 #endif
1013                 rec_del (zh->service->records, &rec);
1014             }
1015             rec_rm (&rec);
1016             return 1;
1017         }
1018         else
1019         {
1020             /* record going to be updated */
1021             if (!delkeys.buf_used)
1022             {
1023                 logf (LOG_LOG, "update %s %s %ld", recordType,
1024                       fname, (long) recordOffset);
1025                 logf (LOG_WARN, "cannot update file above, storeKeys false");
1026             }
1027             else
1028             {
1029                 logf (LOG_LOG, "update %s %s %ld", recordType,
1030                       fname, (long) recordOffset);
1031                 extract_flushRecordKeys (zh, *sysno, 1, &zh->keys);
1032             }
1033         }
1034     }
1035     /* update file type */
1036     xfree (rec->info[recInfo_fileType]);
1037     rec->info[recInfo_fileType] =
1038         rec_strdup (recordType, &rec->size[recInfo_fileType]);
1039
1040     /* update filename */
1041     xfree (rec->info[recInfo_filename]);
1042     rec->info[recInfo_filename] =
1043         rec_strdup (fname, &rec->size[recInfo_filename]);
1044
1045     /* update delete keys */
1046     xfree (rec->info[recInfo_delKeys]);
1047     if (zh->keys.buf_used > 0 && store_keys == 1)
1048     {
1049         rec->size[recInfo_delKeys] = zh->keys.buf_used;
1050         rec->info[recInfo_delKeys] = zh->keys.buf;
1051         zh->keys.buf = NULL;
1052         zh->keys.buf_max = 0;
1053     }
1054     else
1055     {
1056         rec->info[recInfo_delKeys] = NULL;
1057         rec->size[recInfo_delKeys] = 0;
1058     }
1059
1060     /* save file size of original record */
1061     zebraExplain_recordBytesIncrement (zh->service->zei,
1062                                        - recordAttr->recordSize);
1063 #if 0
1064     recordAttr->recordSize = fi->file_moffset - recordOffset;
1065     if (!recordAttr->recordSize)
1066         recordAttr->recordSize = fi->file_max - recordOffset;
1067 #else
1068     recordAttr->recordSize = buf_size;
1069 #endif
1070     zebraExplain_recordBytesIncrement (zh->service->zei,
1071                                        recordAttr->recordSize);
1072
1073     /* set run-number for this record */
1074     recordAttr->runNumber =
1075         zebraExplain_runNumberIncrement (zh->service->zei, 0);
1076
1077     /* update store data */
1078     xfree (rec->info[recInfo_storeData]);
1079     if (store_data == 1)
1080     {
1081         rec->size[recInfo_storeData] = recordAttr->recordSize;
1082         rec->info[recInfo_storeData] = (char *)
1083             xmalloc (recordAttr->recordSize);
1084 #if 1
1085         memcpy (rec->info[recInfo_storeData], buf, recordAttr->recordSize);
1086 #else
1087         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
1088         {
1089             logf (LOG_ERRNO|LOG_FATAL, "seek to %ld in %s",
1090                   (long) recordOffset, fname);
1091             exit (1);
1092         }
1093         if (read (fi->fd, rec->info[recInfo_storeData], recordAttr->recordSize)
1094             < recordAttr->recordSize)
1095         {
1096             logf (LOG_ERRNO|LOG_FATAL, "read %d bytes of %s",
1097                   recordAttr->recordSize, fname);
1098             exit (1);
1099         }
1100 #endif
1101     }
1102     else
1103     {
1104         rec->info[recInfo_storeData] = NULL;
1105         rec->size[recInfo_storeData] = 0;
1106     }
1107     /* update database name */
1108     xfree (rec->info[recInfo_databaseName]);
1109     rec->info[recInfo_databaseName] =
1110         rec_strdup (databaseName, &rec->size[recInfo_databaseName]); 
1111
1112     /* update offset */
1113     recordAttr->recordOffset = recordOffset;
1114     
1115     /* commit this record */
1116     rec_put (zh->service->records, &rec);
1117
1118     return 0;
1119 }
1120
1121 int explain_extract (void *handle, Record rec, data1_node *n)
1122 {
1123     ZebraHandle zh = (ZebraHandle) handle;
1124     struct recExtractCtrl extractCtrl;
1125     int i;
1126
1127     if (zebraExplain_curDatabase (zh->service->zei,
1128                                   rec->info[recInfo_databaseName]))
1129     {
1130         abort();
1131         if (zebraExplain_newDatabase (zh->service->zei,
1132                                       rec->info[recInfo_databaseName], 0))
1133             abort ();
1134     }
1135
1136     zh->keys.buf_used = 0;
1137     zh->keys.prevAttrUse = -1;
1138     zh->keys.prevAttrSet = -1;
1139     zh->keys.prevSeqNo = 0;
1140     zh->sortKeys = 0;
1141     
1142     extractCtrl.init = extract_init;
1143     extractCtrl.tokenAdd = extract_token_add;
1144     extractCtrl.schemaAdd = extract_schema_add;
1145     extractCtrl.dh = zh->service->dh;
1146     for (i = 0; i<256; i++)
1147         extractCtrl.seqno[i] = 0;
1148     extractCtrl.zebra_maps = zh->service->zebra_maps;
1149     extractCtrl.flagShowRecords = 0;
1150     extractCtrl.handle = handle;
1151     
1152     grs_extract_tree(&extractCtrl, n);
1153
1154     logf (LOG_LOG, "flush explain record, sysno=%d", rec->sysno);
1155
1156     if (rec->size[recInfo_delKeys])
1157     {
1158         struct recKeys delkeys;
1159         struct sortKey *sortKeys = 0;
1160
1161         delkeys.buf_used = rec->size[recInfo_delKeys];
1162         delkeys.buf = rec->info[recInfo_delKeys];
1163         extract_flushSortKeys (zh, rec->sysno, 0, &sortKeys);
1164         extract_flushRecordKeys (zh, rec->sysno, 0, &delkeys);
1165     }
1166     extract_flushRecordKeys (zh, rec->sysno, 1, &zh->keys);
1167     extract_flushSortKeys (zh, rec->sysno, 1, &zh->sortKeys);
1168
1169     xfree (rec->info[recInfo_delKeys]);
1170     rec->size[recInfo_delKeys] = zh->keys.buf_used;
1171     rec->info[recInfo_delKeys] = zh->keys.buf;
1172     zh->keys.buf = NULL;
1173     zh->keys.buf_max = 0;
1174     return 0;
1175 }
1176
1177 void extract_flushRecordKeys (ZebraHandle zh, SYSNO sysno,
1178                               int cmd, struct recKeys *reckeys)
1179 {
1180 #if SU_SCHEME
1181 #else
1182     unsigned char attrSet = (unsigned char) -1;
1183     unsigned short attrUse = (unsigned short) -1;
1184 #endif
1185     int seqno = 0;
1186     int off = 0;
1187     int ch = 0;
1188     ZebraExplainInfo zei = zh->service->zei;
1189
1190     if (!zh->key_buf)
1191     {
1192         int mem = 8*1024*1024;
1193         zh->key_buf = (char**) xmalloc (mem);
1194         zh->ptr_top = mem/sizeof(char*);
1195         zh->ptr_i = 0;
1196         zh->key_buf_used = 0;
1197         zh->key_file_no = 0;
1198     }
1199     zebraExplain_recordCountIncrement (zei, cmd ? 1 : -1);
1200     while (off < reckeys->buf_used)
1201     {
1202         const char *src = reckeys->buf + off;
1203         struct it_key key;
1204         int lead;
1205     
1206         lead = *src++;
1207
1208 #if SU_SCHEME
1209         if ((lead & 3) < 3)
1210         {
1211             memcpy (&ch, src, sizeof(ch));
1212             src += sizeof(ch);
1213         }
1214 #else
1215         if (!(lead & 1))
1216         {
1217             memcpy (&attrSet, src, sizeof(attrSet));
1218             src += sizeof(attrSet);
1219         }
1220         if (!(lead & 2))
1221         {
1222             memcpy (&attrUse, src, sizeof(attrUse));
1223             src += sizeof(attrUse);
1224         }
1225 #endif
1226         if (zh->key_buf_used + 1024 > (zh->ptr_top-zh->ptr_i)*sizeof(char*))
1227             extract_flushWriteKeys (zh);
1228         ++(zh->ptr_i);
1229         (zh->key_buf)[zh->ptr_top - zh->ptr_i] =
1230             (char*)zh->key_buf + zh->key_buf_used;
1231 #if SU_SCHEME
1232 #else
1233         ch = zebraExplain_lookupSU (zei, attrSet, attrUse);
1234         if (ch < 0)
1235             ch = zebraExplain_addSU (zei, attrSet, attrUse);
1236 #endif
1237         assert (ch > 0);
1238         zh->key_buf_used +=
1239             key_SU_encode (ch,((char*)zh->key_buf) + zh->key_buf_used);
1240
1241         while (*src)
1242             ((char*)zh->key_buf) [(zh->key_buf_used)++] = *src++;
1243         src++;
1244         ((char*)(zh->key_buf))[(zh->key_buf_used)++] = '\0';
1245         ((char*)(zh->key_buf))[(zh->key_buf_used)++] = cmd;
1246
1247         if (lead & 60)
1248             seqno += ((lead>>2) & 15)-1;
1249         else
1250         {
1251             memcpy (&seqno, src, sizeof(seqno));
1252             src += sizeof(seqno);
1253         }
1254         key.seqno = seqno;
1255         key.sysno = sysno;
1256         memcpy ((char*)zh->key_buf + zh->key_buf_used, &key, sizeof(key));
1257         (zh->key_buf_used) += sizeof(key);
1258         off = src - reckeys->buf;
1259     }
1260     assert (off == reckeys->buf_used);
1261 }
1262
1263 void extract_flushWriteKeys (ZebraHandle zh)
1264 {
1265     FILE *outf;
1266     char out_fname[200];
1267     char *prevcp, *cp;
1268     struct encode_info encode_info;
1269     int ptr_i = zh->ptr_i;
1270 #if SORT_EXTRA
1271     int i;
1272 #endif
1273     if (!zh->key_buf || ptr_i <= 0)
1274         return;
1275
1276     (zh->key_file_no)++;
1277     logf (LOG_LOG, "sorting section %d", (zh->key_file_no));
1278 #if !SORT_EXTRA
1279     qsort (zh->key_buf + zh->ptr_top - ptr_i, ptr_i, sizeof(char*),
1280             key_qsort_compare);
1281     extract_get_fname_tmp (zh, out_fname, zh->key_file_no);
1282
1283     if (!(outf = fopen (out_fname, "wb")))
1284     {
1285         logf (LOG_FATAL|LOG_ERRNO, "fopen %s", out_fname);
1286         exit (1);
1287     }
1288     logf (LOG_LOG, "writing section %d", zh->key_file_no);
1289     prevcp = cp = (zh->key_buf)[zh->ptr_top - ptr_i];
1290     
1291     encode_key_init (&encode_info);
1292     encode_key_write (cp, &encode_info, outf);
1293     
1294     while (--ptr_i > 0)
1295     {
1296         cp = (zh->key_buf)[zh->ptr_top - ptr_i];
1297         if (strcmp (cp, prevcp))
1298         {
1299             encode_key_init (&encode_info);
1300             encode_key_write (cp, &encode_info, outf);
1301             prevcp = cp;
1302         }
1303         else
1304             encode_key_write (cp + strlen(cp), &encode_info, outf);
1305     }
1306 #else
1307     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_x_compare);
1308     extract_get_fname_tmp (out_fname, key_file_no);
1309
1310     if (!(outf = fopen (out_fname, "wb")))
1311     {
1312         logf (LOG_FATAL|LOG_ERRNO, "fopen %s", out_fname);
1313         exit (1);
1314     }
1315     logf (LOG_LOG, "writing section %d", key_file_no);
1316     i = ptr_i;
1317     prevcp =  key_buf[ptr_top-i];
1318     while (1)
1319         if (!--i || strcmp (prevcp, key_buf[ptr_top-i]))
1320         {
1321             key_y_len = strlen(prevcp)+1;
1322 #if 0
1323             logf (LOG_LOG, "key_y_len: %2d %02x %02x %s",
1324                       key_y_len, prevcp[0], prevcp[1], 2+prevcp);
1325 #endif
1326             qsort (key_buf + ptr_top-ptr_i, ptr_i - i,
1327                                    sizeof(char*), key_y_compare);
1328             cp = key_buf[ptr_top-ptr_i];
1329             --key_y_len;
1330             encode_key_init (&encode_info);
1331             encode_key_write (cp, &encode_info, outf);
1332             while (--ptr_i > i)
1333             {
1334                 cp = key_buf[ptr_top-ptr_i];
1335                 encode_key_write (cp+key_y_len, &encode_info, outf);
1336             }
1337             if (!i)
1338                 break;
1339             prevcp = key_buf[ptr_top-ptr_i];
1340         }
1341 #endif
1342     if (fclose (outf))
1343     {
1344         logf (LOG_FATAL|LOG_ERRNO, "fclose %s", out_fname);
1345         exit (1);
1346     }
1347     logf (LOG_LOG, "finished section %d", zh->key_file_no);
1348     zh->ptr_i = 0;
1349     zh->key_buf_used = 0;
1350 }
1351
1352 void extract_add_index_string (RecWord *p, const char *string,
1353                                int length)
1354 {
1355     char *dst;
1356     unsigned char attrSet;
1357     unsigned short attrUse;
1358     int lead = 0;
1359     int diff = 0;
1360     int *pseqno = &p->seqnos[p->reg_type];
1361     ZebraHandle zh = p->extractCtrl->handle;
1362     ZebraExplainInfo zei = zh->service->zei;
1363     struct recKeys *keys = &zh->keys;
1364
1365     if (keys->buf_used+1024 > keys->buf_max)
1366     {
1367         char *b;
1368
1369         b = (char *) xmalloc (keys->buf_max += 128000);
1370         if (keys->buf_used > 0)
1371             memcpy (b, keys->buf, keys->buf_used);
1372         xfree (keys->buf);
1373         keys->buf = b;
1374     }
1375     dst = keys->buf + keys->buf_used;
1376
1377     attrSet = p->attrSet;
1378     if (keys->buf_used > 0 && keys->prevAttrSet == attrSet)
1379         lead |= 1;
1380     else
1381         keys->prevAttrSet = attrSet;
1382     attrUse = p->attrUse;
1383     if (keys->buf_used > 0 && keys->prevAttrUse == attrUse)
1384         lead |= 2;
1385     else
1386         keys->prevAttrUse = attrUse;
1387 #if 1
1388     diff = 1 + *pseqno - keys->prevSeqNo;
1389     if (diff >= 1 && diff <= 15)
1390         lead |= (diff << 2);
1391     else
1392         diff = 0;
1393 #endif
1394     keys->prevSeqNo = *pseqno;
1395     
1396     *dst++ = lead;
1397
1398 #if SU_SCHEME
1399     if ((lead & 3) < 3)
1400     {
1401         int ch = zebraExplain_lookupSU (zei, attrSet, attrUse);
1402         if (ch < 0)
1403         {
1404             ch = zebraExplain_addSU (zei, attrSet, attrUse);
1405             yaz_log (LOG_LOG, "addSU set=%d use=%d SU=%d",
1406                      attrSet, attrUse, ch);
1407         }
1408         assert (ch > 0);
1409         memcpy (dst, &ch, sizeof(ch));
1410         dst += sizeof(ch);
1411     }
1412 #else
1413     if (!(lead & 1))
1414     {
1415         memcpy (dst, &attrSet, sizeof(attrSet));
1416         dst += sizeof(attrSet);
1417     }
1418     if (!(lead & 2))
1419     {
1420         memcpy (dst, &attrUse, sizeof(attrUse));
1421         dst += sizeof(attrUse);
1422     }
1423 #endif
1424     *dst++ = p->reg_type;
1425     memcpy (dst, string, length);
1426     dst += length;
1427     *dst++ = '\0';
1428
1429     if (!diff)
1430     {
1431         memcpy (dst, pseqno, sizeof(*pseqno));
1432         dst += sizeof(*pseqno);
1433     }
1434     keys->buf_used = dst - keys->buf;
1435     if (*pseqno)
1436         (*pseqno)++;
1437 }
1438
1439 static void extract_add_sort_string (RecWord *p, const char *string,
1440                                      int length)
1441 {
1442     struct sortKey *sk;
1443     ZebraHandle zh = p->extractCtrl->handle;
1444
1445     for (sk = zh->sortKeys; sk; sk = sk->next)
1446         if (sk->attrSet == p->attrSet && sk->attrUse == p->attrUse)
1447             return;
1448
1449     sk = (struct sortKey *) xmalloc (sizeof(*sk));
1450     sk->next = zh->sortKeys;
1451     zh->sortKeys = sk;
1452
1453     sk->string = (char *) xmalloc (length);
1454     sk->length = length;
1455     memcpy (sk->string, string, length);
1456
1457     sk->attrSet = p->attrSet;
1458     sk->attrUse = p->attrUse;
1459 }
1460
1461 void extract_add_string (RecWord *p, const char *string, int length)
1462 {
1463     assert (length > 0);
1464     if (zebra_maps_is_sort (p->zebra_maps, p->reg_type))
1465         extract_add_sort_string (p, string, length);
1466     else
1467         extract_add_index_string (p, string, length);
1468 }
1469
1470 static void extract_add_incomplete_field (RecWord *p)
1471 {
1472     const char *b = p->string;
1473     int remain = p->length;
1474     const char **map = 0;
1475
1476     if (remain > 0)
1477         map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
1478
1479     while (map)
1480     {
1481         char buf[IT_MAX_WORD+1];
1482         int i, remain;
1483
1484         /* Skip spaces */
1485         while (map && *map && **map == *CHR_SPACE)
1486         {
1487             remain = p->length - (b - p->string);
1488             if (remain > 0)
1489                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
1490             else
1491                 map = 0;
1492         }
1493         if (!map)
1494             break;
1495         i = 0;
1496         while (map && *map && **map != *CHR_SPACE)
1497         {
1498             const char *cp = *map;
1499
1500             while (i < IT_MAX_WORD && *cp)
1501                 buf[i++] = *(cp++);
1502             remain = p->length - (b - p->string);
1503             if (remain > 0)
1504                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
1505             else
1506                 map = 0;
1507         }
1508         if (!i)
1509             return;
1510         extract_add_string (p, buf, i);
1511     }
1512     (p->seqnos[p->reg_type])++; /* to separate this from next one  */
1513 }
1514
1515 static void extract_add_complete_field (RecWord *p)
1516 {
1517     const char *b = p->string;
1518     char buf[IT_MAX_WORD+1];
1519     const char **map = 0;
1520     int i = 0, remain = p->length;
1521
1522     if (remain > 0)
1523         map = zebra_maps_input (p->zebra_maps, p->reg_type, &b, remain);
1524
1525     while (remain > 0 && i < IT_MAX_WORD)
1526     {
1527         while (map && *map && **map == *CHR_SPACE)
1528         {
1529             remain = p->length - (b - p->string);
1530             if (remain > 0)
1531                 map = zebra_maps_input(p->zebra_maps, p->reg_type, &b, remain);
1532             else
1533                 map = 0;
1534         }
1535         if (!map)
1536             break;
1537
1538         if (i && i < IT_MAX_WORD)
1539             buf[i++] = *CHR_SPACE;
1540         while (map && *map && **map != *CHR_SPACE)
1541         {
1542             const char *cp = *map;
1543
1544             if (i >= IT_MAX_WORD)
1545                 break;
1546             while (i < IT_MAX_WORD && *cp)
1547                 buf[i++] = *(cp++);
1548             remain = p->length  - (b - p->string);
1549             if (remain > 0)
1550                 map = zebra_maps_input (p->zebra_maps, p->reg_type, &b,
1551                                         remain);
1552             else
1553                 map = 0;
1554         }
1555     }
1556     if (!i)
1557         return;
1558     extract_add_string (p, buf, i);
1559 }
1560
1561 void extract_token_add (RecWord *p)
1562 {
1563     WRBUF wrbuf;
1564     if ((wrbuf = zebra_replace(p->zebra_maps, p->reg_type, 0,
1565                                p->string, p->length)))
1566     {
1567         p->string = wrbuf_buf(wrbuf);
1568         p->length = wrbuf_len(wrbuf);
1569     }
1570     if (zebra_maps_is_complete (p->zebra_maps, p->reg_type))
1571         extract_add_complete_field (p);
1572     else
1573         extract_add_incomplete_field(p);
1574 }
1575
1576 void extract_schema_add (struct recExtractCtrl *p, Odr_oid *oid)
1577 {
1578     ZebraHandle zh = (ZebraHandle) (p->handle);
1579     zebraExplain_addSchema (zh->service->zei, oid);
1580 }
1581
1582 void extract_flushSortKeys (ZebraHandle zh, SYSNO sysno,
1583                             int cmd, struct sortKey **skp)
1584 {
1585     struct sortKey *sk = *skp;
1586     SortIdx sortIdx = zh->service->sortIdx;
1587
1588     sortIdx_sysno (sortIdx, sysno);
1589     while (sk)
1590     {
1591         struct sortKey *sk_next = sk->next;
1592         sortIdx_type (sortIdx, sk->attrUse);
1593         sortIdx_add (sortIdx, sk->string, sk->length);
1594         xfree (sk->string);
1595         xfree (sk);
1596         sk = sk_next;
1597     }
1598     yaz_log (LOG_LOG, "extract_flushSortKeys");
1599     *skp = 0;
1600 }
1601
1602 void encode_key_init (struct encode_info *i)
1603 {
1604     i->sysno = 0;
1605     i->seqno = 0;
1606     i->cmd = -1;
1607 }
1608
1609 char *encode_key_int (int d, char *bp)
1610 {
1611     if (d <= 63)
1612         *bp++ = d;
1613     else if (d <= 16383)
1614     {
1615         *bp++ = 64 + (d>>8);
1616         *bp++ = d  & 255;
1617     }
1618     else if (d <= 4194303)
1619     {
1620         *bp++ = 128 + (d>>16);
1621         *bp++ = (d>>8) & 255;
1622         *bp++ = d & 255;
1623     }
1624     else
1625     {
1626         *bp++ = 192 + (d>>24);
1627         *bp++ = (d>>16) & 255;
1628         *bp++ = (d>>8) & 255;
1629         *bp++ = d & 255;
1630     }
1631     return bp;
1632 }
1633
1634 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
1635 {
1636     struct it_key key;
1637     char *bp = i->buf;
1638
1639     while ((*bp++ = *k++))
1640         ;
1641     memcpy (&key, k+1, sizeof(struct it_key));
1642     bp = encode_key_int ( (key.sysno - i->sysno) * 2 + *k, bp);
1643     if (i->sysno != key.sysno)
1644     {
1645         i->sysno = key.sysno;
1646         i->seqno = 0;
1647     }
1648     else if (!i->seqno && !key.seqno && i->cmd == *k)
1649         return;
1650     bp = encode_key_int (key.seqno - i->seqno, bp);
1651     i->seqno = key.seqno;
1652     i->cmd = *k;
1653     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
1654     {
1655         logf (LOG_FATAL|LOG_ERRNO, "fwrite");
1656         exit (1);
1657     }
1658 }
1659