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