5be148815d0c6c1c593b9f652ef5a71f48211f21
[idzebra-moved-to-github.git] / index / extract.c
1 /* $Id: extract.c,v 1.270 2007-11-30 12:19:08 adam Exp $
2    Copyright (C) 1995-2007
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 this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
21 */
22
23 /** \file
24     \brief indexes records and extract tokens for indexing and sorting
25 */
26
27 #include <stdio.h>
28 #include <assert.h>
29 #include <ctype.h>
30 #ifdef WIN32
31 #include <io.h>
32 #endif
33 #if HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <fcntl.h>
37
38
39 #include "index.h"
40 #include "orddict.h"
41 #include <direntz.h>
42 #include <charmap.h>
43 #include <yaz/snprintf.h>
44
45 static int log_level_extract = 0;
46 static int log_level_details = 0;
47 static int log_level_initialized = 0;
48
49 /* 1 if we use eliminitate identical delete/insert keys */
50 /* eventually this the 0-case code will be removed */
51 #define FLUSH2 1
52
53 void extract_flush_record_keys2(ZebraHandle zh, zint sysno,
54                                 zebra_rec_keys_t ins_keys,
55                                 zint ins_rank,
56                                 zebra_rec_keys_t del_keys,
57                                 zint del_rank);
58
59 static void zebra_init_log_level(void)
60 {
61     if (!log_level_initialized)
62     {
63         log_level_initialized = 1;
64
65         log_level_extract = yaz_log_module_level("extract");
66         log_level_details = yaz_log_module_level("indexdetails");
67     }
68 }
69
70 static void extract_flush_sort_keys(ZebraHandle zh, zint sysno,
71                                     int cmd, zebra_rec_keys_t skp);
72 static void extract_schema_add(struct recExtractCtrl *p, Odr_oid *oid);
73 static void extract_token_add(RecWord *p);
74
75 static void check_log_limit(ZebraHandle zh)
76 {
77     if (zh->records_processed + zh->records_skipped == zh->m_file_verbose_limit)
78     {
79         yaz_log(YLOG_LOG, "More than %d file log entries. Omitting rest",
80                 zh->m_file_verbose_limit);
81     }
82 }
83
84 static void logRecord(ZebraHandle zh)
85 {
86     check_log_limit(zh);
87     ++zh->records_processed;
88     if (!(zh->records_processed % 1000))
89     {
90         yaz_log(YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
91                 ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
92                 zh->records_processed, zh->records_inserted, 
93                 zh->records_updated, zh->records_deleted);
94     }
95 }
96
97 static void init_extractCtrl(ZebraHandle zh, struct recExtractCtrl *ctrl)
98 {
99     ctrl->flagShowRecords = !zh->m_flag_rw;
100 }
101
102
103 static void extract_add_index_string(RecWord *p, 
104                                       zinfo_index_category_t cat,
105                                       const char *str, int length);
106
107 static void extract_set_store_data_prepare(struct recExtractCtrl *p);
108
109 static void extract_init(struct recExtractCtrl *p, RecWord *w)
110 {
111     w->seqno = 1;
112     w->index_name = "any";
113     w->index_type = "w";
114     w->extractCtrl = p;
115     w->record_id = 0;
116     w->section_id = 0;
117     w->segment = 0;
118 }
119
120 struct snip_rec_info {
121     ZebraHandle zh;
122     zebra_snippets *snippets;
123 };
124
125
126 static void snippet_add_complete_field(RecWord *p, int ord,
127                                        zebra_map_t zm)
128 {
129     struct snip_rec_info *h = p->extractCtrl->handle;
130
131     const char *b = p->term_buf;
132     char buf[IT_MAX_WORD+1];
133     const char **map = 0;
134     int i = 0, remain = p->term_len;
135     const char *start = b;
136     const char *last = 0;
137
138     if (remain > 0)
139         map = zebra_maps_input(zm, &b, remain, 1);
140
141     while (remain > 0 && i < IT_MAX_WORD)
142     {
143         while (map && *map && **map == *CHR_SPACE)
144         {
145             remain = p->term_len - (b - p->term_buf);
146
147             if (i == 0)
148                 start = b;  /* set to first non-ws area */
149             if (remain > 0)
150             {
151                 int first = i ? 0 : 1;  /* first position */
152
153                 map = zebra_maps_input(zm, &b, remain, first);
154             }
155             else
156                 map = 0;
157         }
158         if (!map)
159             break;
160
161         if (i && i < IT_MAX_WORD)
162             buf[i++] = *CHR_SPACE;
163         while (map && *map && **map != *CHR_SPACE)
164         {
165             const char *cp = *map;
166
167             if (**map == *CHR_CUT)
168             {
169                 i = 0;
170             }
171             else
172             {
173                 if (i >= IT_MAX_WORD)
174                     break;
175                 while (i < IT_MAX_WORD && *cp)
176                     buf[i++] = *(cp++);
177             }
178             last = b;
179             remain = p->term_len  - (b - p->term_buf);
180             if (remain > 0)
181             {
182                 map = zebra_maps_input(zm, &b, remain, 0);
183             }
184             else
185                 map = 0;
186         }
187     }
188     if (!i)
189         return;
190     if (last && start != last)
191         zebra_snippets_appendn(h->snippets, p->seqno, 0, ord,
192                                start, last - start);
193 }
194
195 static void snippet_add_incomplete_field(RecWord *p, int ord, zebra_map_t zm)
196 {
197     struct snip_rec_info *h = p->extractCtrl->handle;
198     const char *b = p->term_buf;
199     int remain = p->term_len;
200     int first = 1;
201     const char **map = 0;
202     const char *start = b;
203     const char *last = b;
204
205     if (remain > 0)
206         map = zebra_maps_input(zm, &b, remain, 0);
207
208     while (map)
209     {
210         char buf[IT_MAX_WORD+1];
211         int i, remain;
212
213         /* Skip spaces */
214         while (map && *map && **map == *CHR_SPACE)
215         {
216             remain = p->term_len - (b - p->term_buf);
217             last = b;
218             if (remain > 0)
219                 map = zebra_maps_input(zm, &b, remain, 0);
220             else
221                 map = 0;
222         }
223         if (!map)
224             break;
225         if (start != last)
226         {
227             zebra_snippets_appendn(h->snippets, p->seqno, 1, ord,
228                                    start, last - start);
229
230         }
231         start = last;
232
233         i = 0;
234         while (map && *map && **map != *CHR_SPACE)
235         {
236             const char *cp = *map;
237
238             while (i < IT_MAX_WORD && *cp)
239                 buf[i++] = *(cp++);
240             remain = p->term_len - (b - p->term_buf);
241             last = b;
242             if (remain > 0)
243                 map = zebra_maps_input(zm, &b, remain, 0);
244             else
245                 map = 0;
246         }
247         if (!i)
248             return;
249
250         if (first)
251         {   
252             first = 0;
253             if (zebra_maps_is_first_in_field(zm))
254             {
255                 /* first in field marker */
256                 p->seqno++;
257             }
258         }
259         if (start != last)
260             zebra_snippets_appendn(h->snippets, p->seqno, 0, ord,
261                                    start, last - start);
262         start = last;
263         p->seqno++;
264     }
265
266 }
267
268 static void snippet_token_add(RecWord *p)
269 {
270     struct snip_rec_info *h = p->extractCtrl->handle;
271     ZebraHandle zh = h->zh;
272     zebra_map_t zm = zebra_map_get(zh->reg->zebra_maps, p->index_type);
273
274     if (zm && zebra_maps_is_index(zm))
275     {
276         ZebraExplainInfo zei = zh->reg->zei;
277         int ch = zebraExplain_lookup_attr_str(
278             zei, zinfo_index_category_index, p->index_type, p->index_name);
279
280         if (zebra_maps_is_complete(zm))
281             snippet_add_complete_field(p, ch, zm);
282         else
283             snippet_add_incomplete_field(p, ch, zm);
284     }
285 }
286
287 static void snippet_schema_add(
288     struct recExtractCtrl *p, Odr_oid *oid)
289 {
290
291 }
292
293 void extract_snippet(ZebraHandle zh, zebra_snippets *sn,
294                      struct ZebraRecStream *stream,
295                      RecType rt, void *recTypeClientData)
296 {
297     struct recExtractCtrl extractCtrl;
298     struct snip_rec_info info;
299     int r;
300
301     extractCtrl.stream = stream;
302     extractCtrl.first_record = 1;
303     extractCtrl.init = extract_init;
304     extractCtrl.tokenAdd = snippet_token_add;
305     extractCtrl.schemaAdd = snippet_schema_add;
306     assert(zh->reg);
307     assert(zh->reg->dh);
308
309     extractCtrl.dh = zh->reg->dh;
310     
311     info.zh = zh;
312     info.snippets = sn;
313     extractCtrl.handle = &info;
314     extractCtrl.match_criteria[0] = '\0';
315     extractCtrl.staticrank = 0;
316     extractCtrl.action = action_insert;
317     
318     init_extractCtrl(zh, &extractCtrl);
319
320     extractCtrl.setStoreData = 0;
321
322     r = (*rt->extract)(recTypeClientData, &extractCtrl);
323
324 }
325
326 static void searchRecordKey(ZebraHandle zh,
327                             zebra_rec_keys_t reckeys,
328                             const char *index_name,
329                             const char **ws, int ws_length)
330 {
331     int i;
332     int ch = -1;
333     zinfo_index_category_t cat = zinfo_index_category_index;
334
335     for (i = 0; i<ws_length; i++)
336         ws[i] = NULL;
337
338     if (ch < 0)
339         ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, "0", index_name);
340     if (ch < 0)
341         ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, "p", index_name);
342     if (ch < 0)
343         ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, "w", index_name);
344
345     if (ch < 0)
346         return ;
347
348     if (zebra_rec_keys_rewind(reckeys))
349     {
350         zint startSeq = -1;
351         const char *str;
352         size_t slen;
353         struct it_key key;
354         zint seqno;
355         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
356         {
357             assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2);
358
359             seqno = key.mem[key.len-1];
360             
361             if (key.mem[0] == ch)
362             {
363                 zint woff;
364                 
365                 if (startSeq == -1)
366                     startSeq = seqno;
367                 woff = seqno - startSeq;
368                 if (woff >= 0 && woff < ws_length)
369                     ws[woff] = str;
370             }
371         }
372     }
373 }
374
375 #define FILE_MATCH_BLANK "\t "
376
377 static char *get_match_from_spec(ZebraHandle zh,
378                           zebra_rec_keys_t reckeys,
379                           const char *fname, const char *spec)
380 {
381     static char dstBuf[2048];      /* static here ??? */
382     char *dst = dstBuf;
383     const char *s = spec;
384
385     while (1)
386     {
387         for (; *s && strchr(FILE_MATCH_BLANK, *s); s++)
388             ;
389         if (!*s)
390             break;
391         if (*s == '(')
392         {
393             const char *ws[32];
394             char attset_str[64], attname_str[64];
395             int i;
396             int first = 1;
397             
398             for (s++; strchr(FILE_MATCH_BLANK, *s); s++)
399                 ;
400             for (i = 0; *s && *s != ',' && *s != ')' && 
401                      !strchr(FILE_MATCH_BLANK, *s); s++)
402                 if (i+1 < sizeof(attset_str))
403                     attset_str[i++] = *s;
404             attset_str[i] = '\0';
405             
406             for (; strchr(FILE_MATCH_BLANK, *s); s++)
407                 ;
408             if (*s != ',')
409                 strcpy(attname_str, attset_str);
410             else
411             {
412                 for (s++; strchr(FILE_MATCH_BLANK, *s); s++)
413                     ;
414                 for (i = 0; *s && *s != ')' && 
415                          !strchr(FILE_MATCH_BLANK, *s); s++)
416                     if (i+1 < sizeof(attname_str))
417                         attname_str[i++] = *s;
418                 attname_str[i] = '\0';
419             }
420
421             searchRecordKey(zh, reckeys, attname_str, ws, 32);
422
423             if (*s != ')')
424             {
425                 yaz_log(YLOG_WARN, "Missing ) in match criteria %s in group %s",
426                       spec, zh->m_group ? zh->m_group : "none");
427                 return NULL;
428             }
429             s++;
430
431             for (i = 0; i<32; i++)
432                 if (ws[i])
433                 {
434                     if (first)
435                     {
436                         *dst++ = ' ';
437                         first = 0;
438                     }
439                     strcpy(dst, ws[i]);
440                     dst += strlen(ws[i]);
441                 }
442             if (first)
443             {
444                 yaz_log(YLOG_WARN, "Record didn't contain match"
445                       " fields in (%s,%s)", attset_str, attname_str);
446                 return NULL;
447             }
448         }
449         else if (*s == '$')
450         {
451             int spec_len;
452             char special[64];
453             const char *spec_src = NULL;
454             const char *s1 = ++s;
455             while (*s1 && !strchr(FILE_MATCH_BLANK, *s1))
456                 s1++;
457
458             spec_len = s1 - s;
459             if (spec_len > sizeof(special)-1)
460                 spec_len = sizeof(special)-1;
461             memcpy(special, s, spec_len);
462             special[spec_len] = '\0';
463             s = s1;
464
465             if (!strcmp(special, "group"))
466                 spec_src = zh->m_group;
467             else if (!strcmp(special, "database"))
468                 spec_src = zh->basenames[0];
469             else if (!strcmp(special, "filename")) {
470                 spec_src = fname;
471             }
472             else if (!strcmp(special, "type"))
473                 spec_src = zh->m_record_type;
474             else 
475                 spec_src = NULL;
476             if (spec_src)
477             {
478                 strcpy(dst, spec_src);
479                 dst += strlen(spec_src);
480             }
481         }
482         else if (*s == '\"' || *s == '\'')
483         {
484             int stopMarker = *s++;
485             char tmpString[64];
486             int i = 0;
487
488             while (*s && *s != stopMarker)
489             {
490                 if (i+1 < sizeof(tmpString))
491                     tmpString[i++] = *s++;
492             }
493             if (*s)
494                 s++;
495             tmpString[i] = '\0';
496             strcpy(dst, tmpString);
497             dst += strlen(tmpString);
498         }
499         else
500         {
501             yaz_log(YLOG_WARN, "Syntax error in match criteria %s in group %s",
502                   spec, zh->m_group ? zh->m_group : "none");
503             return NULL;
504         }
505         *dst++ = 1;
506     }
507     if (dst == dstBuf)
508     {
509         yaz_log(YLOG_WARN, "No match criteria for record %s in group %s",
510               fname, zh->m_group ? zh->m_group : "none");
511         return NULL;
512     }
513     *dst = '\0';
514     return dstBuf;
515 }
516
517 struct recordLogInfo {
518     const char *fname;
519     int recordOffset;
520     struct recordGroup *rGroup;
521 };
522
523 /** \brief add the always-matches index entry and map to real record ID
524     \param ctrl record control
525     \param record_id custom record ID
526     \param sysno system record ID
527     
528     This function serves two purposes.. It adds the always matches
529     entry and makes a pointer from the custom record ID (if defined)
530     back to the system record ID (sysno)
531     See zebra_recid_to_sysno .
532   */
533 static void all_matches_add(struct recExtractCtrl *ctrl, zint record_id,
534                             zint sysno)
535 {
536     RecWord word;
537     extract_init(ctrl, &word);
538     word.record_id = record_id;
539     /* we use the seqno as placeholder for a way to get back to
540        record database from _ALLRECORDS.. This is used if a custom
541        RECORD was defined */
542     word.seqno = sysno;
543     word.index_name = "_ALLRECORDS";
544     word.index_type = "w";
545
546     extract_add_index_string(&word, zinfo_index_category_alwaysmatches,
547                               "", 0);
548 }
549
550 ZEBRA_RES zebra_extract_records_stream(ZebraHandle zh, 
551                                        struct ZebraRecStream *stream,
552                                        enum zebra_recctrl_action_t action,
553                                        int test_mode, 
554                                        const char *recordType,
555                                        zint *sysno,
556                                        const char *match_criteria,
557                                        const char *fname,
558                                        RecType recType,
559                                        void *recTypeClientData);
560
561
562 ZEBRA_RES zebra_extract_file(ZebraHandle zh, zint *sysno, const char *fname, 
563                              int deleteFlag)
564 {
565     ZEBRA_RES r = ZEBRA_OK;
566     int i, fd;
567     char gprefix[128];
568     char ext[128];
569     char ext_res[128];
570     struct file_read_info *fi = 0;
571     const char *original_record_type = 0;
572     RecType recType;
573     void *recTypeClientData;
574     struct ZebraRecStream stream, *streamp;
575
576     zebra_init_log_level();
577
578     if (!zh->m_group || !*zh->m_group)
579         *gprefix = '\0';
580     else
581         sprintf(gprefix, "%s.", zh->m_group);
582     
583     yaz_log(log_level_extract, "zebra_extract_file %s", fname);
584
585     /* determine file extension */
586     *ext = '\0';
587     for (i = strlen(fname); --i >= 0; )
588         if (fname[i] == '/')
589             break;
590         else if (fname[i] == '.')
591         {
592             strcpy(ext, fname+i+1);
593             break;
594         }
595     /* determine file type - depending on extension */
596     original_record_type = zh->m_record_type;
597     if (!zh->m_record_type)
598     {
599         sprintf(ext_res, "%srecordType.%s", gprefix, ext);
600         zh->m_record_type = res_get(zh->res, ext_res);
601     }
602     if (!zh->m_record_type)
603     {
604         check_log_limit(zh);
605         if (zh->records_processed + zh->records_skipped
606             < zh->m_file_verbose_limit)
607             yaz_log(YLOG_LOG, "? %s", fname);
608         zh->records_skipped++;
609         return 0;
610     }
611     /* determine match criteria */
612     if (!zh->m_record_id)
613     {
614         sprintf(ext_res, "%srecordId.%s", gprefix, ext);
615         zh->m_record_id = res_get(zh->res, ext_res);
616     }
617
618     if (!(recType =
619           recType_byName(zh->reg->recTypes, zh->res, zh->m_record_type,
620                           &recTypeClientData)))
621     {
622         yaz_log(YLOG_WARN, "No such record type: %s", zh->m_record_type);
623         return ZEBRA_FAIL;
624     }
625
626     switch(recType->version)
627     {
628     case 0:
629         break;
630     default:
631         yaz_log(YLOG_WARN, "Bad filter version: %s", zh->m_record_type);
632     }
633     if (sysno && deleteFlag)
634     {
635         streamp = 0;
636         fi = 0;
637     }
638     else
639     {
640         char full_rep[1024];
641
642         if (zh->path_reg && !yaz_is_abspath(fname))
643         {
644             strcpy(full_rep, zh->path_reg);
645             strcat(full_rep, "/");
646             strcat(full_rep, fname);
647         }
648         else
649             strcpy(full_rep, fname);
650         
651         if ((fd = open(full_rep, O_BINARY|O_RDONLY)) == -1)
652         {
653             yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", full_rep);
654             zh->m_record_type = original_record_type;
655             return ZEBRA_FAIL;
656         }
657         streamp = &stream;
658         zebra_create_stream_fd(streamp, fd, 0);
659     }
660     r = zebra_extract_records_stream(zh, streamp,
661                                      deleteFlag ? 
662                                      action_delete : action_update,
663                                      0, /* tst_mode */
664                                      zh->m_record_type,
665                                      sysno,
666                                      0, /*match_criteria */
667                                      fname,
668                                      recType, recTypeClientData);
669     if (streamp)
670         stream.destroy(streamp);
671     zh->m_record_type = original_record_type;
672     return r;
673 }
674
675 /*
676   If sysno is provided, then it's used to identify the reocord.
677   If not, and match_criteria is provided, then sysno is guessed
678   If not, and a record is provided, then sysno is got from there
679   
680  */
681
682 ZEBRA_RES zebra_buffer_extract_record(ZebraHandle zh, 
683                                       const char *buf, size_t buf_size,
684                                       enum zebra_recctrl_action_t action,
685                                       int test_mode, 
686                                       const char *recordType,
687                                       zint *sysno,
688                                       const char *match_criteria,
689                                       const char *fname)
690 {
691     struct ZebraRecStream stream;
692     ZEBRA_RES res;
693     void *clientData;
694     RecType recType = 0;
695
696     if (recordType && *recordType)
697     {
698         yaz_log(log_level_extract,
699                 "Record type explicitly specified: %s", recordType);
700         recType = recType_byName(zh->reg->recTypes, zh->res, recordType,
701                                   &clientData);
702     } 
703     else
704     {
705         if (!(zh->m_record_type))
706         {
707             yaz_log(YLOG_WARN, "No such record type defined");
708             return ZEBRA_FAIL;
709         }
710         yaz_log(log_level_extract, "Get record type from rgroup: %s",
711                 zh->m_record_type);
712         recType = recType_byName(zh->reg->recTypes, zh->res,
713                                   zh->m_record_type, &clientData);
714         recordType = zh->m_record_type;
715     }
716     
717     if (!recType)
718     {
719         yaz_log(YLOG_WARN, "No such record type: %s", recordType);
720         return ZEBRA_FAIL;
721     }
722
723     zebra_create_stream_mem(&stream, buf, buf_size);
724
725     res = zebra_extract_records_stream(zh, &stream,
726                                        action,
727                                        test_mode, 
728                                        recordType,
729                                        sysno,
730                                        match_criteria,
731                                        fname,
732                                        recType, clientData);
733     stream.destroy(&stream);
734     return res;
735 }
736
737 ZEBRA_RES zebra_extract_records_stream(ZebraHandle zh, 
738                                        struct ZebraRecStream *stream,
739                                        enum zebra_recctrl_action_t action,
740                                        int test_mode, 
741                                        const char *recordType,
742                                        zint *sysno,
743                                        const char *match_criteria,
744                                        const char *fname,
745                                        RecType recType,
746                                        void *recTypeClientData)
747 {
748     ZEBRA_RES res = ZEBRA_OK;
749     while (1)
750     {
751         int more = 0;
752         res = zebra_extract_record_stream(zh, stream,
753                                           action,
754                                           test_mode, 
755                                           recordType,
756                                           sysno,
757                                           match_criteria,
758                                           fname,
759                                           recType, recTypeClientData, &more);
760         if (!more)
761         {
762             res = ZEBRA_OK;
763             break;
764         }
765         if (res != ZEBRA_OK)
766             break;
767         if (sysno)
768             break;
769     }
770     return res;
771 }
772
773
774 static WRBUF wrbuf_hex_str(const char *cstr)
775 {
776     size_t i;
777     WRBUF w = wrbuf_alloc();
778     for (i = 0; cstr[i]; i++)
779     {
780         if (cstr[i] < ' ' || cstr[i] > 126)
781             wrbuf_printf(w, "\\%02X", cstr[i] & 0xff);
782         else
783             wrbuf_putc(w, cstr[i]);
784     }
785     return w;
786 }
787
788 ZEBRA_RES zebra_extract_record_stream(ZebraHandle zh, 
789                                       struct ZebraRecStream *stream,
790                                       enum zebra_recctrl_action_t action,
791                                       int test_mode, 
792                                       const char *recordType,
793                                       zint *sysno,
794                                       const char *match_criteria,
795                                       const char *fname,
796                                       RecType recType,
797                                       void *recTypeClientData,
798                                       int *more)
799
800 {
801     zint sysno0 = 0;
802     RecordAttr *recordAttr;
803     struct recExtractCtrl extractCtrl;
804     int r;
805     const char *matchStr = 0;
806     Record rec;
807     off_t start_offset = 0, end_offset = 0;
808     const char *pr_fname = fname;  /* filename to print .. */
809     int show_progress = zh->records_processed + zh->records_skipped 
810         < zh->m_file_verbose_limit ? 1:0;
811
812     zebra_init_log_level();
813
814     if (!pr_fname)
815         pr_fname = "<no file>";  /* make it printable if file is omitted */
816
817     zebra_rec_keys_reset(zh->reg->keys);
818     zebra_rec_keys_reset(zh->reg->sortKeys);
819
820     if (zebraExplain_curDatabase(zh->reg->zei, zh->basenames[0]))
821     {
822         if (zebraExplain_newDatabase(zh->reg->zei, zh->basenames[0], 
823                                       zh->m_explain_database))
824             return ZEBRA_FAIL;
825     }
826
827     if (stream)
828     {
829         off_t null_offset = 0;
830         extractCtrl.stream = stream;
831
832         start_offset = stream->tellf(stream);
833
834         extractCtrl.first_record = start_offset ? 0 : 1;
835         
836         stream->endf(stream, &null_offset);;
837
838         extractCtrl.init = extract_init;
839         extractCtrl.tokenAdd = extract_token_add;
840         extractCtrl.schemaAdd = extract_schema_add;
841         extractCtrl.dh = zh->reg->dh;
842         extractCtrl.handle = zh;
843         extractCtrl.match_criteria[0] = '\0';
844         extractCtrl.staticrank = 0;
845         extractCtrl.action = action;
846
847         init_extractCtrl(zh, &extractCtrl);
848
849         extract_set_store_data_prepare(&extractCtrl);
850         
851         r = (*recType->extract)(recTypeClientData, &extractCtrl);
852
853         if (action == action_update)
854         {
855             action = extractCtrl.action;
856         }
857         
858         switch (r)
859         {
860         case RECCTRL_EXTRACT_EOF:
861             return ZEBRA_FAIL;
862         case RECCTRL_EXTRACT_ERROR_GENERIC:
863             /* error occured during extraction ... */
864             yaz_log(YLOG_WARN, "extract error: generic");
865             return ZEBRA_FAIL;
866         case RECCTRL_EXTRACT_ERROR_NO_SUCH_FILTER:
867             /* error occured during extraction ... */
868             yaz_log(YLOG_WARN, "extract error: no such filter");
869             return ZEBRA_FAIL;
870         case RECCTRL_EXTRACT_SKIP:
871             if (show_progress)
872                 yaz_log(YLOG_LOG, "skip %s %s " ZINT_FORMAT,
873                          recordType, pr_fname, (zint) start_offset);
874             *more = 1;
875             
876             end_offset = stream->endf(stream, 0);
877             if (end_offset)
878                 stream->seekf(stream, end_offset);
879
880             return ZEBRA_OK;
881         case RECCTRL_EXTRACT_OK:
882             break;
883         default:
884             yaz_log(YLOG_WARN, "extract error: unknown error: %d", r);
885             return ZEBRA_FAIL;
886         }
887         end_offset = stream->endf(stream, 0);
888         if (end_offset)
889             stream->seekf(stream, end_offset);
890         else
891             end_offset = stream->tellf(stream);
892
893         if (extractCtrl.match_criteria[0])
894             match_criteria = extractCtrl.match_criteria;
895     }
896
897     *more = 1;
898     if (!sysno)
899     {
900         sysno = &sysno0;
901
902         if (match_criteria && *match_criteria) {
903             matchStr = match_criteria;
904         } else {
905             if (zh->m_record_id && *zh->m_record_id) {
906                 matchStr = get_match_from_spec(zh, zh->reg->keys, pr_fname, 
907                                                zh->m_record_id);
908                 if (!matchStr)
909                 {
910                     yaz_log(YLOG_LOG, "error %s %s " ZINT_FORMAT, recordType,
911                              pr_fname, (zint) start_offset);
912                     return ZEBRA_FAIL;
913                 }
914             }
915         }
916         if (matchStr) 
917         {
918             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
919             char *rinfo = dict_lookup_ord(zh->reg->matchDict, db_ord,
920                                           matchStr);
921
922             
923             if (log_level_extract)
924             {
925                 WRBUF w = wrbuf_hex_str(matchStr);
926                 yaz_log(log_level_extract, "matchStr: %s", wrbuf_cstr(w));
927                 wrbuf_destroy(w);
928             }
929             if (rinfo)
930             {
931                 assert(*rinfo == sizeof(*sysno));
932                 memcpy(sysno, rinfo+1, sizeof(*sysno));
933             }
934        }
935     }
936
937     if (zebra_rec_keys_empty(zh->reg->keys))
938     {
939         /* the extraction process returned no information - the record
940            is probably empty - unless flagShowRecords is in use */
941         if (test_mode)
942             return ZEBRA_OK;
943     }
944
945     if (! *sysno)
946     {
947         /* new record */
948         if (action == action_delete)
949         {
950             yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType,
951                          pr_fname, (zint) start_offset);
952             yaz_log(YLOG_WARN, "cannot delete record above (seems new)");
953             return ZEBRA_FAIL;
954         }
955         else if (action == action_replace)
956         {
957             yaz_log(YLOG_LOG, "update %s %s " ZINT_FORMAT, recordType,
958                          pr_fname, (zint) start_offset);
959             yaz_log(YLOG_WARN, "cannot update record above (seems new)");
960             return ZEBRA_FAIL;
961         }
962         if (show_progress)
963             yaz_log(YLOG_LOG, "add %s %s " ZINT_FORMAT, recordType, pr_fname,
964                      (zint) start_offset);
965         rec = rec_new(zh->reg->records);
966
967         *sysno = rec->sysno;
968
969
970         if (stream)
971         {
972             all_matches_add(&extractCtrl,
973                             zebra_rec_keys_get_custom_record_id(zh->reg->keys),
974                             *sysno);
975         }
976
977
978         recordAttr = rec_init_attr(zh->reg->zei, rec);
979         if (extractCtrl.staticrank < 0)
980         {
981             yaz_log(YLOG_WARN, "Negative staticrank for record. Set to 0");
982             extractCtrl.staticrank = 0;
983         }
984
985         if (matchStr)
986         {
987             int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
988             dict_insert_ord(zh->reg->matchDict, db_ord, matchStr,
989                             sizeof(*sysno), sysno);
990         }
991
992         extract_flush_sort_keys(zh, *sysno, 1, zh->reg->sortKeys);
993 #if FLUSH2
994         extract_flush_record_keys2(zh, *sysno,
995                                    zh->reg->keys, extractCtrl.staticrank,
996                                    0, recordAttr->staticrank);
997 #else
998         extract_flush_record_keys(zh, *sysno, 1, zh->reg->keys,
999                                   extractCtrl.staticrank);
1000 #endif
1001         recordAttr->staticrank = extractCtrl.staticrank;
1002         zh->records_inserted++;
1003     } 
1004     else
1005     {
1006         /* record already exists */
1007         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
1008         zebra_rec_keys_t sortKeys = zebra_rec_keys_open();
1009         if (action == action_insert)
1010         {
1011             yaz_log(YLOG_LOG, "skipped %s %s " ZINT_FORMAT, 
1012                          recordType, pr_fname, (zint) start_offset);
1013             logRecord(zh);
1014             return ZEBRA_FAIL;
1015         }
1016
1017         rec = rec_get(zh->reg->records, *sysno);
1018         assert(rec);
1019
1020         if (stream)
1021         {
1022             all_matches_add(&extractCtrl,
1023                             zebra_rec_keys_get_custom_record_id(zh->reg->keys),
1024                             *sysno);
1025         }
1026         
1027         recordAttr = rec_init_attr(zh->reg->zei, rec);
1028
1029         /* decrease total size */
1030         zebraExplain_recordBytesIncrement(zh->reg->zei,
1031                                            - recordAttr->recordSize);
1032
1033         zebra_rec_keys_set_buf(delkeys,
1034                                rec->info[recInfo_delKeys],
1035                                rec->size[recInfo_delKeys],
1036                                0);
1037         zebra_rec_keys_set_buf(sortKeys,
1038                                rec->info[recInfo_sortKeys],
1039                                rec->size[recInfo_sortKeys],
1040                                0);
1041
1042         extract_flush_sort_keys(zh, *sysno, 0, sortKeys);
1043 #if !FLUSH2
1044         extract_flush_record_keys(zh, *sysno, 0, delkeys,
1045                                   recordAttr->staticrank);
1046 #endif
1047         if (action == action_delete)
1048         {
1049             /* record going to be deleted */
1050 #if FLUSH2
1051             extract_flush_record_keys2(zh, *sysno, 0, recordAttr->staticrank,
1052                                        delkeys, recordAttr->staticrank);
1053 #endif       
1054             if (zebra_rec_keys_empty(delkeys))
1055             {
1056                 yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType,
1057                         pr_fname, (zint) start_offset);
1058                 yaz_log(YLOG_WARN, "cannot delete file above, "
1059                         "storeKeys false (3)");
1060             }
1061             else
1062             {
1063                 if (show_progress)
1064                     yaz_log(YLOG_LOG, "delete %s %s " ZINT_FORMAT, recordType,
1065                             pr_fname, (zint) start_offset);
1066                 zh->records_deleted++;
1067                 if (matchStr)
1068                 {
1069                     int db_ord = zebraExplain_get_database_ord(zh->reg->zei);
1070                     dict_delete_ord(zh->reg->matchDict, db_ord, matchStr);
1071                 }
1072                 rec_del(zh->reg->records, &rec);
1073             }
1074             zebra_rec_keys_close(delkeys);
1075             zebra_rec_keys_close(sortKeys);
1076             rec_free(&rec);
1077             logRecord(zh);
1078             return ZEBRA_OK;
1079         }
1080         else
1081         {   /* update or special_update */
1082             if (show_progress)
1083                 yaz_log(YLOG_LOG, "update %s %s " ZINT_FORMAT, recordType,
1084                         pr_fname, (zint) start_offset);
1085             extract_flush_sort_keys(zh, *sysno, 1, zh->reg->sortKeys);
1086
1087 #if FLUSH2
1088             extract_flush_record_keys2(zh, *sysno,
1089                                        zh->reg->keys, extractCtrl.staticrank,
1090                                        delkeys, recordAttr->staticrank);
1091 #else
1092             extract_flush_record_keys(zh, *sysno, 1, 
1093                                       zh->reg->keys, extractCtrl.staticrank);
1094 #endif
1095             recordAttr->staticrank = extractCtrl.staticrank;
1096             zh->records_updated++;
1097         }
1098         zebra_rec_keys_close(delkeys);
1099         zebra_rec_keys_close(sortKeys);
1100     }
1101     /* update file type */
1102     xfree(rec->info[recInfo_fileType]);
1103     rec->info[recInfo_fileType] =
1104         rec_strdup(recordType, &rec->size[recInfo_fileType]);
1105
1106     /* update filename */
1107     xfree(rec->info[recInfo_filename]);
1108     rec->info[recInfo_filename] =
1109         rec_strdup(fname, &rec->size[recInfo_filename]);
1110
1111     /* update delete keys */
1112     xfree(rec->info[recInfo_delKeys]);
1113     if (!zebra_rec_keys_empty(zh->reg->keys) && zh->m_store_keys == 1)
1114     {
1115         zebra_rec_keys_get_buf(zh->reg->keys,
1116                                &rec->info[recInfo_delKeys],
1117                                &rec->size[recInfo_delKeys]);
1118     }
1119     else
1120     {
1121         rec->info[recInfo_delKeys] = NULL;
1122         rec->size[recInfo_delKeys] = 0;
1123     }
1124     /* update sort keys */
1125     xfree(rec->info[recInfo_sortKeys]);
1126
1127     zebra_rec_keys_get_buf(zh->reg->sortKeys,
1128                            &rec->info[recInfo_sortKeys],
1129                            &rec->size[recInfo_sortKeys]);
1130
1131     if (stream)
1132     {
1133         recordAttr->recordSize = end_offset - start_offset;
1134         zebraExplain_recordBytesIncrement(zh->reg->zei,
1135                                           recordAttr->recordSize);
1136     }
1137
1138     /* set run-number for this record */
1139     recordAttr->runNumber =
1140         zebraExplain_runNumberIncrement(zh->reg->zei, 0);
1141
1142     /* update store data */
1143     xfree(rec->info[recInfo_storeData]);
1144
1145     /* update store data */
1146     if (zh->store_data_buf)
1147     {
1148         rec->size[recInfo_storeData] = zh->store_data_size;
1149         rec->info[recInfo_storeData] = zh->store_data_buf;
1150         zh->store_data_buf = 0;
1151         recordAttr->recordSize = zh->store_data_size;
1152     }
1153     else if (zh->m_store_data)
1154     {
1155         off_t cur_offset = stream->tellf(stream);
1156
1157         rec->size[recInfo_storeData] = recordAttr->recordSize;
1158         rec->info[recInfo_storeData] = (char *)
1159             xmalloc(recordAttr->recordSize);
1160         stream->seekf(stream, start_offset);
1161         stream->readf(stream, rec->info[recInfo_storeData],
1162                       recordAttr->recordSize);
1163         stream->seekf(stream, cur_offset);
1164     }
1165     else
1166     {
1167         rec->info[recInfo_storeData] = NULL;
1168         rec->size[recInfo_storeData] = 0;
1169     }
1170     /* update database name */
1171     xfree(rec->info[recInfo_databaseName]);
1172     rec->info[recInfo_databaseName] =
1173         rec_strdup(zh->basenames[0], &rec->size[recInfo_databaseName]); 
1174
1175     /* update offset */
1176     recordAttr->recordOffset = start_offset;
1177     
1178     /* commit this record */
1179     rec_put(zh->reg->records, &rec);
1180     logRecord(zh);
1181     return ZEBRA_OK;
1182 }
1183
1184 ZEBRA_RES zebra_extract_explain(void *handle, Record rec, data1_node *n)
1185 {
1186     ZebraHandle zh = (ZebraHandle) handle;
1187     struct recExtractCtrl extractCtrl;
1188
1189     if (zebraExplain_curDatabase(zh->reg->zei,
1190                                   rec->info[recInfo_databaseName]))
1191     {
1192         abort();
1193         if (zebraExplain_newDatabase(zh->reg->zei,
1194                                       rec->info[recInfo_databaseName], 0))
1195             abort();
1196     }
1197
1198     zebra_rec_keys_reset(zh->reg->keys);
1199     zebra_rec_keys_reset(zh->reg->sortKeys);
1200
1201     extractCtrl.init = extract_init;
1202     extractCtrl.tokenAdd = extract_token_add;
1203     extractCtrl.schemaAdd = extract_schema_add;
1204     extractCtrl.dh = zh->reg->dh;
1205
1206     init_extractCtrl(zh, &extractCtrl);
1207
1208     extractCtrl.flagShowRecords = 0;
1209     extractCtrl.match_criteria[0] = '\0';
1210     extractCtrl.staticrank = 0;
1211     extractCtrl.action = action_update;
1212
1213     extractCtrl.handle = handle;
1214     extractCtrl.first_record = 1;
1215     
1216     extract_set_store_data_prepare(&extractCtrl);
1217
1218     if (n)
1219         grs_extract_tree(&extractCtrl, n);
1220
1221     if (rec->size[recInfo_delKeys])
1222     {
1223         zebra_rec_keys_t delkeys = zebra_rec_keys_open();
1224         
1225         zebra_rec_keys_t sortkeys = zebra_rec_keys_open();
1226
1227         zebra_rec_keys_set_buf(delkeys, rec->info[recInfo_delKeys],
1228                                rec->size[recInfo_delKeys],
1229                                0);
1230 #if FLUSH2
1231         extract_flush_record_keys2(zh, rec->sysno, 
1232                                    zh->reg->keys, 0, delkeys, 0);
1233 #else
1234         extract_flush_record_keys(zh, rec->sysno, 0, delkeys, 0);
1235         extract_flush_record_keys(zh, rec->sysno, 1, zh->reg->keys, 0);
1236 #endif
1237         zebra_rec_keys_close(delkeys);
1238
1239         zebra_rec_keys_set_buf(sortkeys, rec->info[recInfo_sortKeys],
1240                                rec->size[recInfo_sortKeys],
1241                                0);
1242
1243         extract_flush_sort_keys(zh, rec->sysno, 0, sortkeys);
1244         zebra_rec_keys_close(sortkeys);
1245     }
1246     else
1247     {
1248 #if FLUSH2
1249         extract_flush_record_keys2(zh, rec->sysno, zh->reg->keys, 0, 0, 0);
1250 #else
1251         extract_flush_record_keys(zh, rec->sysno, 1, zh->reg->keys, 0);        
1252 #endif
1253     }
1254     extract_flush_sort_keys(zh, rec->sysno, 1, zh->reg->sortKeys);
1255     
1256     xfree(rec->info[recInfo_delKeys]);
1257     zebra_rec_keys_get_buf(zh->reg->keys,
1258                            &rec->info[recInfo_delKeys], 
1259                            &rec->size[recInfo_delKeys]);
1260
1261     xfree(rec->info[recInfo_sortKeys]);
1262     zebra_rec_keys_get_buf(zh->reg->sortKeys,
1263                            &rec->info[recInfo_sortKeys],
1264                            &rec->size[recInfo_sortKeys]);
1265     return ZEBRA_OK;
1266 }
1267
1268 void extract_rec_keys_log(ZebraHandle zh, int is_insert,
1269                           zebra_rec_keys_t reckeys,
1270                           int level)
1271 {
1272     if (zebra_rec_keys_rewind(reckeys))
1273     {
1274         size_t slen;
1275         const char *str;
1276         struct it_key key;
1277         NMEM nmem = nmem_create();
1278
1279         while(zebra_rec_keys_read(reckeys, &str, &slen, &key))
1280         {
1281             char keystr[200]; /* room for zints to print */
1282             char *dst_term = 0;
1283             int ord = CAST_ZINT_TO_INT(key.mem[0]);
1284             const char *index_type;
1285             int i;
1286             const char *string_index;
1287             
1288             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type,
1289                                     0/* db */, &string_index);
1290             assert(index_type);
1291             zebra_term_untrans_iconv(zh, nmem, index_type,
1292                                      &dst_term, str);
1293             *keystr = '\0';
1294             for (i = 0; i<key.len; i++)
1295             {
1296                 sprintf(keystr + strlen(keystr), ZINT_FORMAT " ", key.mem[i]);
1297             }
1298
1299             if (*str < CHR_BASE_CHAR)
1300             {
1301                 int i;
1302                 char dst_buf[200]; /* room for special chars */
1303
1304                 strcpy(dst_buf , "?");
1305
1306                 if (!strcmp(str, ""))
1307                     strcpy(dst_buf, "alwaysmatches");
1308                 if (!strcmp(str, FIRST_IN_FIELD_STR))
1309                     strcpy(dst_buf, "firstinfield");
1310                 else if (!strcmp(str, CHR_UNKNOWN))
1311                     strcpy(dst_buf, "unknown");
1312                 else if (!strcmp(str, CHR_SPACE))
1313                     strcpy(dst_buf, "space");
1314                 
1315                 for (i = 0; i<slen; i++)
1316                 {
1317                     sprintf(dst_buf + strlen(dst_buf), " %d", str[i] & 0xff);
1318                 }
1319                 yaz_log(level, "%s%s %s %s", keystr, index_type,
1320                         string_index, dst_buf);
1321                 
1322             }
1323             else
1324                 yaz_log(level, "%s%s %s \"%s\"", keystr, index_type,
1325                         string_index, dst_term);
1326
1327             nmem_reset(nmem);
1328         }
1329         nmem_destroy(nmem);
1330     }
1331 }
1332
1333 void extract_rec_keys_adjust(ZebraHandle zh, int is_insert,
1334                              zebra_rec_keys_t reckeys)
1335 {
1336     ZebraExplainInfo zei = zh->reg->zei;
1337     struct ord_stat {
1338         int no;
1339         int ord;
1340         struct ord_stat *next;
1341     };
1342
1343     if (zebra_rec_keys_rewind(reckeys))
1344     {
1345         struct ord_stat *ord_list = 0;
1346         struct ord_stat *p;
1347         size_t slen;
1348         const char *str;
1349         struct it_key key_in;
1350         while(zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1351         {
1352             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
1353
1354             for (p = ord_list; p ; p = p->next)
1355                 if (p->ord == ord)
1356                 {
1357                     p->no++;
1358                     break;
1359                 }
1360             if (!p)
1361             {
1362                 p = xmalloc(sizeof(*p));
1363                 p->no = 1;
1364                 p->ord = ord;
1365                 p->next = ord_list;
1366                 ord_list = p;
1367             }
1368         }
1369
1370         p = ord_list;
1371         while (p)
1372         {
1373             struct ord_stat *p1 = p;
1374
1375             if (is_insert)
1376                 zebraExplain_ord_adjust_occurrences(zei, p->ord, p->no, 1);
1377             else
1378                 zebraExplain_ord_adjust_occurrences(zei, p->ord, - p->no, -1);
1379             p = p->next;
1380             xfree(p1);
1381         }
1382     }
1383 }
1384
1385 void extract_flush_record_keys2(ZebraHandle zh, zint sysno,
1386                                 zebra_rec_keys_t ins_keys, zint ins_rank,
1387                                 zebra_rec_keys_t del_keys, zint del_rank)
1388 {
1389     ZebraExplainInfo zei = zh->reg->zei;
1390     int normal = 0;
1391     int optimized = 0;
1392
1393     if (!zh->reg->key_block)
1394     {
1395         int mem = 1024*1024 * atoi( res_get_def( zh->res, "memmax", "8"));
1396         const char *key_tmp_dir = res_get_def(zh->res, "keyTmpDir", ".");
1397         int use_threads = atoi(res_get_def(zh->res, "threads", "1"));
1398         zh->reg->key_block = key_block_create(mem, key_tmp_dir, use_threads);
1399     }
1400
1401     if (ins_keys)
1402     {
1403         extract_rec_keys_adjust(zh, 1, ins_keys);
1404         if (!del_keys)
1405             zebraExplain_recordCountIncrement(zei, 1);
1406         zebra_rec_keys_rewind(ins_keys);
1407     }
1408     if (del_keys)
1409     {
1410         extract_rec_keys_adjust(zh, 0, del_keys);
1411         if (!ins_keys)
1412             zebraExplain_recordCountIncrement(zei, -1);
1413         zebra_rec_keys_rewind(del_keys);
1414     }
1415
1416     while (1)
1417     {
1418         size_t del_slen;
1419         const char *del_str;
1420         struct it_key del_key_in;
1421         int del = 0;
1422
1423         size_t ins_slen;
1424         const char *ins_str;
1425         struct it_key ins_key_in;
1426         int ins = 0;
1427
1428         if (del_keys)
1429             del = zebra_rec_keys_read(del_keys, &del_str, &del_slen,
1430                                       &del_key_in);
1431         if (ins_keys)
1432             ins = zebra_rec_keys_read(ins_keys, &ins_str, &ins_slen,
1433                                       &ins_key_in);
1434
1435         if (del && ins && ins_rank == del_rank
1436             && !key_compare(&del_key_in, &ins_key_in) 
1437             && ins_slen == del_slen && !memcmp(del_str, ins_str, del_slen))
1438         {
1439             optimized++;
1440             continue;
1441         }
1442         if (!del && !ins)
1443             break;
1444         
1445         normal++;
1446         if (del)
1447             key_block_write(zh->reg->key_block, sysno, 
1448                             &del_key_in, 0, del_str, del_slen,
1449                             del_rank, zh->m_staticrank);
1450         if (ins)
1451             key_block_write(zh->reg->key_block, sysno, 
1452                             &ins_key_in, 1, ins_str, ins_slen,
1453                             ins_rank, zh->m_staticrank);
1454     }
1455     yaz_log(log_level_extract, "normal=%d optimized=%d", normal, optimized);
1456 }
1457
1458
1459 ZEBRA_RES zebra_rec_keys_to_snippets(ZebraHandle zh,
1460                                      zebra_rec_keys_t reckeys,
1461                                      zebra_snippets *snippets)
1462 {
1463     NMEM nmem = nmem_create();
1464     if (zebra_rec_keys_rewind(reckeys)) 
1465     {
1466         const char *str;
1467         size_t slen;
1468         struct it_key key;
1469         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1470         {
1471             char *dst_term = 0;
1472             int ord;
1473             zint seqno;
1474             const char *index_type;
1475
1476             assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2);
1477             seqno = key.mem[key.len-1];
1478             ord = CAST_ZINT_TO_INT(key.mem[0]);
1479             
1480             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type,
1481                                     0/* db */, 0 /* string_index */);
1482             assert(index_type);
1483             zebra_term_untrans_iconv(zh, nmem, index_type,
1484                                      &dst_term, str);
1485             zebra_snippets_append(snippets, seqno, 0, ord, dst_term);
1486             nmem_reset(nmem);
1487         }
1488     }
1489     nmem_destroy(nmem);
1490     return ZEBRA_OK;
1491 }
1492
1493 void print_rec_keys(ZebraHandle zh, zebra_rec_keys_t reckeys)
1494 {
1495     yaz_log(YLOG_LOG, "print_rec_keys");
1496     if (zebra_rec_keys_rewind(reckeys))
1497     {
1498         const char *str;
1499         size_t slen;
1500         struct it_key key;
1501         while (zebra_rec_keys_read(reckeys, &str, &slen, &key))
1502         {
1503             char dst_buf[IT_MAX_WORD];
1504             zint seqno;
1505             const char *index_type;
1506             int ord = CAST_ZINT_TO_INT(key.mem[0]);
1507             const char *db = 0;
1508             assert(key.len <= IT_KEY_LEVEL_MAX && key.len > 2);
1509
1510             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, &db, 0);
1511             
1512             seqno = key.mem[key.len-1];
1513             
1514             zebra_term_untrans(zh, index_type, dst_buf, str);
1515             
1516             yaz_log(YLOG_LOG, "ord=%d seqno=" ZINT_FORMAT 
1517                     " term=%s", ord, seqno, dst_buf); 
1518         }
1519     }
1520 }
1521
1522 static void extract_add_index_string(RecWord *p, zinfo_index_category_t cat,
1523                                      const char *str, int length)
1524 {
1525     struct it_key key;
1526     ZebraHandle zh = p->extractCtrl->handle;
1527     ZebraExplainInfo zei = zh->reg->zei;
1528     int ch, i;
1529
1530     ch = zebraExplain_lookup_attr_str(zei, cat, p->index_type, p->index_name);
1531     if (ch < 0)
1532         ch = zebraExplain_add_attr_str(zei, cat, p->index_type, p->index_name);
1533
1534     i = 0;
1535     key.mem[i++] = ch;
1536     key.mem[i++] = p->record_id;
1537     key.mem[i++] = p->section_id;
1538
1539     if (zh->m_segment_indexing)
1540         key.mem[i++] = p->segment;
1541     key.mem[i++] = p->seqno;
1542     key.len = i;
1543
1544     zebra_rec_keys_write(zh->reg->keys, str, length, &key);
1545 }
1546
1547 static void extract_add_sort_string(RecWord *p, const char *str, int length)
1548 {
1549     struct it_key key;
1550     ZebraHandle zh = p->extractCtrl->handle;
1551     ZebraExplainInfo zei = zh->reg->zei;
1552     int ch;
1553     zinfo_index_category_t cat = zinfo_index_category_sort;
1554
1555     ch = zebraExplain_lookup_attr_str(zei, cat, p->index_type, p->index_name);
1556     if (ch < 0)
1557         ch = zebraExplain_add_attr_str(zei, cat, p->index_type, p->index_name);
1558     key.len = 2;
1559     key.mem[0] = ch;
1560     key.mem[1] = p->record_id;
1561
1562     zebra_rec_keys_write(zh->reg->sortKeys, str, length, &key);
1563 }
1564
1565 static void extract_add_staticrank_string(RecWord *p,
1566                                           const char *str, int length)
1567 {
1568     char valz[40];
1569     struct recExtractCtrl *ctrl = p->extractCtrl;
1570
1571     if (length > sizeof(valz)-1)
1572         length = sizeof(valz)-1;
1573
1574     memcpy(valz, str, length);
1575     valz[length] = '\0';
1576     ctrl->staticrank = atozint(valz);
1577 }
1578
1579 static void extract_add_string(RecWord *p, zebra_map_t zm,
1580                                const char *string, int length)
1581 {
1582     assert(length > 0);
1583
1584     if (!p->index_name)
1585         return;
1586
1587     if (zebra_maps_is_index(zm))
1588     {
1589         extract_add_index_string(p, zinfo_index_category_index,
1590                                  string, length);
1591         if (zebra_maps_is_alwaysmatches(zm))
1592         {
1593             RecWord word;
1594             memcpy(&word, p, sizeof(word));
1595
1596             word.seqno = 1;
1597             extract_add_index_string(
1598                 &word, zinfo_index_category_alwaysmatches, "", 0);
1599         }
1600     }
1601     else if (zebra_maps_is_sort(zm))
1602     {
1603         extract_add_sort_string(p, string, length);
1604     }
1605     else if (zebra_maps_is_staticrank(zm))
1606     {
1607         extract_add_staticrank_string(p, string, length);
1608     }
1609 }
1610
1611 static void extract_add_incomplete_field(RecWord *p, zebra_map_t zm)
1612 {
1613     const char *b = p->term_buf;
1614     int remain = p->term_len;
1615     int first = 1;
1616     const char **map = 0;
1617     
1618     if (remain > 0)
1619         map = zebra_maps_input(zm, &b, remain, 0);
1620
1621     while (map)
1622     {
1623         char buf[IT_MAX_WORD+1];
1624         int i, remain;
1625
1626         /* Skip spaces */
1627         while (map && *map && **map == *CHR_SPACE)
1628         {
1629             remain = p->term_len - (b - p->term_buf);
1630             if (remain > 0)
1631                 map = zebra_maps_input(zm, &b, remain, 0);
1632             else
1633                 map = 0;
1634         }
1635         if (!map)
1636             break;
1637         i = 0;
1638         while (map && *map && **map != *CHR_SPACE)
1639         {
1640             const char *cp = *map;
1641
1642             while (i < IT_MAX_WORD && *cp)
1643                 buf[i++] = *(cp++);
1644             remain = p->term_len - (b - p->term_buf);
1645             if (remain > 0)
1646                 map = zebra_maps_input(zm, &b, remain, 0);
1647             else
1648                 map = 0;
1649         }
1650         if (!i)
1651             return;
1652
1653         if (first)
1654         {   
1655             first = 0;
1656             if (zebra_maps_is_first_in_field(zm))
1657             {
1658                 /* first in field marker */
1659                 extract_add_string(p, zm, FIRST_IN_FIELD_STR, FIRST_IN_FIELD_LEN);
1660                 p->seqno++;
1661             }
1662         }
1663         extract_add_string(p, zm, buf, i);
1664         p->seqno++;
1665     }
1666 }
1667
1668 static void extract_add_complete_field(RecWord *p, zebra_map_t zm)
1669 {
1670     const char *b = p->term_buf;
1671     char buf[IT_MAX_WORD+1];
1672     const char **map = 0;
1673     int i = 0, remain = p->term_len;
1674
1675     if (remain > 0)
1676         map = zebra_maps_input(zm, &b, remain, 1);
1677
1678     while (remain > 0 && i < IT_MAX_WORD)
1679     {
1680         while (map && *map && **map == *CHR_SPACE)
1681         {
1682             remain = p->term_len - (b - p->term_buf);
1683
1684             if (remain > 0)
1685             {
1686                 int first = i ? 0 : 1;  /* first position */
1687                 map = zebra_maps_input(zm, &b, remain, first);
1688             }
1689             else
1690                 map = 0;
1691         }
1692         if (!map)
1693             break;
1694
1695         if (i && i < IT_MAX_WORD)
1696             buf[i++] = *CHR_SPACE;
1697         while (map && *map && **map != *CHR_SPACE)
1698         {
1699             const char *cp = *map;
1700
1701             if (**map == *CHR_CUT)
1702             {
1703                 i = 0;
1704             }
1705             else
1706             {
1707                 if (i >= IT_MAX_WORD)
1708                     break;
1709                 while (i < IT_MAX_WORD && *cp)
1710                     buf[i++] = *(cp++);
1711             }
1712             remain = p->term_len  - (b - p->term_buf);
1713             if (remain > 0)
1714             {
1715                 map = zebra_maps_input(zm, &b, remain, 0);
1716             }
1717             else
1718                 map = 0;
1719         }
1720     }
1721     if (!i)
1722         return;
1723     extract_add_string(p, zm, buf, i);
1724 }
1725
1726 static void extract_add_icu(RecWord *p, zebra_map_t zm)
1727 {
1728     struct it_key key;
1729     const char *res_buf = 0;
1730     size_t res_len = 0;
1731     ZebraHandle zh = p->extractCtrl->handle;
1732     int r = zebra_map_tokenize(zm, p->term_buf, p->term_len,
1733                                &res_buf, &res_len);
1734     int cat = zinfo_index_category_index;
1735     int ch = zebraExplain_lookup_attr_str(zh->reg->zei, cat, p->index_type, p->index_name);
1736     if (ch < 0)
1737         ch = zebraExplain_add_attr_str(zh->reg->zei, cat, p->index_type, p->index_name);
1738     while (r)
1739     {
1740         int i = 0;
1741         key.mem[i++] = ch;
1742         key.mem[i++] = p->record_id;
1743         key.mem[i++] = p->section_id;
1744         
1745         if (zh->m_segment_indexing)
1746             key.mem[i++] = p->segment;
1747         key.mem[i++] = p->seqno;
1748         key.len = i;
1749
1750         zebra_rec_keys_write(zh->reg->keys, res_buf, res_len, &key);
1751         
1752         p->seqno++;
1753         r = zebra_map_tokenize(zm, 0, 0, &res_buf, &res_len);
1754     }
1755 }
1756
1757
1758 /** \brief top-level indexing handler for recctrl system
1759     \param p token data to be indexed
1760
1761     Call sequence:
1762     extract_token
1763     zebra_add_{in}_complete
1764     extract_add_string
1765     
1766     extract_add_index_string
1767     or
1768     extract_add_sort_string
1769     or
1770     extract_add_staticrank_string
1771     
1772 */
1773 static void extract_token_add(RecWord *p)
1774 {
1775     ZebraHandle zh = p->extractCtrl->handle;
1776     zebra_map_t zm = zebra_map_get_or_add(zh->reg->zebra_maps, p->index_type);
1777     WRBUF wrbuf;
1778
1779     if (log_level_details)
1780     {
1781         yaz_log(log_level_details, "extract_token_add "
1782                 "type=%s index=%s seqno=" ZINT_FORMAT " s=%.*s",
1783                 p->index_type, p->index_name, 
1784                 p->seqno, p->term_len, p->term_buf);
1785     }
1786     if ((wrbuf = zebra_replace(zm, 0, p->term_buf, p->term_len)))
1787     {
1788         p->term_buf = wrbuf_buf(wrbuf);
1789         p->term_len = wrbuf_len(wrbuf);
1790     }
1791     if (zebra_maps_is_icu(zm))
1792     {
1793         extract_add_icu(p, zm);
1794     }
1795     else
1796     {
1797         if (zebra_maps_is_complete(zm))
1798             extract_add_complete_field(p, zm);
1799         else
1800             extract_add_incomplete_field(p, zm);
1801     }
1802 }
1803
1804 static void extract_set_store_data_cb(struct recExtractCtrl *p,
1805                                       void *buf, size_t sz)
1806 {
1807     ZebraHandle zh = (ZebraHandle) p->handle;
1808
1809     xfree(zh->store_data_buf);
1810     zh->store_data_buf = 0;
1811     zh->store_data_size = 0;
1812     if (buf && sz)
1813     {
1814         zh->store_data_buf = xmalloc(sz);
1815         zh->store_data_size = sz;
1816         memcpy(zh->store_data_buf, buf, sz);
1817     }
1818 }
1819
1820 static void extract_set_store_data_prepare(struct recExtractCtrl *p)
1821 {
1822     ZebraHandle zh = (ZebraHandle) p->handle;
1823     xfree(zh->store_data_buf);
1824     zh->store_data_buf = 0;
1825     zh->store_data_size = 0;
1826     p->setStoreData = extract_set_store_data_cb;
1827 }
1828
1829 static void extract_schema_add(struct recExtractCtrl *p, Odr_oid *oid)
1830 {
1831     ZebraHandle zh = (ZebraHandle) p->handle;
1832     zebraExplain_addSchema(zh->reg->zei, oid);
1833 }
1834
1835 void extract_flush_sort_keys(ZebraHandle zh, zint sysno,
1836                              int cmd, zebra_rec_keys_t reckeys)
1837 {
1838 #if 0
1839     yaz_log(YLOG_LOG, "extract_flush_sort_keys cmd=%d sysno=" ZINT_FORMAT,
1840             cmd, sysno);
1841     extract_rec_keys_log(zh, cmd, reckeys, YLOG_LOG);
1842 #endif
1843
1844     if (zebra_rec_keys_rewind(reckeys))
1845     {
1846         zebra_sort_index_t si = zh->reg->sort_index;
1847         size_t slen;
1848         const char *str;
1849         struct it_key key_in;
1850
1851         zebra_sort_sysno(si, sysno);
1852
1853         while (zebra_rec_keys_read(reckeys, &str, &slen, &key_in))
1854         {
1855             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
1856             
1857             zebra_sort_type(si, ord);
1858             if (cmd == 1)
1859                 zebra_sort_add(si, str, slen);
1860             else
1861                 zebra_sort_delete(si);
1862         }
1863     }
1864 }
1865
1866 /*
1867  * Local variables:
1868  * c-basic-offset: 4
1869  * indent-tabs-mode: nil
1870  * End:
1871  * vim: shiftwidth=4 tabstop=8 expandtab
1872  */
1873