Added code which maintains number of term occurrences and document
[idzebra-moved-to-github.git] / index / extract.c
1 /* $Id: extract.c,v 1.210 2006-05-10 12:31:08 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 #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 ZEBRA_RES 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 ZEBRA_FAIL;
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 ZEBRA_FAIL;
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 ZEBRA_FAIL;
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 ZEBRA_FAIL;
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 ZEBRA_FAIL;
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 ZEBRA_OK;
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 ZEBRA_OK;
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 ZEBRA_OK;
528         }
529
530         rec = rec_new (zh->reg->records);
531         
532         *sysno = rec->sysno;
533         
534         if (zh->records_processed < zh->m_file_verbose_limit)
535         {
536             if (matchStr)
537                 yaz_log(YLOG_LOG, "add %s %s " PRINTF_OFF_T 
538                         " " ZINT_FORMAT " %s" ,
539                         zh->m_record_type,
540                         fname, recordOffset, *sysno, matchStr);
541             else
542                 yaz_log(YLOG_LOG, "add %s %s " PRINTF_OFF_T 
543                         " " ZINT_FORMAT , 
544                         zh->m_record_type,
545                         fname, recordOffset, *sysno);
546         }
547         recordAttr = rec_init_attr (zh->reg->zei, rec);
548         recordAttr->staticrank = extractCtrl.staticrank;
549
550         if (matchStr)
551         {
552             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
553             dict_insert_ord(zh->reg->matchDict, db_ord, matchStr,
554                             sizeof(*sysno), sysno);
555         }
556
557
558 #if NATTR
559         extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
560 #else
561         extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
562 #endif
563         extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys,
564                                  recordAttr->staticrank);
565         zh->records_inserted++;
566     }
567     else
568     {
569         /* record already exists */
570         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
571
572 #if NATTR
573         zebra_rec_keys_t sortKeys = zebra_rec_keys_open();
574 #else
575         struct sortKeys sortKeys;
576 #endif
577
578         rec = rec_get (zh->reg->records, *sysno);
579         assert (rec);
580         
581         recordAttr = rec_init_attr (zh->reg->zei, rec);
582
583         zebra_rec_keys_set_buf(delkeys,
584                                rec->info[recInfo_delKeys],
585                                rec->size[recInfo_delKeys],
586                                0);
587
588 #if NATTR
589         zebra_rec_keys_set_buf(sortKeys,
590                                rec->info[recInfo_sortKeys],
591                                rec->size[recInfo_sortKeys],
592                                0);
593         extract_flushSortKeys (zh, *sysno, 0, sortKeys);
594 #else
595         sortKeys.buf_used = rec->size[recInfo_sortKeys];
596         sortKeys.buf = rec->info[recInfo_sortKeys];
597         extract_flushSortKeys (zh, *sysno, 0, &sortKeys);
598 #endif
599
600         extract_flushRecordKeys (zh, *sysno, 0, delkeys,
601                                  recordAttr->staticrank); /* old values */  
602         if (deleteFlag)
603         {
604             /* record going to be deleted */
605             if (zebra_rec_keys_empty(delkeys))
606             {
607                 yaz_log (YLOG_LOG, "delete %s %s " PRINTF_OFF_T 
608                          " " ZINT_FORMAT,
609                          zh->m_record_type, fname, recordOffset, *sysno);
610                 yaz_log (YLOG_WARN, "cannot delete file above, storeKeys false (1)");
611             }
612             else
613             {
614                 if (zh->records_processed < zh->m_file_verbose_limit)
615                 {
616                     if (matchStr)
617                         yaz_log(YLOG_LOG, "delete %s %s " PRINTF_OFF_T 
618                                 " " ZINT_FORMAT " %s" ,
619                                 zh->m_record_type,
620                                 fname, recordOffset, *sysno, matchStr);
621                     else
622                         yaz_log(YLOG_LOG, "delete %s %s " PRINTF_OFF_T 
623                                 " " ZINT_FORMAT , 
624                                 zh->m_record_type,
625                                 fname, recordOffset, *sysno);
626                 }
627                 zh->records_deleted++;
628                 if (matchStr)
629                 {
630                     int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
631                     dict_delete_ord(zh->reg->matchDict, db_ord, matchStr);
632                 }
633                 rec_del (zh->reg->records, &rec);
634             }
635             rec_rm (&rec);
636             logRecord (zh);
637             return ZEBRA_OK;
638         }
639         else
640         {
641             /* flush new keys for sort&search etc */
642             if (zh->records_processed < zh->m_file_verbose_limit)
643             {
644                 if (matchStr)
645                     yaz_log(YLOG_LOG, "update %s %s " PRINTF_OFF_T 
646                             " " ZINT_FORMAT " %s" ,
647                             zh->m_record_type,
648                             fname, recordOffset, *sysno, matchStr);
649                 else
650                     yaz_log(YLOG_LOG, "update %s %s " PRINTF_OFF_T 
651                             " " ZINT_FORMAT , 
652                             zh->m_record_type,
653                             fname, recordOffset, *sysno);
654             }
655             recordAttr->staticrank = extractCtrl.staticrank;
656 #if NATTR
657             extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
658 #else
659             extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
660 #endif
661             extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys,
662                                          recordAttr->staticrank);
663             zh->records_updated++;
664         }
665         zebra_rec_keys_close(delkeys);
666 #if NATTR
667         zebra_rec_keys_close(sortKeys);
668 #endif
669     }
670     /* update file type */
671     xfree (rec->info[recInfo_fileType]);
672     rec->info[recInfo_fileType] =
673         rec_strdup (zh->m_record_type, &rec->size[recInfo_fileType]);
674
675     /* update filename */
676     xfree (rec->info[recInfo_filename]);
677     rec->info[recInfo_filename] =
678         rec_strdup (fname, &rec->size[recInfo_filename]);
679
680     /* update delete keys */
681     xfree (rec->info[recInfo_delKeys]);
682     if (!zebra_rec_keys_empty(zh->reg->keys) && zh->m_store_keys == 1)
683     {
684         zebra_rec_keys_get_buf(zh->reg->keys,
685                                &rec->info[recInfo_delKeys],
686                                &rec->size[recInfo_delKeys]);
687     }
688     else
689     {
690         rec->info[recInfo_delKeys] = NULL;
691         rec->size[recInfo_delKeys] = 0;
692     }
693
694     /* update sort keys */
695     xfree (rec->info[recInfo_sortKeys]);
696
697 #if NATTR
698     zebra_rec_keys_get_buf(zh->reg->sortKeys,
699                            &rec->info[recInfo_sortKeys],
700                            &rec->size[recInfo_sortKeys]);
701 #else
702     rec->size[recInfo_sortKeys] = zh->reg->sortKeys.buf_used;
703     rec->info[recInfo_sortKeys] = zh->reg->sortKeys.buf;
704     zh->reg->sortKeys.buf = NULL;
705     zh->reg->sortKeys.buf_max = 0;
706 #endif
707
708     /* save file size of original record */
709     zebraExplain_recordBytesIncrement (zh->reg->zei,
710                                        - recordAttr->recordSize);
711     recordAttr->recordSize = fi->file_moffset - recordOffset;
712     if (!recordAttr->recordSize)
713         recordAttr->recordSize = fi->file_max - recordOffset;
714     zebraExplain_recordBytesIncrement (zh->reg->zei,
715                                        recordAttr->recordSize);
716
717     /* set run-number for this record */
718     recordAttr->runNumber = zebraExplain_runNumberIncrement (zh->reg->zei,
719                                                              0);
720
721     /* update store data */
722     xfree (rec->info[recInfo_storeData]);
723     if (zh->store_data_buf)
724     {
725         rec->size[recInfo_storeData] = zh->store_data_size;
726         rec->info[recInfo_storeData] = zh->store_data_buf;
727         zh->store_data_buf = 0;
728     }
729     else if (zh->m_store_data)
730     {
731         rec->size[recInfo_storeData] = recordAttr->recordSize;
732         rec->info[recInfo_storeData] = (char *)
733             xmalloc (recordAttr->recordSize);
734         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
735         {
736             yaz_log (YLOG_ERRNO|YLOG_FATAL, "seek to " PRINTF_OFF_T " in %s",
737                   recordOffset, fname);
738             exit (1);
739         }
740         if (read (fi->fd, rec->info[recInfo_storeData], recordAttr->recordSize)
741             < recordAttr->recordSize)
742         {
743             yaz_log (YLOG_ERRNO|YLOG_FATAL, "read %d bytes of %s",
744                   recordAttr->recordSize, fname);
745             exit (1);
746         }
747     }
748     else
749     {
750         rec->info[recInfo_storeData] = NULL;
751         rec->size[recInfo_storeData] = 0;
752     }
753     /* update database name */
754     xfree (rec->info[recInfo_databaseName]);
755     rec->info[recInfo_databaseName] =
756         rec_strdup (zh->basenames[0], &rec->size[recInfo_databaseName]); 
757
758     /* update offset */
759     recordAttr->recordOffset = recordOffset;
760     
761     /* commit this record */
762     rec_put (zh->reg->records, &rec);
763     logRecord (zh);
764     return ZEBRA_OK;
765 }
766
767 ZEBRA_RES zebra_extract_file(ZebraHandle zh, SYSNO *sysno, const char *fname, 
768                              int deleteFlag)
769 {
770     ZEBRA_RES r = ZEBRA_OK;
771     int i, fd;
772     char gprefix[128];
773     char ext[128];
774     char ext_res[128];
775     struct file_read_info *fi;
776     const char *original_record_type = 0;
777     RecType recType;
778     void *recTypeClientData;
779
780     if (!zh->m_group || !*zh->m_group)
781         *gprefix = '\0';
782     else
783         sprintf (gprefix, "%s.", zh->m_group);
784     
785     yaz_log (YLOG_DEBUG, "fileExtract %s", fname);
786
787     /* determine file extension */
788     *ext = '\0';
789     for (i = strlen(fname); --i >= 0; )
790         if (fname[i] == '/')
791             break;
792         else if (fname[i] == '.')
793         {
794             strcpy (ext, fname+i+1);
795             break;
796         }
797     /* determine file type - depending on extension */
798     original_record_type = zh->m_record_type;
799     if (!zh->m_record_type)
800     {
801         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
802         zh->m_record_type = res_get (zh->res, ext_res);
803     }
804     if (!zh->m_record_type)
805     {
806         if (zh->records_processed < zh->m_file_verbose_limit)
807             yaz_log (YLOG_LOG, "? %s", fname);
808         return 0;
809     }
810     /* determine match criteria */
811     if (!zh->m_record_id)
812     {
813         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
814         zh->m_record_id = res_get (zh->res, ext_res);
815     }
816
817     if (!(recType =
818           recType_byName (zh->reg->recTypes, zh->res, zh->m_record_type,
819                           &recTypeClientData)))
820     {
821         yaz_log(YLOG_WARN, "No such record type: %s", zh->m_record_type);
822         return ZEBRA_FAIL;
823     }
824
825     switch(recType->version)
826     {
827     case 0:
828         break;
829     default:
830         yaz_log(YLOG_WARN, "Bad filter version: %s", zh->m_record_type);
831     }
832     if (sysno && deleteFlag)
833         fd = -1;
834     else
835     {
836         char full_rep[1024];
837
838         if (zh->path_reg && !yaz_is_abspath (fname))
839         {
840             strcpy (full_rep, zh->path_reg);
841             strcat (full_rep, "/");
842             strcat (full_rep, fname);
843         }
844         else
845             strcpy (full_rep, fname);
846         
847         if ((fd = open (full_rep, O_BINARY|O_RDONLY)) == -1)
848         {
849             yaz_log (YLOG_WARN|YLOG_ERRNO, "open %s", full_rep);
850             zh->m_record_type = original_record_type;
851             return ZEBRA_FAIL;
852         }
853     }
854     fi = file_read_start (fd);
855     while(1)
856     {
857         fi->file_moffset = fi->file_offset;
858         fi->file_more = 0;  /* file_end not called (yet) */
859         r = file_extract_record (zh, sysno, fname, deleteFlag, fi, 1,
860                                  recType, recTypeClientData);
861         if (fi->file_more)
862         {   /* file_end has been called so reset offset .. */
863             fi->file_offset = fi->file_moffset;
864             lseek(fi->fd, fi->file_moffset, SEEK_SET);
865         }
866         if (r != ZEBRA_OK)
867         {
868             break;
869         }
870         if (sysno)
871         {
872             break;
873         }
874     }
875     file_read_stop (fi);
876     if (fd != -1)
877         close (fd);
878     zh->m_record_type = original_record_type;
879     return r;
880 }
881
882 /*
883   If sysno is provided, then it's used to identify the reocord.
884   If not, and match_criteria is provided, then sysno is guessed
885   If not, and a record is provided, then sysno is got from there
886   
887  */
888 ZEBRA_RES buffer_extract_record(ZebraHandle zh, 
889                                 const char *buf, size_t buf_size,
890                                 int delete_flag,
891                                 int test_mode, 
892                                 const char *recordType,
893                                 SYSNO *sysno,
894                                 const char *match_criteria,
895                                 const char *fname,
896                                 int force_update,
897                                 int allow_update)
898 {
899     SYSNO sysno0 = 0;
900     RecordAttr *recordAttr;
901     struct recExtractCtrl extractCtrl;
902     int r;
903     const char *matchStr = 0;
904     RecType recType = NULL;
905     void *clientData;
906     Record rec;
907     long recordOffset = 0;
908     struct zebra_fetch_control fc;
909     const char *pr_fname = fname;  /* filename to print .. */
910     int show_progress = zh->records_processed < zh->m_file_verbose_limit ? 1:0;
911
912     if (!pr_fname)
913         pr_fname = "<no file>";  /* make it printable if file is omitted */
914
915     fc.fd = -1;
916     fc.record_int_buf = buf;
917     fc.record_int_len = buf_size;
918     fc.record_int_pos = 0;
919     fc.offset_end = 0;
920     fc.record_offset = 0;
921
922     extractCtrl.offset = 0;
923     extractCtrl.readf = zebra_record_int_read;
924     extractCtrl.seekf = zebra_record_int_seek;
925     extractCtrl.tellf = zebra_record_int_tell;
926     extractCtrl.endf = zebra_record_int_end;
927     extractCtrl.first_record = 1;
928     extractCtrl.fh = &fc;
929
930     zebra_rec_keys_reset(zh->reg->keys);
931
932 #if NATTR
933     zebra_rec_keys_reset(zh->reg->sortKeys);
934 #else
935     zh->reg->sortKeys.buf_used = 0;
936 #endif
937     if (zebraExplain_curDatabase (zh->reg->zei, zh->basenames[0]))
938     {
939         if (zebraExplain_newDatabase (zh->reg->zei, zh->basenames[0], 
940                                       zh->m_explain_database))
941             return ZEBRA_FAIL;
942     }
943     
944     if (recordType && *recordType)
945     {
946         yaz_log (YLOG_DEBUG, "Record type explicitly specified: %s", recordType);
947         recType = recType_byName (zh->reg->recTypes, zh->res, recordType,
948                                   &clientData);
949     } 
950     else
951     {
952         if (!(zh->m_record_type))
953         {
954             yaz_log (YLOG_WARN, "No such record type defined");
955             return ZEBRA_FAIL;
956         }
957         yaz_log (YLOG_DEBUG, "Get record type from rgroup: %s",zh->m_record_type);
958         recType = recType_byName (zh->reg->recTypes, zh->res,
959                                   zh->m_record_type, &clientData);
960         recordType = zh->m_record_type;
961     }
962     
963     if (!recType)
964     {
965         yaz_log (YLOG_WARN, "No such record type: %s", recordType);
966         return ZEBRA_FAIL;
967     }
968     
969     extractCtrl.init = extract_init;
970     extractCtrl.tokenAdd = extract_token_add;
971     extractCtrl.schemaAdd = extract_schema_add;
972     extractCtrl.dh = zh->reg->dh;
973     extractCtrl.handle = zh;
974     extractCtrl.match_criteria[0] = '\0';
975     extractCtrl.staticrank = 0;
976     
977     init_extractCtrl(zh, &extractCtrl);
978
979     extract_set_store_data_prepare(&extractCtrl);
980
981     r = (*recType->extract)(clientData, &extractCtrl);
982
983     if (r == RECCTRL_EXTRACT_EOF)
984         return ZEBRA_FAIL;
985     else if (r == RECCTRL_EXTRACT_ERROR_GENERIC)
986     {
987         /* error occured during extraction ... */
988         yaz_log (YLOG_WARN, "extract error: generic");
989         return ZEBRA_FAIL;
990     }
991     else if (r == RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER)
992     {
993         /* error occured during extraction ... */
994         yaz_log (YLOG_WARN, "extract error: no such filter");
995         return ZEBRA_FAIL;
996     }
997
998     if (extractCtrl.match_criteria[0])
999         match_criteria = extractCtrl.match_criteria;
1000
1001     if (!sysno) {
1002
1003         sysno = &sysno0;
1004
1005         if (match_criteria && *match_criteria) {
1006             matchStr = match_criteria;
1007         } else {
1008             if (zh->m_record_id && *zh->m_record_id) {
1009                 matchStr = fileMatchStr (zh, zh->reg->keys, pr_fname, 
1010                                          zh->m_record_id);
1011                 if (!matchStr)
1012                 {
1013                     yaz_log (YLOG_WARN, "Bad match criteria (recordID)");
1014                     return ZEBRA_FAIL;
1015                 }
1016             }
1017         }
1018         if (matchStr) 
1019         {
1020             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1021             char *rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord,
1022                                           matchStr);
1023             if (rinfo)
1024             {
1025                 assert(*rinfo == sizeof(*sysno));
1026                 memcpy (sysno, rinfo+1, sizeof(*sysno));
1027             }
1028         }
1029     }
1030     if (zebra_rec_keys_empty(zh->reg->keys))
1031     {
1032         /* the extraction process returned no information - the record
1033            is probably empty - unless flagShowRecords is in use */
1034         if (test_mode)
1035             return ZEBRA_OK;
1036     }
1037
1038     if (! *sysno)
1039     {
1040         /* new record */
1041         if (delete_flag)
1042         {
1043             yaz_log (YLOG_LOG, "delete %s %s %ld", recordType,
1044                          pr_fname, (long) recordOffset);
1045             yaz_log (YLOG_WARN, "cannot delete record above (seems new)");
1046             return ZEBRA_FAIL;
1047         }
1048         if (show_progress)
1049             yaz_log (YLOG_LOG, "add %s %s %ld", recordType, pr_fname,
1050                      (long) recordOffset);
1051         rec = rec_new (zh->reg->records);
1052
1053         *sysno = rec->sysno;
1054
1055         recordAttr = rec_init_attr (zh->reg->zei, rec);
1056         recordAttr->staticrank = extractCtrl.staticrank;
1057
1058         if (matchStr)
1059         {
1060             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1061             dict_insert_ord(zh->reg->matchDict, db_ord, matchStr,
1062                             sizeof(*sysno), sysno);
1063         }
1064
1065
1066 #if NATTR
1067         extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
1068 #else
1069         extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
1070 #endif
1071         
1072 #if 0
1073         print_rec_keys(zh, zh->reg->keys);
1074 #endif
1075         extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys,
1076                          recordAttr->staticrank);
1077         zh->records_inserted++;
1078     } 
1079     else
1080     {
1081         /* record already exists */
1082         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
1083 #if NATTR
1084         zebra_rec_keys_t sortKeys = zebra_rec_keys_open();
1085 #else
1086         struct sortKeys sortKeys;
1087 #endif
1088
1089         if (!allow_update)
1090         {
1091             yaz_log (YLOG_LOG, "skipped %s %s %ld", 
1092                          recordType, pr_fname, (long) recordOffset);
1093             logRecord(zh);
1094             return ZEBRA_FAIL;
1095         }
1096
1097         rec = rec_get (zh->reg->records, *sysno);
1098         assert (rec);
1099         
1100         recordAttr = rec_init_attr (zh->reg->zei, rec);
1101
1102         zebra_rec_keys_set_buf(delkeys,
1103                                rec->info[recInfo_delKeys],
1104                                rec->size[recInfo_delKeys],
1105                                0);
1106 #if NATTR
1107         zebra_rec_keys_set_buf(sortKeys,
1108                                rec->info[recInfo_sortKeys],
1109                                rec->size[recInfo_sortKeys],
1110                                0);
1111 #else
1112         sortKeys.buf_used = rec->size[recInfo_sortKeys];
1113         sortKeys.buf = rec->info[recInfo_sortKeys];
1114 #endif
1115
1116 #if NATTR
1117         extract_flushSortKeys (zh, *sysno, 0, sortKeys);
1118 #else
1119         extract_flushSortKeys (zh, *sysno, 0, &sortKeys);
1120 #endif
1121         extract_flushRecordKeys (zh, *sysno, 0, delkeys,
1122                                  recordAttr->staticrank);
1123         if (delete_flag)
1124         {
1125             /* record going to be deleted */
1126             if (zebra_rec_keys_empty(delkeys))
1127             {
1128                 yaz_log (YLOG_LOG, "delete %s %s %ld", recordType,
1129                      pr_fname, (long) recordOffset);
1130                 yaz_log (YLOG_WARN, "cannot delete file above, "
1131                              "storeKeys false (3)");
1132             }
1133             else
1134             {
1135                 if (show_progress)
1136                     yaz_log (YLOG_LOG, "delete %s %s %ld", recordType,
1137                              pr_fname, (long) recordOffset);
1138                 zh->records_deleted++;
1139                 if (matchStr)
1140                 {
1141                     int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1142                     dict_delete_ord(zh->reg->matchDict, db_ord, matchStr);
1143                 }
1144                 rec_del (zh->reg->records, &rec);
1145             }
1146             rec_rm (&rec);
1147             logRecord(zh);
1148             return ZEBRA_OK;
1149         }
1150         else
1151         {
1152             if (show_progress)
1153                     yaz_log (YLOG_LOG, "update %s %s %ld", recordType,
1154                              pr_fname, (long) recordOffset);
1155             recordAttr->staticrank = extractCtrl.staticrank;
1156 #if NATTR
1157             extract_flushSortKeys (zh, *sysno, 1, zh->reg->sortKeys);
1158 #else
1159             extract_flushSortKeys (zh, *sysno, 1, &zh->reg->sortKeys);
1160 #endif
1161             extract_flushRecordKeys (zh, *sysno, 1, zh->reg->keys, 
1162                                          recordAttr->staticrank);
1163             zh->records_updated++;
1164         }
1165         zebra_rec_keys_close(delkeys);
1166 #if NATTR
1167         zebra_rec_keys_close(sortKeys);
1168 #endif
1169     }
1170     /* update file type */
1171     xfree (rec->info[recInfo_fileType]);
1172     rec->info[recInfo_fileType] =
1173         rec_strdup (recordType, &rec->size[recInfo_fileType]);
1174
1175     /* update filename */
1176     xfree (rec->info[recInfo_filename]);
1177     rec->info[recInfo_filename] =
1178         rec_strdup (fname, &rec->size[recInfo_filename]);
1179
1180     /* update delete keys */
1181     xfree (rec->info[recInfo_delKeys]);
1182     if (!zebra_rec_keys_empty(zh->reg->keys) && zh->m_store_keys == 1)
1183     {
1184         zebra_rec_keys_get_buf(zh->reg->keys,
1185                                &rec->info[recInfo_delKeys],
1186                                &rec->size[recInfo_delKeys]);
1187     }
1188     else
1189     {
1190         rec->info[recInfo_delKeys] = NULL;
1191         rec->size[recInfo_delKeys] = 0;
1192     }
1193     /* update sort keys */
1194     xfree (rec->info[recInfo_sortKeys]);
1195
1196 #if NATTR
1197     zebra_rec_keys_get_buf(zh->reg->sortKeys,
1198                            &rec->info[recInfo_sortKeys],
1199                            &rec->size[recInfo_sortKeys]);
1200 #else
1201     rec->size[recInfo_sortKeys] = zh->reg->sortKeys.buf_used;
1202     rec->info[recInfo_sortKeys] = zh->reg->sortKeys.buf;
1203     zh->reg->sortKeys.buf = NULL;
1204     zh->reg->sortKeys.buf_max = 0;
1205 #endif
1206
1207     /* save file size of original record */
1208     zebraExplain_recordBytesIncrement (zh->reg->zei,
1209                                        - recordAttr->recordSize);
1210 #if 0
1211     recordAttr->recordSize = fi->file_moffset - recordOffset;
1212     if (!recordAttr->recordSize)
1213         recordAttr->recordSize = fi->file_max - recordOffset;
1214 #else
1215     recordAttr->recordSize = buf_size;
1216 #endif
1217     zebraExplain_recordBytesIncrement (zh->reg->zei,
1218                                        recordAttr->recordSize);
1219
1220     /* set run-number for this record */
1221     recordAttr->runNumber =
1222         zebraExplain_runNumberIncrement (zh->reg->zei, 0);
1223
1224     /* update store data */
1225     xfree (rec->info[recInfo_storeData]);
1226
1227     /* update store data */
1228     if (zh->store_data_buf)
1229     {
1230         rec->size[recInfo_storeData] = zh->store_data_size;
1231         rec->info[recInfo_storeData] = zh->store_data_buf;
1232         zh->store_data_buf = 0;
1233     }
1234     else if (zh->m_store_data)
1235     {
1236         rec->size[recInfo_storeData] = recordAttr->recordSize;
1237         rec->info[recInfo_storeData] = (char *)
1238             xmalloc (recordAttr->recordSize);
1239         memcpy (rec->info[recInfo_storeData], buf, recordAttr->recordSize);
1240     }
1241     else
1242     {
1243         rec->info[recInfo_storeData] = NULL;
1244         rec->size[recInfo_storeData] = 0;
1245     }
1246     /* update database name */
1247     xfree (rec->info[recInfo_databaseName]);
1248     rec->info[recInfo_databaseName] =
1249         rec_strdup (zh->basenames[0], &rec->size[recInfo_databaseName]); 
1250
1251     /* update offset */
1252     recordAttr->recordOffset = recordOffset;
1253     
1254     /* commit this record */
1255     rec_put (zh->reg->records, &rec);
1256     logRecord(zh);
1257     return ZEBRA_OK;
1258 }
1259
1260 int explain_extract (void *handle, Record rec, data1_node *n)
1261 {
1262     ZebraHandle zh = (ZebraHandle) handle;
1263     struct recExtractCtrl extractCtrl;
1264
1265     if (zebraExplain_curDatabase (zh->reg->zei,
1266                                   rec->info[recInfo_databaseName]))
1267     {
1268         abort();
1269         if (zebraExplain_newDatabase (zh->reg->zei,
1270                                       rec->info[recInfo_databaseName], 0))
1271             abort ();
1272     }
1273
1274     zebra_rec_keys_reset(zh->reg->keys);
1275     
1276 #if NATTR
1277     zebra_rec_keys_reset(zh->reg->sortKeys);
1278 #else
1279     zh->reg->sortKeys.buf_used = 0;
1280 #endif
1281     extractCtrl.init = extract_init;
1282     extractCtrl.tokenAdd = extract_token_add;
1283     extractCtrl.schemaAdd = extract_schema_add;
1284     extractCtrl.dh = zh->reg->dh;
1285
1286     init_extractCtrl(zh, &extractCtrl);
1287
1288     extractCtrl.flagShowRecords = 0;
1289     extractCtrl.match_criteria[0] = '\0';
1290     extractCtrl.staticrank = 0;
1291     extractCtrl.handle = handle;
1292     extractCtrl.first_record = 1;
1293     
1294     extract_set_store_data_prepare(&extractCtrl);
1295
1296     if (n)
1297         grs_extract_tree(&extractCtrl, n);
1298
1299     if (rec->size[recInfo_delKeys])
1300     {
1301         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
1302         
1303 #if NATTR
1304         zebra_rec_keys_t sortkeys = zebra_rec_keys_open();
1305 #else
1306         struct sortKeys sortkeys;
1307 #endif
1308
1309         zebra_rec_keys_set_buf(delkeys, rec->info[recInfo_delKeys],
1310                                rec->size[recInfo_delKeys],
1311                                0);
1312         extract_flushRecordKeys (zh, rec->sysno, 0, delkeys, 0);
1313         zebra_rec_keys_close(delkeys);
1314 #if NATTR
1315         zebra_rec_keys_set_buf(sortkeys, rec->info[recInfo_sortKeys],
1316                                rec->size[recInfo_sortKeys],
1317                                0);
1318
1319         extract_flushSortKeys (zh, rec->sysno, 0, sortkeys);
1320         zebra_rec_keys_close(sortkeys);
1321 #else
1322         sortkeys.buf_used = rec->size[recInfo_sortKeys];
1323         sortkeys.buf = rec->info[recInfo_sortKeys];
1324         extract_flushSortKeys (zh, rec->sysno, 0, &sortkeys);
1325 #endif
1326     }
1327     extract_flushRecordKeys (zh, rec->sysno, 1, zh->reg->keys, 0);
1328 #if NATTR
1329     extract_flushSortKeys (zh, rec->sysno, 1, zh->reg->sortKeys);
1330 #else
1331     extract_flushSortKeys (zh, rec->sysno, 1, &zh->reg->sortKeys);
1332 #endif
1333
1334     xfree (rec->info[recInfo_delKeys]);
1335     zebra_rec_keys_get_buf(zh->reg->keys,
1336                            &rec->info[recInfo_delKeys], 
1337                            &rec->size[recInfo_delKeys]);
1338
1339     xfree (rec->info[recInfo_sortKeys]);
1340 #if NATTR
1341     zebra_rec_keys_get_buf(zh->reg->sortKeys,
1342                            &rec->info[recInfo_sortKeys],
1343                            &rec->size[recInfo_sortKeys]);
1344 #else
1345     rec->size[recInfo_sortKeys] = zh->reg->sortKeys.buf_used;
1346     rec->info[recInfo_sortKeys] = zh->reg->sortKeys.buf;
1347     zh->reg->sortKeys.buf = NULL;
1348     zh->reg->sortKeys.buf_max = 0;
1349 #endif
1350
1351     return 0;
1352 }
1353
1354 void extract_rec_keys_adjust(ZebraHandle zh, int is_insert,
1355                              zebra_rec_keys_t reckeys)
1356 {
1357     ZebraExplainInfo zei = zh->reg->zei;
1358     struct ord_stat {
1359         int no;
1360         int ord;
1361         struct ord_stat *next;
1362     };
1363
1364     if (zebra_rec_keys_rewind(reckeys))
1365     {
1366         struct ord_stat *ord_list = 0;
1367         struct ord_stat *p;
1368         size_t slen;
1369         const char *str;
1370         struct it_key key_in;
1371         while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1372         {
1373             int ord = key_in.mem[0]; 
1374
1375             for (p = ord_list; p ; p = p->next)
1376                 if (p->ord == ord)
1377                 {
1378                     p->no++;
1379                     break;
1380                 }
1381             if (!p)
1382             {
1383                 p = xmalloc(sizeof(*p));
1384                 p->no = 1;
1385                 p->ord = ord;
1386                 p->next = ord_list;
1387                 ord_list = p;
1388             }
1389         }
1390
1391         p = ord_list;
1392         while (p)
1393         {
1394             struct ord_stat *p1 = p;
1395
1396             if (is_insert)
1397                 zebraExplain_ord_adjust_occurrences(zei, p->ord, p->no, 1);
1398             else
1399                 zebraExplain_ord_adjust_occurrences(zei, p->ord, - p->no, -1);
1400             p = p->next;
1401             xfree(p1);
1402         }
1403     }
1404 }
1405
1406 void extract_flushRecordKeys (ZebraHandle zh, SYSNO sysno,
1407                               int cmd,
1408                               zebra_rec_keys_t reckeys,
1409                               zint staticrank)
1410 {
1411     ZebraExplainInfo zei = zh->reg->zei;
1412
1413     extract_rec_keys_adjust(zh, cmd, reckeys);
1414
1415     if (!zh->reg->key_buf)
1416     {
1417         int mem= 1024*1024* atoi( res_get_def( zh->res, "memmax", "8"));
1418         if (mem <= 0)
1419         {
1420             yaz_log(YLOG_WARN, "Invalid memory setting, using default 8 MB");
1421             mem= 1024*1024*8;
1422         }
1423         /* FIXME: That "8" should be in a default settings include */
1424         /* not hard-coded here! -H */
1425         zh->reg->key_buf = (char**) xmalloc (mem);
1426         zh->reg->ptr_top = mem/sizeof(char*);
1427         zh->reg->ptr_i = 0;
1428         zh->reg->key_buf_used = 0;
1429         zh->reg->key_file_no = 0;
1430     }
1431     zebraExplain_recordCountIncrement (zei, cmd ? 1 : -1);
1432
1433     if (zebra_rec_keys_rewind(reckeys))
1434     {
1435         size_t slen;
1436         const char *str;
1437         struct it_key key_in;
1438         while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1439         {
1440             int ch = 0;
1441             struct it_key key_out;
1442             zint *keyp = key_out.mem;
1443
1444             assert(key_in.len == 4);
1445             
1446             /* check for buffer overflow */
1447             if (zh->reg->key_buf_used + 1024 > 
1448                 (zh->reg->ptr_top -zh->reg->ptr_i)*sizeof(char*))
1449                 extract_flushWriteKeys (zh, 0);
1450             
1451             ++(zh->reg->ptr_i);
1452             assert(zh->reg->ptr_i > 0);
1453             (zh->reg->key_buf)[zh->reg->ptr_top - zh->reg->ptr_i] =
1454                 (char*)zh->reg->key_buf + zh->reg->key_buf_used;
1455
1456             /* encode the ordinal value (field/use/attribute) .. */
1457             ch = (int) key_in.mem[0];
1458             zh->reg->key_buf_used +=
1459                 key_SU_encode(ch, (char*)zh->reg->key_buf +
1460                               zh->reg->key_buf_used);
1461
1462             /* copy the 0-terminated stuff from str to output */
1463             memcpy((char*)zh->reg->key_buf + zh->reg->key_buf_used, str, slen);
1464             zh->reg->key_buf_used += slen;
1465             ((char*)zh->reg->key_buf)[(zh->reg->key_buf_used)++] = '\0';
1466
1467             /* the delete/insert indicator */
1468             ((char*)zh->reg->key_buf)[(zh->reg->key_buf_used)++] = cmd;
1469
1470             if (zh->m_staticrank) /* rank config enabled ? */
1471             {
1472                 if (staticrank < 0)
1473                 {
1474                     yaz_log(YLOG_WARN, "staticrank = %ld. Setting to 0",
1475                             (long) staticrank);
1476                     staticrank = 0;
1477                 }
1478                 *keyp++ = staticrank;
1479                 key_out.len = 4;
1480             }
1481             else
1482                 key_out.len = 3;
1483             
1484             if (key_in.mem[1]) /* filter specified record ID */
1485                 *keyp++ = key_in.mem[1];
1486             else
1487                 *keyp++ = sysno;
1488             *keyp++ = key_in.mem[2];  /* section_id */
1489             *keyp++ = key_in.mem[3];  /* sequence .. */
1490             
1491             memcpy((char*)zh->reg->key_buf + zh->reg->key_buf_used,
1492                    &key_out, sizeof(key_out));
1493             (zh->reg->key_buf_used) += sizeof(key_out);
1494         }
1495     }
1496 }
1497
1498 void extract_flushWriteKeys (ZebraHandle zh, int final)
1499         /* optimizing: if final=1, and no files written yet */
1500         /* push the keys directly to merge, sidestepping the */
1501         /* temp file altogether. Speeds small updates */
1502 {
1503     FILE *outf;
1504     char out_fname[200];
1505     char *prevcp, *cp;
1506     struct encode_info encode_info;
1507     int ptr_i = zh->reg->ptr_i;
1508     int temp_policy;
1509 #if SORT_EXTRA
1510     int i;
1511 #endif
1512     if (!zh->reg->key_buf || ptr_i <= 0)
1513     {
1514         yaz_log (YLOG_DEBUG, "  nothing to flush section=%d buf=%p i=%d",
1515                zh->reg->key_file_no, zh->reg->key_buf, ptr_i);
1516         yaz_log (YLOG_DEBUG, "  buf=%p ",
1517                zh->reg->key_buf);
1518         yaz_log (YLOG_DEBUG, "  ptr=%d ",zh->reg->ptr_i);
1519         yaz_log (YLOG_DEBUG, "  reg=%p ",zh->reg);
1520                
1521         return;
1522     }
1523
1524     (zh->reg->key_file_no)++;
1525     yaz_log (YLOG_LOG, "sorting section %d", (zh->reg->key_file_no));
1526     yaz_log (YLOG_DEBUG, "  sort_buff at %p n=%d",
1527                     zh->reg->key_buf + zh->reg->ptr_top - ptr_i,ptr_i);
1528 #if !SORT_EXTRA
1529     qsort (zh->reg->key_buf + zh->reg->ptr_top - ptr_i, ptr_i,
1530                sizeof(char*), key_qsort_compare);
1531
1532     /* zebra.cfg: tempfiles:  
1533        Y: always use temp files (old way) 
1534        A: use temp files, if more than one (auto) 
1535           = if this is both the last and the first 
1536        N: never bother with temp files (new) */
1537
1538     temp_policy=toupper(res_get_def(zh->res,"tempfiles","auto")[0]);
1539     if (temp_policy != 'Y' && temp_policy != 'N' && temp_policy != 'A') {
1540         yaz_log (YLOG_WARN, "Illegal tempfiles setting '%c'. using 'Auto' ", 
1541                         temp_policy);
1542         temp_policy='A';
1543     }
1544
1545     if (   ( temp_policy =='N' )   ||     /* always from memory */
1546          ( ( temp_policy =='A' ) &&       /* automatic */
1547              (zh->reg->key_file_no == 1) &&  /* this is first time */
1548              (final) ) )                     /* and last (=only) time */
1549     { /* go directly from memory */
1550         zh->reg->key_file_no =0; /* signal not to read files */
1551         zebra_index_merge(zh); 
1552         zh->reg->ptr_i = 0;
1553         zh->reg->key_buf_used = 0; 
1554         return; 
1555     }
1556
1557     /* Not doing directly from memory, write into a temp file */
1558     extract_get_fname_tmp (zh, out_fname, zh->reg->key_file_no);
1559
1560     if (!(outf = fopen (out_fname, "wb")))
1561     {
1562         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fopen %s", out_fname);
1563         exit (1);
1564     }
1565     yaz_log (YLOG_LOG, "writing section %d", zh->reg->key_file_no);
1566     prevcp = cp = (zh->reg->key_buf)[zh->reg->ptr_top - ptr_i];
1567     
1568     encode_key_init (&encode_info);
1569     encode_key_write (cp, &encode_info, outf);
1570     
1571     while (--ptr_i > 0)
1572     {
1573         cp = (zh->reg->key_buf)[zh->reg->ptr_top - ptr_i];
1574         if (strcmp (cp, prevcp))
1575         {
1576             encode_key_flush ( &encode_info, outf);
1577             encode_key_init (&encode_info);
1578             encode_key_write (cp, &encode_info, outf);
1579             prevcp = cp;
1580         }
1581         else
1582             encode_key_write (cp + strlen(cp), &encode_info, outf);
1583     }
1584     encode_key_flush ( &encode_info, outf);
1585 #else
1586     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_x_compare);
1587     extract_get_fname_tmp (out_fname, key_file_no);
1588
1589     if (!(outf = fopen (out_fname, "wb")))
1590     {
1591         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fopen %s", out_fname);
1592         exit (1);
1593     }
1594     yaz_log (YLOG_LOG, "writing section %d", key_file_no);
1595     i = ptr_i;
1596     prevcp =  key_buf[ptr_top-i];
1597     while (1)
1598         if (!--i || strcmp (prevcp, key_buf[ptr_top-i]))
1599         {
1600             key_y_len = strlen(prevcp)+1;
1601 #if 0
1602             yaz_log (YLOG_LOG, "key_y_len: %2d %02x %02x %s",
1603                       key_y_len, prevcp[0], prevcp[1], 2+prevcp);
1604 #endif
1605             qsort (key_buf + ptr_top-ptr_i, ptr_i - i,
1606                                    sizeof(char*), key_y_compare);
1607             cp = key_buf[ptr_top-ptr_i];
1608             --key_y_len;
1609             encode_key_init (&encode_info);
1610             encode_key_write (cp, &encode_info, outf);
1611             while (--ptr_i > i)
1612             {
1613                 cp = key_buf[ptr_top-ptr_i];
1614                 encode_key_write (cp+key_y_len, &encode_info, outf);
1615             }
1616             encode_key_flush ( &encode_info, outf);
1617             if (!i)
1618                 break;
1619             prevcp = key_buf[ptr_top-ptr_i];
1620         }
1621 #endif
1622     if (fclose (outf))
1623     {
1624         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fclose %s", out_fname);
1625         exit (1);
1626     }
1627     yaz_log (YLOG_LOG, "finished section %d", zh->reg->key_file_no);
1628     zh->reg->ptr_i = 0;
1629     zh->reg->key_buf_used = 0;
1630 }
1631
1632 ZEBRA_RES zebra_snippets_rec_keys(ZebraHandle zh,
1633                                   zebra_rec_keys_t reckeys,
1634                                   zebra_snippets *snippets)
1635 {
1636     NMEM nmem = nmem_create();
1637     if (zebra_rec_keys_rewind(reckeys)) 
1638     {
1639         const char *str;
1640         size_t slen;
1641         struct it_key key;
1642         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1643         {
1644             char dst_buf[IT_MAX_WORD];
1645             char *dst_term = dst_buf;
1646             int ord, seqno;
1647             int index_type;
1648             assert(key.len <= 4 && key.len > 2);
1649             seqno = (int) key.mem[key.len-1];
1650             ord = key.mem[0];
1651             
1652             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type,
1653                                     0/* db */, 0/* set */, 0/* use */,
1654                                     0 /* string_index */);
1655             assert(index_type);
1656             zebra_term_untrans_iconv(zh, nmem, index_type,
1657                                      &dst_term, str);
1658             zebra_snippets_append(snippets, seqno, ord, dst_term);
1659             nmem_reset(nmem);
1660         }
1661     }
1662     nmem_destroy(nmem);
1663     return ZEBRA_OK;
1664 }
1665
1666 void print_rec_keys(ZebraHandle zh, zebra_rec_keys_t reckeys)
1667 {
1668     yaz_log(YLOG_LOG, "print_rec_keys");
1669     if (zebra_rec_keys_rewind(reckeys))
1670     {
1671         const char *str;
1672         size_t slen;
1673         struct it_key key;
1674         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1675         {
1676             char dst_buf[IT_MAX_WORD];
1677             int seqno;
1678             int index_type;
1679             const char *db = 0;
1680             assert(key.len <= 4 && key.len > 2);
1681
1682             zebraExplain_lookup_ord(zh->reg->zei,
1683                                     key.mem[0], &index_type, &db, 0, 0, 0);
1684             
1685             seqno = (int) key.mem[key.len-1];
1686             
1687             zebra_term_untrans(zh, index_type, dst_buf, str);
1688             
1689             yaz_log(YLOG_LOG, "ord=" ZINT_FORMAT " seqno=%d term=%s",
1690                     key.mem[0], seqno, dst_buf); 
1691         }
1692     }
1693 }
1694
1695 void extract_add_index_string (RecWord *p, const char *str, int length)
1696 {
1697     struct it_key key;
1698
1699     ZebraHandle zh = p->extractCtrl->handle;
1700     ZebraExplainInfo zei = zh->reg->zei;
1701     int ch;
1702
1703     if (p->index_name)
1704     {
1705         ch = zebraExplain_lookup_attr_str(zei, p->index_type, p->index_name);
1706         if (ch < 0)
1707             ch = zebraExplain_add_attr_str(zei, p->index_type, p->index_name);
1708     }
1709     else
1710     {
1711 #if NATTR
1712         return;
1713 #else
1714         ch = zebraExplain_lookup_attr_su(zei, p->index_type, 
1715                                          p->attrSet, p->attrUse);
1716         if (ch < 0)
1717             ch = zebraExplain_add_attr_su(zei, p->index_type,
1718                                           p->attrSet, p->attrUse);
1719 #endif
1720     }
1721     key.len = 4;
1722     key.mem[0] = ch;
1723     key.mem[1] = p->record_id;
1724     key.mem[2] = p->section_id;
1725     key.mem[3] = p->seqno;
1726
1727 #if 0
1728     if (1)
1729     {
1730         char strz[80];
1731         int i;
1732
1733         strz[0] = 0;
1734         for (i = 0; i<length && i < 20; i++)
1735             sprintf(strz+strlen(strz), "%02X", str[i] & 0xff);
1736         /* just for debugging .. */
1737         yaz_log(YLOG_LOG, "add: set=%d use=%d "
1738                 "record_id=%lld section_id=%lld seqno=%lld %s",
1739                 p->attrSet, p->attrUse, p->record_id, p->section_id, p->seqno,
1740                 strz);
1741     }
1742 #endif
1743
1744     zebra_rec_keys_write(zh->reg->keys, str, length, &key);
1745 }
1746
1747 #if NATTR
1748 static void extract_add_sort_string (RecWord *p, const char *str, int length)
1749 {
1750     struct it_key key;
1751
1752     ZebraHandle zh = p->extractCtrl->handle;
1753     ZebraExplainInfo zei = zh->reg->zei;
1754     int ch;
1755
1756     if (p->index_name)
1757     {
1758         ch = zebraExplain_lookup_attr_str(zei, p->index_type, p->index_name);
1759         if (ch < 0)
1760             ch = zebraExplain_add_attr_str(zei, p->index_type, p->index_name);
1761     }
1762     else
1763     {
1764         return;
1765     }
1766     key.len = 4;
1767     key.mem[0] = ch;
1768     key.mem[1] = p->record_id;
1769     key.mem[2] = p->section_id;
1770     key.mem[3] = p->seqno;
1771
1772     zebra_rec_keys_write(zh->reg->sortKeys, str, length, &key);
1773 }
1774 #else
1775 static void extract_add_sort_string (RecWord *p, const char *str, int length)
1776 {
1777     ZebraHandle zh = p->extractCtrl->handle;
1778     struct sortKeys *sk = &zh->reg->sortKeys;
1779     int off = 0;
1780
1781     while (off < sk->buf_used)
1782     {
1783         int set, use, slen;
1784
1785         off += key_SU_decode(&set, (unsigned char *) sk->buf + off);
1786         off += key_SU_decode(&use, (unsigned char *) sk->buf + off);
1787         off += key_SU_decode(&slen, (unsigned char *) sk->buf + off);
1788         off += slen;
1789         if (p->attrSet == set && p->attrUse == use)
1790             return;
1791     }
1792     assert (off == sk->buf_used);
1793     
1794     if (sk->buf_used + IT_MAX_WORD > sk->buf_max)
1795     {
1796         char *b;
1797         
1798         b = (char *) xmalloc (sk->buf_max += 128000);
1799         if (sk->buf_used > 0)
1800             memcpy (b, sk->buf, sk->buf_used);
1801         xfree (sk->buf);
1802         sk->buf = b;
1803     }
1804     off += key_SU_encode(p->attrSet, sk->buf + off);
1805     off += key_SU_encode(p->attrUse, sk->buf + off);
1806     off += key_SU_encode(length, sk->buf + off);
1807     memcpy (sk->buf + off, str, length);
1808     sk->buf_used = off + length;
1809 }
1810 #endif
1811
1812 void extract_add_string (RecWord *p, const char *string, int length)
1813 {
1814     assert (length > 0);
1815     if (zebra_maps_is_sort (p->zebra_maps, p->index_type))
1816         extract_add_sort_string (p, string, length);
1817     else
1818         extract_add_index_string (p, string, length);
1819 }
1820
1821 static void extract_add_incomplete_field (RecWord *p)
1822 {
1823     const char *b = p->term_buf;
1824     int remain = p->term_len;
1825     const char **map = 0;
1826     
1827     yaz_log(YLOG_DEBUG, "Incomplete field, w='%.*s'", p->term_len, p->term_buf);
1828
1829     if (remain > 0)
1830         map = zebra_maps_input(p->zebra_maps, p->index_type, &b, remain, 0);
1831
1832     while (map)
1833     {
1834         char buf[IT_MAX_WORD+1];
1835         int i, remain;
1836
1837         /* Skip spaces */
1838         while (map && *map && **map == *CHR_SPACE)
1839         {
1840             remain = p->term_len - (b - p->term_buf);
1841             if (remain > 0)
1842                 map = zebra_maps_input(p->zebra_maps, p->index_type, &b,
1843                                        remain, 0);
1844             else
1845                 map = 0;
1846         }
1847         if (!map)
1848             break;
1849         i = 0;
1850         while (map && *map && **map != *CHR_SPACE)
1851         {
1852             const char *cp = *map;
1853
1854             while (i < IT_MAX_WORD && *cp)
1855                 buf[i++] = *(cp++);
1856             remain = p->term_len - (b - p->term_buf);
1857             if (remain > 0)
1858                 map = zebra_maps_input(p->zebra_maps, p->index_type, &b, remain, 0);
1859             else
1860                 map = 0;
1861         }
1862         if (!i)
1863             return;
1864         extract_add_string (p, buf, i);
1865         p->seqno++;
1866     }
1867 }
1868
1869 static void extract_add_complete_field (RecWord *p)
1870 {
1871     const char *b = p->term_buf;
1872     char buf[IT_MAX_WORD+1];
1873     const char **map = 0;
1874     int i = 0, remain = p->term_len;
1875
1876     yaz_log(YLOG_DEBUG, "Complete field, w='%.*s'",
1877             p->term_len, p->term_buf);
1878
1879     if (remain > 0)
1880         map = zebra_maps_input (p->zebra_maps, p->index_type, &b, remain, 1);
1881
1882     while (remain > 0 && i < IT_MAX_WORD)
1883     {
1884         while (map && *map && **map == *CHR_SPACE)
1885         {
1886             remain = p->term_len - (b - p->term_buf);
1887
1888             if (remain > 0)
1889             {
1890                 int first = i ? 0 : 1;  /* first position */
1891                 map = zebra_maps_input(p->zebra_maps, p->index_type, &b, remain, first);
1892             }
1893             else
1894                 map = 0;
1895         }
1896         if (!map)
1897             break;
1898
1899         if (i && i < IT_MAX_WORD)
1900             buf[i++] = *CHR_SPACE;
1901         while (map && *map && **map != *CHR_SPACE)
1902         {
1903             const char *cp = *map;
1904
1905             if (**map == *CHR_CUT)
1906             {
1907                 i = 0;
1908             }
1909             else
1910             {
1911                 if (i >= IT_MAX_WORD)
1912                     break;
1913                 yaz_log(YLOG_DEBUG, "Adding string to index '%d'", **map);
1914                 while (i < IT_MAX_WORD && *cp)
1915                     buf[i++] = *(cp++);
1916             }
1917             remain = p->term_len  - (b - p->term_buf);
1918             if (remain > 0)
1919             {
1920                 map = zebra_maps_input (p->zebra_maps, p->index_type, &b,
1921                                         remain, 0);
1922             }
1923             else
1924                 map = 0;
1925         }
1926     }
1927     if (!i)
1928         return;
1929     extract_add_string (p, buf, i);
1930 }
1931
1932 void extract_token_add (RecWord *p)
1933 {
1934     WRBUF wrbuf;
1935 #if 0
1936     yaz_log (YLOG_LOG, "token_add "
1937              "reg_type=%c attrSet=%d attrUse=%d seqno=%d s=%.*s",
1938              p->reg_type, p->attrSet, p->attrUse, p->seqno, p->length,
1939              p->string);
1940 #endif
1941     if ((wrbuf = zebra_replace(p->zebra_maps, p->index_type, 0,
1942                                p->term_buf, p->term_len)))
1943     {
1944         p->term_buf = wrbuf_buf(wrbuf);
1945         p->term_len = wrbuf_len(wrbuf);
1946     }
1947     if (zebra_maps_is_complete (p->zebra_maps, p->index_type))
1948         extract_add_complete_field (p);
1949     else
1950         extract_add_incomplete_field(p);
1951 }
1952
1953 static void extract_set_store_data_cb(struct recExtractCtrl *p,
1954                                       void *buf, size_t sz)
1955 {
1956     ZebraHandle zh = (ZebraHandle) p->handle;
1957
1958     xfree(zh->store_data_buf);
1959     zh->store_data_buf = 0;
1960     zh->store_data_size = 0;
1961     if (buf && sz)
1962     {
1963         zh->store_data_buf = xmalloc(sz);
1964         zh->store_data_size = sz;
1965         memcpy(zh->store_data_buf, buf, sz);
1966     }
1967 }
1968
1969 static void extract_set_store_data_prepare(struct recExtractCtrl *p)
1970 {
1971     ZebraHandle zh = (ZebraHandle) p->handle;
1972     xfree(zh->store_data_buf);
1973     zh->store_data_buf = 0;
1974     zh->store_data_size = 0;
1975     p->setStoreData = extract_set_store_data_cb;
1976 }
1977
1978 void extract_schema_add (struct recExtractCtrl *p, Odr_oid *oid)
1979 {
1980     ZebraHandle zh = (ZebraHandle) p->handle;
1981     zebraExplain_addSchema (zh->reg->zei, oid);
1982 }
1983
1984 #if NATTR
1985 #error not done yet with zebra_rec_keys_t
1986 void extract_flushSortKeys (ZebraHandle zh, SYSNO sysno,
1987                             int cmd, struct recKeys *reckeys)
1988 {
1989     SortIdx sortIdx = zh->reg->sortIdx;
1990     void *decode_handle = iscz1_start();
1991     int off = 0;
1992     int ch = 0;
1993
1994     while (off < reckeys->buf_used)
1995     {
1996         const char *src = reckeys->buf + off;
1997         struct it_key key;
1998         char *dst = (char*) &key;
1999
2000         iscz1_decode(decode_handle, &dst, &src);
2001         assert(key.len == 4);
2002
2003         ch = (int) key.mem[0];  /* ordinal for field/use/attribute */
2004
2005         sortIdx_type(sortIdx, ch);
2006         if (cmd == 1)
2007             sortIdx_add(sortIdx, src, strlen(src));
2008         else
2009             sortIdx_add(sortIdx, "", 1);
2010         
2011         src += strlen(src);
2012         src++;
2013
2014         off = src - reckeys->buf;
2015     }
2016     assert (off == reckeys->buf_used);
2017     iscz1_stop(decode_handle);
2018 }
2019 #else
2020 void extract_flushSortKeys (ZebraHandle zh, SYSNO sysno,
2021                             int cmd, struct sortKeys *sk)
2022 {
2023     SortIdx sortIdx = zh->reg->sortIdx;
2024     int off = 0;
2025
2026     sortIdx_sysno (sortIdx, sysno);
2027
2028     while (off < sk->buf_used)
2029     {
2030         int set, use, slen;
2031         
2032         off += key_SU_decode(&set, (unsigned char *) sk->buf + off);
2033         off += key_SU_decode(&use, (unsigned char *) sk->buf + off);
2034         off += key_SU_decode(&slen, (unsigned char *) sk->buf + off);
2035         
2036         sortIdx_type(sortIdx, use);
2037         if (cmd == 1)
2038             sortIdx_add(sortIdx, sk->buf + off, slen);
2039         else
2040             sortIdx_add(sortIdx, "", 1);
2041         off += slen;
2042     }
2043 }
2044 #endif
2045
2046 void encode_key_init (struct encode_info *i)
2047 {
2048     i->sysno = 0;
2049     i->seqno = 0;
2050     i->cmd = -1;
2051     i->prevsys=0;
2052     i->prevseq=0;
2053     i->prevcmd=-1;
2054     i->keylen=0;
2055     i->encode_handle = iscz1_start();
2056     i->decode_handle = iscz1_start();
2057 }
2058
2059 #define OLDENCODE 1
2060
2061 #ifdef OLDENCODE
2062 /* this is the old encode_key_write 
2063  * may be deleted once we are confident that the new works
2064  * HL 15-oct-2002
2065  */
2066 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
2067 {
2068     struct it_key key;
2069     char *bp = i->buf, *bp0;
2070     const char *src = (char *) &key;
2071
2072     /* copy term to output buf */
2073     while ((*bp++ = *k++))
2074         ;
2075     /* and copy & align key so we can mangle */
2076     memcpy (&key, k+1, sizeof(struct it_key));  /* *k is insert/delete */
2077
2078 #if 0
2079     /* debugging */
2080     key_logdump_txt(YLOG_LOG, &key, *k ? "i" : "d");
2081 #endif
2082     assert(key.mem[0] >= 0);
2083
2084     bp0 = bp++;
2085     iscz1_encode(i->encode_handle, &bp, &src);
2086
2087     *bp0 = (*k * 128) + bp - bp0 - 1; /* length and insert/delete combined */
2088     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
2089     {
2090         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fwrite");
2091         exit (1);
2092     }
2093
2094 #if 0
2095     /* debugging */
2096     if (1)
2097     {
2098         struct it_key key2;
2099         const char *src = bp0+1;
2100         char *dst = (char*) &key2;
2101         iscz1_decode(i->decode_handle, &dst, &src);
2102
2103         key_logdump_txt(YLOG_LOG, &key2, *k ? "i" : "d");
2104
2105         assert(key2.mem[1]);
2106     }
2107 #endif
2108 }
2109
2110 void encode_key_flush (struct encode_info *i, FILE *outf)
2111
2112     iscz1_stop(i->encode_handle);
2113     iscz1_stop(i->decode_handle);
2114 }
2115
2116 #else
2117
2118 /* new encode_key_write
2119  * The idea is to buffer one more key, and compare them
2120  * If we are going to delete and insert the same key, 
2121  * we may as well not bother. Should make a difference in 
2122  * updates with small modifications (appending to a mbox)
2123  */
2124 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
2125 {
2126     struct it_key key;
2127     char *bp; 
2128
2129     if (*k)  /* first time for new key */
2130     {
2131         bp = i->buf;
2132         while ((*bp++ = *k++))
2133             ;
2134         i->keylen= bp - i->buf -1;    
2135         assert(i->keylen+1+sizeof(struct it_key) < ENCODE_BUFLEN);
2136     }
2137     else
2138     {
2139         bp=i->buf + i->keylen;
2140         *bp++=0;
2141         k++;
2142     }
2143
2144     memcpy (&key, k+1, sizeof(struct it_key));
2145     if (0==i->prevsys) /* no previous filter, fill up */
2146     {
2147         i->prevsys=key.sysno;
2148         i->prevseq=key.seqno;
2149         i->prevcmd=*k;
2150     }
2151     else if ( (i->prevsys==key.sysno) &&
2152               (i->prevseq==key.seqno) &&
2153               (i->prevcmd!=*k) )
2154     { /* same numbers, diff cmd, they cancel out */
2155         i->prevsys=0;
2156     }
2157     else 
2158     { /* different stuff, write previous, move buf */
2159         bp = encode_key_int ( (i->prevsys - i->sysno) * 2 + i->prevcmd, bp);
2160         if (i->sysno != i->prevsys)
2161         {
2162             i->sysno = i->prevsys;
2163             i->seqno = 0;
2164         }
2165         else if (!i->seqno && !i->prevseq && i->cmd == i->prevcmd)
2166         {
2167             return; /* ??? Filters some sort of duplicates away */
2168                     /* ??? Can this ever happen   -H 15oct02 */
2169         }
2170         bp = encode_key_int (i->prevseq - i->seqno, bp);
2171         i->seqno = i->prevseq;
2172         i->cmd = i->prevcmd;
2173         if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
2174         {
2175             yaz_log (YLOG_FATAL|YLOG_ERRNO, "fwrite");
2176             exit (1);
2177         }
2178         i->keylen=0; /* ok, it's written, forget it */
2179         i->prevsys=key.sysno;
2180         i->prevseq=key.seqno;
2181         i->prevcmd=*k;
2182     }
2183 }
2184
2185 void encode_key_flush (struct encode_info *i, FILE *outf)
2186 { /* flush the last key from i */
2187     char *bp =i->buf + i->keylen;
2188     if (0==i->prevsys)
2189     {
2190         return; /* nothing to flush */
2191     }
2192     *bp++=0;
2193     bp = encode_key_int ( (i->prevsys - i->sysno) * 2 + i->prevcmd, bp);
2194     if (i->sysno != i->prevsys)
2195     {
2196         i->sysno = i->prevsys;
2197         i->seqno = 0;
2198     }
2199     else if (!i->seqno && !i->prevseq && i->cmd == i->prevcmd)
2200     {
2201         return; /* ??? Filters some sort of duplicates away */
2202                 /* ??? Can this ever happen   -H 15oct02 */
2203     }
2204     bp = encode_key_int (i->prevseq - i->seqno, bp);
2205     i->seqno = i->prevseq;
2206     i->cmd = i->prevcmd;
2207     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
2208     {
2209         yaz_log (YLOG_FATAL|YLOG_ERRNO, "fwrite");
2210         exit (1);
2211     }
2212     i->keylen=0; /* ok, it's written, forget it */
2213     i->prevsys=0; /* forget the values too */
2214     i->prevseq=0;
2215 }
2216 #endif
2217 /*
2218  * Local variables:
2219  * c-basic-offset: 4
2220  * indent-tabs-mode: nil
2221  * End:
2222  * vim: shiftwidth=4 tabstop=8 expandtab
2223  */
2224