e06b9ae9287bbfb3d7abe85457195095ce22569e
[idzebra-moved-to-github.git] / index / extract.c
1 /* $Id: extract.c,v 1.212 2006-05-10 14:13:45 adam Exp $
2    Copyright (C) 1995-2006
3    Index Data ApS
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23 #include <stdio.h>
24 #include <assert.h>
25 #include <ctype.h>
26 #ifdef WIN32
27 #include <io.h>
28 #endif
29 #if HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #include <fcntl.h>
33
34 #include "index.h"
35 #include "orddict.h"
36 #include <direntz.h>
37 #include <charmap.h>
38
39 #ifdef WIN32
40 #define PRINTF_OFF_T "%I64d"
41 #else
42 /* !WIN32 */
43 #if SIZEOF_OFF_T == SIZEOF_LONG_LONG
44 #define PRINTF_OFF_T "%lld"
45 #else
46 #define PRINTF_OFF_T "%ld"
47 #endif
48
49 #endif
50
51
52 #define USE_SHELLSORT 0
53
54 #if USE_SHELLSORT
55 static void shellsort(void *ar, int r, size_t s,
56                       int (*cmp)(const void *a, const void *b))
57 {
58     char *a = ar;
59     char v[100];
60     int h, i, j, k;
61     static const int incs[16] = { 1391376, 463792, 198768, 86961, 33936,
62                                   13776, 4592, 1968, 861, 336, 
63                                   112, 48, 21, 7, 3, 1 };
64     for ( k = 0; k < 16; k++)
65         for (h = incs[k], i = h; i < r; i++)
66         { 
67             memcpy (v, a+s*i, s);
68             j = i;
69             while (j > h && (*cmp)(a + s*(j-h), v) > 0)
70             {
71                 memcpy (a + s*j, a + s*(j-h), s);
72                 j -= h;
73             }
74             memcpy (a+s*j, v, s);
75         } 
76 }
77 #endif
78
79 static void logRecord (ZebraHandle zh)
80 {
81     ++zh->records_processed;
82     if (!(zh->records_processed % 1000))
83     {
84         yaz_log (YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
85                         ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
86               zh->records_processed, zh->records_inserted, zh->records_updated,
87               zh->records_deleted);
88     }
89 }
90
91 static void extract_set_store_data_prepare(struct recExtractCtrl *p);
92
93 static void extract_init (struct recExtractCtrl *p, RecWord *w)
94 {
95     w->zebra_maps = p->zebra_maps;
96     w->seqno = 1;
97 #if NATTR
98 #else
99     w->attrSet = VAL_BIB1;
100     w->attrUse = 1016;
101 #endif
102     w->index_name = 0;
103     w->index_type = 'w';
104     w->extractCtrl = p;
105     w->record_id = 0;
106     w->section_id = 0;
107 }
108
109 static void searchRecordKey(ZebraHandle zh,
110                             zebra_rec_keys_t reckeys,
111                             int attrSetS, int attrUseS,
112                             const char **ws, int ws_length)
113 {
114     int i;
115     int ch;
116
117     for (i = 0; i<ws_length; i++)
118         ws[i] = NULL;
119
120     ch = zebraExplain_lookup_attr_su_any_index(zh->reg->zei,
121                                                attrSetS, attrUseS);
122     if (ch < 0)
123         return ;
124
125     if (zebra_rec_keys_rewind(reckeys))
126     {
127         int startSeq = -1;
128         const char *str;
129         size_t slen;
130         struct it_key key;
131         zint seqno;
132         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
133         {
134             assert(key.len <= 4 && key.len > 2);
135
136             seqno = key.mem[key.len-1];
137             
138             if (key.mem[0] == ch)
139             {
140                 int woff;
141                 
142                 if (startSeq == -1)
143                     startSeq = seqno;
144                 woff = seqno - startSeq;
145                 if (woff >= 0 && woff < ws_length)
146                     ws[woff] = str;
147             }
148         }
149     }
150 }
151
152 struct file_read_info {
153     off_t file_max;         /* maximum offset so far */
154     off_t file_offset;      /* current offset */
155     off_t file_moffset;     /* offset of rec/rec boundary */
156     int file_more;
157     int fd;
158 };
159
160 static struct file_read_info *file_read_start (int fd)
161 {
162     struct file_read_info *fi = (struct file_read_info *)
163         xmalloc (sizeof(*fi));
164
165     fi->fd = fd;
166     fi->file_max = 0;
167     fi->file_moffset = 0;
168     fi->file_offset = 0;
169     fi->file_more = 0;
170     return fi;
171 }
172
173 static void file_read_stop (struct file_read_info *fi)
174 {
175     xfree (fi);
176 }
177
178 static off_t file_seek (void *handle, off_t offset)
179 {
180     struct file_read_info *p = (struct file_read_info *) handle;
181     p->file_offset = offset;
182     return lseek (p->fd, offset, SEEK_SET);
183 }
184
185 static off_t file_tell (void *handle)
186 {
187     struct file_read_info *p = (struct file_read_info *) handle;
188     return p->file_offset;
189 }
190
191 static int file_read (void *handle, char *buf, size_t count)
192 {
193     struct file_read_info *p = (struct file_read_info *) handle;
194     int fd = p->fd;
195     int r;
196     r = read (fd, buf, count);
197     if (r > 0)
198     {
199         p->file_offset += r;
200         if (p->file_offset > p->file_max)
201             p->file_max = p->file_offset;
202     }
203     return r;
204 }
205
206 static void file_end (void *handle, off_t offset)
207 {
208     struct file_read_info *p = (struct file_read_info *) handle;
209
210     if (offset != p->file_moffset)
211     {
212         p->file_moffset = offset;
213         p->file_more = 1;
214     }
215 }
216
217 #define FILE_MATCH_BLANK "\t "
218
219 static char *fileMatchStr (ZebraHandle zh,
220                            zebra_rec_keys_t reckeys,
221                            const char *fname, const char *spec)
222 {
223     static char dstBuf[2048];      /* static here ??? */
224     char *dst = dstBuf;
225     const char *s = spec;
226
227     while (1)
228     {
229         for (; *s && strchr(FILE_MATCH_BLANK, *s); s++)
230             ;
231         if (!*s)
232             break;
233         if (*s == '(')
234         {
235             const char *ws[32];
236             char attset_str[64], attname_str[64];
237             data1_attset *attset;
238             int i;
239             int attSet = 1, attUse = 1;
240             int first = 1;
241             
242             for (s++; strchr(FILE_MATCH_BLANK, *s); s++)
243                 ;
244             for (i = 0; *s && *s != ',' && *s != ')' && 
245                      !strchr(FILE_MATCH_BLANK, *s); s++)
246                 if (i+1 < sizeof(attset_str))
247                     attset_str[i++] = *s;
248             attset_str[i] = '\0';
249             
250             for (; strchr(FILE_MATCH_BLANK, *s); s++)
251                 ;
252             if (*s == ',')
253             {
254                 for (s++; strchr(FILE_MATCH_BLANK, *s); s++)
255                     ;
256                 for (i = 0; *s && *s != ')' && 
257                          !strchr(FILE_MATCH_BLANK, *s); s++)
258                     if (i+1 < sizeof(attname_str))
259                         attname_str[i++] = *s;
260                 attname_str[i] = '\0';
261             }
262             
263             if ((attset = data1_get_attset (zh->reg->dh, attset_str)))
264             {
265                 data1_att *att;
266                 attSet = attset->reference;
267                 att = data1_getattbyname(zh->reg->dh, attset, attname_str);
268                 if (att)
269                     attUse = att->value;
270                 else
271                     attUse = atoi (attname_str);
272             }
273             searchRecordKey (zh, reckeys, attSet, attUse, ws, 32);
274
275             if (*s != ')')
276             {
277                 yaz_log (YLOG_WARN, "Missing ) in match criteria %s in group %s",
278                       spec, zh->m_group ? zh->m_group : "none");
279                 return NULL;
280             }
281             s++;
282
283             for (i = 0; i<32; i++)
284                 if (ws[i])
285                 {
286                     if (first)
287                     {
288                         *dst++ = ' ';
289                         first = 0;
290                     }
291                     strcpy (dst, ws[i]);
292                     dst += strlen(ws[i]);
293                 }
294             if (first)
295             {
296                 yaz_log (YLOG_WARN, "Record didn't contain match"
297                       " fields in (%s,%s)", attset_str, attname_str);
298                 return NULL;
299             }
300         }
301         else if (*s == '$')
302         {
303             int spec_len;
304             char special[64];
305             const char *spec_src = NULL;
306             const char *s1 = ++s;
307             while (*s1 && !strchr(FILE_MATCH_BLANK, *s1))
308                 s1++;
309
310             spec_len = s1 - s;
311             if (spec_len > sizeof(special)-1)
312                 spec_len = sizeof(special)-1;
313             memcpy (special, s, spec_len);
314             special[spec_len] = '\0';
315             s = s1;
316
317             if (!strcmp (special, "group"))
318                 spec_src = zh->m_group;
319             else if (!strcmp (special, "database"))
320                 spec_src = zh->basenames[0];
321             else if (!strcmp (special, "filename")) {
322                 spec_src = fname;
323             }
324             else if (!strcmp (special, "type"))
325                 spec_src = zh->m_record_type;
326             else 
327                 spec_src = NULL;
328             if (spec_src)
329             {
330                 strcpy (dst, spec_src);
331                 dst += strlen (spec_src);
332             }
333         }
334         else if (*s == '\"' || *s == '\'')
335         {
336             int stopMarker = *s++;
337             char tmpString[64];
338             int i = 0;
339
340             while (*s && *s != stopMarker)
341             {
342                 if (i+1 < sizeof(tmpString))
343                     tmpString[i++] = *s++;
344             }
345             if (*s)
346                 s++;
347             tmpString[i] = '\0';
348             strcpy (dst, tmpString);
349             dst += strlen (tmpString);
350         }
351         else
352         {
353             yaz_log (YLOG_WARN, "Syntax error in match criteria %s in group %s",
354                   spec, zh->m_group ? zh->m_group : "none");
355             return NULL;
356         }
357         *dst++ = 1;
358     }
359     if (dst == dstBuf)
360     {
361         yaz_log (YLOG_WARN, "No match criteria for record %s in group %s",
362               fname, zh->m_group ? zh->m_group : "none");
363         return NULL;
364     }
365     *dst = '\0';
366     return dstBuf;
367 }
368
369 struct recordLogInfo {
370     const char *fname;
371     int recordOffset;
372     struct recordGroup *rGroup;
373 };
374
375 static void init_extractCtrl(ZebraHandle zh, struct recExtractCtrl *ctrl)
376 {
377     int i;
378     for (i = 0; i<256; i++)
379     {
380         if (zebra_maps_is_positioned(zh->reg->zebra_maps, i))
381             ctrl->seqno[i] = 1;
382         else
383             ctrl->seqno[i] = 0;
384     }
385     ctrl->zebra_maps = zh->reg->zebra_maps;
386     ctrl->flagShowRecords = !zh->m_flag_rw;
387 }
388
389 static ZEBRA_RES file_extract_record(ZebraHandle zh,
390                                      SYSNO *sysno, const char *fname,
391                                      int deleteFlag,
392                                      struct file_read_info *fi,
393                                      int force_update,
394                                      RecType recType,
395                                      void *recTypeClientData)
396 {
397     const char *match_str_to_print = "";
398     RecordAttr *recordAttr;
399     int r;
400     const char *matchStr = 0;
401     SYSNO sysnotmp;
402     Record rec;
403     off_t recordOffset = 0;
404     struct recExtractCtrl extractCtrl;
405     
406     /* announce database */
407     if (zebraExplain_curDatabase (zh->reg->zei, zh->basenames[0]))
408     {
409         if (zebraExplain_newDatabase (zh->reg->zei, zh->basenames[0],
410                                       zh->m_explain_database))
411             return ZEBRA_FAIL;
412     }
413
414     if (fi->fd != -1)
415     {
416         /* we are going to read from a file, so prepare the extraction */
417         zebra_rec_keys_reset(zh->reg->keys);
418
419 #if NATTR
420         zebra_rec_keys_reset(zh->reg->sortKeys);
421 #else
422         zh->reg->sortKeys.buf_used = 0;
423 #endif
424         recordOffset = fi->file_moffset;
425         extractCtrl.handle = zh;
426         extractCtrl.offset = fi->file_moffset;
427         extractCtrl.readf = file_read;
428         extractCtrl.seekf = file_seek;
429         extractCtrl.tellf = file_tell;
430         extractCtrl.endf = file_end;
431         extractCtrl.fh = fi;
432         extractCtrl.init = extract_init;
433         extractCtrl.tokenAdd = extract_token_add;
434         extractCtrl.schemaAdd = extract_schema_add;
435         extractCtrl.dh = zh->reg->dh;
436         extractCtrl.match_criteria[0] = '\0';
437         extractCtrl.staticrank = 0;
438         
439         extractCtrl.first_record = fi->file_offset ? 0 : 1;
440
441         extract_set_store_data_prepare(&extractCtrl);
442
443         init_extractCtrl(zh, &extractCtrl);
444
445         if (!zh->m_flag_rw)
446             printf ("File: %s " PRINTF_OFF_T "\n", fname, recordOffset);
447         if (zh->m_flag_rw)
448         {
449             char msg[512];
450             sprintf (msg, "%s:" PRINTF_OFF_T , fname, recordOffset);
451             yaz_log_init_prefix2 (msg);
452         }
453
454         r = (*recType->extract)(recTypeClientData, &extractCtrl);
455
456         yaz_log_init_prefix2 (0);
457         if (r == RECCTRL_EXTRACT_EOF)
458             return ZEBRA_FAIL;
459         else if (r == RECCTRL_EXTRACT_ERROR_GENERIC)
460         {
461             /* error occured during extraction ... */
462             if (zh->m_flag_rw &&
463                 zh->records_processed < zh->m_file_verbose_limit)
464             {
465                 yaz_log (YLOG_WARN, "fail %s %s " PRINTF_OFF_T, zh->m_record_type,
466                       fname, recordOffset);
467             }
468             return ZEBRA_FAIL;
469         }
470         else if (r == RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER)
471         {
472             /* error occured during extraction ... */
473             if (zh->m_flag_rw &&
474                 zh->records_processed < zh->m_file_verbose_limit)
475             {
476                 yaz_log (YLOG_WARN, "no filter for %s %s " 
477                       PRINTF_OFF_T, zh->m_record_type,
478                       fname, recordOffset);
479             }
480             return ZEBRA_FAIL;
481         }
482         if (extractCtrl.match_criteria[0])
483             matchStr = extractCtrl.match_criteria;      
484     }
485
486     /* if matchStr is set now - we assume it's printable .
487        For internal matchStr (see below) we don't print */
488     if (matchStr)
489         match_str_to_print = matchStr;
490
491     /* perform internal match if sysno not known and if match criteria is
492        specified already */
493     if (!sysno) 
494     {
495         sysnotmp = 0;
496         sysno = &sysnotmp;
497
498         if (matchStr == 0 && zh->m_record_id && *zh->m_record_id)
499         {
500             matchStr = fileMatchStr (zh, zh->reg->keys, fname, 
501                                      zh->m_record_id);
502             if (!matchStr)
503             {
504                 yaz_log(YLOG_WARN, "Bad match criteria");
505                 return ZEBRA_FAIL;
506             }
507         }
508         if (matchStr)
509         {
510             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
511             char *rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord,
512                                           matchStr);
513             if (rinfo)
514             {
515                 assert(*rinfo == sizeof(*sysno));
516                 memcpy (sysno, rinfo+1, sizeof(*sysno));
517             }
518         }
519     }
520     if (! *sysno && zebra_rec_keys_empty(zh->reg->keys) )
521     {
522          /* the extraction process returned no information - the record
523             is probably empty - unless flagShowRecords is in use */
524          if (!zh->m_flag_rw)
525              return ZEBRA_OK;
526   
527          if (zh->records_processed < zh->m_file_verbose_limit)
528              yaz_log (YLOG_WARN, "empty %s %s " PRINTF_OFF_T, zh->m_record_type,
529             fname, recordOffset);
530          return ZEBRA_OK;
531     }
532
533     if (! *sysno)
534     {
535         /* new record */
536         if (deleteFlag)
537         {
538             yaz_log (YLOG_LOG, "delete %s %s " PRINTF_OFF_T, zh->m_record_type,
539                   fname, recordOffset);
540             yaz_log (YLOG_WARN, "cannot delete record above (seems new)");
541             return ZEBRA_OK;
542         }
543
544         rec = rec_new (zh->reg->records);
545         
546         *sysno = rec->sysno;
547         
548         if (zh->records_processed < zh->m_file_verbose_limit)
549         {
550             yaz_log(YLOG_LOG, "add %s %s " PRINTF_OFF_T 
551                     " " ZINT_FORMAT " %s" ,
552                     zh->m_record_type,
553                     fname, recordOffset, *sysno, match_str_to_print);
554         }
555         recordAttr = rec_init_attr (zh->reg->zei, rec);
556         recordAttr->staticrank = extractCtrl.staticrank;
557
558         if (matchStr)
559         {
560             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
561             dict_insert_ord(zh->reg->matchDict, db_ord, matchStr,
562                             sizeof(*sysno), sysno);
563         }
564
565
566 #if NATTR
567         extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
568 #else
569         extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
570 #endif
571         extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys,
572                                  recordAttr->staticrank);
573         zh->records_inserted++;
574     }
575     else
576     {
577         /* record already exists */
578         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
579
580 #if NATTR
581         zebra_rec_keys_t sortKeys = zebra_rec_keys_open();
582 #else
583         struct sortKeys sortKeys;
584 #endif
585
586         rec = rec_get (zh->reg->records, *sysno);
587         assert (rec);
588         
589         recordAttr = rec_init_attr (zh->reg->zei, rec);
590
591         zebra_rec_keys_set_buf(delkeys,
592                                rec->info[recInfo_delKeys],
593                                rec->size[recInfo_delKeys],
594                                0);
595
596 #if NATTR
597         zebra_rec_keys_set_buf(sortKeys,
598                                rec->info[recInfo_sortKeys],
599                                rec->size[recInfo_sortKeys],
600                                0);
601         extract_flushSortKeys (zh, *sysno, 0, sortKeys);
602 #else
603         sortKeys.buf_used = rec->size[recInfo_sortKeys];
604         sortKeys.buf = rec->info[recInfo_sortKeys];
605         extract_flushSortKeys (zh, *sysno, 0, &sortKeys);
606 #endif
607
608         extract_flushRecordKeys (zh, *sysno, 0, delkeys,
609                                  recordAttr->staticrank); /* old values */  
610         if (deleteFlag)
611         {
612             /* record going to be deleted */
613             if (zebra_rec_keys_empty(delkeys))
614             {
615                 yaz_log (YLOG_LOG, "delete %s %s " PRINTF_OFF_T 
616                          " " ZINT_FORMAT,
617                          zh->m_record_type, fname, recordOffset, *sysno);
618                 yaz_log (YLOG_WARN, "cannot delete file above, storeKeys false (1)");
619             }
620             else
621             {
622                 if (zh->records_processed < zh->m_file_verbose_limit)
623                 {
624                     yaz_log(YLOG_LOG, "delete %s %s " PRINTF_OFF_T 
625                             " " ZINT_FORMAT " %s" ,
626                             zh->m_record_type,
627                             fname, recordOffset, *sysno, match_str_to_print);
628                 }
629                 zh->records_deleted++;
630                 if (matchStr)
631                 {
632                     int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
633                     dict_delete_ord(zh->reg->matchDict, db_ord, matchStr);
634                 }
635                 rec_del (zh->reg->records, &rec);
636             }
637             rec_rm (&rec);
638             logRecord (zh);
639             return ZEBRA_OK;
640         }
641         else
642         {
643             /* flush new keys for sort&search etc */
644             if (zh->records_processed < zh->m_file_verbose_limit)
645             {
646                 yaz_log(YLOG_LOG, "update %s %s " PRINTF_OFF_T 
647                         " " ZINT_FORMAT " %s" ,
648                         zh->m_record_type,
649                         fname, recordOffset, *sysno, match_str_to_print);
650             }
651             recordAttr->staticrank = extractCtrl.staticrank;
652 #if NATTR
653             extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
654 #else
655             extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
656 #endif
657             extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys,
658                                          recordAttr->staticrank);
659             zh->records_updated++;
660         }
661         zebra_rec_keys_close(delkeys);
662 #if NATTR
663         zebra_rec_keys_close(sortKeys);
664 #endif
665     }
666     /* update file type */
667     xfree (rec->info[recInfo_fileType]);
668     rec->info[recInfo_fileType] =
669         rec_strdup (zh->m_record_type, &rec->size[recInfo_fileType]);
670
671     /* update filename */
672     xfree (rec->info[recInfo_filename]);
673     rec->info[recInfo_filename] =
674         rec_strdup (fname, &rec->size[recInfo_filename]);
675
676     /* update delete keys */
677     xfree (rec->info[recInfo_delKeys]);
678     if (!zebra_rec_keys_empty(zh->reg->keys) && zh->m_store_keys == 1)
679     {
680         zebra_rec_keys_get_buf(zh->reg->keys,
681                                &rec->info[recInfo_delKeys],
682                                &rec->size[recInfo_delKeys]);
683     }
684     else
685     {
686         rec->info[recInfo_delKeys] = NULL;
687         rec->size[recInfo_delKeys] = 0;
688     }
689
690     /* update sort keys */
691     xfree (rec->info[recInfo_sortKeys]);
692
693 #if NATTR
694     zebra_rec_keys_get_buf(zh->reg->sortKeys,
695                            &rec->info[recInfo_sortKeys],
696                            &rec->size[recInfo_sortKeys]);
697 #else
698     rec->size[recInfo_sortKeys] = zh->reg->sortKeys.buf_used;
699     rec->info[recInfo_sortKeys] = zh->reg->sortKeys.buf;
700     zh->reg->sortKeys.buf = NULL;
701     zh->reg->sortKeys.buf_max = 0;
702 #endif
703
704     /* save file size of original record */
705     zebraExplain_recordBytesIncrement (zh->reg->zei,
706                                        - recordAttr->recordSize);
707     recordAttr->recordSize = fi->file_moffset - recordOffset;
708     if (!recordAttr->recordSize)
709         recordAttr->recordSize = fi->file_max - recordOffset;
710     zebraExplain_recordBytesIncrement (zh->reg->zei,
711                                        recordAttr->recordSize);
712
713     /* set run-number for this record */
714     recordAttr->runNumber = zebraExplain_runNumberIncrement (zh->reg->zei,
715                                                              0);
716
717     /* update store data */
718     xfree (rec->info[recInfo_storeData]);
719     if (zh->store_data_buf)
720     {
721         rec->size[recInfo_storeData] = zh->store_data_size;
722         rec->info[recInfo_storeData] = zh->store_data_buf;
723         zh->store_data_buf = 0;
724     }
725     else if (zh->m_store_data)
726     {
727         rec->size[recInfo_storeData] = recordAttr->recordSize;
728         rec->info[recInfo_storeData] = (char *)
729             xmalloc (recordAttr->recordSize);
730         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
731         {
732             yaz_log (YLOG_ERRNO|YLOG_FATAL, "seek to " PRINTF_OFF_T " in %s",
733                   recordOffset, fname);
734             exit (1);
735         }
736         if (read (fi->fd, rec->info[recInfo_storeData], recordAttr->recordSize)
737             < recordAttr->recordSize)
738         {
739             yaz_log (YLOG_ERRNO|YLOG_FATAL, "read %d bytes of %s",
740                   recordAttr->recordSize, fname);
741             exit (1);
742         }
743     }
744     else
745     {
746         rec->info[recInfo_storeData] = NULL;
747         rec->size[recInfo_storeData] = 0;
748     }
749     /* update database name */
750     xfree (rec->info[recInfo_databaseName]);
751     rec->info[recInfo_databaseName] =
752         rec_strdup (zh->basenames[0], &rec->size[recInfo_databaseName]); 
753
754     /* update offset */
755     recordAttr->recordOffset = recordOffset;
756     
757     /* commit this record */
758     rec_put (zh->reg->records, &rec);
759     logRecord (zh);
760     return ZEBRA_OK;
761 }
762
763 ZEBRA_RES zebra_extract_file(ZebraHandle zh, SYSNO *sysno, const char *fname, 
764                              int deleteFlag)
765 {
766     ZEBRA_RES r = ZEBRA_OK;
767     int i, fd;
768     char gprefix[128];
769     char ext[128];
770     char ext_res[128];
771     struct file_read_info *fi;
772     const char *original_record_type = 0;
773     RecType recType;
774     void *recTypeClientData;
775
776     if (!zh->m_group || !*zh->m_group)
777         *gprefix = '\0';
778     else
779         sprintf (gprefix, "%s.", zh->m_group);
780     
781     yaz_log (YLOG_DEBUG, "fileExtract %s", fname);
782
783     /* determine file extension */
784     *ext = '\0';
785     for (i = strlen(fname); --i >= 0; )
786         if (fname[i] == '/')
787             break;
788         else if (fname[i] == '.')
789         {
790             strcpy (ext, fname+i+1);
791             break;
792         }
793     /* determine file type - depending on extension */
794     original_record_type = zh->m_record_type;
795     if (!zh->m_record_type)
796     {
797         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
798         zh->m_record_type = res_get (zh->res, ext_res);
799     }
800     if (!zh->m_record_type)
801     {
802         if (zh->records_processed < zh->m_file_verbose_limit)
803             yaz_log (YLOG_LOG, "? %s", fname);
804         return 0;
805     }
806     /* determine match criteria */
807     if (!zh->m_record_id)
808     {
809         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
810         zh->m_record_id = res_get (zh->res, ext_res);
811     }
812
813     if (!(recType =
814           recType_byName (zh->reg->recTypes, zh->res, zh->m_record_type,
815                           &recTypeClientData)))
816     {
817         yaz_log(YLOG_WARN, "No such record type: %s", zh->m_record_type);
818         return ZEBRA_FAIL;
819     }
820
821     switch(recType->version)
822     {
823     case 0:
824         break;
825     default:
826         yaz_log(YLOG_WARN, "Bad filter version: %s", zh->m_record_type);
827     }
828     if (sysno && deleteFlag)
829         fd = -1;
830     else
831     {
832         char full_rep[1024];
833
834         if (zh->path_reg && !yaz_is_abspath (fname))
835         {
836             strcpy (full_rep, zh->path_reg);
837             strcat (full_rep, "/");
838             strcat (full_rep, fname);
839         }
840         else
841             strcpy (full_rep, fname);
842         
843         if ((fd = open (full_rep, O_BINARY|O_RDONLY)) == -1)
844         {
845             yaz_log (YLOG_WARN|YLOG_ERRNO, "open %s", full_rep);
846             zh->m_record_type = original_record_type;
847             return ZEBRA_FAIL;
848         }
849     }
850     fi = file_read_start (fd);
851     while(1)
852     {
853         fi->file_moffset = fi->file_offset;
854         fi->file_more = 0;  /* file_end not called (yet) */
855         r = file_extract_record (zh, sysno, fname, deleteFlag, fi, 1,
856                                  recType, recTypeClientData);
857         if (fi->file_more)
858         {   /* file_end has been called so reset offset .. */
859             fi->file_offset = fi->file_moffset;
860             lseek(fi->fd, fi->file_moffset, SEEK_SET);
861         }
862         if (r != ZEBRA_OK)
863         {
864             break;
865         }
866         if (sysno)
867         {
868             break;
869         }
870     }
871     file_read_stop (fi);
872     if (fd != -1)
873         close (fd);
874     zh->m_record_type = original_record_type;
875     return r;
876 }
877
878 /*
879   If sysno is provided, then it's used to identify the reocord.
880   If not, and match_criteria is provided, then sysno is guessed
881   If not, and a record is provided, then sysno is got from there
882   
883  */
884 ZEBRA_RES buffer_extract_record(ZebraHandle zh, 
885                                 const char *buf, size_t buf_size,
886                                 int delete_flag,
887                                 int test_mode, 
888                                 const char *recordType,
889                                 SYSNO *sysno,
890                                 const char *match_criteria,
891                                 const char *fname,
892                                 int force_update,
893                                 int allow_update)
894 {
895     SYSNO sysno0 = 0;
896     RecordAttr *recordAttr;
897     struct recExtractCtrl extractCtrl;
898     int r;
899     const char *matchStr = 0;
900     RecType recType = NULL;
901     void *clientData;
902     Record rec;
903     long recordOffset = 0;
904     struct zebra_fetch_control fc;
905     const char *pr_fname = fname;  /* filename to print .. */
906     int show_progress = zh->records_processed < zh->m_file_verbose_limit ? 1:0;
907
908     if (!pr_fname)
909         pr_fname = "<no file>";  /* make it printable if file is omitted */
910
911     fc.fd = -1;
912     fc.record_int_buf = buf;
913     fc.record_int_len = buf_size;
914     fc.record_int_pos = 0;
915     fc.offset_end = 0;
916     fc.record_offset = 0;
917
918     extractCtrl.offset = 0;
919     extractCtrl.readf = zebra_record_int_read;
920     extractCtrl.seekf = zebra_record_int_seek;
921     extractCtrl.tellf = zebra_record_int_tell;
922     extractCtrl.endf = zebra_record_int_end;
923     extractCtrl.first_record = 1;
924     extractCtrl.fh = &fc;
925
926     zebra_rec_keys_reset(zh->reg->keys);
927
928 #if NATTR
929     zebra_rec_keys_reset(zh->reg->sortKeys);
930 #else
931     zh->reg->sortKeys.buf_used = 0;
932 #endif
933     if (zebraExplain_curDatabase (zh->reg->zei, zh->basenames[0]))
934     {
935         if (zebraExplain_newDatabase (zh->reg->zei, zh->basenames[0], 
936                                       zh->m_explain_database))
937             return ZEBRA_FAIL;
938     }
939     
940     if (recordType && *recordType)
941     {
942         yaz_log (YLOG_DEBUG, "Record type explicitly specified: %s", recordType);
943         recType = recType_byName (zh->reg->recTypes, zh->res, recordType,
944                                   &clientData);
945     } 
946     else
947     {
948         if (!(zh->m_record_type))
949         {
950             yaz_log (YLOG_WARN, "No such record type defined");
951             return ZEBRA_FAIL;
952         }
953         yaz_log (YLOG_DEBUG, "Get record type from rgroup: %s",zh->m_record_type);
954         recType = recType_byName (zh->reg->recTypes, zh->res,
955                                   zh->m_record_type, &clientData);
956         recordType = zh->m_record_type;
957     }
958     
959     if (!recType)
960     {
961         yaz_log (YLOG_WARN, "No such record type: %s", recordType);
962         return ZEBRA_FAIL;
963     }
964     
965     extractCtrl.init = extract_init;
966     extractCtrl.tokenAdd = extract_token_add;
967     extractCtrl.schemaAdd = extract_schema_add;
968     extractCtrl.dh = zh->reg->dh;
969     extractCtrl.handle = zh;
970     extractCtrl.match_criteria[0] = '\0';
971     extractCtrl.staticrank = 0;
972     
973     init_extractCtrl(zh, &extractCtrl);
974
975     extract_set_store_data_prepare(&extractCtrl);
976
977     r = (*recType->extract)(clientData, &extractCtrl);
978
979     if (r == RECCTRL_EXTRACT_EOF)
980         return ZEBRA_FAIL;
981     else if (r == RECCTRL_EXTRACT_ERROR_GENERIC)
982     {
983         /* error occured during extraction ... */
984         yaz_log (YLOG_WARN, "extract error: generic");
985         return ZEBRA_FAIL;
986     }
987     else if (r == RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER)
988     {
989         /* error occured during extraction ... */
990         yaz_log (YLOG_WARN, "extract error: no such filter");
991         return ZEBRA_FAIL;
992     }
993
994     if (extractCtrl.match_criteria[0])
995         match_criteria = extractCtrl.match_criteria;
996
997     if (!sysno) {
998
999         sysno = &sysno0;
1000
1001         if (match_criteria && *match_criteria) {
1002             matchStr = match_criteria;
1003         } else {
1004             if (zh->m_record_id && *zh->m_record_id) {
1005                 matchStr = fileMatchStr (zh, zh->reg->keys, pr_fname, 
1006                                          zh->m_record_id);
1007                 if (!matchStr)
1008                 {
1009                     yaz_log (YLOG_WARN, "Bad match criteria (recordID)");
1010                     return ZEBRA_FAIL;
1011                 }
1012             }
1013         }
1014         if (matchStr) 
1015         {
1016             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1017             char *rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord,
1018                                           matchStr);
1019             if (rinfo)
1020             {
1021                 assert(*rinfo == sizeof(*sysno));
1022                 memcpy (sysno, rinfo+1, sizeof(*sysno));
1023             }
1024         }
1025     }
1026     if (zebra_rec_keys_empty(zh->reg->keys))
1027     {
1028         /* the extraction process returned no information - the record
1029            is probably empty - unless flagShowRecords is in use */
1030         if (test_mode)
1031             return ZEBRA_OK;
1032     }
1033
1034     if (! *sysno)
1035     {
1036         /* new record */
1037         if (delete_flag)
1038         {
1039             yaz_log (YLOG_LOG, "delete %s %s %ld", recordType,
1040                          pr_fname, (long) recordOffset);
1041             yaz_log (YLOG_WARN, "cannot delete record above (seems new)");
1042             return ZEBRA_FAIL;
1043         }
1044         if (show_progress)
1045             yaz_log (YLOG_LOG, "add %s %s %ld", recordType, pr_fname,
1046                      (long) recordOffset);
1047         rec = rec_new (zh->reg->records);
1048
1049         *sysno = rec->sysno;
1050
1051         recordAttr = rec_init_attr (zh->reg->zei, rec);
1052         recordAttr->staticrank = extractCtrl.staticrank;
1053
1054         if (matchStr)
1055         {
1056             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1057             dict_insert_ord(zh->reg->matchDict, db_ord, matchStr,
1058                             sizeof(*sysno), sysno);
1059         }
1060
1061
1062 #if NATTR
1063         extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
1064 #else
1065         extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
1066 #endif
1067         
1068 #if 0
1069         print_rec_keys(zh, zh->reg->keys);
1070 #endif
1071         extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys,
1072                          recordAttr->staticrank);
1073         zh->records_inserted++;
1074     } 
1075     else
1076     {
1077         /* record already exists */
1078         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
1079 #if NATTR
1080         zebra_rec_keys_t sortKeys = zebra_rec_keys_open();
1081 #else
1082         struct sortKeys sortKeys;
1083 #endif
1084
1085         if (!allow_update)
1086         {
1087             yaz_log (YLOG_LOG, "skipped %s %s %ld", 
1088                          recordType, pr_fname, (long) recordOffset);
1089             logRecord(zh);
1090             return ZEBRA_FAIL;
1091         }
1092
1093         rec = rec_get (zh->reg->records, *sysno);
1094         assert (rec);
1095         
1096         recordAttr = rec_init_attr (zh->reg->zei, rec);
1097
1098         zebra_rec_keys_set_buf(delkeys,
1099                                rec->info[recInfo_delKeys],
1100                                rec->size[recInfo_delKeys],
1101                                0);
1102 #if NATTR
1103         zebra_rec_keys_set_buf(sortKeys,
1104                                rec->info[recInfo_sortKeys],
1105                                rec->size[recInfo_sortKeys],
1106                                0);
1107 #else
1108         sortKeys.buf_used = rec->size[recInfo_sortKeys];
1109         sortKeys.buf = rec->info[recInfo_sortKeys];
1110 #endif
1111
1112 #if NATTR
1113         extract_flushSortKeys (zh, *sysno, 0, sortKeys);
1114 #else
1115         extract_flushSortKeys (zh, *sysno, 0, &sortKeys);
1116 #endif
1117         extract_flushRecordKeys (zh, *sysno, 0, delkeys,
1118                                  recordAttr->staticrank);
1119         if (delete_flag)
1120         {
1121             /* record going to be deleted */
1122             if (zebra_rec_keys_empty(delkeys))
1123             {
1124                 yaz_log (YLOG_LOG, "delete %s %s %ld", recordType,
1125                      pr_fname, (long) recordOffset);
1126                 yaz_log (YLOG_WARN, "cannot delete file above, "
1127                              "storeKeys false (3)");
1128             }
1129             else
1130             {
1131                 if (show_progress)
1132                     yaz_log (YLOG_LOG, "delete %s %s %ld", recordType,
1133                              pr_fname, (long) recordOffset);
1134                 zh->records_deleted++;
1135                 if (matchStr)
1136                 {
1137                     int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1138                     dict_delete_ord(zh->reg->matchDict, db_ord, matchStr);
1139                 }
1140                 rec_del (zh->reg->records, &rec);
1141             }
1142             rec_rm (&rec);
1143             logRecord(zh);
1144             return ZEBRA_OK;
1145         }
1146         else
1147         {
1148             if (show_progress)
1149                     yaz_log (YLOG_LOG, "update %s %s %ld", recordType,
1150                              pr_fname, (long) recordOffset);
1151             recordAttr->staticrank = extractCtrl.staticrank;
1152 #if NATTR
1153             extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
1154 #else
1155             extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
1156 #endif
1157             extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys, 
1158                                          recordAttr->staticrank);
1159             zh->records_updated++;
1160         }
1161         zebra_rec_keys_close(delkeys);
1162 #if NATTR
1163         zebra_rec_keys_close(sortKeys);
1164 #endif
1165     }
1166     /* update file type */
1167     xfree (rec->info[recInfo_fileType]);
1168     rec->info[recInfo_fileType] =
1169         rec_strdup (recordType, &rec->size[recInfo_fileType]);
1170
1171     /* update filename */
1172     xfree (rec->info[recInfo_filename]);
1173     rec->info[recInfo_filename] =
1174         rec_strdup (fname, &rec->size[recInfo_filename]);
1175
1176     /* update delete keys */
1177     xfree (rec->info[recInfo_delKeys]);
1178     if (!zebra_rec_keys_empty(zh->reg->keys) && zh->m_store_keys == 1)
1179     {
1180         zebra_rec_keys_get_buf(zh->reg->keys,
1181                                &rec->info[recInfo_delKeys],
1182                                &rec->size[recInfo_delKeys]);
1183     }
1184     else
1185     {
1186         rec->info[recInfo_delKeys] = NULL;
1187         rec->size[recInfo_delKeys] = 0;
1188     }
1189     /* update sort keys */
1190     xfree (rec->info[recInfo_sortKeys]);
1191
1192 #if NATTR
1193     zebra_rec_keys_get_buf(zh->reg->sortKeys,
1194                            &rec->info[recInfo_sortKeys],
1195                            &rec->size[recInfo_sortKeys]);
1196 #else
1197     rec->size[recInfo_sortKeys] = zh->reg->sortKeys.buf_used;
1198     rec->info[recInfo_sortKeys] = zh->reg->sortKeys.buf;
1199     zh->reg->sortKeys.buf = NULL;
1200     zh->reg->sortKeys.buf_max = 0;
1201 #endif
1202
1203     /* save file size of original record */
1204     zebraExplain_recordBytesIncrement (zh->reg->zei,
1205                                        - recordAttr->recordSize);
1206 #if 0
1207     recordAttr->recordSize = fi->file_moffset - recordOffset;
1208     if (!recordAttr->recordSize)
1209         recordAttr->recordSize = fi->file_max - recordOffset;
1210 #else
1211     recordAttr->recordSize = buf_size;
1212 #endif
1213     zebraExplain_recordBytesIncrement (zh->reg->zei,
1214                                        recordAttr->recordSize);
1215
1216     /* set run-number for this record */
1217     recordAttr->runNumber =
1218         zebraExplain_runNumberIncrement (zh->reg->zei, 0);
1219
1220     /* update store data */
1221     xfree (rec->info[recInfo_storeData]);
1222
1223     /* update store data */
1224     if (zh->store_data_buf)
1225     {
1226         rec->size[recInfo_storeData] = zh->store_data_size;
1227         rec->info[recInfo_storeData] = zh->store_data_buf;
1228         zh->store_data_buf = 0;
1229     }
1230     else if (zh->m_store_data)
1231     {
1232         rec->size[recInfo_storeData] = recordAttr->recordSize;
1233         rec->info[recInfo_storeData] = (char *)
1234             xmalloc (recordAttr->recordSize);
1235         memcpy (rec->info[recInfo_storeData], buf, recordAttr->recordSize);
1236     }
1237     else
1238     {
1239         rec->info[recInfo_storeData] = NULL;
1240         rec->size[recInfo_storeData] = 0;
1241     }
1242     /* update database name */
1243     xfree (rec->info[recInfo_databaseName]);
1244     rec->info[recInfo_databaseName] =
1245         rec_strdup (zh->basenames[0], &rec->size[recInfo_databaseName]); 
1246
1247     /* update offset */
1248     recordAttr->recordOffset = recordOffset;
1249     
1250     /* commit this record */
1251     rec_put (zh->reg->records, &rec);
1252     logRecord(zh);
1253     return ZEBRA_OK;
1254 }
1255
1256 int explain_extract (void *handle, Record rec, data1_node *n)
1257 {
1258     ZebraHandle zh = (ZebraHandle) handle;
1259     struct recExtractCtrl extractCtrl;
1260
1261     if (zebraExplain_curDatabase (zh->reg->zei,
1262                                   rec->info[recInfo_databaseName]))
1263     {
1264         abort();
1265         if (zebraExplain_newDatabase (zh->reg->zei,
1266                                       rec->info[recInfo_databaseName], 0))
1267             abort ();
1268     }
1269
1270     zebra_rec_keys_reset(zh->reg->keys);
1271     
1272 #if NATTR
1273     zebra_rec_keys_reset(zh->reg->sortKeys);
1274 #else
1275     zh->reg->sortKeys.buf_used = 0;
1276 #endif
1277     extractCtrl.init = extract_init;
1278     extractCtrl.tokenAdd = extract_token_add;
1279     extractCtrl.schemaAdd = extract_schema_add;
1280     extractCtrl.dh = zh->reg->dh;
1281
1282     init_extractCtrl(zh, &extractCtrl);
1283
1284     extractCtrl.flagShowRecords = 0;
1285     extractCtrl.match_criteria[0] = '\0';
1286     extractCtrl.staticrank = 0;
1287     extractCtrl.handle = handle;
1288     extractCtrl.first_record = 1;
1289     
1290     extract_set_store_data_prepare(&extractCtrl);
1291
1292     if (n)
1293         grs_extract_tree(&extractCtrl, n);
1294
1295     if (rec->size[recInfo_delKeys])
1296     {
1297         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
1298         
1299 #if NATTR
1300         zebra_rec_keys_t sortkeys = zebra_rec_keys_open();
1301 #else
1302         struct sortKeys sortkeys;
1303 #endif
1304
1305         zebra_rec_keys_set_buf(delkeys, rec->info[recInfo_delKeys],
1306                                rec->size[recInfo_delKeys],
1307                                0);
1308         extract_flushRecordKeys (zh, rec->sysno, 0, delkeys, 0);
1309         zebra_rec_keys_close(delkeys);
1310 #if NATTR
1311         zebra_rec_keys_set_buf(sortkeys, rec->info[recInfo_sortKeys],
1312                                rec->size[recInfo_sortKeys],
1313                                0);
1314
1315         extract_flushSortKeys (zh, rec->sysno, 0, sortkeys);
1316         zebra_rec_keys_close(sortkeys);
1317 #else
1318         sortkeys.buf_used = rec->size[recInfo_sortKeys];
1319         sortkeys.buf = rec->info[recInfo_sortKeys];
1320         extract_flushSortKeys (zh, rec->sysno, 0, &sortkeys);
1321 #endif
1322     }
1323     extract_flushRecordKeys (zh, rec->sysno, 1, zh->reg->keys, 0);
1324 #if NATTR
1325     extract_flushSortKeys (zh, rec->sysno, 1, zh->reg->sortKeys);
1326 #else
1327     extract_flushSortKeys (zh, rec->sysno, 1, &zh->reg->sortKeys);
1328 #endif
1329
1330     xfree (rec->info[recInfo_delKeys]);
1331     zebra_rec_keys_get_buf(zh->reg->keys,
1332                            &rec->info[recInfo_delKeys], 
1333                            &rec->size[recInfo_delKeys]);
1334
1335     xfree (rec->info[recInfo_sortKeys]);
1336 #if NATTR
1337     zebra_rec_keys_get_buf(zh->reg->sortKeys,
1338                            &rec->info[recInfo_sortKeys],
1339                            &rec->size[recInfo_sortKeys]);
1340 #else
1341     rec->size[recInfo_sortKeys] = zh->reg->sortKeys.buf_used;
1342     rec->info[recInfo_sortKeys] = zh->reg->sortKeys.buf;
1343     zh->reg->sortKeys.buf = NULL;
1344     zh->reg->sortKeys.buf_max = 0;
1345 #endif
1346
1347     return 0;
1348 }
1349
1350 void extract_rec_keys_adjust(ZebraHandle zh, int is_insert,
1351                              zebra_rec_keys_t reckeys)
1352 {
1353     ZebraExplainInfo zei = zh->reg->zei;
1354     struct ord_stat {
1355         int no;
1356         int ord;
1357         struct ord_stat *next;
1358     };
1359
1360     if (zebra_rec_keys_rewind(reckeys))
1361     {
1362         struct ord_stat *ord_list = 0;
1363         struct ord_stat *p;
1364         size_t slen;
1365         const char *str;
1366         struct it_key key_in;
1367         while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1368         {
1369             int ord = key_in.mem[0]; 
1370
1371             for (p = ord_list; p ; p = p->next)
1372                 if (p->ord == ord)
1373                 {
1374                     p->no++;
1375                     break;
1376                 }
1377             if (!p)
1378             {
1379                 p = xmalloc(sizeof(*p));
1380                 p->no = 1;
1381                 p->ord = ord;
1382                 p->next = ord_list;
1383                 ord_list = p;
1384             }
1385         }
1386
1387         p = ord_list;
1388         while (p)
1389         {
1390             struct ord_stat *p1 = p;
1391
1392             if (is_insert)
1393                 zebraExplain_ord_adjust_occurrences(zei, p->ord, p->no, 1);
1394             else
1395                 zebraExplain_ord_adjust_occurrences(zei, p->ord, - p->no, -1);
1396             p = p->next;
1397             xfree(p1);
1398         }
1399     }
1400 }
1401
1402 void extract_flushRecordKeys (ZebraHandle zh, SYSNO sysno,
1403                               int cmd,
1404                               zebra_rec_keys_t reckeys,
1405                               zint staticrank)
1406 {
1407     ZebraExplainInfo zei = zh->reg->zei;
1408
1409     extract_rec_keys_adjust(zh, cmd, reckeys);
1410
1411     if (!zh->reg->key_buf)
1412     {
1413         int mem= 1024*1024* atoi( res_get_def( zh->res, "memmax", "8"));
1414         if (mem <= 0)
1415         {
1416             yaz_log(YLOG_WARN, "Invalid memory setting, using default 8 MB");
1417             mem= 1024*1024*8;
1418         }
1419         /* FIXME: That "8" should be in a default settings include */
1420         /* not hard-coded here! -H */
1421         zh->reg->key_buf = (char**) xmalloc (mem);
1422         zh->reg->ptr_top = mem/sizeof(char*);
1423         zh->reg->ptr_i = 0;
1424         zh->reg->key_buf_used = 0;
1425         zh->reg->key_file_no = 0;
1426     }
1427     zebraExplain_recordCountIncrement (zei, cmd ? 1 : -1);
1428
1429     if (zebra_rec_keys_rewind(reckeys))
1430     {
1431         size_t slen;
1432         const char *str;
1433         struct it_key key_in;
1434         while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1435         {
1436             int ch = 0;
1437             struct it_key key_out;
1438             zint *keyp = key_out.mem;
1439
1440             assert(key_in.len == 4);
1441             
1442             /* check for buffer overflow */
1443             if (zh->reg->key_buf_used + 1024 > 
1444                 (zh->reg->ptr_top -zh->reg->ptr_i)*sizeof(char*))
1445                 extract_flushWriteKeys (zh, 0);
1446             
1447             ++(zh->reg->ptr_i);
1448             assert(zh->reg->ptr_i > 0);
1449             (zh->reg->key_buf)[zh->reg->ptr_top - zh->reg->ptr_i] =
1450                 (char*)zh->reg->key_buf + zh->reg->key_buf_used;
1451
1452             /* encode the ordinal value (field/use/attribute) .. */
1453             ch = (int) key_in.mem[0];
1454             zh->reg->key_buf_used +=
1455                 key_SU_encode(ch, (char*)zh->reg->key_buf +
1456                               zh->reg->key_buf_used);
1457
1458             /* copy the 0-terminated stuff from str to output */
1459             memcpy((char*)zh->reg->key_buf + zh->reg->key_buf_used, str, slen);
1460             zh->reg->key_buf_used += slen;
1461             ((char*)zh->reg->key_buf)[(zh->reg->key_buf_used)++] = '\0';
1462
1463             /* the delete/insert indicator */
1464             ((char*)zh->reg->key_buf)[(zh->reg->key_buf_used)++] = cmd;
1465
1466             if (zh->m_staticrank) /* rank config enabled ? */
1467             {
1468                 if (staticrank < 0)
1469                 {
1470                     yaz_log(YLOG_WARN, "staticrank = %ld. Setting to 0",
1471                             (long) staticrank);
1472                     staticrank = 0;
1473                 }
1474                 *keyp++ = staticrank;
1475                 key_out.len = 4;
1476             }
1477             else
1478                 key_out.len = 3;
1479             
1480             if (key_in.mem[1]) /* filter specified record ID */
1481                 *keyp++ = key_in.mem[1];
1482             else
1483                 *keyp++ = sysno;
1484             *keyp++ = key_in.mem[2];  /* section_id */
1485             *keyp++ = key_in.mem[3];  /* sequence .. */
1486             
1487             memcpy((char*)zh->reg->key_buf + zh->reg->key_buf_used,
1488                    &key_out, sizeof(key_out));
1489             (zh->reg->key_buf_used) += sizeof(key_out);
1490         }
1491     }
1492 }
1493
1494 void extract_flushWriteKeys (ZebraHandle zh, int final)
1495         /* optimizing: if final=1, and no files written yet */
1496         /* push the keys directly to merge, sidestepping the */
1497         /* temp file altogether. Speeds small updates */
1498 {
1499     FILE *outf;
1500     char out_fname[200];
1501     char *prevcp, *cp;
1502     struct encode_info encode_info;
1503     int ptr_i = zh->reg->ptr_i;
1504     int temp_policy;
1505 #if SORT_EXTRA
1506     int i;
1507 #endif
1508     if (!zh->reg->key_buf || ptr_i <= 0)
1509     {
1510         yaz_log (YLOG_DEBUG, "  nothing to flush section=%d buf=%p i=%d",
1511                zh->reg->key_file_no, zh->reg->key_buf, ptr_i);
1512         yaz_log (YLOG_DEBUG, "  buf=%p ",
1513                zh->reg->key_buf);
1514         yaz_log (YLOG_DEBUG, "  ptr=%d ",zh->reg->ptr_i);
1515         yaz_log (YLOG_DEBUG, "  reg=%p ",zh->reg);
1516                
1517         return;
1518     }
1519
1520     (zh->reg->key_file_no)++;
1521     yaz_log (YLOG_LOG, "sorting section %d", (zh->reg->key_file_no));
1522     yaz_log (YLOG_DEBUG, "  sort_buff at %p n=%d",
1523                     zh->reg->key_buf + zh->reg->ptr_top - ptr_i,ptr_i);
1524 #if !SORT_EXTRA
1525     qsort (zh->reg->key_buf + zh->reg->ptr_top - ptr_i, ptr_i,
1526                sizeof(char*), key_qsort_compare);
1527
1528     /* zebra.cfg: tempfiles:  
1529        Y: always use temp files (old way) 
1530        A: use temp files, if more than one (auto) 
1531           = if this is both the last and the first 
1532        N: never bother with temp files (new) */
1533
1534     temp_policy=toupper(res_get_def(zh->res,"tempfiles","auto")[0]);
1535     if (temp_policy != 'Y' && temp_policy != 'N' && temp_policy != 'A') {
1536         yaz_log (YLOG_WARN, "Illegal tempfiles setting '%c'. using 'Auto' ", 
1537                         temp_policy);
1538         temp_policy='A';
1539     }
1540
1541     if (   ( temp_policy =='N' )   ||     /* always from memory */
1542          ( ( temp_policy =='A' ) &&       /* automatic */
1543              (zh->reg->key_file_no == 1) &&  /* this is first time */
1544              (final) ) )                     /* and last (=only) time */
1545     { /* go directly from memory */
1546         zh->reg->key_file_no =0; /* signal not to read files */
1547         zebra_index_merge(zh); 
1548         zh->reg->ptr_i = 0;
1549         zh->reg->key_buf_used = 0; 
1550         return; 
1551     }
1552
1553     /* Not doing directly from memory, write into a temp file */
1554     extract_get_fname_tmp (zh, out_fname, zh->reg->key_file_no);
1555
1556     if (!(outf = fopen (out_fname, "wb")))
1557     {
1558         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fopen %s", out_fname);
1559         exit (1);
1560     }
1561     yaz_log (YLOG_LOG, "writing section %d", zh->reg->key_file_no);
1562     prevcp = cp = (zh->reg->key_buf)[zh->reg->ptr_top - ptr_i];
1563     
1564     encode_key_init (&encode_info);
1565     encode_key_write (cp, &encode_info, outf);
1566     
1567     while (--ptr_i > 0)
1568     {
1569         cp = (zh->reg->key_buf)[zh->reg->ptr_top - ptr_i];
1570         if (strcmp (cp, prevcp))
1571         {
1572             encode_key_flush ( &encode_info, outf);
1573             encode_key_init (&encode_info);
1574             encode_key_write (cp, &encode_info, outf);
1575             prevcp = cp;
1576         }
1577         else
1578             encode_key_write (cp + strlen(cp), &encode_info, outf);
1579     }
1580     encode_key_flush ( &encode_info, outf);
1581 #else
1582     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_x_compare);
1583     extract_get_fname_tmp (out_fname, key_file_no);
1584
1585     if (!(outf = fopen (out_fname, "wb")))
1586     {
1587         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fopen %s", out_fname);
1588         exit (1);
1589     }
1590     yaz_log (YLOG_LOG, "writing section %d", key_file_no);
1591     i = ptr_i;
1592     prevcp =  key_buf[ptr_top-i];
1593     while (1)
1594         if (!--i || strcmp (prevcp, key_buf[ptr_top-i]))
1595         {
1596             key_y_len = strlen(prevcp)+1;
1597 #if 0
1598             yaz_log (YLOG_LOG, "key_y_len: %2d %02x %02x %s",
1599                       key_y_len, prevcp[0], prevcp[1], 2+prevcp);
1600 #endif
1601             qsort (key_buf + ptr_top-ptr_i, ptr_i - i,
1602                                    sizeof(char*), key_y_compare);
1603             cp = key_buf[ptr_top-ptr_i];
1604             --key_y_len;
1605             encode_key_init (&encode_info);
1606             encode_key_write (cp, &encode_info, outf);
1607             while (--ptr_i > i)
1608             {
1609                 cp = key_buf[ptr_top-ptr_i];
1610                 encode_key_write (cp+key_y_len, &encode_info, outf);
1611             }
1612             encode_key_flush ( &encode_info, outf);
1613             if (!i)
1614                 break;
1615             prevcp = key_buf[ptr_top-ptr_i];
1616         }
1617 #endif
1618     if (fclose (outf))
1619     {
1620         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fclose %s", out_fname);
1621         exit (1);
1622     }
1623     yaz_log (YLOG_LOG, "finished section %d", zh->reg->key_file_no);
1624     zh->reg->ptr_i = 0;
1625     zh->reg->key_buf_used = 0;
1626 }
1627
1628 ZEBRA_RES zebra_snippets_rec_keys(ZebraHandle zh,
1629                                   zebra_rec_keys_t reckeys,
1630                                   zebra_snippets *snippets)
1631 {
1632     NMEM nmem = nmem_create();
1633     if (zebra_rec_keys_rewind(reckeys)) 
1634     {
1635         const char *str;
1636         size_t slen;
1637         struct it_key key;
1638         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1639         {
1640             char dst_buf[IT_MAX_WORD];
1641             char *dst_term = dst_buf;
1642             int ord, seqno;
1643             int index_type;
1644             assert(key.len <= 4 && key.len > 2);
1645             seqno = (int) key.mem[key.len-1];
1646             ord = key.mem[0];
1647             
1648             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type,
1649                                     0/* db */, 0/* set */, 0/* use */,
1650                                     0 /* string_index */);
1651             assert(index_type);
1652             zebra_term_untrans_iconv(zh, nmem, index_type,
1653                                      &dst_term, str);
1654             zebra_snippets_append(snippets, seqno, ord, dst_term);
1655             nmem_reset(nmem);
1656         }
1657     }
1658     nmem_destroy(nmem);
1659     return ZEBRA_OK;
1660 }
1661
1662 void print_rec_keys(ZebraHandle zh, zebra_rec_keys_t reckeys)
1663 {
1664     yaz_log(YLOG_LOG, "print_rec_keys");
1665     if (zebra_rec_keys_rewind(reckeys))
1666     {
1667         const char *str;
1668         size_t slen;
1669         struct it_key key;
1670         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1671         {
1672             char dst_buf[IT_MAX_WORD];
1673             int seqno;
1674             int index_type;
1675             const char *db = 0;
1676             assert(key.len <= 4 && key.len > 2);
1677
1678             zebraExplain_lookup_ord(zh->reg->zei,
1679                                     key.mem[0], &index_type, &db, 0, 0, 0);
1680             
1681             seqno = (int) key.mem[key.len-1];
1682             
1683             zebra_term_untrans(zh, index_type, dst_buf, str);
1684             
1685             yaz_log(YLOG_LOG, "ord=" ZINT_FORMAT " seqno=%d term=%s",
1686                     key.mem[0], seqno, dst_buf); 
1687         }
1688     }
1689 }
1690
1691 void extract_add_index_string (RecWord *p, const char *str, int length)
1692 {
1693     struct it_key key;
1694
1695     ZebraHandle zh = p->extractCtrl->handle;
1696     ZebraExplainInfo zei = zh->reg->zei;
1697     int ch;
1698
1699     if (p->index_name)
1700     {
1701         ch = zebraExplain_lookup_attr_str(zei, p->index_type, p->index_name);
1702         if (ch < 0)
1703             ch = zebraExplain_add_attr_str(zei, p->index_type, p->index_name);
1704     }
1705     else
1706     {
1707 #if NATTR
1708         return;
1709 #else
1710         ch = zebraExplain_lookup_attr_su(zei, p->index_type, 
1711                                          p->attrSet, p->attrUse);
1712         if (ch < 0)
1713             ch = zebraExplain_add_attr_su(zei, p->index_type,
1714                                           p->attrSet, p->attrUse);
1715 #endif
1716     }
1717     key.len = 4;
1718     key.mem[0] = ch;
1719     key.mem[1] = p->record_id;
1720     key.mem[2] = p->section_id;
1721     key.mem[3] = p->seqno;
1722
1723 #if 0
1724     if (1)
1725     {
1726         char strz[80];
1727         int i;
1728
1729         strz[0] = 0;
1730         for (i = 0; i<length && i < 20; i++)
1731             sprintf(strz+strlen(strz), "%02X", str[i] & 0xff);
1732         /* just for debugging .. */
1733         yaz_log(YLOG_LOG, "add: set=%d use=%d "
1734                 "record_id=%lld section_id=%lld seqno=%lld %s",
1735                 p->attrSet, p->attrUse, p->record_id, p->section_id, p->seqno,
1736                 strz);
1737     }
1738 #endif
1739
1740     zebra_rec_keys_write(zh->reg->keys, str, length, &key);
1741 }
1742
1743 #if NATTR
1744 static void extract_add_sort_string (RecWord *p, const char *str, int length)
1745 {
1746     struct it_key key;
1747
1748     ZebraHandle zh = p->extractCtrl->handle;
1749     ZebraExplainInfo zei = zh->reg->zei;
1750     int ch;
1751
1752     if (p->index_name)
1753     {
1754         ch = zebraExplain_lookup_attr_str(zei, p->index_type, p->index_name);
1755         if (ch < 0)
1756             ch = zebraExplain_add_attr_str(zei, p->index_type, p->index_name);
1757     }
1758     else
1759     {
1760         return;
1761     }
1762     key.len = 4;
1763     key.mem[0] = ch;
1764     key.mem[1] = p->record_id;
1765     key.mem[2] = p->section_id;
1766     key.mem[3] = p->seqno;
1767
1768     zebra_rec_keys_write(zh->reg->sortKeys, str, length, &key);
1769 }
1770 #else
1771 static void extract_add_sort_string (RecWord *p, const char *str, int length)
1772 {
1773     ZebraHandle zh = p->extractCtrl->handle;
1774     struct sortKeys *sk = &zh->reg->sortKeys;
1775     int off = 0;
1776
1777     while (off < sk->buf_used)
1778     {
1779         int set, use, slen;
1780
1781         off += key_SU_decode(&set, (unsigned char *) sk->buf + off);
1782         off += key_SU_decode(&use, (unsigned char *) sk->buf + off);
1783         off += key_SU_decode(&slen, (unsigned char *) sk->buf + off);
1784         off += slen;
1785         if (p->attrSet == set && p->attrUse == use)
1786             return;
1787     }
1788     assert (off == sk->buf_used);
1789     
1790     if (sk->buf_used + IT_MAX_WORD > sk->buf_max)
1791     {
1792         char *b;
1793         
1794         b = (char *) xmalloc (sk->buf_max += 128000);
1795         if (sk->buf_used > 0)
1796             memcpy (b, sk->buf, sk->buf_used);
1797         xfree (sk->buf);
1798         sk->buf = b;
1799     }
1800     off += key_SU_encode(p->attrSet, sk->buf + off);
1801     off += key_SU_encode(p->attrUse, sk->buf + off);
1802     off += key_SU_encode(length, sk->buf + off);
1803     memcpy (sk->buf + off, str, length);
1804     sk->buf_used = off + length;
1805 }
1806 #endif
1807
1808 void extract_add_string (RecWord *p, const char *string, int length)
1809 {
1810     assert (length > 0);
1811     if (zebra_maps_is_sort (p->zebra_maps, p->index_type))
1812         extract_add_sort_string (p, string, length);
1813     else
1814         extract_add_index_string (p, string, length);
1815 }
1816
1817 static void extract_add_incomplete_field (RecWord *p)
1818 {
1819     const char *b = p->term_buf;
1820     int remain = p->term_len;
1821     const char **map = 0;
1822     
1823     yaz_log(YLOG_DEBUG, "Incomplete field, w='%.*s'", p->term_len, p->term_buf);
1824
1825     if (remain > 0)
1826         map = zebra_maps_input(p->zebra_maps, p->index_type, &b, remain, 0);
1827
1828     while (map)
1829     {
1830         char buf[IT_MAX_WORD+1];
1831         int i, remain;
1832
1833         /* Skip spaces */
1834         while (map && *map && **map == *CHR_SPACE)
1835         {
1836             remain = p->term_len - (b - p->term_buf);
1837             if (remain > 0)
1838                 map = zebra_maps_input(p->zebra_maps, p->index_type, &b,
1839                                        remain, 0);
1840             else
1841                 map = 0;
1842         }
1843         if (!map)
1844             break;
1845         i = 0;
1846         while (map && *map && **map != *CHR_SPACE)
1847         {
1848             const char *cp = *map;
1849
1850             while (i < IT_MAX_WORD && *cp)
1851                 buf[i++] = *(cp++);
1852             remain = p->term_len - (b - p->term_buf);
1853             if (remain > 0)
1854                 map = zebra_maps_input(p->zebra_maps, p->index_type, &b, remain, 0);
1855             else
1856                 map = 0;
1857         }
1858         if (!i)
1859             return;
1860         extract_add_string (p, buf, i);
1861         p->seqno++;
1862     }
1863 }
1864
1865 static void extract_add_complete_field (RecWord *p)
1866 {
1867     const char *b = p->term_buf;
1868     char buf[IT_MAX_WORD+1];
1869     const char **map = 0;
1870     int i = 0, remain = p->term_len;
1871
1872     yaz_log(YLOG_DEBUG, "Complete field, w='%.*s'",
1873             p->term_len, p->term_buf);
1874
1875     if (remain > 0)
1876         map = zebra_maps_input (p->zebra_maps, p->index_type, &b, remain, 1);
1877
1878     while (remain > 0 && i < IT_MAX_WORD)
1879     {
1880         while (map && *map && **map == *CHR_SPACE)
1881         {
1882             remain = p->term_len - (b - p->term_buf);
1883
1884             if (remain > 0)
1885             {
1886                 int first = i ? 0 : 1;  /* first position */
1887                 map = zebra_maps_input(p->zebra_maps, p->index_type, &b, remain, first);
1888             }
1889             else
1890                 map = 0;
1891         }
1892         if (!map)
1893             break;
1894
1895         if (i && i < IT_MAX_WORD)
1896             buf[i++] = *CHR_SPACE;
1897         while (map && *map && **map != *CHR_SPACE)
1898         {
1899             const char *cp = *map;
1900
1901             if (**map == *CHR_CUT)
1902             {
1903                 i = 0;
1904             }
1905             else
1906             {
1907                 if (i >= IT_MAX_WORD)
1908                     break;
1909                 yaz_log(YLOG_DEBUG, "Adding string to index '%d'", **map);
1910                 while (i < IT_MAX_WORD && *cp)
1911                     buf[i++] = *(cp++);
1912             }
1913             remain = p->term_len  - (b - p->term_buf);
1914             if (remain > 0)
1915             {
1916                 map = zebra_maps_input (p->zebra_maps, p->index_type, &b,
1917                                         remain, 0);
1918             }
1919             else
1920                 map = 0;
1921         }
1922     }
1923     if (!i)
1924         return;
1925     extract_add_string (p, buf, i);
1926 }
1927
1928 void extract_token_add (RecWord *p)
1929 {
1930     WRBUF wrbuf;
1931 #if 0
1932     yaz_log (YLOG_LOG, "token_add "
1933              "reg_type=%c attrSet=%d attrUse=%d seqno=%d s=%.*s",
1934              p->reg_type, p->attrSet, p->attrUse, p->seqno, p->length,
1935              p->string);
1936 #endif
1937     if ((wrbuf = zebra_replace(p->zebra_maps, p->index_type, 0,
1938                                p->term_buf, p->term_len)))
1939     {
1940         p->term_buf = wrbuf_buf(wrbuf);
1941         p->term_len = wrbuf_len(wrbuf);
1942     }
1943     if (zebra_maps_is_complete (p->zebra_maps, p->index_type))
1944         extract_add_complete_field (p);
1945     else
1946         extract_add_incomplete_field(p);
1947 }
1948
1949 static void extract_set_store_data_cb(struct recExtractCtrl *p,
1950                                       void *buf, size_t sz)
1951 {
1952     ZebraHandle zh = (ZebraHandle) p->handle;
1953
1954     xfree(zh->store_data_buf);
1955     zh->store_data_buf = 0;
1956     zh->store_data_size = 0;
1957     if (buf && sz)
1958     {
1959         zh->store_data_buf = xmalloc(sz);
1960         zh->store_data_size = sz;
1961         memcpy(zh->store_data_buf, buf, sz);
1962     }
1963 }
1964
1965 static void extract_set_store_data_prepare(struct recExtractCtrl *p)
1966 {
1967     ZebraHandle zh = (ZebraHandle) p->handle;
1968     xfree(zh->store_data_buf);
1969     zh->store_data_buf = 0;
1970     zh->store_data_size = 0;
1971     p->setStoreData = extract_set_store_data_cb;
1972 }
1973
1974 void extract_schema_add (struct recExtractCtrl *p, Odr_oid *oid)
1975 {
1976     ZebraHandle zh = (ZebraHandle) p->handle;
1977     zebraExplain_addSchema (zh->reg->zei, oid);
1978 }
1979
1980 #if NATTR
1981 #error not done yet with zebra_rec_keys_t
1982 void extract_flushSortKeys (ZebraHandle zh, SYSNO sysno,
1983                             int cmd, struct recKeys *reckeys)
1984 {
1985     SortIdx sortIdx = zh->reg->sortIdx;
1986     void *decode_handle = iscz1_start();
1987     int off = 0;
1988     int ch = 0;
1989
1990     while (off < reckeys->buf_used)
1991     {
1992         const char *src = reckeys->buf + off;
1993         struct it_key key;
1994         char *dst = (char*) &key;
1995
1996         iscz1_decode(decode_handle, &dst, &src);
1997         assert(key.len == 4);
1998
1999         ch = (int) key.mem[0];  /* ordinal for field/use/attribute */
2000
2001         sortIdx_type(sortIdx, ch);
2002         if (cmd == 1)
2003             sortIdx_add(sortIdx, src, strlen(src));
2004         else
2005             sortIdx_add(sortIdx, "", 1);
2006         
2007         src += strlen(src);
2008         src++;
2009
2010         off = src - reckeys->buf;
2011     }
2012     assert (off == reckeys->buf_used);
2013     iscz1_stop(decode_handle);
2014 }
2015 #else
2016 void extract_flushSortKeys (ZebraHandle zh, SYSNO sysno,
2017                             int cmd, struct sortKeys *sk)
2018 {
2019     SortIdx sortIdx = zh->reg->sortIdx;
2020     int off = 0;
2021
2022     sortIdx_sysno (sortIdx, sysno);
2023
2024     while (off < sk->buf_used)
2025     {
2026         int set, use, slen;
2027         
2028         off += key_SU_decode(&set, (unsigned char *) sk->buf + off);
2029         off += key_SU_decode(&use, (unsigned char *) sk->buf + off);
2030         off += key_SU_decode(&slen, (unsigned char *) sk->buf + off);
2031         
2032         sortIdx_type(sortIdx, use);
2033         if (cmd == 1)
2034             sortIdx_add(sortIdx, sk->buf + off, slen);
2035         else
2036             sortIdx_add(sortIdx, "", 1);
2037         off += slen;
2038     }
2039 }
2040 #endif
2041
2042 void encode_key_init (struct encode_info *i)
2043 {
2044     i->sysno = 0;
2045     i->seqno = 0;
2046     i->cmd = -1;
2047     i->prevsys=0;
2048     i->prevseq=0;
2049     i->prevcmd=-1;
2050     i->keylen=0;
2051     i->encode_handle = iscz1_start();
2052     i->decode_handle = iscz1_start();
2053 }
2054
2055 #define OLDENCODE 1
2056
2057 #ifdef OLDENCODE
2058 /* this is the old encode_key_write 
2059  * may be deleted once we are confident that the new works
2060  * HL 15-oct-2002
2061  */
2062 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
2063 {
2064     struct it_key key;
2065     char *bp = i->buf, *bp0;
2066     const char *src = (char *) &key;
2067
2068     /* copy term to output buf */
2069     while ((*bp++ = *k++))
2070         ;
2071     /* and copy & align key so we can mangle */
2072     memcpy (&key, k+1, sizeof(struct it_key));  /* *k is insert/delete */
2073
2074 #if 0
2075     /* debugging */
2076     key_logdump_txt(YLOG_LOG, &key, *k ? "i" : "d");
2077 #endif
2078     assert(key.mem[0] >= 0);
2079
2080     bp0 = bp++;
2081     iscz1_encode(i->encode_handle, &bp, &src);
2082
2083     *bp0 = (*k * 128) + bp - bp0 - 1; /* length and insert/delete combined */
2084     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
2085     {
2086         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fwrite");
2087         exit (1);
2088     }
2089
2090 #if 0
2091     /* debugging */
2092     if (1)
2093     {
2094         struct it_key key2;
2095         const char *src = bp0+1;
2096         char *dst = (char*) &key2;
2097         iscz1_decode(i->decode_handle, &dst, &src);
2098
2099         key_logdump_txt(YLOG_LOG, &key2, *k ? "i" : "d");
2100
2101         assert(key2.mem[1]);
2102     }
2103 #endif
2104 }
2105
2106 void encode_key_flush (struct encode_info *i, FILE *outf)
2107
2108     iscz1_stop(i->encode_handle);
2109     iscz1_stop(i->decode_handle);
2110 }
2111
2112 #else
2113
2114 /* new encode_key_write
2115  * The idea is to buffer one more key, and compare them
2116  * If we are going to delete and insert the same key, 
2117  * we may as well not bother. Should make a difference in 
2118  * updates with small modifications (appending to a mbox)
2119  */
2120 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
2121 {
2122     struct it_key key;
2123     char *bp; 
2124
2125     if (*k)  /* first time for new key */
2126     {
2127         bp = i->buf;
2128         while ((*bp++ = *k++))
2129             ;
2130         i->keylen= bp - i->buf -1;    
2131         assert(i->keylen+1+sizeof(struct it_key) < ENCODE_BUFLEN);
2132     }
2133     else
2134     {
2135         bp=i->buf + i->keylen;
2136         *bp++=0;
2137         k++;
2138     }
2139
2140     memcpy (&key, k+1, sizeof(struct it_key));
2141     if (0==i->prevsys) /* no previous filter, fill up */
2142     {
2143         i->prevsys=key.sysno;
2144         i->prevseq=key.seqno;
2145         i->prevcmd=*k;
2146     }
2147     else if ( (i->prevsys==key.sysno) &&
2148               (i->prevseq==key.seqno) &&
2149               (i->prevcmd!=*k) )
2150     { /* same numbers, diff cmd, they cancel out */
2151         i->prevsys=0;
2152     }
2153     else 
2154     { /* different stuff, write previous, move buf */
2155         bp = encode_key_int ( (i->prevsys - i->sysno) * 2 + i->prevcmd, bp);
2156         if (i->sysno != i->prevsys)
2157         {
2158             i->sysno = i->prevsys;
2159             i->seqno = 0;
2160         }
2161         else if (!i->seqno && !i->prevseq && i->cmd == i->prevcmd)
2162         {
2163             return; /* ??? Filters some sort of duplicates away */
2164                     /* ??? Can this ever happen   -H 15oct02 */
2165         }
2166         bp = encode_key_int (i->prevseq - i->seqno, bp);
2167         i->seqno = i->prevseq;
2168         i->cmd = i->prevcmd;
2169         if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
2170         {
2171             yaz_log (YLOG_FATAL|YLOG_ERRNO, "fwrite");
2172             exit (1);
2173         }
2174         i->keylen=0; /* ok, it's written, forget it */
2175         i->prevsys=key.sysno;
2176         i->prevseq=key.seqno;
2177         i->prevcmd=*k;
2178     }
2179 }
2180
2181 void encode_key_flush (struct encode_info *i, FILE *outf)
2182 { /* flush the last key from i */
2183     char *bp =i->buf + i->keylen;
2184     if (0==i->prevsys)
2185     {
2186         return; /* nothing to flush */
2187     }
2188     *bp++=0;
2189     bp = encode_key_int ( (i->prevsys - i->sysno) * 2 + i->prevcmd, bp);
2190     if (i->sysno != i->prevsys)
2191     {
2192         i->sysno = i->prevsys;
2193         i->seqno = 0;
2194     }
2195     else if (!i->seqno && !i->prevseq && i->cmd == i->prevcmd)
2196     {
2197         return; /* ??? Filters some sort of duplicates away */
2198                 /* ??? Can this ever happen   -H 15oct02 */
2199     }
2200     bp = encode_key_int (i->prevseq - i->seqno, bp);
2201     i->seqno = i->prevseq;
2202     i->cmd = i->prevcmd;
2203     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
2204     {
2205         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fwrite");
2206         exit (1);
2207     }
2208     i->keylen=0; /* ok, it's written, forget it */
2209     i->prevsys=0; /* forget the values too */
2210     i->prevseq=0;
2211 }
2212 #endif
2213 /*
2214  * Local variables:
2215  * c-basic-offset: 4
2216  * indent-tabs-mode: nil
2217  * End:
2218  * vim: shiftwidth=4 tabstop=8 expandtab
2219  */
2220