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