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