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