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