Make codec routines static
[idzebra-moved-to-github.git] / index / zrpn.c
1 /* $Id: zrpn.c,v 1.139 2004-06-02 12:29:03 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004
3    Index Data Aps
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23
24 #include <stdio.h>
25 #include <assert.h>
26 #ifdef WIN32
27 #include <io.h>
28 #else
29 #include <unistd.h>
30 #endif
31 #include <ctype.h>
32
33 #include "index.h"
34 #include <zebra_xpath.h>
35
36 #include <charmap.h>
37 #include <rstemp.h>
38 #include <rsnull.h>
39 #include <rsbool.h>
40 #include <rsbetween.h>
41
42 struct rpn_char_map_info {
43     ZebraMaps zm;
44     int reg_type;
45 };
46
47 typedef struct {
48     int type;
49     int major;
50     int minor;
51     Z_AttributesPlusTerm *zapt;
52 } AttrType;
53
54
55 static const char **rpn_char_map_handler (void *vp, const char **from, int len)
56 {
57     struct rpn_char_map_info *p = (struct rpn_char_map_info *) vp;
58     const char **out = zebra_maps_input (p->zm, p->reg_type, from, len);
59 #if 0
60     if (out && *out)
61     {
62         const char *outp = *out;
63         yaz_log (LOG_LOG, "---");
64         while (*outp)
65         {
66             yaz_log (LOG_LOG, "%02X", *outp);
67             outp++;
68         }
69     }
70 #endif
71     return out;
72 }
73
74 static void rpn_char_map_prepare (struct zebra_register *reg, int reg_type,
75                                   struct rpn_char_map_info *map_info)
76 {
77     map_info->zm = reg->zebra_maps;
78     map_info->reg_type = reg_type;
79     dict_grep_cmap (reg->dict, map_info, rpn_char_map_handler);
80 }
81
82 static int attr_find_ex (AttrType *src, oid_value *attributeSetP,
83                          const char **string_value)
84 {
85     int num_attributes;
86
87     num_attributes = src->zapt->attributes->num_attributes;
88     while (src->major < num_attributes)
89     {
90         Z_AttributeElement *element;
91
92         element = src->zapt->attributes->attributes[src->major];
93         if (src->type == *element->attributeType)
94         {
95             switch (element->which) 
96             {
97             case Z_AttributeValue_numeric:
98                 ++(src->major);
99                 if (element->attributeSet && attributeSetP)
100                 {
101                     oident *attrset;
102
103                     attrset = oid_getentbyoid (element->attributeSet);
104                     *attributeSetP = attrset->value;
105                 }
106                 return *element->value.numeric;
107                 break;
108             case Z_AttributeValue_complex:
109                 if (src->minor >= element->value.complex->num_list)
110                     break;
111                 if (element->attributeSet && attributeSetP)
112                 {
113                     oident *attrset;
114                     
115                     attrset = oid_getentbyoid (element->attributeSet);
116                     *attributeSetP = attrset->value;
117                 }
118                 if (element->value.complex->list[src->minor]->which ==  
119                     Z_StringOrNumeric_numeric)
120                 {
121                     ++(src->minor);
122                     return
123                         *element->value.complex->list[src->minor-1]->u.numeric;
124                 }
125                 else if (element->value.complex->list[src->minor]->which ==  
126                          Z_StringOrNumeric_string)
127                 {
128                     if (!string_value)
129                         break;
130                     ++(src->minor);
131                     *string_value = 
132                         element->value.complex->list[src->minor-1]->u.string;
133                     return -2;
134                 }
135                 else
136                     break;
137             default:
138                 assert (0);
139             }
140         }
141         ++(src->major);
142     }
143     return -1;
144 }
145
146 static int attr_find (AttrType *src, oid_value *attributeSetP)
147 {
148     return attr_find_ex (src, attributeSetP, 0);
149 }
150
151 static void attr_init (AttrType *src, Z_AttributesPlusTerm *zapt,
152                        int type)
153 {
154     src->zapt = zapt;
155     src->type = type;
156     src->major = 0;
157     src->minor = 0;
158 }
159
160 #define TERM_COUNT        
161        
162 struct grep_info {        
163 #ifdef TERM_COUNT        
164     int *term_no;        
165 #endif        
166     ISAMS_P *isam_p_buf;
167     int isam_p_size;        
168     int isam_p_indx;
169     ZebraHandle zh;
170     int reg_type;
171     ZebraSet termset;
172 };        
173
174 static void term_untrans  (ZebraHandle zh, int reg_type,
175                            char *dst, const char *src)
176 {
177     int len = 0;
178     while (*src)
179     {
180         const char *cp = zebra_maps_output (zh->reg->zebra_maps,
181                                             reg_type, &src);
182         if (!cp && len < IT_MAX_WORD-1)
183             dst[len++] = *src++;
184         else
185             while (*cp && len < IT_MAX_WORD-1)
186                 dst[len++] = *cp++;
187     }
188     dst[len] = '\0';
189 }
190
191 static void add_isam_p (const char *name, const char *info,
192                         struct grep_info *p)
193 {
194     if (p->isam_p_indx == p->isam_p_size)
195     {
196         ISAMS_P *new_isam_p_buf;
197 #ifdef TERM_COUNT        
198         int *new_term_no;        
199 #endif
200         p->isam_p_size = 2*p->isam_p_size + 100;
201         new_isam_p_buf = (ISAMS_P *) xmalloc (sizeof(*new_isam_p_buf) *
202                                              p->isam_p_size);
203         if (p->isam_p_buf)
204         {
205             memcpy (new_isam_p_buf, p->isam_p_buf,
206                     p->isam_p_indx * sizeof(*p->isam_p_buf));
207             xfree (p->isam_p_buf);
208         }
209         p->isam_p_buf = new_isam_p_buf;
210
211 #ifdef TERM_COUNT
212         new_term_no = (int *) xmalloc (sizeof(*new_term_no) *
213                                        p->isam_p_size);
214         if (p->term_no)
215         {
216             memcpy (new_term_no, p->isam_p_buf,
217                     p->isam_p_indx * sizeof(*p->term_no));
218             xfree (p->term_no);
219         }
220         p->term_no = new_term_no;
221 #endif
222     }
223     assert (*info == sizeof(*p->isam_p_buf));
224     memcpy (p->isam_p_buf + p->isam_p_indx, info+1, sizeof(*p->isam_p_buf));
225
226 #if 1
227     if (p->termset)
228     {
229         const char *db;
230         int set, use;
231         char term_tmp[IT_MAX_WORD];
232         int su_code = 0;
233         int len = key_SU_decode (&su_code, name);
234         
235         term_untrans  (p->zh, p->reg_type, term_tmp, name+len+1);
236         logf (LOG_LOG, "grep: %d %c %s", su_code, name[len], term_tmp);
237         zebraExplain_lookup_ord (p->zh->reg->zei,
238                                  su_code, &db, &set, &use);
239         logf (LOG_LOG, "grep:  set=%d use=%d db=%s", set, use, db);
240         
241         resultSetAddTerm (p->zh, p->termset, name[len], db,
242                           set, use, term_tmp);
243     }
244 #endif
245     (p->isam_p_indx)++;
246 }
247
248 static int grep_handle (char *name, const char *info, void *p)
249 {
250     add_isam_p (name, info, (struct grep_info *) p);
251     return 0;
252 }
253
254 static int term_pre (ZebraMaps zebra_maps, int reg_type, const char **src,
255                      const char *ct1, const char *ct2)
256 {
257     const char *s1, *s0 = *src;
258     const char **map;
259
260     /* skip white space */
261     while (*s0)
262     {
263         if (ct1 && strchr (ct1, *s0))
264             break;
265         if (ct2 && strchr (ct2, *s0))
266             break;
267         s1 = s0;
268         map = zebra_maps_input (zebra_maps, reg_type, &s1, strlen(s1));
269         if (**map != *CHR_SPACE)
270             break;
271         s0 = s1;
272     }
273     *src = s0;
274     return *s0;
275 }
276
277 #define REGEX_CHARS " []()|.*+?!"
278
279 /* term_100: handle term, where trunc=none (no operators at all) */
280 static int term_100 (ZebraMaps zebra_maps, int reg_type,
281                      const char **src, char *dst, int space_split,
282                      char *dst_term)
283 {
284     const char *s0, *s1;
285     const char **map;
286     int i = 0;
287     int j = 0;
288
289     const char *space_start = 0;
290     const char *space_end = 0;
291
292     if (!term_pre (zebra_maps, reg_type, src, NULL, NULL))
293         return 0;
294     s0 = *src;
295     while (*s0)
296     {
297         s1 = s0;
298         map = zebra_maps_input (zebra_maps, reg_type, &s0, strlen(s0));
299         if (space_split)
300         {
301             if (**map == *CHR_SPACE)
302                 break;
303         }
304         else  /* complete subfield only. */
305         {
306             if (**map == *CHR_SPACE)
307             {   /* save space mapping for later  .. */
308                 space_start = s1;
309                 space_end = s0;
310                 continue;
311             }
312             else if (space_start)
313             {   /* reload last space */
314                 while (space_start < space_end)
315                 {
316                     if (strchr (REGEX_CHARS, *space_start))
317                         dst[i++] = '\\';
318                     dst_term[j++] = *space_start;
319                     dst[i++] = *space_start++;
320                 }
321                 /* and reset */
322                 space_start = space_end = 0;
323             }
324         }
325         /* add non-space char */
326         while (s1 < s0)
327         {
328             if (strchr(REGEX_CHARS, *s1))
329                 dst[i++] = '\\';
330             dst_term[j++] = *s1;
331             dst[i++] = *s1++;
332         }
333     }
334     dst[i] = '\0';
335     dst_term[j] = '\0';
336     *src = s0;
337     return i;
338 }
339
340 /* term_101: handle term, where trunc=Process # */
341 static int term_101 (ZebraMaps zebra_maps, int reg_type,
342                      const char **src, char *dst, int space_split,
343                      char *dst_term)
344 {
345     const char *s0, *s1;
346     const char **map;
347     int i = 0;
348     int j = 0;
349
350     if (!term_pre (zebra_maps, reg_type, src, "#", "#"))
351         return 0;
352     s0 = *src;
353     while (*s0)
354     {
355         if (*s0 == '#')
356         {
357             dst[i++] = '.';
358             dst[i++] = '*';
359             dst_term[j++] = *s0++;
360         }
361         else
362         {
363             s1 = s0;
364             map = zebra_maps_input (zebra_maps, reg_type, &s0, strlen(s0));
365             if (space_split && **map == *CHR_SPACE)
366                 break;
367             while (s1 < s0)
368             {
369                 if (strchr(REGEX_CHARS, *s1))
370                     dst[i++] = '\\';
371                 dst_term[j++] = *s1;
372                 dst[i++] = *s1++;
373             }
374         }
375     }
376     dst[i] = '\0';
377     dst_term[j++] = '\0';
378     *src = s0;
379     return i;
380 }
381
382 /* term_103: handle term, where trunc=re-2 (regular expressions) */
383 static int term_103 (ZebraMaps zebra_maps, int reg_type, const char **src,
384                      char *dst, int *errors, int space_split,
385                      char *dst_term)
386 {
387     int i = 0;
388     int j = 0;
389     const char *s0, *s1;
390     const char **map;
391
392     if (!term_pre (zebra_maps, reg_type, src, "^\\()[].*+?|", "("))
393         return 0;
394     s0 = *src;
395     if (errors && *s0 == '+' && s0[1] && s0[2] == '+' && s0[3] &&
396         isdigit (s0[1]))
397     {
398         *errors = s0[1] - '0';
399         s0 += 3;
400         if (*errors > 3)
401             *errors = 3;
402     }
403     while (*s0)
404     {
405         if (strchr ("^\\()[].*+?|-", *s0))
406         {
407             dst_term[j++] = *s0;
408             dst[i++] = *s0++;
409         }
410         else
411         {
412             s1 = s0;
413             map = zebra_maps_input (zebra_maps, reg_type, &s0, strlen(s0));
414             if (**map == *CHR_SPACE)
415                 break;
416             while (s1 < s0)
417             {
418                 if (strchr(REGEX_CHARS, *s1))
419                     dst[i++] = '\\';
420                 dst_term[j++] = *s1;
421                 dst[i++] = *s1++;
422             }
423         }
424     }
425     dst[i] = '\0';
426     dst_term[j] = '\0';
427     *src = s0;
428     return i;
429 }
430
431 /* term_103: handle term, where trunc=re-1 (regular expressions) */
432 static int term_102 (ZebraMaps zebra_maps, int reg_type, const char **src,
433                      char *dst, int space_split, char *dst_term)
434 {
435     return term_103 (zebra_maps, reg_type, src, dst, NULL, space_split,
436                      dst_term);
437 }
438
439
440 /* term_104: handle term, where trunc=Process # and ! */
441 static int term_104 (ZebraMaps zebra_maps, int reg_type,
442                      const char **src, char *dst, int space_split,
443                      char *dst_term)
444 {
445     const char *s0, *s1;
446     const char **map;
447     int i = 0;
448     int j = 0;
449
450     if (!term_pre (zebra_maps, reg_type, src, "?*#", "?*#"))
451         return 0;
452     s0 = *src;
453     while (*s0)
454     {
455         if (*s0 == '?')
456         {
457             dst_term[j++] = *s0++;
458             if (*s0 >= '0' && *s0 <= '9')
459             {
460                 int limit = 0;
461                 while (*s0 >= '0' && *s0 <= '9')
462                 {
463                     limit = limit * 10 + (*s0 - '0');
464                     dst_term[j++] = *s0++;
465                 }
466                 if (limit > 20)
467                     limit = 20;
468                 while (--limit >= 0)
469                 {
470                     dst[i++] = '.';
471                     dst[i++] = '?';
472                 }
473             }
474             else
475             {
476                 dst[i++] = '.';
477                 dst[i++] = '*';
478             }
479         }
480         else if (*s0 == '*')
481         {
482             dst[i++] = '.';
483             dst[i++] = '*';
484             dst_term[j++] = *s0++;
485         }
486         else if (*s0 == '#')
487         {
488             dst[i++] = '.';
489             dst_term[j++] = *s0++;
490         }
491         {
492             s1 = s0;
493             map = zebra_maps_input (zebra_maps, reg_type, &s0, strlen(s0));
494             if (space_split && **map == *CHR_SPACE)
495                 break;
496             while (s1 < s0)
497             {
498                 if (strchr(REGEX_CHARS, *s1))
499                     dst[i++] = '\\';
500                 dst_term[j++] = *s1;
501                 dst[i++] = *s1++;
502             }
503         }
504     }
505     dst[i] = '\0';
506     dst_term[j++] = '\0';
507     *src = s0;
508     return i;
509 }
510
511 /* term_105/106: handle term, where trunc=Process * and ! and right trunc */
512 static int term_105 (ZebraMaps zebra_maps, int reg_type,
513                      const char **src, char *dst, int space_split,
514                      char *dst_term, int right_truncate)
515 {
516     const char *s0, *s1;
517     const char **map;
518     int i = 0;
519     int j = 0;
520
521     if (!term_pre (zebra_maps, reg_type, src, "*!", "*!"))
522         return 0;
523     s0 = *src;
524     while (*s0)
525     {
526         if (*s0 == '*')
527         {
528             dst[i++] = '.';
529             dst[i++] = '*';
530             dst_term[j++] = *s0++;
531         }
532         else if (*s0 == '!')
533         {
534             dst[i++] = '.';
535             dst_term[j++] = *s0++;
536         }
537         {
538             s1 = s0;
539             map = zebra_maps_input (zebra_maps, reg_type, &s0, strlen(s0));
540             if (space_split && **map == *CHR_SPACE)
541                 break;
542             while (s1 < s0)
543             {
544                 if (strchr(REGEX_CHARS, *s1))
545                     dst[i++] = '\\';
546                 dst_term[j++] = *s1;
547                 dst[i++] = *s1++;
548             }
549         }
550     }
551     if (right_truncate)
552     {
553         dst[i++] = '.';
554         dst[i++] = '*';
555     }
556     dst[i] = '\0';
557     
558     dst_term[j++] = '\0';
559     *src = s0;
560     return i;
561 }
562
563
564 /* gen_regular_rel - generate regular expression from relation
565  *  val:     border value (inclusive)
566  *  islt:    1 if <=; 0 if >=.
567  */
568 static void gen_regular_rel (char *dst, int val, int islt)
569 {
570     int dst_p;
571     int w, d, i;
572     int pos = 0;
573     char numstr[20];
574
575     logf (LOG_DEBUG, "gen_regular_rel. val=%d, islt=%d", val, islt);
576     if (val >= 0)
577     {
578         if (islt)
579             strcpy (dst, "(-[0-9]+|(");
580         else
581             strcpy (dst, "((");
582     } 
583     else
584     {
585         if (!islt)
586         {
587             strcpy (dst, "([0-9]+|-(");
588             dst_p = strlen (dst);
589             islt = 1;
590         }
591         else
592         {
593             strcpy (dst, "(-(");
594             islt = 0;
595         }
596         val = -val;
597     }
598     dst_p = strlen (dst);
599     sprintf (numstr, "%d", val);
600     for (w = strlen(numstr); --w >= 0; pos++)
601     {
602         d = numstr[w];
603         if (pos > 0)
604         {
605             if (islt)
606             {
607                 if (d == '0')
608                     continue;
609                 d--;
610             } 
611             else
612             {
613                 if (d == '9')
614                     continue;
615                 d++;
616             }
617         }
618         
619         strcpy (dst + dst_p, numstr);
620         dst_p = strlen(dst) - pos - 1;
621
622         if (islt)
623         {
624             if (d != '0')
625             {
626                 dst[dst_p++] = '[';
627                 dst[dst_p++] = '0';
628                 dst[dst_p++] = '-';
629                 dst[dst_p++] = d;
630                 dst[dst_p++] = ']';
631             }
632             else
633                 dst[dst_p++] = d;
634         }
635         else
636         {
637             if (d != '9')
638             { 
639                 dst[dst_p++] = '[';
640                 dst[dst_p++] = d;
641                 dst[dst_p++] = '-';
642                 dst[dst_p++] = '9';
643                 dst[dst_p++] = ']';
644             }
645             else
646                 dst[dst_p++] = d;
647         }
648         for (i = 0; i<pos; i++)
649         {
650             dst[dst_p++] = '[';
651             dst[dst_p++] = '0';
652             dst[dst_p++] = '-';
653             dst[dst_p++] = '9';
654             dst[dst_p++] = ']';
655         }
656         dst[dst_p++] = '|';
657     }
658     dst[dst_p] = '\0';
659     if (islt)
660     {
661         /* match everything less than 10^(pos-1) */
662         strcat (dst, "0*");
663         for (i=1; i<pos; i++)
664             strcat (dst, "[0-9]?");
665     }
666     else
667     {
668         /* match everything greater than 10^pos */
669         for (i = 0; i <= pos; i++)
670             strcat (dst, "[0-9]");
671         strcat (dst, "[0-9]*");
672     }
673     strcat (dst, "))");
674 }
675
676 void string_rel_add_char (char **term_p, const char *src, int *indx)
677 {
678     if (src[*indx] == '\\')
679         *(*term_p)++ = src[(*indx)++];
680     *(*term_p)++ = src[(*indx)++];
681 }
682
683 /*
684  *   >  abc     ([b-].*|a[c-].*|ab[d-].*|abc.+)
685  *              ([^-a].*|a[^-b].*ab[^-c].*|abc.+)
686  *   >= abc     ([b-].*|a[c-].*|ab[c-].*)
687  *              ([^-a].*|a[^-b].*|ab[c-].*)
688  *   <  abc     ([-0].*|a[-a].*|ab[-b].*)
689  *              ([^a-].*|a[^b-].*|ab[^c-].*)
690  *   <= abc     ([-0].*|a[-a].*|ab[-b].*|abc)
691  *              ([^a-].*|a[^b-].*|ab[^c-].*|abc)
692  */
693 static int string_relation (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
694                             const char **term_sub, char *term_dict,
695                             oid_value attributeSet,
696                             int reg_type, int space_split, char *term_dst)
697 {
698     AttrType relation;
699     int relation_value;
700     int i;
701     char *term_tmp = term_dict + strlen(term_dict);
702     char term_component[2*IT_MAX_WORD+20];
703
704     attr_init (&relation, zapt, 2);
705     relation_value = attr_find (&relation, NULL);
706
707     logf (LOG_DEBUG, "string relation value=%d", relation_value);
708     switch (relation_value)
709     {
710     case 1:
711         if (!term_100 (zh->reg->zebra_maps, reg_type,
712                        term_sub, term_component,
713                        space_split, term_dst))
714             return 0;
715         logf (LOG_DEBUG, "Relation <");
716         
717         *term_tmp++ = '(';
718         for (i = 0; term_component[i]; )
719         {
720             int j = 0;
721
722             if (i)
723                 *term_tmp++ = '|';
724             while (j < i)
725                 string_rel_add_char (&term_tmp, term_component, &j);
726
727             *term_tmp++ = '[';
728
729             *term_tmp++ = '^';
730             string_rel_add_char (&term_tmp, term_component, &i);
731             *term_tmp++ = '-';
732
733             *term_tmp++ = ']';
734             *term_tmp++ = '.';
735             *term_tmp++ = '*';
736
737             if ((term_tmp - term_dict) > IT_MAX_WORD)
738                 break;
739         }
740         *term_tmp++ = ')';
741         *term_tmp = '\0';
742         break;
743     case 2:
744         if (!term_100 (zh->reg->zebra_maps, reg_type,
745                        term_sub, term_component,
746                        space_split, term_dst))
747             return 0;
748         logf (LOG_DEBUG, "Relation <=");
749
750         *term_tmp++ = '(';
751         for (i = 0; term_component[i]; )
752         {
753             int j = 0;
754
755             while (j < i)
756                 string_rel_add_char (&term_tmp, term_component, &j);
757             *term_tmp++ = '[';
758
759             *term_tmp++ = '^';
760             string_rel_add_char (&term_tmp, term_component, &i);
761             *term_tmp++ = '-';
762
763             *term_tmp++ = ']';
764             *term_tmp++ = '.';
765             *term_tmp++ = '*';
766
767             *term_tmp++ = '|';
768
769             if ((term_tmp - term_dict) > IT_MAX_WORD)
770                 break;
771         }
772         for (i = 0; term_component[i]; )
773             string_rel_add_char (&term_tmp, term_component, &i);
774         *term_tmp++ = ')';
775         *term_tmp = '\0';
776         break;
777     case 5:
778         if (!term_100 (zh->reg->zebra_maps, reg_type,
779                        term_sub, term_component, space_split, term_dst))
780             return 0;
781         logf (LOG_DEBUG, "Relation >");
782
783         *term_tmp++ = '(';
784         for (i = 0; term_component[i];)
785         {
786             int j = 0;
787
788             while (j < i)
789                 string_rel_add_char (&term_tmp, term_component, &j);
790             *term_tmp++ = '[';
791             
792             *term_tmp++ = '^';
793             *term_tmp++ = '-';
794             string_rel_add_char (&term_tmp, term_component, &i);
795
796             *term_tmp++ = ']';
797             *term_tmp++ = '.';
798             *term_tmp++ = '*';
799
800             *term_tmp++ = '|';
801
802             if ((term_tmp - term_dict) > IT_MAX_WORD)
803                 break;
804         }
805         for (i = 0; term_component[i];)
806             string_rel_add_char (&term_tmp, term_component, &i);
807         *term_tmp++ = '.';
808         *term_tmp++ = '+';
809         *term_tmp++ = ')';
810         *term_tmp = '\0';
811         break;
812     case 4:
813         if (!term_100 (zh->reg->zebra_maps, reg_type, term_sub,
814                        term_component, space_split, term_dst))
815             return 0;
816         logf (LOG_DEBUG, "Relation >=");
817
818         *term_tmp++ = '(';
819         for (i = 0; term_component[i];)
820         {
821             int j = 0;
822
823             if (i)
824                 *term_tmp++ = '|';
825             while (j < i)
826                 string_rel_add_char (&term_tmp, term_component, &j);
827             *term_tmp++ = '[';
828
829             if (term_component[i+1])
830             {
831                 *term_tmp++ = '^';
832                 *term_tmp++ = '-';
833                 string_rel_add_char (&term_tmp, term_component, &i);
834             }
835             else
836             {
837                 string_rel_add_char (&term_tmp, term_component, &i);
838                 *term_tmp++ = '-';
839             }
840             *term_tmp++ = ']';
841             *term_tmp++ = '.';
842             *term_tmp++ = '*';
843
844             if ((term_tmp - term_dict) > IT_MAX_WORD)
845                 break;
846         }
847         *term_tmp++ = ')';
848         *term_tmp = '\0';
849         break;
850     case 3:
851     default:
852         logf (LOG_DEBUG, "Relation =");
853         if (!term_100 (zh->reg->zebra_maps, reg_type, term_sub,
854                        term_component, space_split, term_dst))
855             return 0;
856         strcat (term_tmp, "(");
857         strcat (term_tmp, term_component);
858         strcat (term_tmp, ")");
859     }
860     return 1;
861 }
862
863 static int string_term (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
864                         const char **term_sub, 
865                         oid_value attributeSet, NMEM stream,
866                         struct grep_info *grep_info,
867                         int reg_type, int complete_flag,
868                         int num_bases, char **basenames,
869                         char *term_dst, int xpath_use);
870
871 static RSET term_trunc (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
872                         const char **term_sub, 
873                         oid_value attributeSet, NMEM stream,
874                         struct grep_info *grep_info,
875                         int reg_type, int complete_flag,
876                         int num_bases, char **basenames,
877                         char *term_dst,
878                         const char *rank_type, int xpath_use)
879 {
880     int r;
881     grep_info->isam_p_indx = 0;
882     r = string_term (zh, zapt, term_sub, attributeSet, stream, grep_info,
883                      reg_type, complete_flag, num_bases, basenames,
884                      term_dst, xpath_use);
885     if (r < 1)
886         return 0;
887     logf (LOG_DEBUG, "term: %s", term_dst);
888     return rset_trunc (zh, grep_info->isam_p_buf,
889                        grep_info->isam_p_indx, term_dst,
890                        strlen(term_dst), rank_type, 1 /* preserve pos */,
891                        zapt->term->which);
892 }
893
894
895 static int string_term (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
896                         const char **term_sub, 
897                         oid_value attributeSet, NMEM stream,
898                         struct grep_info *grep_info,
899                         int reg_type, int complete_flag,
900                         int num_bases, char **basenames,
901                         char *term_dst, int xpath_use)
902 {
903     char term_dict[2*IT_MAX_WORD+4000];
904     int j, r, base_no;
905     AttrType truncation;
906     int truncation_value;
907     AttrType use;
908     int use_value;
909     const char *use_string = 0;
910     oid_value curAttributeSet = attributeSet;
911     const char *termp;
912     struct rpn_char_map_info rcmi;
913     int space_split = complete_flag ? 0 : 1;
914
915     int bases_ok = 0;     /* no of databases with OK attribute */
916     int errCode = 0;      /* err code (if any is not OK) */
917     char *errString = 0;  /* addinfo */
918
919     rpn_char_map_prepare (zh->reg, reg_type, &rcmi);
920     attr_init (&use, zapt, 1);
921     use_value = attr_find_ex (&use, &curAttributeSet, &use_string);
922     logf (LOG_DEBUG, "string_term, use value %d", use_value);
923     attr_init (&truncation, zapt, 5);
924     truncation_value = attr_find (&truncation, NULL);
925     logf (LOG_DEBUG, "truncation value %d", truncation_value);
926
927     if (use_value == -1)    /* no attribute - assumy "any" */
928         use_value = 1016;
929     for (base_no = 0; base_no < num_bases; base_no++)
930     {
931         attent attp;
932         data1_local_attribute id_xpath_attr;
933         data1_local_attribute *local_attr;
934         int max_pos, prefix_len = 0;
935
936         termp = *term_sub;
937
938         if (zebraExplain_curDatabase (zh->reg->zei, basenames[base_no]))
939         {
940             zh->errCode = 109; /* Database unavailable */
941             zh->errString = basenames[base_no];
942             return -1;
943         }
944         if (xpath_use > 0 && use_value == -2) 
945         {
946             use_value = xpath_use;
947             attp.local_attributes = &id_xpath_attr;
948             attp.attset_ordinal = VAL_IDXPATH;
949             id_xpath_attr.next = 0;
950             id_xpath_attr.local = use_value;
951         }
952         else if (curAttributeSet == VAL_IDXPATH)
953         {
954             attp.local_attributes = &id_xpath_attr;
955             attp.attset_ordinal = VAL_IDXPATH;
956             id_xpath_attr.next = 0;
957             id_xpath_attr.local = use_value;
958         }
959         else
960         {
961             if ((r=att_getentbyatt (zh, &attp, curAttributeSet, use_value,
962                                             use_string)))
963             {
964                 logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d r=%d",
965                       curAttributeSet, use_value, r);
966                 if (r == -1)
967                 {
968                     /* set was found, but value wasn't defined */
969                     errCode = 114;
970                     if (use_string)
971                         errString = nmem_strdup(stream, use_string);
972                     else
973                     {
974                         char val_str[32];
975                         sprintf (val_str, "%d", use_value);
976                         errString = nmem_strdup (stream, val_str);
977                     }
978                 }
979                 else
980                 {
981                     int oid[OID_SIZE];
982                     struct oident oident;
983                     
984                     oident.proto = PROTO_Z3950;
985                     oident.oclass = CLASS_ATTSET;
986                     oident.value = curAttributeSet;
987                     oid_ent_to_oid (&oident, oid);
988                     
989                     errCode = 121;
990                     errString = nmem_strdup (stream, oident.desc);
991                 }
992                 continue;
993             }
994         }
995         for (local_attr = attp.local_attributes; local_attr;
996              local_attr = local_attr->next)
997         {
998             int ord;
999             char ord_buf[32];
1000             int i, ord_len;
1001             
1002             ord = zebraExplain_lookupSU (zh->reg->zei, attp.attset_ordinal,
1003                                          local_attr->local);
1004             if (ord < 0)
1005                 continue;
1006             if (prefix_len)
1007                 term_dict[prefix_len++] = '|';
1008             else
1009                 term_dict[prefix_len++] = '(';
1010             
1011             ord_len = key_SU_encode (ord, ord_buf);
1012             for (i = 0; i<ord_len; i++)
1013             {
1014                 term_dict[prefix_len++] = 1;
1015                 term_dict[prefix_len++] = ord_buf[i];
1016             }
1017         }
1018         if (!prefix_len)
1019         {
1020 #if 1
1021             bases_ok++;
1022 #else
1023             char val_str[32];
1024             sprintf (val_str, "%d", use_value);
1025             errCode = 114;
1026             errString = nmem_strdup (stream, val_str);
1027 #endif
1028             continue;
1029         }
1030         bases_ok++; /* this has OK attributes */
1031
1032         term_dict[prefix_len++] = ')';
1033         term_dict[prefix_len++] = 1;
1034         term_dict[prefix_len++] = reg_type;
1035         logf (LOG_DEBUG, "reg_type = %d", term_dict[prefix_len-1]);
1036         term_dict[prefix_len] = '\0';
1037         j = prefix_len;
1038         switch (truncation_value)
1039         {
1040         case -1:         /* not specified */
1041         case 100:        /* do not truncate */
1042             if (!string_relation (zh, zapt, &termp, term_dict,
1043                                   attributeSet,
1044                                   reg_type, space_split, term_dst))
1045                 return 0;
1046             logf (LOG_LOG, "dict_lookup_grep: %s", term_dict+prefix_len);
1047             r = dict_lookup_grep (zh->reg->dict, term_dict, 0,
1048                                   grep_info, &max_pos, 0, grep_handle);
1049             if (r)
1050                 logf (LOG_WARN, "dict_lookup_grep fail %d", r);
1051             break;
1052         case 1:          /* right truncation */
1053             term_dict[j++] = '(';
1054             if (!term_100 (zh->reg->zebra_maps, reg_type,
1055                            &termp, term_dict + j, space_split, term_dst))
1056                 return 0;
1057             strcat (term_dict, ".*)");
1058             dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1059                               &max_pos, 0, grep_handle);
1060             break;
1061         case 2:          /* keft truncation */
1062             term_dict[j++] = '('; term_dict[j++] = '.'; term_dict[j++] = '*';
1063             if (!term_100 (zh->reg->zebra_maps, reg_type,
1064                            &termp, term_dict + j, space_split, term_dst))
1065                 return 0;
1066             strcat (term_dict, ")");
1067             dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1068                               &max_pos, 0, grep_handle);
1069             break;
1070         case 3:          /* left&right truncation */
1071             term_dict[j++] = '('; term_dict[j++] = '.'; term_dict[j++] = '*';
1072             if (!term_100 (zh->reg->zebra_maps, reg_type,
1073                            &termp, term_dict + j, space_split, term_dst))
1074                 return 0;
1075             strcat (term_dict, ".*)");
1076             dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1077                               &max_pos, 0, grep_handle);
1078             break;
1079             zh->errCode = 120;
1080             return -1;
1081         case 101:        /* process # in term */
1082             term_dict[j++] = '(';
1083             if (!term_101 (zh->reg->zebra_maps, reg_type,
1084                            &termp, term_dict + j, space_split, term_dst))
1085                 return 0;
1086             strcat (term_dict, ")");
1087             r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1088                                   &max_pos, 0, grep_handle);
1089             if (r)
1090                 logf (LOG_WARN, "dict_lookup_grep err, trunc=#: %d", r);
1091             break;
1092         case 102:        /* Regexp-1 */
1093             term_dict[j++] = '(';
1094             if (!term_102 (zh->reg->zebra_maps, reg_type,
1095                            &termp, term_dict + j, space_split, term_dst))
1096                 return 0;
1097             strcat (term_dict, ")");
1098             logf (LOG_DEBUG, "Regexp-1 tolerance=%d", r);
1099             r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1100                                   &max_pos, 0, grep_handle);
1101             if (r)
1102                 logf (LOG_WARN, "dict_lookup_grep err, trunc=regular: %d",
1103                       r);
1104             break;
1105         case 103:       /* Regexp-2 */
1106             r = 1;
1107             term_dict[j++] = '(';
1108             if (!term_103 (zh->reg->zebra_maps, reg_type,
1109                            &termp, term_dict + j, &r, space_split, term_dst))
1110                 return 0;
1111             strcat (term_dict, ")");
1112             logf (LOG_DEBUG, "Regexp-2 tolerance=%d", r);
1113             r = dict_lookup_grep (zh->reg->dict, term_dict, r, grep_info,
1114                                   &max_pos, 2, grep_handle);
1115             if (r)
1116                 logf (LOG_WARN, "dict_lookup_grep err, trunc=eregular: %d",
1117                       r);
1118             break;
1119         case 104:        /* process # and ! in term */
1120             term_dict[j++] = '(';
1121             if (!term_104 (zh->reg->zebra_maps, reg_type,
1122                            &termp, term_dict + j, space_split, term_dst))
1123                 return 0;
1124             strcat (term_dict, ")");
1125             r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1126                                   &max_pos, 0, grep_handle);
1127             if (r)
1128                 logf (LOG_WARN, "dict_lookup_grep err, trunc=#/!: %d", r);
1129             break;
1130         case 105:        /* process * and ! in term */
1131             term_dict[j++] = '(';
1132             if (!term_105 (zh->reg->zebra_maps, reg_type,
1133                            &termp, term_dict + j, space_split, term_dst, 1))
1134                 return 0;
1135             strcat (term_dict, ")");
1136             r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1137                                   &max_pos, 0, grep_handle);
1138             if (r)
1139                 logf (LOG_WARN, "dict_lookup_grep err, trunc=*/!: %d", r);
1140             break;
1141         case 106:        /* process * and ! in term */
1142             term_dict[j++] = '(';
1143             if (!term_105 (zh->reg->zebra_maps, reg_type,
1144                            &termp, term_dict + j, space_split, term_dst, 0))
1145                 return 0;
1146             strcat (term_dict, ")");
1147             r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1148                                   &max_pos, 0, grep_handle);
1149             if (r)
1150                 logf (LOG_WARN, "dict_lookup_grep err, trunc=*/!: %d", r);
1151             break;
1152         }
1153     }
1154     if (!bases_ok)
1155     {
1156         zh->errCode = errCode;
1157         zh->errString = errString;
1158         return -1;
1159     }
1160     *term_sub = termp;
1161     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
1162     return 1;
1163 }
1164
1165
1166 /* convert APT search term to UTF8 */
1167 static int zapt_term_to_utf8 (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1168                               char *termz)
1169 {
1170     size_t sizez;
1171     Z_Term *term = zapt->term;
1172
1173     switch (term->which)
1174     {
1175     case Z_Term_general:
1176         if (zh->iconv_to_utf8 != 0)
1177         {
1178             char *inbuf = term->u.general->buf;
1179             size_t inleft = term->u.general->len;
1180             char *outbuf = termz;
1181             size_t outleft = IT_MAX_WORD-1;
1182             size_t ret;
1183
1184             ret = yaz_iconv(zh->iconv_to_utf8, &inbuf, &inleft,
1185                         &outbuf, &outleft);
1186             if (ret == (size_t)(-1))
1187             {
1188                 ret = yaz_iconv(zh->iconv_to_utf8, 0, 0, 0, 0);
1189                 zh->errCode = 125;
1190                 return -1;
1191             }
1192             *outbuf = 0;
1193         }
1194         else
1195         {
1196             sizez = term->u.general->len;
1197             if (sizez > IT_MAX_WORD-1)
1198                 sizez = IT_MAX_WORD-1;
1199             memcpy (termz, term->u.general->buf, sizez);
1200             termz[sizez] = '\0';
1201         }
1202         break;
1203     case Z_Term_characterString:
1204         sizez = strlen(term->u.characterString);
1205         if (sizez > IT_MAX_WORD-1)
1206             sizez = IT_MAX_WORD-1;
1207         memcpy (termz, term->u.characterString, sizez);
1208         termz[sizez] = '\0';
1209         break;
1210     default:
1211         zh->errCode = 124;
1212         return -1;
1213     }
1214     return 0;
1215 }
1216
1217 /* convert APT SCAN term to internal cmap */
1218 static int trans_scan_term (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1219                             char *termz, int reg_type)
1220 {
1221     char termz0[IT_MAX_WORD];
1222
1223     if (zapt_term_to_utf8(zh, zapt, termz0))
1224         return -1;    /* error */
1225     else
1226     {
1227         const char **map;
1228         const char *cp = (const char *) termz0;
1229         const char *cp_end = cp + strlen(cp);
1230         const char *src;
1231         int i = 0;
1232         const char *space_map = NULL;
1233         int len;
1234             
1235         while ((len = (cp_end - cp)) > 0)
1236         {
1237             map = zebra_maps_input (zh->reg->zebra_maps, reg_type, &cp, len);
1238             if (**map == *CHR_SPACE)
1239                 space_map = *map;
1240             else
1241             {
1242                 if (i && space_map)
1243                     for (src = space_map; *src; src++)
1244                         termz[i++] = *src;
1245                 space_map = NULL;
1246                 for (src = *map; *src; src++)
1247                     termz[i++] = *src;
1248             }
1249         }
1250         termz[i] = '\0';
1251     }
1252     return 0;
1253 }
1254
1255 static RSET rpn_prox (ZebraHandle zh, RSET *rset, int rset_no,
1256                       int ordered, int exclusion, int relation, int distance)
1257 {
1258     int i;
1259     RSFD *rsfd;
1260     int  *more;
1261     struct it_key **buf;
1262     RSET result;
1263     char prox_term[1024];
1264     int length_prox_term = 0;
1265     int min_nn = 10000000;
1266     int term_index;
1267     int term_type = Z_Term_characterString;
1268     const char *flags = NULL;
1269     
1270     rsfd = (RSFD *) xmalloc (sizeof(*rsfd)*rset_no);
1271     more = (int *) xmalloc (sizeof(*more)*rset_no);
1272     buf = (struct it_key **) xmalloc (sizeof(*buf)*rset_no);
1273
1274     *prox_term = '\0';
1275     for (i = 0; i<rset_no; i++)
1276     {
1277         int j;
1278         for (j = 0; j<rset[i]->no_rset_terms; j++)
1279         {
1280             const char *nflags = rset[i]->rset_terms[j]->flags;
1281             char *term = rset[i]->rset_terms[j]->name;
1282             int lterm = strlen(term);
1283             if (lterm + length_prox_term < sizeof(prox_term)-1)
1284             {
1285                 if (length_prox_term)
1286                     prox_term[length_prox_term++] = ' ';
1287                 strcpy (prox_term + length_prox_term, term);
1288                 length_prox_term += lterm;
1289             }
1290             if (min_nn > rset[i]->rset_terms[j]->nn)
1291                 min_nn = rset[i]->rset_terms[j]->nn;
1292             flags = nflags;
1293             term_type = rset[i]->rset_terms[j]->type;
1294
1295             /* only if all term types are of type characterString .. */
1296             /* the resulting term is of that type */
1297             if (term_type != Z_Term_characterString)
1298                 term_type = Z_Term_general;
1299         }
1300     }
1301     for (i = 0; i<rset_no; i++)
1302     {
1303         buf[i] = 0;
1304         rsfd[i] = 0;
1305     }
1306     for (i = 0; i<rset_no; i++)
1307     {
1308         buf[i] = (struct it_key *) xmalloc (sizeof(**buf));
1309         rsfd[i] = rset_open (rset[i], RSETF_READ);
1310         if (!(more[i] = rset_read (rset[i], rsfd[i], buf[i], &term_index)))
1311             break;
1312     }
1313     if (i != rset_no)
1314     {
1315         /* at least one is empty ... return null set */
1316         rset_null_parms parms;
1317         
1318         parms.rset_term = rset_term_create (prox_term, length_prox_term,
1319                                             flags, term_type);
1320         parms.rset_term->nn = 0;
1321         result = rset_create (rset_kind_null, &parms);
1322     }
1323     else if (ordered && relation == 3 && exclusion == 0 && distance == 1)
1324     {
1325         /* special proximity case = phrase search ... */
1326         rset_temp_parms parms;
1327         RSFD rsfd_result;
1328
1329         parms.rset_term = rset_term_create (prox_term, length_prox_term,
1330                                             flags, term_type);
1331         parms.rset_term->nn = min_nn;
1332         parms.cmp = key_compare_it;
1333         parms.key_size = sizeof (struct it_key);
1334         parms.temp_path = res_get (zh->res, "setTmpDir");
1335         result = rset_create (rset_kind_temp, &parms);
1336         rsfd_result = rset_open (result, RSETF_WRITE);
1337
1338         while (*more)
1339         {
1340             for (i = 1; i<rset_no; i++)
1341             {
1342                 int cmp;
1343                 
1344                 if (!more[i])
1345                 {
1346                     *more = 0;
1347                     break;
1348                 }
1349                 cmp = key_compare_it (buf[i], buf[i-1]);
1350                 if (cmp > 1)
1351                 {
1352                     more[i-1] = rset_read (rset[i-1], rsfd[i-1],
1353                                            buf[i-1], &term_index);
1354                     break;
1355                 }
1356                 else if (cmp == 1)
1357                 {
1358                     if (buf[i-1]->seqno+1 != buf[i]->seqno)
1359                     {
1360                         more[i-1] = rset_read (rset[i-1], rsfd[i-1],
1361                                                buf[i-1], &term_index);
1362                         break;
1363                     }
1364                 }
1365                 else
1366                 {
1367                     more[i] = rset_read (rset[i], rsfd[i], buf[i],
1368                                          &term_index);
1369                     break;
1370                 }
1371             }
1372             if (i == rset_no)
1373             {
1374                 rset_write (result, rsfd_result, buf[0]);
1375                 more[0] = rset_read (*rset, *rsfd, *buf, &term_index);
1376             }
1377         }
1378         rset_close (result, rsfd_result);
1379     }
1380     else if (rset_no == 2)
1381     {
1382         /* generic proximity case (two input sets only) ... */
1383         rset_temp_parms parms;
1384         RSFD rsfd_result;
1385
1386         yaz_log (LOG_LOG, "generic prox, dist=%d, relation=%d, ordered=%d"
1387                           ", exclusion=%d",
1388                           distance, relation, ordered, exclusion);
1389         parms.rset_term = rset_term_create (prox_term, length_prox_term,
1390                                             flags, term_type);
1391         parms.rset_term->nn = min_nn;
1392         parms.cmp = key_compare_it;
1393         parms.key_size = sizeof (struct it_key);
1394         parms.temp_path = res_get (zh->res, "setTmpDir");
1395         result = rset_create (rset_kind_temp, &parms);
1396         rsfd_result = rset_open (result, RSETF_WRITE);
1397
1398         while (more[0] && more[1]) 
1399         {
1400             int cmp = key_compare_it (buf[0], buf[1]);
1401             if (cmp < -1)
1402                 more[0] = rset_read (rset[0], rsfd[0], buf[0], &term_index);
1403             else if (cmp > 1)
1404                 more[1] = rset_read (rset[1], rsfd[1], buf[1], &term_index);
1405             else
1406             {
1407                 int sysno = buf[0]->sysno;
1408                 int seqno[500];
1409                 int n = 0;
1410                 
1411                 seqno[n++] = buf[0]->seqno;
1412                 while ((more[0] = rset_read (rset[0], rsfd[0], buf[0],
1413                                              &term_index)) &&
1414                        sysno == buf[0]->sysno)
1415                     if (n < 500)
1416                         seqno[n++] = buf[0]->seqno;
1417                 do
1418                 {
1419                     for (i = 0; i<n; i++)
1420                     {
1421                         int diff = buf[1]->seqno - seqno[i];
1422                         int excl = exclusion;
1423                         if (!ordered && diff < 0)
1424                             diff = -diff;
1425                         switch (relation)
1426                         {
1427                         case 1:      /* < */
1428                             if (diff < distance && diff >= 0)
1429                                 excl = !excl;
1430                             break;
1431                         case 2:      /* <= */
1432                             if (diff <= distance && diff >= 0)
1433                                 excl = !excl;
1434                             break;
1435                         case 3:      /* == */
1436                             if (diff == distance && diff >= 0)
1437                                 excl = !excl;
1438                             break;
1439                         case 4:      /* >= */
1440                             if (diff >= distance && diff >= 0)
1441                                 excl = !excl;
1442                             break;
1443                         case 5:      /* > */
1444                             if (diff > distance && diff >= 0)
1445                                 excl = !excl;
1446                             break;
1447                         case 6:      /* != */
1448                             if (diff != distance && diff >= 0)
1449                                 excl = !excl;
1450                             break;
1451                         }
1452                         if (excl)
1453                         {
1454                             rset_write (result, rsfd_result, buf[1]);
1455                             break;
1456                         }
1457                     }
1458                 } while ((more[1] = rset_read (rset[1], rsfd[1], buf[1],
1459                                                &term_index)) &&
1460                          sysno == buf[1]->sysno);
1461             }
1462         }
1463         rset_close (result, rsfd_result);
1464     }
1465     else
1466     {
1467         rset_null_parms parms;
1468         
1469         parms.rset_term = rset_term_create (prox_term, length_prox_term,
1470                                             flags, term_type);
1471         parms.rset_term->nn = 0;
1472         result = rset_create (rset_kind_null, &parms);
1473     }
1474     for (i = 0; i<rset_no; i++)
1475     {
1476         if (rsfd[i])
1477             rset_close (rset[i], rsfd[i]);
1478         xfree (buf[i]);
1479     }
1480     xfree (buf);
1481     xfree (more);
1482     xfree (rsfd);
1483     return result;
1484 }
1485
1486
1487 char *normalize_term(ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1488                      const char *termz, NMEM stream, unsigned reg_id)
1489 {
1490     WRBUF wrbuf = 0;
1491     AttrType truncation;
1492     int truncation_value;
1493     char *ex_list = 0;
1494
1495     attr_init (&truncation, zapt, 5);
1496     truncation_value = attr_find (&truncation, NULL);
1497
1498     switch (truncation_value)
1499     {
1500     default:
1501         ex_list = "";
1502         break;
1503     case 101:
1504         ex_list = "#";
1505         break;
1506     case 102:
1507     case 103:
1508         ex_list = 0;
1509         break;
1510     case 104:
1511         ex_list = "!#";
1512         break;
1513     case 105:
1514         ex_list = "!*";
1515         break;
1516     }
1517     if (ex_list)
1518         wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, ex_list,
1519                               termz, strlen(termz));
1520     if (!wrbuf)
1521         return nmem_strdup(stream, termz);
1522     else
1523     {
1524         char *buf = (char*) nmem_malloc (stream, wrbuf_len(wrbuf)+1);
1525         memcpy (buf, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1526         buf[wrbuf_len(wrbuf)] = '\0';
1527         return buf;
1528     }
1529 }
1530
1531 static void grep_info_delete (struct grep_info *grep_info)
1532 {
1533 #ifdef TERM_COUNT
1534     xfree(grep_info->term_no);
1535 #endif
1536     xfree (grep_info->isam_p_buf);
1537 }
1538
1539 static int grep_info_prepare (ZebraHandle zh,
1540                               Z_AttributesPlusTerm *zapt,
1541                               struct grep_info *grep_info,
1542                               int reg_type,
1543                               NMEM stream)
1544 {
1545     AttrType termset;
1546     int termset_value_numeric;
1547     const char *termset_value_string;
1548
1549 #ifdef TERM_COUNT
1550     grep_info->term_no = 0;
1551 #endif
1552     grep_info->isam_p_size = 0;
1553     grep_info->isam_p_buf = NULL;
1554     grep_info->zh = zh;
1555     grep_info->reg_type = reg_type;
1556     grep_info->termset = 0;
1557
1558     if (!zapt)
1559         return 0;
1560     attr_init (&termset, zapt, 8);
1561     termset_value_numeric =
1562         attr_find_ex (&termset, NULL, &termset_value_string);
1563     if (termset_value_numeric != -1)
1564     {
1565         char resname[32];
1566         const char *termset_name = 0;
1567         if (termset_value_numeric != -2)
1568         {
1569     
1570             sprintf (resname, "%d", termset_value_numeric);
1571             termset_name = resname;
1572         }
1573         else
1574             termset_name = termset_value_string;
1575         logf (LOG_LOG, "creating termset set %s", termset_name);
1576         grep_info->termset = resultSetAdd (zh, termset_name, 1);
1577         if (!grep_info->termset)
1578         {
1579             zh->errCode = 128;
1580             zh->errString = nmem_strdup (stream, termset_name);
1581             return -1;
1582         }
1583     }
1584     return 0;
1585 }
1586                                
1587
1588 static RSET rpn_search_APT_phrase (ZebraHandle zh,
1589                                    Z_AttributesPlusTerm *zapt,
1590                                    const char *termz_org,
1591                                    oid_value attributeSet,
1592                                    NMEM stream,
1593                                    int reg_type, int complete_flag,
1594                                    const char *rank_type, int xpath_use,
1595                                    int num_bases, char **basenames)
1596 {
1597     char term_dst[IT_MAX_WORD+1];
1598     RSET rset[60], result;
1599     int i, rset_no = 0;
1600     struct grep_info grep_info;
1601     char *termz = normalize_term(zh, zapt, termz_org, stream, reg_type);
1602     const char *termp = termz;
1603
1604     *term_dst = 0;
1605     if (grep_info_prepare (zh, zapt, &grep_info, reg_type, stream))
1606         return 0;
1607     while (1)
1608     { 
1609         logf (LOG_DEBUG, "APT_phrase termp=%s", termp);
1610         rset[rset_no] = term_trunc (zh, zapt, &termp, attributeSet,
1611                                     stream, &grep_info,
1612                                     reg_type, complete_flag,
1613                                     num_bases, basenames,
1614                                     term_dst, rank_type,
1615                                     xpath_use);
1616         if (!rset[rset_no])
1617             break;
1618         if (++rset_no >= (int) (sizeof(rset)/sizeof(*rset)))
1619             break;
1620     }
1621     grep_info_delete (&grep_info);
1622     if (rset_no == 0)
1623     {
1624         rset_null_parms parms;
1625         
1626         parms.rset_term = rset_term_create (termz, -1, rank_type,
1627                                             zapt->term->which);
1628         return rset_create (rset_kind_null, &parms);
1629     }
1630     else if (rset_no == 1)
1631         return (rset[0]);
1632     result = rpn_prox (zh, rset, rset_no, 1, 0, 3, 1);
1633     for (i = 0; i<rset_no; i++)
1634         rset_delete (rset[i]);
1635     return result;
1636 }
1637
1638 static RSET rpn_search_APT_or_list (ZebraHandle zh,
1639                                     Z_AttributesPlusTerm *zapt,
1640                                     const char *termz_org,
1641                                     oid_value attributeSet,
1642                                     NMEM stream,
1643                                     int reg_type, int complete_flag,
1644                                     const char *rank_type,
1645                                     int xpath_use,
1646                                     int num_bases, char **basenames)
1647 {
1648     char term_dst[IT_MAX_WORD+1];
1649     RSET rset[60], result;
1650     int i, rset_no = 0;
1651     struct grep_info grep_info;
1652     char *termz = normalize_term(zh, zapt, termz_org, stream, reg_type);
1653     const char *termp = termz;
1654
1655     if (grep_info_prepare (zh, zapt, &grep_info, reg_type, stream))
1656         return 0;
1657     while (1)
1658     { 
1659         logf (LOG_DEBUG, "APT_or_list termp=%s", termp);
1660         rset[rset_no] = term_trunc (zh, zapt, &termp, attributeSet,
1661                                     stream, &grep_info,
1662                                     reg_type, complete_flag,
1663                                     num_bases, basenames,
1664                                     term_dst, rank_type,
1665                                     xpath_use);
1666         if (!rset[rset_no])
1667             break;
1668         if (++rset_no >= (int) (sizeof(rset)/sizeof(*rset)))
1669             break;
1670     }
1671     grep_info_delete (&grep_info);
1672     if (rset_no == 0)
1673     {
1674         rset_null_parms parms;
1675         
1676         parms.rset_term = rset_term_create (termz, -1, rank_type,
1677                                             zapt->term->which);
1678         return rset_create (rset_kind_null, &parms);
1679     }
1680     result = rset[0];
1681     for (i = 1; i<rset_no; i++)
1682     {
1683         rset_bool_parms bool_parms;
1684
1685         bool_parms.rset_l = result;
1686         bool_parms.rset_r = rset[i];
1687         bool_parms.key_size = sizeof(struct it_key);
1688         bool_parms.cmp = key_compare_it;
1689         bool_parms.log_item = key_logdump_txt;
1690         result = rset_create (rset_kind_or, &bool_parms);
1691     }
1692     return result;
1693 }
1694
1695 static RSET rpn_search_APT_and_list (ZebraHandle zh,
1696                                      Z_AttributesPlusTerm *zapt,
1697                                      const char *termz_org,
1698                                      oid_value attributeSet,
1699                                      NMEM stream,
1700                                      int reg_type, int complete_flag,
1701                                      const char *rank_type, 
1702                                      int xpath_use,
1703                                      int num_bases, char **basenames)
1704 {
1705     char term_dst[IT_MAX_WORD+1];
1706     RSET rset[60], result;
1707     int i, rset_no = 0;
1708     struct grep_info grep_info;
1709     char *termz = normalize_term(zh, zapt, termz_org, stream, reg_type);
1710     const char *termp = termz;
1711
1712     if (grep_info_prepare (zh, zapt, &grep_info, reg_type, stream))
1713         return 0;
1714     while (1)
1715     { 
1716         logf (LOG_DEBUG, "APT_and_list termp=%s", termp);
1717         rset[rset_no] = term_trunc (zh, zapt, &termp, attributeSet,
1718                                     stream, &grep_info,
1719                                     reg_type, complete_flag,
1720                                     num_bases, basenames,
1721                                     term_dst, rank_type,
1722                                     xpath_use);
1723         if (!rset[rset_no])
1724             break;
1725         assert (rset[rset_no]);
1726         if (++rset_no >= (int) (sizeof(rset)/sizeof(*rset)))
1727             break;
1728     }
1729     grep_info_delete (&grep_info);
1730     if (rset_no == 0)
1731     {
1732         rset_null_parms parms;
1733         
1734         parms.rset_term = rset_term_create (termz, -1, rank_type,
1735                                             zapt->term->which);
1736         return rset_create (rset_kind_null, &parms);
1737     }
1738     result = rset[0];
1739     for (i = 1; i<rset_no; i++)
1740     {
1741         rset_bool_parms bool_parms;
1742
1743         bool_parms.rset_l = result;
1744         bool_parms.rset_r = rset[i];
1745         bool_parms.key_size = sizeof(struct it_key);
1746         bool_parms.cmp = key_compare_it;
1747         bool_parms.log_item = key_logdump_txt;
1748         result = rset_create (rset_kind_and, &bool_parms);
1749     }
1750     return result;
1751 }
1752
1753 static int numeric_relation (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1754                              const char **term_sub,
1755                              char *term_dict,
1756                              oid_value attributeSet,
1757                              struct grep_info *grep_info,
1758                              int *max_pos,
1759                              int reg_type,
1760                              char *term_dst)
1761 {
1762     AttrType relation;
1763     int relation_value;
1764     int term_value;
1765     int r;
1766     char *term_tmp = term_dict + strlen(term_dict);
1767
1768     attr_init (&relation, zapt, 2);
1769     relation_value = attr_find (&relation, NULL);
1770
1771     logf (LOG_DEBUG, "numeric relation value=%d", relation_value);
1772
1773     if (!term_100 (zh->reg->zebra_maps, reg_type, term_sub, term_tmp, 1,
1774                    term_dst))
1775         return 0;
1776     term_value = atoi (term_tmp);
1777     switch (relation_value)
1778     {
1779     case 1:
1780         logf (LOG_DEBUG, "Relation <");
1781         gen_regular_rel (term_tmp, term_value-1, 1);
1782         break;
1783     case 2:
1784         logf (LOG_DEBUG, "Relation <=");
1785         gen_regular_rel (term_tmp, term_value, 1);
1786         break;
1787     case 4:
1788         logf (LOG_DEBUG, "Relation >=");
1789         gen_regular_rel (term_tmp, term_value, 0);
1790         break;
1791     case 5:
1792         logf (LOG_DEBUG, "Relation >");
1793         gen_regular_rel (term_tmp, term_value+1, 0);
1794         break;
1795     case 3:
1796     default:
1797         logf (LOG_DEBUG, "Relation =");
1798         sprintf (term_tmp, "(0*%d)", term_value);
1799     }
1800     logf (LOG_DEBUG, "dict_lookup_grep: %s", term_tmp);
1801     r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info, max_pos,
1802                           0, grep_handle);
1803     if (r)
1804         logf (LOG_WARN, "dict_lookup_grep fail, rel=gt: %d", r);
1805     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
1806     return 1;
1807 }
1808
1809 static int numeric_term (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1810                          const char **term_sub, 
1811                          oid_value attributeSet, struct grep_info *grep_info,
1812                          int reg_type, int complete_flag,
1813                          int num_bases, char **basenames,
1814                          char *term_dst, int xpath_use, NMEM stream)
1815 {
1816     char term_dict[2*IT_MAX_WORD+2];
1817     int r, base_no;
1818     AttrType use;
1819     int use_value;
1820     const char *use_string = 0;
1821     oid_value curAttributeSet = attributeSet;
1822     const char *termp;
1823     struct rpn_char_map_info rcmi;
1824
1825     int bases_ok = 0;     /* no of databases with OK attribute */
1826     int errCode = 0;      /* err code (if any is not OK) */
1827     char *errString = 0;  /* addinfo */
1828
1829     rpn_char_map_prepare (zh->reg, reg_type, &rcmi);
1830     attr_init (&use, zapt, 1);
1831     use_value = attr_find_ex (&use, &curAttributeSet, &use_string);
1832
1833     if (use_value == -1)
1834         use_value = 1016;
1835
1836     for (base_no = 0; base_no < num_bases; base_no++)
1837     {
1838         attent attp;
1839         data1_local_attribute id_xpath_attr;
1840         data1_local_attribute *local_attr;
1841         int max_pos, prefix_len = 0;
1842
1843         termp = *term_sub;
1844         if (use_value == -2)  /* string attribute (assume IDXPATH/any) */
1845         {
1846             use_value = xpath_use;
1847             attp.local_attributes = &id_xpath_attr;
1848             attp.attset_ordinal = VAL_IDXPATH;
1849             id_xpath_attr.next = 0;
1850             id_xpath_attr.local = use_value;
1851         }
1852         else if (curAttributeSet == VAL_IDXPATH)
1853         {
1854             attp.local_attributes = &id_xpath_attr;
1855             attp.attset_ordinal = VAL_IDXPATH;
1856             id_xpath_attr.next = 0;
1857             id_xpath_attr.local = use_value;
1858         }
1859         else
1860         {
1861             if ((r=att_getentbyatt (zh, &attp, curAttributeSet, use_value,
1862                                             use_string)))
1863             {
1864                 logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d r=%d",
1865                       curAttributeSet, use_value, r);
1866                 if (r == -1)
1867                 {
1868                     char val_str[32];
1869                     sprintf (val_str, "%d", use_value);
1870                     errString = nmem_strdup (stream, val_str);
1871                     errCode = 114;
1872                 }
1873                 else
1874                     errCode = 121;
1875                 continue;
1876             }
1877         }
1878         if (zebraExplain_curDatabase (zh->reg->zei, basenames[base_no]))
1879         {
1880             zh->errCode = 109; /* Database unavailable */
1881             zh->errString = basenames[base_no];
1882             return -1;
1883         }
1884         for (local_attr = attp.local_attributes; local_attr;
1885              local_attr = local_attr->next)
1886         {
1887             int ord;
1888             char ord_buf[32];
1889             int i, ord_len;
1890
1891             ord = zebraExplain_lookupSU (zh->reg->zei, attp.attset_ordinal,
1892                                           local_attr->local);
1893             if (ord < 0)
1894                 continue;
1895             if (prefix_len)
1896                 term_dict[prefix_len++] = '|';
1897             else
1898                 term_dict[prefix_len++] = '(';
1899
1900             ord_len = key_SU_encode (ord, ord_buf);
1901             for (i = 0; i<ord_len; i++)
1902             {
1903                 term_dict[prefix_len++] = 1;
1904                 term_dict[prefix_len++] = ord_buf[i];
1905             }
1906         }
1907         if (!prefix_len)
1908         {
1909             char val_str[32];
1910             sprintf (val_str, "%d", use_value);
1911             errCode = 114;
1912             errString = nmem_strdup (stream, val_str);
1913             continue;
1914         }
1915         bases_ok++;
1916         term_dict[prefix_len++] = ')';        
1917         term_dict[prefix_len++] = 1;
1918         term_dict[prefix_len++] = reg_type;
1919         logf (LOG_DEBUG, "reg_type = %d", term_dict[prefix_len-1]);
1920         term_dict[prefix_len] = '\0';
1921         if (!numeric_relation (zh, zapt, &termp, term_dict,
1922                                attributeSet, grep_info, &max_pos, reg_type,
1923                                term_dst))
1924             return 0;
1925     }
1926     if (!bases_ok)
1927     {
1928         zh->errCode = errCode;
1929         zh->errString = errString;
1930         return -1;
1931     }
1932     *term_sub = termp;
1933     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
1934     return 1;
1935 }
1936
1937 static RSET rpn_search_APT_numeric (ZebraHandle zh,
1938                                     Z_AttributesPlusTerm *zapt,
1939                                     const char *termz,
1940                                     oid_value attributeSet,
1941                                     NMEM stream,
1942                                     int reg_type, int complete_flag,
1943                                     const char *rank_type, int xpath_use,
1944                                     int num_bases, char **basenames)
1945 {
1946     char term_dst[IT_MAX_WORD+1];
1947     const char *termp = termz;
1948     RSET rset[60], result;
1949     int i, r, rset_no = 0;
1950     struct grep_info grep_info;
1951
1952     if (grep_info_prepare (zh, zapt, &grep_info, reg_type, stream))
1953         return 0;
1954     while (1)
1955     { 
1956         logf (LOG_DEBUG, "APT_numeric termp=%s", termp);
1957         grep_info.isam_p_indx = 0;
1958         r = numeric_term (zh, zapt, &termp, attributeSet, &grep_info,
1959                           reg_type, complete_flag, num_bases, basenames,
1960                           term_dst, xpath_use,
1961                           stream);
1962         if (r < 1)
1963             break;
1964         logf (LOG_DEBUG, "term: %s", term_dst);
1965         rset[rset_no] = rset_trunc (zh, grep_info.isam_p_buf,
1966                                     grep_info.isam_p_indx, term_dst,
1967                                     strlen(term_dst), rank_type,
1968                                     0 /* preserve position */,
1969                                     zapt->term->which);
1970         assert (rset[rset_no]);
1971         if (++rset_no >= (int) (sizeof(rset)/sizeof(*rset)))
1972             break;
1973     }
1974     grep_info_delete (&grep_info);
1975     if (rset_no == 0)
1976     {
1977         rset_null_parms parms;
1978         
1979         parms.rset_term = rset_term_create (term_dst, -1, rank_type,
1980                                             zapt->term->which);
1981         return rset_create (rset_kind_null, &parms);
1982     }
1983     result = rset[0];
1984     for (i = 1; i<rset_no; i++)
1985     {
1986         rset_bool_parms bool_parms;
1987
1988         bool_parms.rset_l = result;
1989         bool_parms.rset_r = rset[i];
1990         bool_parms.key_size = sizeof(struct it_key);
1991         bool_parms.cmp = key_compare_it;
1992         bool_parms.log_item = key_logdump_txt;
1993         result = rset_create (rset_kind_and, &bool_parms);
1994     }
1995     return result;
1996 }
1997
1998 static RSET rpn_search_APT_local (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1999                                   const char *termz,
2000                                   oid_value attributeSet,
2001                                   NMEM stream,
2002                                   const char *rank_type)
2003 {
2004     RSET result;
2005     RSFD rsfd;
2006     struct it_key key;
2007     rset_temp_parms parms;
2008
2009     parms.rset_term = rset_term_create (termz, -1, rank_type,
2010                                         zapt->term->which);
2011     parms.cmp = key_compare_it;
2012     parms.key_size = sizeof (struct it_key);
2013     parms.temp_path = res_get (zh->res, "setTmpDir");
2014     result = rset_create (rset_kind_temp, &parms);
2015     rsfd = rset_open (result, RSETF_WRITE);
2016
2017     key.sysno = atoi (termz);
2018     key.seqno = 1;
2019     if (key.sysno <= 0)
2020         key.sysno = 1;
2021     rset_write (result, rsfd, &key);
2022     rset_close (result, rsfd);
2023     return result;
2024 }
2025
2026 static RSET rpn_sort_spec (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
2027                            oid_value attributeSet, NMEM stream,
2028                            Z_SortKeySpecList *sort_sequence,
2029                            const char *rank_type)
2030 {
2031     rset_null_parms parms;    
2032     int i;
2033     int sort_relation_value;
2034     AttrType sort_relation_type;
2035     int use_value;
2036     AttrType use_type;
2037     Z_SortKeySpec *sks;
2038     Z_SortKey *sk;
2039     Z_AttributeElement *ae;
2040     int oid[OID_SIZE];
2041     oident oe;
2042     char termz[20];
2043     
2044     attr_init (&sort_relation_type, zapt, 7);
2045     sort_relation_value = attr_find (&sort_relation_type, &attributeSet);
2046
2047     attr_init (&use_type, zapt, 1);
2048     use_value = attr_find (&use_type, &attributeSet);
2049
2050     if (!sort_sequence->specs)
2051     {
2052         sort_sequence->num_specs = 10;
2053         sort_sequence->specs = (Z_SortKeySpec **)
2054             nmem_malloc (stream, sort_sequence->num_specs *
2055                          sizeof(*sort_sequence->specs));
2056         for (i = 0; i<sort_sequence->num_specs; i++)
2057             sort_sequence->specs[i] = 0;
2058     }
2059     if (zapt->term->which != Z_Term_general)
2060         i = 0;
2061     else
2062         i = atoi_n ((char *) zapt->term->u.general->buf,
2063                     zapt->term->u.general->len);
2064     if (i >= sort_sequence->num_specs)
2065         i = 0;
2066     sprintf (termz, "%d", i);
2067
2068     oe.proto = PROTO_Z3950;
2069     oe.oclass = CLASS_ATTSET;
2070     oe.value = attributeSet;
2071     if (!oid_ent_to_oid (&oe, oid))
2072         return 0;
2073
2074     sks = (Z_SortKeySpec *) nmem_malloc (stream, sizeof(*sks));
2075     sks->sortElement = (Z_SortElement *)
2076         nmem_malloc (stream, sizeof(*sks->sortElement));
2077     sks->sortElement->which = Z_SortElement_generic;
2078     sk = sks->sortElement->u.generic = (Z_SortKey *)
2079         nmem_malloc (stream, sizeof(*sk));
2080     sk->which = Z_SortKey_sortAttributes;
2081     sk->u.sortAttributes = (Z_SortAttributes *)
2082         nmem_malloc (stream, sizeof(*sk->u.sortAttributes));
2083
2084     sk->u.sortAttributes->id = oid;
2085     sk->u.sortAttributes->list = (Z_AttributeList *)
2086         nmem_malloc (stream, sizeof(*sk->u.sortAttributes->list));
2087     sk->u.sortAttributes->list->num_attributes = 1;
2088     sk->u.sortAttributes->list->attributes = (Z_AttributeElement **)
2089         nmem_malloc (stream, sizeof(*sk->u.sortAttributes->list->attributes));
2090     ae = *sk->u.sortAttributes->list->attributes = (Z_AttributeElement *)
2091         nmem_malloc (stream, sizeof(**sk->u.sortAttributes->list->attributes));
2092     ae->attributeSet = 0;
2093     ae->attributeType = (int *)
2094         nmem_malloc (stream, sizeof(*ae->attributeType));
2095     *ae->attributeType = 1;
2096     ae->which = Z_AttributeValue_numeric;
2097     ae->value.numeric = (int *)
2098         nmem_malloc (stream, sizeof(*ae->value.numeric));
2099     *ae->value.numeric = use_value;
2100
2101     sks->sortRelation = (int *)
2102         nmem_malloc (stream, sizeof(*sks->sortRelation));
2103     if (sort_relation_value == 1)
2104         *sks->sortRelation = Z_SortKeySpec_ascending;
2105     else if (sort_relation_value == 2)
2106         *sks->sortRelation = Z_SortKeySpec_descending;
2107     else 
2108         *sks->sortRelation = Z_SortKeySpec_ascending;
2109
2110     sks->caseSensitivity = (int *)
2111         nmem_malloc (stream, sizeof(*sks->caseSensitivity));
2112     *sks->caseSensitivity = 0;
2113
2114     sks->which = Z_SortKeySpec_null;
2115     sks->u.null = odr_nullval ();
2116     sort_sequence->specs[i] = sks;
2117
2118     parms.rset_term = rset_term_create (termz, -1, rank_type,
2119                                         zapt->term->which);
2120     return rset_create (rset_kind_null, &parms);
2121 }
2122
2123
2124 static int parse_xpath(ZebraHandle zh, Z_AttributesPlusTerm *zapt,
2125                        oid_value attributeSet,
2126                        struct xpath_location_step *xpath, int max, NMEM mem)
2127 {
2128     oid_value curAttributeSet = attributeSet;
2129     AttrType use;
2130     const char *use_string = 0;
2131     
2132     attr_init (&use, zapt, 1);
2133     attr_find_ex (&use, &curAttributeSet, &use_string);
2134
2135     if (!use_string || *use_string != '/')
2136         return -1;
2137
2138     return zebra_parse_xpath_str(use_string, xpath, max, mem);
2139 }
2140  
2141                
2142
2143 static RSET xpath_trunc(ZebraHandle zh, NMEM stream,
2144                         int reg_type, const char *term, int use,
2145                         oid_value curAttributeSet)
2146 {
2147     RSET rset;
2148     struct grep_info grep_info;
2149     char term_dict[2048];
2150     char ord_buf[32];
2151     int prefix_len = 0;
2152     int ord = zebraExplain_lookupSU (zh->reg->zei, curAttributeSet, use);
2153     int ord_len, i, r, max_pos;
2154     int term_type = Z_Term_characterString;
2155     const char *flags = "void";
2156
2157     if (grep_info_prepare (zh, 0 /* zapt */, &grep_info, '0', stream))
2158     {
2159         rset_null_parms parms;
2160         
2161         parms.rset_term = rset_term_create (term, strlen(term),
2162                                             flags, term_type);
2163         parms.rset_term->nn = 0;
2164         return rset_create (rset_kind_null, &parms);
2165     }
2166
2167     if (ord < 0)
2168     {
2169         rset_null_parms parms;
2170         
2171         parms.rset_term = rset_term_create (term, strlen(term),
2172                                             flags, term_type);
2173         parms.rset_term->nn = 0;
2174         return rset_create (rset_kind_null, &parms);
2175     }
2176     if (prefix_len)
2177         term_dict[prefix_len++] = '|';
2178     else
2179         term_dict[prefix_len++] = '(';
2180     
2181     ord_len = key_SU_encode (ord, ord_buf);
2182     for (i = 0; i<ord_len; i++)
2183     {
2184         term_dict[prefix_len++] = 1;
2185         term_dict[prefix_len++] = ord_buf[i];
2186     }
2187     term_dict[prefix_len++] = ')';
2188     term_dict[prefix_len++] = 1;
2189     term_dict[prefix_len++] = reg_type;
2190     
2191     strcpy (term_dict+prefix_len, term);
2192     
2193     grep_info.isam_p_indx = 0;
2194     r = dict_lookup_grep (zh->reg->dict, term_dict, 0,
2195                           &grep_info, &max_pos, 0, grep_handle);
2196     yaz_log (LOG_LOG, "%s %d positions", term,
2197              grep_info.isam_p_indx);
2198     rset = rset_trunc (zh, grep_info.isam_p_buf,
2199                        grep_info.isam_p_indx, term, strlen(term),
2200                        flags, 1, term_type);
2201     grep_info_delete (&grep_info);
2202     return rset;
2203 }
2204
2205 static RSET rpn_search_xpath (ZebraHandle zh,
2206                               oid_value attributeSet,
2207                               int num_bases, char **basenames,
2208                               NMEM stream, const char *rank_type, RSET rset,
2209                               int xpath_len, struct xpath_location_step *xpath)
2210 {
2211     oid_value curAttributeSet = attributeSet;
2212     int base_no;
2213     int i;
2214
2215     if (xpath_len < 0)
2216         return rset;
2217
2218     yaz_log (LOG_LOG, "len=%d", xpath_len);
2219     for (i = 0; i<xpath_len; i++)
2220     {
2221         yaz_log (LOG_LOG, "XPATH %d %s", i, xpath[i].part);
2222
2223     }
2224
2225     curAttributeSet = VAL_IDXPATH;
2226
2227     /*
2228       //a    ->    a/.*
2229       //a/b  ->    b/a/.*
2230       /a     ->    a/
2231       /a/b   ->    b/a/
2232
2233       /      ->    none
2234
2235    a[@attr=value]/b[@other=othervalue]
2236
2237  /e/@a val      range(e/,range(@a,freetext(w,1015,val),@a),e/)
2238  /a/b val       range(b/a/,freetext(w,1016,val),b/a/)
2239  /a/b/@c val    range(b/a/,range(@c,freetext(w,1016,val),@c),b/a/)
2240  /a/b[@c=y] val range(b/a/,freetext(w,1016,val),b/a/,@c=y)
2241  /a[@c=y]/b val range(a/,range(b/a/,freetext(w,1016,val),b/a/),a/,@c=y)
2242  /a[@c=x]/b[@c=y] range(a/,range(b/a/,freetext(w,1016,val),b/a/,@c=y),a/,@c=x)
2243       
2244     */
2245
2246     dict_grep_cmap (zh->reg->dict, 0, 0);
2247
2248     for (base_no = 0; base_no < num_bases; base_no++)
2249     {
2250         int level = xpath_len;
2251         int first_path = 1;
2252         
2253         if (zebraExplain_curDatabase (zh->reg->zei, basenames[base_no]))
2254         {
2255             zh->errCode = 109; /* Database unavailable */
2256             zh->errString = basenames[base_no];
2257             return rset;
2258         }
2259         while (--level >= 0)
2260         {
2261             char xpath_rev[128];
2262             int i, len;
2263             rset_between_parms parms;
2264             RSET rset_start_tag = 0, rset_end_tag = 0, rset_attr = 0;
2265
2266             *xpath_rev = 0;
2267             len = 0;
2268             for (i = level; i >= 1; --i)
2269             {
2270                 const char *cp = xpath[i].part;
2271                 if (*cp)
2272                 {
2273                     for (;*cp; cp++)
2274                         if (*cp == '*')
2275                         {
2276                             memcpy (xpath_rev + len, "[^/]*", 5);
2277                             len += 5;
2278                         }
2279                         else if (*cp == ' ')
2280                         {
2281
2282                             xpath_rev[len++] = 1;
2283                             xpath_rev[len++] = ' ';
2284                         }
2285
2286                         else
2287                             xpath_rev[len++] = *cp;
2288                     xpath_rev[len++] = '/';
2289                 }
2290                 else if (i == 1)  /* // case */
2291                 {
2292                     xpath_rev[len++] = '.';
2293                     xpath_rev[len++] = '*';
2294                 }
2295             }
2296             xpath_rev[len] = 0;
2297
2298             if (xpath[level].predicate &&
2299                 xpath[level].predicate->which == XPATH_PREDICATE_RELATION &&
2300                 xpath[level].predicate->u.relation.name[0])
2301             {
2302                 WRBUF wbuf = wrbuf_alloc();
2303                 wrbuf_puts(wbuf, xpath[level].predicate->u.relation.name+1);
2304                 if (xpath[level].predicate->u.relation.value)
2305                 {
2306                     const char *cp = xpath[level].predicate->u.relation.value;
2307                     wrbuf_putc(wbuf, '=');
2308                     
2309                     while (*cp)
2310                     {
2311                         if (strchr(REGEX_CHARS, *cp))
2312                             wrbuf_putc(wbuf, '\\');
2313                         wrbuf_putc(wbuf, *cp);
2314                         cp++;
2315                     }
2316                 }
2317                 wrbuf_puts(wbuf, "");
2318                 rset_attr = xpath_trunc (
2319                     zh, stream, '0', wrbuf_buf(wbuf), 3, curAttributeSet);
2320                 wrbuf_free(wbuf, 1);
2321             } 
2322             else 
2323             {
2324                 if (!first_path)
2325                     continue;
2326             }
2327             yaz_log (LOG_LOG, "xpath_rev (%d) = %s", level, xpath_rev);
2328             if (strlen(xpath_rev))
2329             {
2330                 rset_start_tag = xpath_trunc(zh, stream, 
2331                                          '0', xpath_rev, 1, curAttributeSet);
2332             
2333                 rset_end_tag = xpath_trunc(zh, stream,
2334                                        '0', xpath_rev, 2, curAttributeSet);
2335
2336                 parms.key_size = sizeof(struct it_key);
2337                 parms.cmp = key_compare_it;
2338                 parms.rset_l = rset_start_tag;
2339                 parms.rset_m = rset;
2340                 parms.rset_r = rset_end_tag;
2341                 parms.rset_attr = rset_attr;
2342                 parms.printer = key_print_it;
2343                 rset = rset_create (rset_kind_between, &parms);
2344             }
2345             first_path = 0;
2346         }
2347     }
2348
2349     return rset;
2350 }
2351
2352
2353
2354 static RSET rpn_search_APT (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
2355                             oid_value attributeSet, NMEM stream,
2356                             Z_SortKeySpecList *sort_sequence,
2357                             int num_bases, char **basenames)
2358 {
2359     unsigned reg_id;
2360     char *search_type = NULL;
2361     char rank_type[128];
2362     int complete_flag;
2363     int sort_flag;
2364     char termz[IT_MAX_WORD+1];
2365     RSET rset = 0;
2366     int xpath_len;
2367     int xpath_use = 0;
2368     struct xpath_location_step xpath[10];
2369
2370     zebra_maps_attr (zh->reg->zebra_maps, zapt, &reg_id, &search_type,
2371                      rank_type, &complete_flag, &sort_flag);
2372     
2373     logf (LOG_DEBUG, "reg_id=%c", reg_id);
2374     logf (LOG_DEBUG, "complete_flag=%d", complete_flag);
2375     logf (LOG_DEBUG, "search_type=%s", search_type);
2376     logf (LOG_DEBUG, "rank_type=%s", rank_type);
2377
2378     if (zapt_term_to_utf8(zh, zapt, termz))
2379         return 0;
2380
2381     if (sort_flag)
2382         return rpn_sort_spec (zh, zapt, attributeSet, stream, sort_sequence,
2383                               rank_type);
2384     xpath_len = parse_xpath(zh, zapt, attributeSet, xpath, 10, stream);
2385     if (xpath_len >= 0)
2386     {
2387         xpath_use = 1016;
2388         if (xpath[xpath_len-1].part[0] == '@')
2389             xpath_use = 1015;
2390     }
2391
2392     if (!strcmp (search_type, "phrase"))
2393     {
2394         rset = rpn_search_APT_phrase (zh, zapt, termz, attributeSet, stream,
2395                                       reg_id, complete_flag, rank_type,
2396                                       xpath_use,
2397                                       num_bases, basenames);
2398     }
2399     else if (!strcmp (search_type, "and-list"))
2400     {
2401         rset = rpn_search_APT_and_list (zh, zapt, termz, attributeSet, stream,
2402                                         reg_id, complete_flag, rank_type,
2403                                         xpath_use,
2404                                         num_bases, basenames);
2405     }
2406     else if (!strcmp (search_type, "or-list"))
2407     {
2408         rset = rpn_search_APT_or_list (zh, zapt, termz, attributeSet, stream,
2409                                        reg_id, complete_flag, rank_type,
2410                                        xpath_use,
2411                                        num_bases, basenames);
2412     }
2413     else if (!strcmp (search_type, "local"))
2414     {
2415         rset = rpn_search_APT_local (zh, zapt, termz, attributeSet, stream,
2416                                      rank_type);
2417     }
2418     else if (!strcmp (search_type, "numeric"))
2419     {
2420         rset = rpn_search_APT_numeric (zh, zapt, termz, attributeSet, stream,
2421                                        reg_id, complete_flag, rank_type,
2422                                        xpath_use,
2423                                        num_bases, basenames);
2424     }
2425     else if (!strcmp (search_type, "always"))
2426     {
2427         rset = 0;
2428     }
2429     else
2430         zh->errCode = 118;
2431     return rpn_search_xpath (zh, attributeSet, num_bases, basenames,
2432                              stream, rank_type, rset, xpath_len, xpath);
2433 }
2434
2435 static RSET rpn_search_structure (ZebraHandle zh, Z_RPNStructure *zs,
2436                                   oid_value attributeSet, NMEM stream,
2437                                   Z_SortKeySpecList *sort_sequence,
2438                                   int num_bases, char **basenames)
2439 {
2440     RSET r = NULL;
2441     if (zs->which == Z_RPNStructure_complex)
2442     {
2443         Z_Operator *zop = zs->u.complex->roperator;
2444         rset_bool_parms bool_parms;
2445
2446         bool_parms.rset_l = rpn_search_structure (zh, zs->u.complex->s1,
2447                                                   attributeSet, stream,
2448                                                   sort_sequence,
2449                                                   num_bases, basenames);
2450         if (bool_parms.rset_l == NULL)
2451             return NULL;
2452         bool_parms.rset_r = rpn_search_structure (zh, zs->u.complex->s2,
2453                                                   attributeSet, stream,
2454                                                   sort_sequence,
2455                                                   num_bases, basenames);
2456         if (bool_parms.rset_r == NULL)
2457         {
2458             rset_delete (bool_parms.rset_l);
2459             return NULL;
2460         }
2461         bool_parms.key_size = sizeof(struct it_key);
2462         bool_parms.cmp = key_compare_it;
2463         bool_parms.log_item = key_logdump_txt;
2464
2465         switch (zop->which)
2466         {
2467         case Z_Operator_and:
2468             r = rset_create (rset_kind_and, &bool_parms);
2469             break;
2470         case Z_Operator_or:
2471             r = rset_create (rset_kind_or, &bool_parms);
2472             break;
2473         case Z_Operator_and_not:
2474             r = rset_create (rset_kind_not, &bool_parms);
2475             break;
2476         case Z_Operator_prox:
2477             if (zop->u.prox->which != Z_ProximityOperator_known)
2478             {
2479                 zh->errCode = 132;
2480                 return NULL;
2481             }
2482             if (*zop->u.prox->u.known != Z_ProxUnit_word)
2483             {
2484                 char *val = (char *) nmem_malloc (stream, 16);
2485                 zh->errCode = 132;
2486                 zh->errString = val;
2487                 sprintf (val, "%d", *zop->u.prox->u.known);
2488                 return NULL;
2489             }
2490             else
2491             {
2492                 RSET rsets[2];
2493
2494                 rsets[0] = bool_parms.rset_l;
2495                 rsets[1] = bool_parms.rset_r;
2496                 
2497                 r = rpn_prox (zh, rsets, 2, 
2498                               *zop->u.prox->ordered,
2499                               (!zop->u.prox->exclusion ? 0 :
2500                                *zop->u.prox->exclusion),
2501                               *zop->u.prox->relationType,
2502                               *zop->u.prox->distance);
2503                 rset_delete (rsets[0]);
2504                 rset_delete (rsets[1]);
2505             }
2506             break;
2507         default:
2508             zh->errCode = 110;
2509             return NULL;
2510         }
2511     }
2512     else if (zs->which == Z_RPNStructure_simple)
2513     {
2514         if (zs->u.simple->which == Z_Operand_APT)
2515         {
2516             logf (LOG_DEBUG, "rpn_search_APT");
2517             r = rpn_search_APT (zh, zs->u.simple->u.attributesPlusTerm,
2518                                 attributeSet, stream, sort_sequence,
2519                                 num_bases, basenames);
2520         }
2521         else if (zs->u.simple->which == Z_Operand_resultSetId)
2522         {
2523             logf (LOG_DEBUG, "rpn_search_ref");
2524             r = resultSetRef (zh, zs->u.simple->u.resultSetId);
2525             if (!r)
2526             {
2527                 r = rset_create (rset_kind_null, NULL);
2528                 zh->errCode = 30;
2529                 zh->errString =
2530                     nmem_strdup (stream, zs->u.simple->u.resultSetId);
2531                 return 0;
2532             }
2533             else
2534                 rset_dup(r);
2535         }
2536         else
2537         {
2538             zh->errCode = 3;
2539             return 0;
2540         }
2541     }
2542     else
2543     {
2544         zh->errCode = 3;
2545         return 0;
2546     }
2547     return r;
2548 }
2549
2550
2551 RSET rpn_search (ZebraHandle zh, NMEM nmem,
2552                  Z_RPNQuery *rpn, int num_bases, char **basenames, 
2553                  const char *setname,
2554                  ZebraSet sset)
2555 {
2556     RSET rset;
2557     oident *attrset;
2558     oid_value attributeSet;
2559     Z_SortKeySpecList *sort_sequence;
2560     int sort_status, i;
2561
2562     zh->errCode = 0;
2563     zh->errString = NULL;
2564     zh->hits = 0;
2565
2566     sort_sequence = (Z_SortKeySpecList *)
2567         nmem_malloc (nmem, sizeof(*sort_sequence));
2568     sort_sequence->num_specs = 10;
2569     sort_sequence->specs = (Z_SortKeySpec **)
2570         nmem_malloc (nmem, sort_sequence->num_specs *
2571                      sizeof(*sort_sequence->specs));
2572     for (i = 0; i<sort_sequence->num_specs; i++)
2573         sort_sequence->specs[i] = 0;
2574     
2575     attrset = oid_getentbyoid (rpn->attributeSetId);
2576     attributeSet = attrset->value;
2577     rset = rpn_search_structure (zh, rpn->RPNStructure, attributeSet,
2578                                  nmem, sort_sequence, num_bases, basenames);
2579     if (!rset)
2580         return 0;
2581
2582     if (zh->errCode)
2583         logf (LOG_DEBUG, "search error: %d", zh->errCode);
2584     
2585     for (i = 0; sort_sequence->specs[i]; i++)
2586         ;
2587     sort_sequence->num_specs = i;
2588     if (!i)
2589         resultSetRank (zh, sset, rset);
2590     else
2591     {
2592         logf (LOG_DEBUG, "resultSetSortSingle in rpn_search");
2593         resultSetSortSingle (zh, nmem, sset, rset,
2594                              sort_sequence, &sort_status);
2595         if (zh->errCode)
2596         {
2597             logf (LOG_DEBUG, "resultSetSortSingle status = %d", zh->errCode);
2598         }
2599     }
2600     return rset;
2601 }
2602
2603 struct scan_info_entry {
2604     char *term;
2605     ISAMS_P isam_p;
2606 };
2607
2608 struct scan_info {
2609     struct scan_info_entry *list;
2610     ODR odr;
2611     int before, after;
2612     char prefix[20];
2613 };
2614
2615 static int scan_handle (char *name, const char *info, int pos, void *client)
2616 {
2617     int len_prefix, idx;
2618     struct scan_info *scan_info = (struct scan_info *) client;
2619
2620     len_prefix = strlen(scan_info->prefix);
2621     if (memcmp (name, scan_info->prefix, len_prefix))
2622         return 1;
2623     if (pos > 0)        idx = scan_info->after - pos + scan_info->before;
2624     else
2625         idx = - pos - 1;
2626     scan_info->list[idx].term = (char *)
2627         odr_malloc (scan_info->odr, strlen(name + len_prefix)+1);
2628     strcpy (scan_info->list[idx].term, name + len_prefix);
2629     assert (*info == sizeof(ISAMS_P));
2630     memcpy (&scan_info->list[idx].isam_p, info+1, sizeof(ISAMS_P));
2631     return 0;
2632 }
2633
2634 static void scan_term_untrans (ZebraHandle zh, NMEM stream, int reg_type,
2635                                char **dst, const char *src)
2636 {
2637     char term_src[IT_MAX_WORD];
2638     char term_dst[IT_MAX_WORD];
2639     
2640     term_untrans (zh, reg_type, term_src, src);
2641
2642     if (zh->iconv_from_utf8 != 0)
2643     {
2644         int len;
2645         char *inbuf = term_src;
2646         size_t inleft = strlen(term_src);
2647         char *outbuf = term_dst;
2648         size_t outleft = sizeof(term_dst)-1;
2649         size_t ret;
2650         
2651         ret = yaz_iconv (zh->iconv_from_utf8, &inbuf, &inleft,
2652                          &outbuf, &outleft);
2653         if (ret == (size_t)(-1))
2654             len = 0;
2655         else
2656             len = outbuf - term_dst;
2657         *dst = nmem_malloc (stream, len + 1);
2658         if (len > 0)
2659             memcpy (*dst, term_dst, len);
2660         (*dst)[len] = '\0';
2661     }
2662     else
2663         *dst = nmem_strdup (stream, term_src);
2664 }
2665
2666 static void count_set (RSET r, int *count)
2667 {
2668     int psysno = 0;
2669     int kno = 0;
2670     struct it_key key;
2671     RSFD rfd;
2672     int term_index;
2673
2674     logf (LOG_DEBUG, "count_set");
2675
2676     *count = 0;
2677     rfd = rset_open (r, RSETF_READ);
2678     while (rset_read (r, rfd, &key, &term_index))
2679     {
2680         if (key.sysno != psysno)
2681         {
2682             psysno = key.sysno;
2683             (*count)++;
2684         }
2685         kno++;
2686     }
2687     rset_close (r, rfd);
2688     logf (LOG_DEBUG, "%d keys, %d records", kno, *count);
2689 }
2690
2691 void rpn_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
2692                oid_value attributeset,
2693                int num_bases, char **basenames,
2694                int *position, int *num_entries, ZebraScanEntry **list,
2695                int *is_partial, RSET limit_set, int return_zero)
2696 {
2697     int i;
2698     int pos = *position;
2699     int num = *num_entries;
2700     int before;
2701     int after;
2702     int base_no;
2703     char termz[IT_MAX_WORD+20];
2704     AttrType use;
2705     int use_value;
2706     const char *use_string = 0;
2707     struct scan_info *scan_info_array;
2708     ZebraScanEntry *glist;
2709     int ords[32], ord_no = 0;
2710     int ptr[32];
2711
2712     int bases_ok = 0;     /* no of databases with OK attribute */
2713     int errCode = 0;      /* err code (if any is not OK) */
2714     char *errString = 0;  /* addinfo */
2715
2716     unsigned reg_id;
2717     char *search_type = NULL;
2718     char rank_type[128];
2719     int complete_flag;
2720     int sort_flag;
2721
2722     *list = 0;
2723
2724     if (attributeset == VAL_NONE)
2725         attributeset = VAL_BIB1;
2726
2727     if (!limit_set)
2728     {
2729         AttrType termset;
2730         int termset_value_numeric;
2731         const char *termset_value_string;
2732         attr_init (&termset, zapt, 8);
2733         termset_value_numeric =
2734             attr_find_ex (&termset, NULL, &termset_value_string);
2735         if (termset_value_numeric != -1)
2736         {
2737             char resname[32];
2738             const char *termset_name = 0;
2739             
2740             if (termset_value_numeric != -2)
2741             {
2742                 
2743                 sprintf (resname, "%d", termset_value_numeric);
2744                 termset_name = resname;
2745             }
2746             else
2747                 termset_name = termset_value_string;
2748             
2749             limit_set = resultSetRef (zh, termset_name);
2750         }
2751     }
2752         
2753     yaz_log (LOG_DEBUG, "position = %d, num = %d set=%d",
2754              pos, num, attributeset);
2755         
2756     attr_init (&use, zapt, 1);
2757     use_value = attr_find_ex (&use, &attributeset, &use_string);
2758
2759     if (zebra_maps_attr (zh->reg->zebra_maps, zapt, &reg_id, &search_type,
2760                          rank_type, &complete_flag, &sort_flag))
2761     {
2762         *num_entries = 0;
2763         zh->errCode = 113;
2764         return ;
2765     }
2766     yaz_log (LOG_DEBUG, "use_value = %d", use_value);
2767
2768     if (use_value == -1)
2769         use_value = 1016;
2770     for (base_no = 0; base_no < num_bases && ord_no < 32; base_no++)
2771     {
2772         int r;
2773         attent attp;
2774         data1_local_attribute *local_attr;
2775
2776         if ((r=att_getentbyatt (zh, &attp, attributeset, use_value,
2777                                 use_string)))
2778         {
2779             logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d",
2780                   attributeset, use_value);
2781             if (r == -1)
2782             {
2783                 char val_str[32];
2784                 sprintf (val_str, "%d", use_value);
2785                 errCode = 114;
2786                 errString = odr_strdup (stream, val_str);
2787             }   
2788             else
2789                 errCode = 121;
2790             continue;
2791         }
2792         if (zebraExplain_curDatabase (zh->reg->zei, basenames[base_no]))
2793         {
2794             zh->errString = basenames[base_no];
2795             zh->errCode = 109; /* Database unavailable */
2796             *num_entries = 0;
2797             return;
2798         }
2799         bases_ok++;
2800         for (local_attr = attp.local_attributes; local_attr && ord_no < 32;
2801              local_attr = local_attr->next)
2802         {
2803             int ord;
2804
2805             ord = zebraExplain_lookupSU (zh->reg->zei, attp.attset_ordinal,
2806                                          local_attr->local);
2807             if (ord > 0)
2808                 ords[ord_no++] = ord;
2809         }
2810     }
2811     if (!bases_ok && errCode)
2812     {
2813         zh->errCode = errCode;
2814         zh->errString = errString;
2815         *num_entries = 0;
2816     }
2817     if (ord_no == 0)
2818     {
2819         char val_str[32];
2820         sprintf (val_str, "%d", use_value);
2821         zh->errCode = 114;
2822         zh->errString = odr_strdup (stream, val_str);
2823
2824         *num_entries = 0;
2825         return;
2826     }
2827     /* prepare dictionary scanning */
2828     before = pos-1;
2829     after = 1+num-pos;
2830     scan_info_array = (struct scan_info *)
2831         odr_malloc (stream, ord_no * sizeof(*scan_info_array));
2832     for (i = 0; i < ord_no; i++)
2833     {
2834         int j, prefix_len = 0;
2835         int before_tmp = before, after_tmp = after;
2836         struct scan_info *scan_info = scan_info_array + i;
2837         struct rpn_char_map_info rcmi;
2838
2839         rpn_char_map_prepare (zh->reg, reg_id, &rcmi);
2840
2841         scan_info->before = before;
2842         scan_info->after = after;
2843         scan_info->odr = stream;
2844
2845         scan_info->list = (struct scan_info_entry *)
2846             odr_malloc (stream, (before+after) * sizeof(*scan_info->list));
2847         for (j = 0; j<before+after; j++)
2848             scan_info->list[j].term = NULL;
2849
2850         prefix_len += key_SU_encode (ords[i], termz + prefix_len);
2851         termz[prefix_len++] = reg_id;
2852         termz[prefix_len] = 0;
2853         strcpy (scan_info->prefix, termz);
2854
2855         if (trans_scan_term (zh, zapt, termz+prefix_len, reg_id))
2856             return ;
2857                     
2858         dict_scan (zh->reg->dict, termz, &before_tmp, &after_tmp,
2859                    scan_info, scan_handle);
2860     }
2861     glist = (ZebraScanEntry *)
2862         odr_malloc (stream, (before+after)*sizeof(*glist));
2863
2864     /* consider terms after main term */
2865     for (i = 0; i < ord_no; i++)
2866         ptr[i] = before;
2867     
2868     *is_partial = 0;
2869     for (i = 0; i<after; i++)
2870     {
2871         int j, j0 = -1;
2872         const char *mterm = NULL;
2873         const char *tst;
2874         RSET rset;
2875         
2876         for (j = 0; j < ord_no; j++)
2877         {
2878             if (ptr[j] < before+after &&
2879                 (tst=scan_info_array[j].list[ptr[j]].term) &&
2880                 (!mterm || strcmp (tst, mterm) < 0))
2881             {
2882                 j0 = j;
2883                 mterm = tst;
2884             }
2885         }
2886         if (j0 == -1)
2887             break;
2888         scan_term_untrans (zh, stream->mem, reg_id,
2889                            &glist[i+before].term, mterm);
2890         rset = rset_trunc (zh, &scan_info_array[j0].list[ptr[j0]].isam_p, 1,
2891                            glist[i+before].term, strlen(glist[i+before].term),
2892                            NULL, 0, zapt->term->which);
2893
2894         ptr[j0]++;
2895         for (j = j0+1; j<ord_no; j++)
2896         {
2897             if (ptr[j] < before+after &&
2898                 (tst=scan_info_array[j].list[ptr[j]].term) &&
2899                 !strcmp (tst, mterm))
2900             {
2901                 rset_bool_parms bool_parms;
2902                 RSET rset2;
2903
2904                 rset2 =
2905                    rset_trunc (zh, &scan_info_array[j].list[ptr[j]].isam_p, 1,
2906                                glist[i+before].term,
2907                                strlen(glist[i+before].term), NULL, 0,
2908                                zapt->term->which);
2909
2910                 bool_parms.key_size = sizeof(struct it_key);
2911                 bool_parms.cmp = key_compare_it;
2912                 bool_parms.log_item = key_logdump_txt;
2913                 bool_parms.rset_l = rset;
2914                 bool_parms.rset_r = rset2;
2915               
2916                 rset = rset_create (rset_kind_or, &bool_parms);
2917
2918                 ptr[j]++;
2919             }
2920         }
2921         if (limit_set)
2922         {
2923             rset_bool_parms bool_parms;
2924
2925             bool_parms.key_size = sizeof(struct it_key);
2926             bool_parms.cmp = key_compare_it;
2927             bool_parms.log_item = key_logdump_txt;
2928             bool_parms.rset_l = rset;
2929             bool_parms.rset_r = rset_dup(limit_set);
2930
2931             rset = rset_create (rset_kind_and, &bool_parms);
2932         }
2933         count_set (rset, &glist[i+before].occurrences);
2934         rset_delete (rset);
2935     }
2936     if (i < after)
2937     {
2938         *num_entries -= (after-i);
2939         *is_partial = 1;
2940     }
2941
2942     /* consider terms before main term */
2943     for (i = 0; i<ord_no; i++)
2944         ptr[i] = 0;
2945
2946     for (i = 0; i<before; i++)
2947     {
2948         int j, j0 = -1;
2949         const char *mterm = NULL;
2950         const char *tst;
2951         RSET rset;
2952         
2953         for (j = 0; j <ord_no; j++)
2954         {
2955             if (ptr[j] < before &&
2956                 (tst=scan_info_array[j].list[before-1-ptr[j]].term) &&
2957                 (!mterm || strcmp (tst, mterm) > 0))
2958             {
2959                 j0 = j;
2960                 mterm = tst;
2961             }
2962         }
2963         if (j0 == -1)
2964             break;
2965
2966         scan_term_untrans (zh, stream->mem, reg_id,
2967                            &glist[before-1-i].term, mterm);
2968
2969         rset = rset_trunc
2970                (zh, &scan_info_array[j0].list[before-1-ptr[j0]].isam_p, 1,
2971                 glist[before-1-i].term, strlen(glist[before-1-i].term),
2972                 NULL, 0, zapt->term->which);
2973
2974         ptr[j0]++;
2975
2976         for (j = j0+1; j<ord_no; j++)
2977         {
2978             if (ptr[j] < before &&
2979                 (tst=scan_info_array[j].list[before-1-ptr[j]].term) &&
2980                 !strcmp (tst, mterm))
2981             {
2982                 rset_bool_parms bool_parms;
2983                 RSET rset2;
2984
2985                 rset2 = rset_trunc (zh,
2986                          &scan_info_array[j].list[before-1-ptr[j]].isam_p, 1,
2987                                     glist[before-1-i].term,
2988                                     strlen(glist[before-1-i].term), NULL, 0,
2989                                     zapt->term->which);
2990
2991                 bool_parms.key_size = sizeof(struct it_key);
2992                 bool_parms.cmp = key_compare_it;
2993                 bool_parms.log_item = key_logdump_txt;
2994                 bool_parms.rset_l = rset;
2995                 bool_parms.rset_r = rset2;
2996               
2997                 rset = rset_create (rset_kind_or, &bool_parms);
2998
2999                 ptr[j]++;
3000             }
3001         }
3002         if (limit_set)
3003         {
3004             rset_bool_parms bool_parms;
3005
3006             bool_parms.key_size = sizeof(struct it_key);
3007             bool_parms.cmp = key_compare_it;
3008             bool_parms.log_item = key_logdump_txt;
3009             bool_parms.rset_l = rset;
3010             bool_parms.rset_r = rset_dup(limit_set);
3011
3012             rset = rset_create (rset_kind_and, &bool_parms);
3013         }
3014         count_set (rset, &glist[before-1-i].occurrences);
3015         rset_delete (rset);
3016     }
3017     i = before-i;
3018     if (i)
3019     {
3020         *is_partial = 1;
3021         *position -= i;
3022         *num_entries -= i;
3023     }
3024     *list = glist + i;               /* list is set to first 'real' entry */
3025     
3026     logf (LOG_DEBUG, "position = %d, num_entries = %d",
3027           *position, *num_entries);
3028     if (zh->errCode)
3029         logf (LOG_DEBUG, "scan error: %d", zh->errCode);
3030 }
3031