Only issue error 114 if all databases fail
[idzebra-moved-to-github.git] / index / zrpn.c
1 /* $Id: zrpn.c,v 1.134 2003-09-05 10:51:17 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003
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 (use_value == -2)  /* string attribute (assume IDXPATH/any) */
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             {
963                 logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d r=%d",
964                       curAttributeSet, use_value, r);
965                 if (r == -1)
966                 {
967                     /* set was found, but value wasn't defined */
968                     char val_str[32];
969                     sprintf (val_str, "%d", use_value);
970                     errCode = 114;
971                     errString = nmem_strdup (stream, val_str);
972                 }
973                 else
974                 {
975                     int oid[OID_SIZE];
976                     struct oident oident;
977                     
978                     oident.proto = PROTO_Z3950;
979                     oident.oclass = CLASS_ATTSET;
980                     oident.value = curAttributeSet;
981                     oid_ent_to_oid (&oident, oid);
982                     
983                     errCode = 121;
984                     errString = nmem_strdup (stream, oident.desc);
985                 }
986                 continue;
987             }
988         }
989         for (local_attr = attp.local_attributes; local_attr;
990              local_attr = local_attr->next)
991         {
992             int ord;
993             char ord_buf[32];
994             int i, ord_len;
995             
996             ord = zebraExplain_lookupSU (zh->reg->zei, attp.attset_ordinal,
997                                          local_attr->local);
998             if (ord < 0)
999                 continue;
1000             if (prefix_len)
1001                 term_dict[prefix_len++] = '|';
1002             else
1003                 term_dict[prefix_len++] = '(';
1004             
1005             ord_len = key_SU_encode (ord, ord_buf);
1006             for (i = 0; i<ord_len; i++)
1007             {
1008                 term_dict[prefix_len++] = 1;
1009                 term_dict[prefix_len++] = ord_buf[i];
1010             }
1011         }
1012         if (!prefix_len)
1013         {
1014             char val_str[32];
1015             sprintf (val_str, "%d", use_value);
1016             errCode = 114;
1017             errString = nmem_strdup (stream, val_str);
1018             continue;
1019         }
1020         bases_ok++; /* this has OK attributes */
1021
1022         term_dict[prefix_len++] = ')';
1023         term_dict[prefix_len++] = 1;
1024         term_dict[prefix_len++] = reg_type;
1025         logf (LOG_DEBUG, "reg_type = %d", term_dict[prefix_len-1]);
1026         term_dict[prefix_len] = '\0';
1027         j = prefix_len;
1028         switch (truncation_value)
1029         {
1030         case -1:         /* not specified */
1031         case 100:        /* do not truncate */
1032             if (!string_relation (zh, zapt, &termp, term_dict,
1033                                   attributeSet,
1034                                   reg_type, space_split, term_dst))
1035                 return 0;
1036             logf (LOG_LOG, "dict_lookup_grep: %s", term_dict+prefix_len);
1037             r = dict_lookup_grep (zh->reg->dict, term_dict, 0,
1038                                   grep_info, &max_pos, 0, grep_handle);
1039             if (r)
1040                 logf (LOG_WARN, "dict_lookup_grep fail %d", r);
1041             break;
1042         case 1:          /* right truncation */
1043             term_dict[j++] = '(';
1044             if (!term_100 (zh->reg->zebra_maps, reg_type,
1045                            &termp, term_dict + j, space_split, term_dst))
1046                 return 0;
1047             strcat (term_dict, ".*)");
1048             dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1049                               &max_pos, 0, grep_handle);
1050             break;
1051         case 2:          /* keft truncation */
1052             term_dict[j++] = '('; term_dict[j++] = '.'; term_dict[j++] = '*';
1053             if (!term_100 (zh->reg->zebra_maps, reg_type,
1054                            &termp, term_dict + j, space_split, term_dst))
1055                 return 0;
1056             strcat (term_dict, ")");
1057             dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1058                               &max_pos, 0, grep_handle);
1059             break;
1060         case 3:          /* left&right truncation */
1061             term_dict[j++] = '('; term_dict[j++] = '.'; term_dict[j++] = '*';
1062             if (!term_100 (zh->reg->zebra_maps, reg_type,
1063                            &termp, term_dict + j, space_split, term_dst))
1064                 return 0;
1065             strcat (term_dict, ".*)");
1066             dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1067                               &max_pos, 0, grep_handle);
1068             break;
1069             zh->errCode = 120;
1070             return -1;
1071         case 101:        /* process # in term */
1072             term_dict[j++] = '(';
1073             if (!term_101 (zh->reg->zebra_maps, reg_type,
1074                            &termp, term_dict + j, space_split, term_dst))
1075                 return 0;
1076             strcat (term_dict, ")");
1077             r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1078                                   &max_pos, 0, grep_handle);
1079             if (r)
1080                 logf (LOG_WARN, "dict_lookup_grep err, trunc=#: %d", r);
1081             break;
1082         case 102:        /* Regexp-1 */
1083             term_dict[j++] = '(';
1084             if (!term_102 (zh->reg->zebra_maps, reg_type,
1085                            &termp, term_dict + j, space_split, term_dst))
1086                 return 0;
1087             strcat (term_dict, ")");
1088             logf (LOG_DEBUG, "Regexp-1 tolerance=%d", r);
1089             r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1090                                   &max_pos, 0, grep_handle);
1091             if (r)
1092                 logf (LOG_WARN, "dict_lookup_grep err, trunc=regular: %d",
1093                       r);
1094             break;
1095         case 103:       /* Regexp-2 */
1096             r = 1;
1097             term_dict[j++] = '(';
1098             if (!term_103 (zh->reg->zebra_maps, reg_type,
1099                            &termp, term_dict + j, &r, space_split, term_dst))
1100                 return 0;
1101             strcat (term_dict, ")");
1102             logf (LOG_DEBUG, "Regexp-2 tolerance=%d", r);
1103             r = dict_lookup_grep (zh->reg->dict, term_dict, r, grep_info,
1104                                   &max_pos, 2, grep_handle);
1105             if (r)
1106                 logf (LOG_WARN, "dict_lookup_grep err, trunc=eregular: %d",
1107                       r);
1108             break;
1109         case 104:        /* process # and ! in term */
1110             term_dict[j++] = '(';
1111             if (!term_104 (zh->reg->zebra_maps, reg_type,
1112                            &termp, term_dict + j, space_split, term_dst))
1113                 return 0;
1114             strcat (term_dict, ")");
1115             r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1116                                   &max_pos, 0, grep_handle);
1117             if (r)
1118                 logf (LOG_WARN, "dict_lookup_grep err, trunc=#/!: %d", r);
1119             break;
1120         case 105:        /* process * and ! in term */
1121             term_dict[j++] = '(';
1122             if (!term_105 (zh->reg->zebra_maps, reg_type,
1123                            &termp, term_dict + j, space_split, term_dst, 1))
1124                 return 0;
1125             strcat (term_dict, ")");
1126             r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1127                                   &max_pos, 0, grep_handle);
1128             if (r)
1129                 logf (LOG_WARN, "dict_lookup_grep err, trunc=*/!: %d", r);
1130             break;
1131         case 106:        /* process * and ! in term */
1132             term_dict[j++] = '(';
1133             if (!term_105 (zh->reg->zebra_maps, reg_type,
1134                            &termp, term_dict + j, space_split, term_dst, 0))
1135                 return 0;
1136             strcat (term_dict, ")");
1137             r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info,
1138                                   &max_pos, 0, grep_handle);
1139             if (r)
1140                 logf (LOG_WARN, "dict_lookup_grep err, trunc=*/!: %d", r);
1141             break;
1142         }
1143     }
1144     if (!bases_ok)
1145     {
1146         zh->errCode = errCode;
1147         zh->errString = errString;
1148         return -1;
1149     }
1150     *term_sub = termp;
1151     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
1152     return 1;
1153 }
1154
1155
1156 /* convert APT search term to UTF8 */
1157 static int zapt_term_to_utf8 (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1158                               char *termz)
1159 {
1160     size_t sizez;
1161     Z_Term *term = zapt->term;
1162
1163     switch (term->which)
1164     {
1165     case Z_Term_general:
1166         if (zh->iconv_to_utf8 != 0)
1167         {
1168             char *inbuf = term->u.general->buf;
1169             size_t inleft = term->u.general->len;
1170             char *outbuf = termz;
1171             size_t outleft = IT_MAX_WORD-1;
1172             size_t ret;
1173
1174             ret = yaz_iconv(zh->iconv_to_utf8, &inbuf, &inleft,
1175                         &outbuf, &outleft);
1176             if (ret == (size_t)(-1))
1177             {
1178                 ret = yaz_iconv(zh->iconv_to_utf8, 0, 0, 0, 0);
1179                 zh->errCode = 125;
1180                 return -1;
1181             }
1182             *outbuf = 0;
1183         }
1184         else
1185         {
1186             sizez = term->u.general->len;
1187             if (sizez > IT_MAX_WORD-1)
1188                 sizez = IT_MAX_WORD-1;
1189             memcpy (termz, term->u.general->buf, sizez);
1190             termz[sizez] = '\0';
1191         }
1192         break;
1193     case Z_Term_characterString:
1194         sizez = strlen(term->u.characterString);
1195         if (sizez > IT_MAX_WORD-1)
1196             sizez = IT_MAX_WORD-1;
1197         memcpy (termz, term->u.characterString, sizez);
1198         termz[sizez] = '\0';
1199         break;
1200     default:
1201         zh->errCode = 124;
1202         return -1;
1203     }
1204     return 0;
1205 }
1206
1207 /* convert APT SCAN term to internal cmap */
1208 static int trans_scan_term (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1209                             char *termz, int reg_type)
1210 {
1211     char termz0[IT_MAX_WORD];
1212
1213     if (zapt_term_to_utf8(zh, zapt, termz0))
1214         return -1;    /* error */
1215     else
1216     {
1217         const char **map;
1218         const char *cp = (const char *) termz0;
1219         const char *cp_end = cp + strlen(cp);
1220         const char *src;
1221         int i = 0;
1222         const char *space_map = NULL;
1223         int len;
1224             
1225         while ((len = (cp_end - cp)) > 0)
1226         {
1227             map = zebra_maps_input (zh->reg->zebra_maps, reg_type, &cp, len);
1228             if (**map == *CHR_SPACE)
1229                 space_map = *map;
1230             else
1231             {
1232                 if (i && space_map)
1233                     for (src = space_map; *src; src++)
1234                         termz[i++] = *src;
1235                 space_map = NULL;
1236                 for (src = *map; *src; src++)
1237                     termz[i++] = *src;
1238             }
1239         }
1240         termz[i] = '\0';
1241     }
1242     return 0;
1243 }
1244
1245 static RSET rpn_prox (ZebraHandle zh, RSET *rset, int rset_no,
1246                       int ordered, int exclusion, int relation, int distance)
1247 {
1248     int i;
1249     RSFD *rsfd;
1250     int  *more;
1251     struct it_key **buf;
1252     RSET result;
1253     char prox_term[1024];
1254     int length_prox_term = 0;
1255     int min_nn = 10000000;
1256     int term_index;
1257     int term_type = Z_Term_characterString;
1258     const char *flags = NULL;
1259     
1260     rsfd = (RSFD *) xmalloc (sizeof(*rsfd)*rset_no);
1261     more = (int *) xmalloc (sizeof(*more)*rset_no);
1262     buf = (struct it_key **) xmalloc (sizeof(*buf)*rset_no);
1263
1264     *prox_term = '\0';
1265     for (i = 0; i<rset_no; i++)
1266     {
1267         int j;
1268         for (j = 0; j<rset[i]->no_rset_terms; j++)
1269         {
1270             const char *nflags = rset[i]->rset_terms[j]->flags;
1271             char *term = rset[i]->rset_terms[j]->name;
1272             int lterm = strlen(term);
1273             if (lterm + length_prox_term < sizeof(prox_term)-1)
1274             {
1275                 if (length_prox_term)
1276                     prox_term[length_prox_term++] = ' ';
1277                 strcpy (prox_term + length_prox_term, term);
1278                 length_prox_term += lterm;
1279             }
1280             if (min_nn > rset[i]->rset_terms[j]->nn)
1281                 min_nn = rset[i]->rset_terms[j]->nn;
1282             flags = nflags;
1283             term_type = rset[i]->rset_terms[j]->type;
1284
1285             /* only if all term types are of type characterString .. */
1286             /* the resulting term is of that type */
1287             if (term_type != Z_Term_characterString)
1288                 term_type = Z_Term_general;
1289         }
1290     }
1291     for (i = 0; i<rset_no; i++)
1292     {
1293         buf[i] = 0;
1294         rsfd[i] = 0;
1295     }
1296     for (i = 0; i<rset_no; i++)
1297     {
1298         buf[i] = (struct it_key *) xmalloc (sizeof(**buf));
1299         rsfd[i] = rset_open (rset[i], RSETF_READ);
1300         if (!(more[i] = rset_read (rset[i], rsfd[i], buf[i], &term_index)))
1301             break;
1302     }
1303     if (i != rset_no)
1304     {
1305         /* at least one is empty ... return null set */
1306         rset_null_parms parms;
1307         
1308         parms.rset_term = rset_term_create (prox_term, length_prox_term,
1309                                             flags, term_type);
1310         parms.rset_term->nn = 0;
1311         result = rset_create (rset_kind_null, &parms);
1312     }
1313     else if (ordered && relation == 3 && exclusion == 0 && distance == 1)
1314     {
1315         /* special proximity case = phrase search ... */
1316         rset_temp_parms parms;
1317         RSFD rsfd_result;
1318
1319         parms.rset_term = rset_term_create (prox_term, length_prox_term,
1320                                             flags, term_type);
1321         parms.rset_term->nn = min_nn;
1322         parms.cmp = key_compare_it;
1323         parms.key_size = sizeof (struct it_key);
1324         parms.temp_path = res_get (zh->res, "setTmpDir");
1325         result = rset_create (rset_kind_temp, &parms);
1326         rsfd_result = rset_open (result, RSETF_WRITE);
1327
1328         while (*more)
1329         {
1330             for (i = 1; i<rset_no; i++)
1331             {
1332                 int cmp;
1333                 
1334                 if (!more[i])
1335                 {
1336                     *more = 0;
1337                     break;
1338                 }
1339                 cmp = key_compare_it (buf[i], buf[i-1]);
1340                 if (cmp > 1)
1341                 {
1342                     more[i-1] = rset_read (rset[i-1], rsfd[i-1],
1343                                            buf[i-1], &term_index);
1344                     break;
1345                 }
1346                 else if (cmp == 1)
1347                 {
1348                     if (buf[i-1]->seqno+1 != buf[i]->seqno)
1349                     {
1350                         more[i-1] = rset_read (rset[i-1], rsfd[i-1],
1351                                                buf[i-1], &term_index);
1352                         break;
1353                     }
1354                 }
1355                 else
1356                 {
1357                     more[i] = rset_read (rset[i], rsfd[i], buf[i],
1358                                          &term_index);
1359                     break;
1360                 }
1361             }
1362             if (i == rset_no)
1363             {
1364                 rset_write (result, rsfd_result, buf[0]);
1365                 more[0] = rset_read (*rset, *rsfd, *buf, &term_index);
1366             }
1367         }
1368         rset_close (result, rsfd_result);
1369     }
1370     else if (rset_no == 2)
1371     {
1372         /* generic proximity case (two input sets only) ... */
1373         rset_temp_parms parms;
1374         RSFD rsfd_result;
1375
1376         yaz_log (LOG_LOG, "generic prox, dist=%d, relation=%d, ordered=%d"
1377                           ", exclusion=%d",
1378                           distance, relation, ordered, exclusion);
1379         parms.rset_term = rset_term_create (prox_term, length_prox_term,
1380                                             flags, term_type);
1381         parms.rset_term->nn = min_nn;
1382         parms.cmp = key_compare_it;
1383         parms.key_size = sizeof (struct it_key);
1384         parms.temp_path = res_get (zh->res, "setTmpDir");
1385         result = rset_create (rset_kind_temp, &parms);
1386         rsfd_result = rset_open (result, RSETF_WRITE);
1387
1388         while (more[0] && more[1]) 
1389         {
1390             int cmp = key_compare_it (buf[0], buf[1]);
1391             if (cmp < -1)
1392                 more[0] = rset_read (rset[0], rsfd[0], buf[0], &term_index);
1393             else if (cmp > 1)
1394                 more[1] = rset_read (rset[1], rsfd[1], buf[1], &term_index);
1395             else
1396             {
1397                 int sysno = buf[0]->sysno;
1398                 int seqno[500];
1399                 int n = 0;
1400                 
1401                 seqno[n++] = buf[0]->seqno;
1402                 while ((more[0] = rset_read (rset[0], rsfd[0], buf[0],
1403                                              &term_index)) &&
1404                        sysno == buf[0]->sysno)
1405                     if (n < 500)
1406                         seqno[n++] = buf[0]->seqno;
1407                 do
1408                 {
1409                     for (i = 0; i<n; i++)
1410                     {
1411                         int diff = buf[1]->seqno - seqno[i];
1412                         int excl = exclusion;
1413                         if (!ordered && diff < 0)
1414                             diff = -diff;
1415                         switch (relation)
1416                         {
1417                         case 1:      /* < */
1418                             if (diff < distance && diff >= 0)
1419                                 excl = !excl;
1420                             break;
1421                         case 2:      /* <= */
1422                             if (diff <= distance && diff >= 0)
1423                                 excl = !excl;
1424                             break;
1425                         case 3:      /* == */
1426                             if (diff == distance && diff >= 0)
1427                                 excl = !excl;
1428                             break;
1429                         case 4:      /* >= */
1430                             if (diff >= distance && diff >= 0)
1431                                 excl = !excl;
1432                             break;
1433                         case 5:      /* > */
1434                             if (diff > distance && diff >= 0)
1435                                 excl = !excl;
1436                             break;
1437                         case 6:      /* != */
1438                             if (diff != distance && diff >= 0)
1439                                 excl = !excl;
1440                             break;
1441                         }
1442                         if (excl)
1443                         {
1444                             rset_write (result, rsfd_result, buf[1]);
1445                             break;
1446                         }
1447                     }
1448                 } while ((more[1] = rset_read (rset[1], rsfd[1], buf[1],
1449                                                &term_index)) &&
1450                          sysno == buf[1]->sysno);
1451             }
1452         }
1453         rset_close (result, rsfd_result);
1454     }
1455     else
1456     {
1457         rset_null_parms parms;
1458         
1459         parms.rset_term = rset_term_create (prox_term, length_prox_term,
1460                                             flags, term_type);
1461         parms.rset_term->nn = 0;
1462         result = rset_create (rset_kind_null, &parms);
1463     }
1464     for (i = 0; i<rset_no; i++)
1465     {
1466         if (rsfd[i])
1467             rset_close (rset[i], rsfd[i]);
1468         xfree (buf[i]);
1469     }
1470     xfree (buf);
1471     xfree (more);
1472     xfree (rsfd);
1473     return result;
1474 }
1475
1476
1477 char *normalize_term(ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1478                      const char *termz, NMEM stream, unsigned reg_id)
1479 {
1480     WRBUF wrbuf = 0;
1481     AttrType truncation;
1482     int truncation_value;
1483     char *ex_list = 0;
1484
1485     attr_init (&truncation, zapt, 5);
1486     truncation_value = attr_find (&truncation, NULL);
1487
1488     switch (truncation_value)
1489     {
1490     default:
1491         ex_list = "";
1492         break;
1493     case 101:
1494         ex_list = "#";
1495         break;
1496     case 102:
1497     case 103:
1498         ex_list = 0;
1499         break;
1500     case 104:
1501         ex_list = "!#";
1502         break;
1503     case 105:
1504         ex_list = "!*";
1505         break;
1506     }
1507     if (ex_list)
1508         wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, ex_list,
1509                               termz, strlen(termz));
1510     if (!wrbuf)
1511         return nmem_strdup(stream, termz);
1512     else
1513     {
1514         char *buf = (char*) nmem_malloc (stream, wrbuf_len(wrbuf)+1);
1515         memcpy (buf, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1516         buf[wrbuf_len(wrbuf)] = '\0';
1517         return buf;
1518     }
1519 }
1520
1521 static void grep_info_delete (struct grep_info *grep_info)
1522 {
1523 #ifdef TERM_COUNT
1524     xfree(grep_info->term_no);
1525 #endif
1526     xfree (grep_info->isam_p_buf);
1527 }
1528
1529 static int grep_info_prepare (ZebraHandle zh,
1530                               Z_AttributesPlusTerm *zapt,
1531                               struct grep_info *grep_info,
1532                               int reg_type,
1533                               NMEM stream)
1534 {
1535     AttrType termset;
1536     int termset_value_numeric;
1537     const char *termset_value_string;
1538
1539 #ifdef TERM_COUNT
1540     grep_info->term_no = 0;
1541 #endif
1542     grep_info->isam_p_size = 0;
1543     grep_info->isam_p_buf = NULL;
1544     grep_info->zh = zh;
1545     grep_info->reg_type = reg_type;
1546     grep_info->termset = 0;
1547
1548     if (!zapt)
1549         return 0;
1550     attr_init (&termset, zapt, 8);
1551     termset_value_numeric =
1552         attr_find_ex (&termset, NULL, &termset_value_string);
1553     if (termset_value_numeric != -1)
1554     {
1555         char resname[32];
1556         const char *termset_name = 0;
1557         if (termset_value_numeric != -2)
1558         {
1559     
1560             sprintf (resname, "%d", termset_value_numeric);
1561             termset_name = resname;
1562         }
1563         else
1564             termset_name = termset_value_string;
1565         logf (LOG_LOG, "creating termset set %s", termset_name);
1566         grep_info->termset = resultSetAdd (zh, termset_name, 1);
1567         if (!grep_info->termset)
1568         {
1569             zh->errCode = 128;
1570             zh->errString = nmem_strdup (stream, termset_name);
1571             return -1;
1572         }
1573     }
1574     return 0;
1575 }
1576                                
1577
1578 static RSET rpn_search_APT_phrase (ZebraHandle zh,
1579                                    Z_AttributesPlusTerm *zapt,
1580                                    const char *termz_org,
1581                                    oid_value attributeSet,
1582                                    NMEM stream,
1583                                    int reg_type, int complete_flag,
1584                                    const char *rank_type, int xpath_use,
1585                                    int num_bases, char **basenames)
1586 {
1587     char term_dst[IT_MAX_WORD+1];
1588     RSET rset[60], result;
1589     int i, rset_no = 0;
1590     struct grep_info grep_info;
1591     char *termz = normalize_term(zh, zapt, termz_org, stream, reg_type);
1592     const char *termp = termz;
1593
1594     *term_dst = 0;
1595     if (grep_info_prepare (zh, zapt, &grep_info, reg_type, stream))
1596         return 0;
1597     while (1)
1598     { 
1599         logf (LOG_DEBUG, "APT_phrase termp=%s", termp);
1600         rset[rset_no] = term_trunc (zh, zapt, &termp, attributeSet,
1601                                     stream, &grep_info,
1602                                     reg_type, complete_flag,
1603                                     num_bases, basenames,
1604                                     term_dst, rank_type,
1605                                     xpath_use);
1606         if (!rset[rset_no])
1607             break;
1608         if (++rset_no >= (int) (sizeof(rset)/sizeof(*rset)))
1609             break;
1610     }
1611     grep_info_delete (&grep_info);
1612     if (rset_no == 0)
1613     {
1614         rset_null_parms parms;
1615         
1616         parms.rset_term = rset_term_create (termz, -1, rank_type,
1617                                             zapt->term->which);
1618         return rset_create (rset_kind_null, &parms);
1619     }
1620     else if (rset_no == 1)
1621         return (rset[0]);
1622     result = rpn_prox (zh, rset, rset_no, 1, 0, 3, 1);
1623     for (i = 0; i<rset_no; i++)
1624         rset_delete (rset[i]);
1625     return result;
1626 }
1627
1628 static RSET rpn_search_APT_or_list (ZebraHandle zh,
1629                                     Z_AttributesPlusTerm *zapt,
1630                                     const char *termz_org,
1631                                     oid_value attributeSet,
1632                                     NMEM stream,
1633                                     int reg_type, int complete_flag,
1634                                     const char *rank_type,
1635                                     int xpath_use,
1636                                     int num_bases, char **basenames)
1637 {
1638     char term_dst[IT_MAX_WORD+1];
1639     RSET rset[60], result;
1640     int i, rset_no = 0;
1641     struct grep_info grep_info;
1642     char *termz = normalize_term(zh, zapt, termz_org, stream, reg_type);
1643     const char *termp = termz;
1644
1645     if (grep_info_prepare (zh, zapt, &grep_info, reg_type, stream))
1646         return 0;
1647     while (1)
1648     { 
1649         logf (LOG_DEBUG, "APT_or_list termp=%s", termp);
1650         rset[rset_no] = term_trunc (zh, zapt, &termp, attributeSet,
1651                                     stream, &grep_info,
1652                                     reg_type, complete_flag,
1653                                     num_bases, basenames,
1654                                     term_dst, rank_type,
1655                                     xpath_use);
1656         if (!rset[rset_no])
1657             break;
1658         if (++rset_no >= (int) (sizeof(rset)/sizeof(*rset)))
1659             break;
1660     }
1661     grep_info_delete (&grep_info);
1662     if (rset_no == 0)
1663     {
1664         rset_null_parms parms;
1665         
1666         parms.rset_term = rset_term_create (termz, -1, rank_type,
1667                                             zapt->term->which);
1668         return rset_create (rset_kind_null, &parms);
1669     }
1670     result = rset[0];
1671     for (i = 1; i<rset_no; i++)
1672     {
1673         rset_bool_parms bool_parms;
1674
1675         bool_parms.rset_l = result;
1676         bool_parms.rset_r = rset[i];
1677         bool_parms.key_size = sizeof(struct it_key);
1678         bool_parms.cmp = key_compare_it;
1679         result = rset_create (rset_kind_or, &bool_parms);
1680     }
1681     return result;
1682 }
1683
1684 static RSET rpn_search_APT_and_list (ZebraHandle zh,
1685                                      Z_AttributesPlusTerm *zapt,
1686                                      const char *termz_org,
1687                                      oid_value attributeSet,
1688                                      NMEM stream,
1689                                      int reg_type, int complete_flag,
1690                                      const char *rank_type, 
1691                                      int xpath_use,
1692                                      int num_bases, char **basenames)
1693 {
1694     char term_dst[IT_MAX_WORD+1];
1695     RSET rset[60], result;
1696     int i, rset_no = 0;
1697     struct grep_info grep_info;
1698     char *termz = normalize_term(zh, zapt, termz_org, stream, reg_type);
1699     const char *termp = termz;
1700
1701     if (grep_info_prepare (zh, zapt, &grep_info, reg_type, stream))
1702         return 0;
1703     while (1)
1704     { 
1705         logf (LOG_DEBUG, "APT_and_list termp=%s", termp);
1706         rset[rset_no] = term_trunc (zh, zapt, &termp, attributeSet,
1707                                     stream, &grep_info,
1708                                     reg_type, complete_flag,
1709                                     num_bases, basenames,
1710                                     term_dst, rank_type,
1711                                     xpath_use);
1712         if (!rset[rset_no])
1713             break;
1714         assert (rset[rset_no]);
1715         if (++rset_no >= (int) (sizeof(rset)/sizeof(*rset)))
1716             break;
1717     }
1718     grep_info_delete (&grep_info);
1719     if (rset_no == 0)
1720     {
1721         rset_null_parms parms;
1722         
1723         parms.rset_term = rset_term_create (termz, -1, rank_type,
1724                                             zapt->term->which);
1725         return rset_create (rset_kind_null, &parms);
1726     }
1727     result = rset[0];
1728     for (i = 1; i<rset_no; i++)
1729     {
1730         rset_bool_parms bool_parms;
1731
1732         bool_parms.rset_l = result;
1733         bool_parms.rset_r = rset[i];
1734         bool_parms.key_size = sizeof(struct it_key);
1735         bool_parms.cmp = key_compare_it;
1736         result = rset_create (rset_kind_and, &bool_parms);
1737     }
1738     return result;
1739 }
1740
1741 static int numeric_relation (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1742                              const char **term_sub,
1743                              char *term_dict,
1744                              oid_value attributeSet,
1745                              struct grep_info *grep_info,
1746                              int *max_pos,
1747                              int reg_type,
1748                              char *term_dst)
1749 {
1750     AttrType relation;
1751     int relation_value;
1752     int term_value;
1753     int r;
1754     char *term_tmp = term_dict + strlen(term_dict);
1755
1756     attr_init (&relation, zapt, 2);
1757     relation_value = attr_find (&relation, NULL);
1758
1759     logf (LOG_DEBUG, "numeric relation value=%d", relation_value);
1760
1761     if (!term_100 (zh->reg->zebra_maps, reg_type, term_sub, term_tmp, 1,
1762                    term_dst))
1763         return 0;
1764     term_value = atoi (term_tmp);
1765     switch (relation_value)
1766     {
1767     case 1:
1768         logf (LOG_DEBUG, "Relation <");
1769         gen_regular_rel (term_tmp, term_value-1, 1);
1770         break;
1771     case 2:
1772         logf (LOG_DEBUG, "Relation <=");
1773         gen_regular_rel (term_tmp, term_value, 1);
1774         break;
1775     case 4:
1776         logf (LOG_DEBUG, "Relation >=");
1777         gen_regular_rel (term_tmp, term_value, 0);
1778         break;
1779     case 5:
1780         logf (LOG_DEBUG, "Relation >");
1781         gen_regular_rel (term_tmp, term_value+1, 0);
1782         break;
1783     case 3:
1784     default:
1785         logf (LOG_DEBUG, "Relation =");
1786         sprintf (term_tmp, "(0*%d)", term_value);
1787     }
1788     logf (LOG_DEBUG, "dict_lookup_grep: %s", term_tmp);
1789     r = dict_lookup_grep (zh->reg->dict, term_dict, 0, grep_info, max_pos,
1790                           0, grep_handle);
1791     if (r)
1792         logf (LOG_WARN, "dict_lookup_grep fail, rel=gt: %d", r);
1793     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
1794     return 1;
1795 }
1796
1797 static int numeric_term (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1798                          const char **term_sub, 
1799                          oid_value attributeSet, struct grep_info *grep_info,
1800                          int reg_type, int complete_flag,
1801                          int num_bases, char **basenames,
1802                          char *term_dst, int xpath_use, NMEM stream)
1803 {
1804     char term_dict[2*IT_MAX_WORD+2];
1805     int r, base_no;
1806     AttrType use;
1807     int use_value;
1808     const char *use_string = 0;
1809     oid_value curAttributeSet = attributeSet;
1810     const char *termp;
1811     struct rpn_char_map_info rcmi;
1812
1813     int bases_ok = 0;     /* no of databases with OK attribute */
1814     int errCode = 0;      /* err code (if any is not OK) */
1815     char *errString = 0;  /* addinfo */
1816
1817     rpn_char_map_prepare (zh->reg, reg_type, &rcmi);
1818     attr_init (&use, zapt, 1);
1819     use_value = attr_find_ex (&use, &curAttributeSet, &use_string);
1820
1821     if (use_value == -1)
1822         use_value = 1016;
1823
1824     for (base_no = 0; base_no < num_bases; base_no++)
1825     {
1826         attent attp;
1827         data1_local_attribute id_xpath_attr;
1828         data1_local_attribute *local_attr;
1829         int max_pos, prefix_len = 0;
1830
1831         termp = *term_sub;
1832         if (use_value == -2)  /* string attribute (assume IDXPATH/any) */
1833         {
1834             use_value = xpath_use;
1835             attp.local_attributes = &id_xpath_attr;
1836             attp.attset_ordinal = VAL_IDXPATH;
1837             id_xpath_attr.next = 0;
1838             id_xpath_attr.local = use_value;
1839         }
1840         else if (curAttributeSet == VAL_IDXPATH)
1841         {
1842             attp.local_attributes = &id_xpath_attr;
1843             attp.attset_ordinal = VAL_IDXPATH;
1844             id_xpath_attr.next = 0;
1845             id_xpath_attr.local = use_value;
1846         }
1847         else
1848         {
1849             if ((r=att_getentbyatt (zh, &attp, curAttributeSet, use_value)))
1850             {
1851                 logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d r=%d",
1852                       curAttributeSet, use_value, r);
1853                 if (r == -1)
1854                 {
1855                     char val_str[32];
1856                     sprintf (val_str, "%d", use_value);
1857                     errString = nmem_strdup (stream, val_str);
1858                     errCode = 114;
1859                 }
1860                 else
1861                     errCode = 121;
1862                 continue;
1863             }
1864         }
1865         if (zebraExplain_curDatabase (zh->reg->zei, basenames[base_no]))
1866         {
1867             zh->errCode = 109; /* Database unavailable */
1868             zh->errString = basenames[base_no];
1869             return -1;
1870         }
1871         for (local_attr = attp.local_attributes; local_attr;
1872              local_attr = local_attr->next)
1873         {
1874             int ord;
1875             char ord_buf[32];
1876             int i, ord_len;
1877
1878             ord = zebraExplain_lookupSU (zh->reg->zei, attp.attset_ordinal,
1879                                           local_attr->local);
1880             if (ord < 0)
1881                 continue;
1882             if (prefix_len)
1883                 term_dict[prefix_len++] = '|';
1884             else
1885                 term_dict[prefix_len++] = '(';
1886
1887             ord_len = key_SU_encode (ord, ord_buf);
1888             for (i = 0; i<ord_len; i++)
1889             {
1890                 term_dict[prefix_len++] = 1;
1891                 term_dict[prefix_len++] = ord_buf[i];
1892             }
1893         }
1894         if (!prefix_len)
1895         {
1896             char val_str[32];
1897             sprintf (val_str, "%d", use_value);
1898             errCode = 114;
1899             errString = nmem_strdup (stream, val_str);
1900             continue;
1901         }
1902         bases_ok++;
1903         term_dict[prefix_len++] = ')';        
1904         term_dict[prefix_len++] = 1;
1905         term_dict[prefix_len++] = reg_type;
1906         logf (LOG_DEBUG, "reg_type = %d", term_dict[prefix_len-1]);
1907         term_dict[prefix_len] = '\0';
1908         if (!numeric_relation (zh, zapt, &termp, term_dict,
1909                                attributeSet, grep_info, &max_pos, reg_type,
1910                                term_dst))
1911             return 0;
1912     }
1913     if (!bases_ok)
1914     {
1915         zh->errCode = errCode;
1916         zh->errString = errString;
1917         return -1;
1918     }
1919     *term_sub = termp;
1920     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
1921     return 1;
1922 }
1923
1924 static RSET rpn_search_APT_numeric (ZebraHandle zh,
1925                                     Z_AttributesPlusTerm *zapt,
1926                                     const char *termz,
1927                                     oid_value attributeSet,
1928                                     NMEM stream,
1929                                     int reg_type, int complete_flag,
1930                                     const char *rank_type, int xpath_use,
1931                                     int num_bases, char **basenames)
1932 {
1933     char term_dst[IT_MAX_WORD+1];
1934     const char *termp = termz;
1935     RSET rset[60], result;
1936     int i, r, rset_no = 0;
1937     struct grep_info grep_info;
1938
1939     if (grep_info_prepare (zh, zapt, &grep_info, reg_type, stream))
1940         return 0;
1941     while (1)
1942     { 
1943         logf (LOG_DEBUG, "APT_numeric termp=%s", termp);
1944         grep_info.isam_p_indx = 0;
1945         r = numeric_term (zh, zapt, &termp, attributeSet, &grep_info,
1946                           reg_type, complete_flag, num_bases, basenames,
1947                           term_dst, xpath_use,
1948                           stream);
1949         if (r < 1)
1950             break;
1951         logf (LOG_DEBUG, "term: %s", term_dst);
1952         rset[rset_no] = rset_trunc (zh, grep_info.isam_p_buf,
1953                                     grep_info.isam_p_indx, term_dst,
1954                                     strlen(term_dst), rank_type,
1955                                     0 /* preserve position */,
1956                                     zapt->term->which);
1957         assert (rset[rset_no]);
1958         if (++rset_no >= (int) (sizeof(rset)/sizeof(*rset)))
1959             break;
1960     }
1961     grep_info_delete (&grep_info);
1962     if (rset_no == 0)
1963     {
1964         rset_null_parms parms;
1965         
1966         parms.rset_term = rset_term_create (term_dst, -1, rank_type,
1967                                             zapt->term->which);
1968         return rset_create (rset_kind_null, &parms);
1969     }
1970     result = rset[0];
1971     for (i = 1; i<rset_no; i++)
1972     {
1973         rset_bool_parms bool_parms;
1974
1975         bool_parms.rset_l = result;
1976         bool_parms.rset_r = rset[i];
1977         bool_parms.key_size = sizeof(struct it_key);
1978         bool_parms.cmp = key_compare_it;
1979         result = rset_create (rset_kind_and, &bool_parms);
1980     }
1981     return result;
1982 }
1983
1984 static RSET rpn_search_APT_local (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1985                                   const char *termz,
1986                                   oid_value attributeSet,
1987                                   NMEM stream,
1988                                   const char *rank_type)
1989 {
1990     RSET result;
1991     RSFD rsfd;
1992     struct it_key key;
1993     rset_temp_parms parms;
1994
1995     parms.rset_term = rset_term_create (termz, -1, rank_type,
1996                                         zapt->term->which);
1997     parms.cmp = key_compare_it;
1998     parms.key_size = sizeof (struct it_key);
1999     parms.temp_path = res_get (zh->res, "setTmpDir");
2000     result = rset_create (rset_kind_temp, &parms);
2001     rsfd = rset_open (result, RSETF_WRITE);
2002
2003     key.sysno = atoi (termz);
2004     key.seqno = 1;
2005     if (key.sysno <= 0)
2006         key.sysno = 1;
2007     rset_write (result, rsfd, &key);
2008     rset_close (result, rsfd);
2009     return result;
2010 }
2011
2012 static RSET rpn_sort_spec (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
2013                            oid_value attributeSet, NMEM stream,
2014                            Z_SortKeySpecList *sort_sequence,
2015                            const char *rank_type)
2016 {
2017     rset_null_parms parms;    
2018     int i;
2019     int sort_relation_value;
2020     AttrType sort_relation_type;
2021     int use_value;
2022     AttrType use_type;
2023     Z_SortKeySpec *sks;
2024     Z_SortKey *sk;
2025     Z_AttributeElement *ae;
2026     int oid[OID_SIZE];
2027     oident oe;
2028     char termz[20];
2029     
2030     attr_init (&sort_relation_type, zapt, 7);
2031     sort_relation_value = attr_find (&sort_relation_type, &attributeSet);
2032
2033     attr_init (&use_type, zapt, 1);
2034     use_value = attr_find (&use_type, &attributeSet);
2035
2036     if (!sort_sequence->specs)
2037     {
2038         sort_sequence->num_specs = 10;
2039         sort_sequence->specs = (Z_SortKeySpec **)
2040             nmem_malloc (stream, sort_sequence->num_specs *
2041                          sizeof(*sort_sequence->specs));
2042         for (i = 0; i<sort_sequence->num_specs; i++)
2043             sort_sequence->specs[i] = 0;
2044     }
2045     if (zapt->term->which != Z_Term_general)
2046         i = 0;
2047     else
2048         i = atoi_n ((char *) zapt->term->u.general->buf,
2049                     zapt->term->u.general->len);
2050     if (i >= sort_sequence->num_specs)
2051         i = 0;
2052     sprintf (termz, "%d", i);
2053
2054     oe.proto = PROTO_Z3950;
2055     oe.oclass = CLASS_ATTSET;
2056     oe.value = attributeSet;
2057     if (!oid_ent_to_oid (&oe, oid))
2058         return 0;
2059
2060     sks = (Z_SortKeySpec *) nmem_malloc (stream, sizeof(*sks));
2061     sks->sortElement = (Z_SortElement *)
2062         nmem_malloc (stream, sizeof(*sks->sortElement));
2063     sks->sortElement->which = Z_SortElement_generic;
2064     sk = sks->sortElement->u.generic = (Z_SortKey *)
2065         nmem_malloc (stream, sizeof(*sk));
2066     sk->which = Z_SortKey_sortAttributes;
2067     sk->u.sortAttributes = (Z_SortAttributes *)
2068         nmem_malloc (stream, sizeof(*sk->u.sortAttributes));
2069
2070     sk->u.sortAttributes->id = oid;
2071     sk->u.sortAttributes->list = (Z_AttributeList *)
2072         nmem_malloc (stream, sizeof(*sk->u.sortAttributes->list));
2073     sk->u.sortAttributes->list->num_attributes = 1;
2074     sk->u.sortAttributes->list->attributes = (Z_AttributeElement **)
2075         nmem_malloc (stream, sizeof(*sk->u.sortAttributes->list->attributes));
2076     ae = *sk->u.sortAttributes->list->attributes = (Z_AttributeElement *)
2077         nmem_malloc (stream, sizeof(**sk->u.sortAttributes->list->attributes));
2078     ae->attributeSet = 0;
2079     ae->attributeType = (int *)
2080         nmem_malloc (stream, sizeof(*ae->attributeType));
2081     *ae->attributeType = 1;
2082     ae->which = Z_AttributeValue_numeric;
2083     ae->value.numeric = (int *)
2084         nmem_malloc (stream, sizeof(*ae->value.numeric));
2085     *ae->value.numeric = use_value;
2086
2087     sks->sortRelation = (int *)
2088         nmem_malloc (stream, sizeof(*sks->sortRelation));
2089     if (sort_relation_value == 1)
2090         *sks->sortRelation = Z_SortRelation_ascending;
2091     else if (sort_relation_value == 2)
2092         *sks->sortRelation = Z_SortRelation_descending;
2093     else 
2094         *sks->sortRelation = Z_SortRelation_ascending;
2095
2096     sks->caseSensitivity = (int *)
2097         nmem_malloc (stream, sizeof(*sks->caseSensitivity));
2098     *sks->caseSensitivity = 0;
2099
2100     sks->which = Z_SortKeySpec_null;
2101     sks->u.null = odr_nullval ();
2102     sort_sequence->specs[i] = sks;
2103
2104     parms.rset_term = rset_term_create (termz, -1, rank_type,
2105                                         zapt->term->which);
2106     return rset_create (rset_kind_null, &parms);
2107 }
2108
2109 /* pop - moved to xpath.c */
2110 #if 0
2111
2112 struct xpath_predicate {
2113     int which;
2114     union {
2115 #define XPATH_PREDICATE_RELATION 1
2116         struct {
2117             char *name;
2118             char *op;
2119             char *value;
2120         } relation;
2121 #define XPATH_PREDICATE_BOOLEAN 2
2122         struct {
2123             const char *op;
2124             struct xpath_predicate *left;
2125             struct xpath_predicate *right;
2126         } boolean;
2127     } u;
2128 };
2129
2130 struct xpath_location_step {
2131     char *part;
2132     struct xpath_predicate *predicate;
2133 };
2134
2135 #endif
2136
2137 static int parse_xpath(ZebraHandle zh, Z_AttributesPlusTerm *zapt,
2138                        oid_value attributeSet,
2139                        struct xpath_location_step *xpath, int max, NMEM mem)
2140 {
2141     oid_value curAttributeSet = attributeSet;
2142     AttrType use;
2143     const char *use_string = 0;
2144     
2145     attr_init (&use, zapt, 1);
2146     attr_find_ex (&use, &curAttributeSet, &use_string);
2147
2148     if (!use_string || *use_string != '/')
2149         return -1;
2150
2151     return zebra_parse_xpath_str(use_string, xpath, max, mem);
2152 }
2153  
2154                
2155
2156 static RSET xpath_trunc(ZebraHandle zh, NMEM stream,
2157                         int reg_type, const char *term, int use,
2158                         oid_value curAttributeSet)
2159 {
2160     RSET rset;
2161     struct grep_info grep_info;
2162     char term_dict[2048];
2163     char ord_buf[32];
2164     int prefix_len = 0;
2165     int ord = zebraExplain_lookupSU (zh->reg->zei, curAttributeSet, use);
2166     int ord_len, i, r, max_pos;
2167     int term_type = Z_Term_characterString;
2168     const char *flags = "void";
2169
2170     if (grep_info_prepare (zh, 0 /* zapt */, &grep_info, '0', stream))
2171     {
2172         rset_null_parms parms;
2173         
2174         parms.rset_term = rset_term_create (term, strlen(term),
2175                                             flags, term_type);
2176         parms.rset_term->nn = 0;
2177         return rset_create (rset_kind_null, &parms);
2178     }
2179
2180     if (ord < 0)
2181     {
2182         rset_null_parms parms;
2183         
2184         parms.rset_term = rset_term_create (term, strlen(term),
2185                                             flags, term_type);
2186         parms.rset_term->nn = 0;
2187         return rset_create (rset_kind_null, &parms);
2188     }
2189     if (prefix_len)
2190         term_dict[prefix_len++] = '|';
2191     else
2192         term_dict[prefix_len++] = '(';
2193     
2194     ord_len = key_SU_encode (ord, ord_buf);
2195     for (i = 0; i<ord_len; i++)
2196     {
2197         term_dict[prefix_len++] = 1;
2198         term_dict[prefix_len++] = ord_buf[i];
2199     }
2200     term_dict[prefix_len++] = ')';
2201     term_dict[prefix_len++] = 1;
2202     term_dict[prefix_len++] = reg_type;
2203     
2204     strcpy (term_dict+prefix_len, term);
2205     
2206     grep_info.isam_p_indx = 0;
2207     r = dict_lookup_grep (zh->reg->dict, term_dict, 0,
2208                           &grep_info, &max_pos, 0, grep_handle);
2209     yaz_log (LOG_LOG, "%s %d positions", term,
2210              grep_info.isam_p_indx);
2211     rset = rset_trunc (zh, grep_info.isam_p_buf,
2212                        grep_info.isam_p_indx, term, strlen(term),
2213                        flags, 1, term_type);
2214     grep_info_delete (&grep_info);
2215     return rset;
2216 }
2217
2218 static RSET rpn_search_xpath (ZebraHandle zh,
2219                               oid_value attributeSet,
2220                               int num_bases, char **basenames,
2221                               NMEM stream, const char *rank_type, RSET rset,
2222                               int xpath_len, struct xpath_location_step *xpath)
2223 {
2224     oid_value curAttributeSet = attributeSet;
2225     int base_no;
2226     int i;
2227
2228     if (xpath_len < 0)
2229         return rset;
2230
2231     yaz_log (LOG_LOG, "len=%d", xpath_len);
2232     for (i = 0; i<xpath_len; i++)
2233     {
2234         yaz_log (LOG_LOG, "XPATH %d %s", i, xpath[i].part);
2235
2236     }
2237
2238     curAttributeSet = VAL_IDXPATH;
2239
2240     /*
2241       //a    ->    a/.*
2242       //a/b  ->    b/a/.*
2243       /a     ->    a/
2244       /a/b   ->    b/a/
2245
2246       /      ->    none
2247
2248    a[@attr=value]/b[@other=othervalue]
2249
2250  /e/@a val      range(e/,range(@a,freetext(w,1015,val),@a),e/)
2251  /a/b val       range(b/a/,freetext(w,1016,val),b/a/)
2252  /a/b/@c val    range(b/a/,range(@c,freetext(w,1016,val),@c),b/a/)
2253  /a/b[@c=y] val range(b/a/,freetext(w,1016,val),b/a/,@c=y)
2254  /a[@c=y]/b val range(a/,range(b/a/,freetext(w,1016,val),b/a/),a/,@c=y)
2255  /a[@c=x]/b[@c=y] range(a/,range(b/a/,freetext(w,1016,val),b/a/,@c=y),a/,@c=x)
2256       
2257     */
2258
2259     dict_grep_cmap (zh->reg->dict, 0, 0);
2260
2261     for (base_no = 0; base_no < num_bases; base_no++)
2262     {
2263         int level = xpath_len;
2264         int first_path = 1;
2265         
2266         if (zebraExplain_curDatabase (zh->reg->zei, basenames[base_no]))
2267         {
2268             zh->errCode = 109; /* Database unavailable */
2269             zh->errString = basenames[base_no];
2270             return rset;
2271         }
2272         while (--level >= 0)
2273         {
2274             char xpath_rev[128];
2275             int i, len;
2276             rset_between_parms parms;
2277             RSET rset_start_tag = 0, rset_end_tag = 0, rset_attr = 0;
2278
2279             *xpath_rev = 0;
2280             len = 0;
2281             for (i = level; i >= 1; --i)
2282             {
2283                 const char *cp = xpath[i].part;
2284                 if (*cp)
2285                 {
2286                     for (;*cp; cp++)
2287                         if (*cp == '*')
2288                         {
2289                             memcpy (xpath_rev + len, "[^/]*", 5);
2290                             len += 5;
2291                         }
2292                         else if (*cp == ' ')
2293                         {
2294
2295                             xpath_rev[len++] = 1;
2296                             xpath_rev[len++] = ' ';
2297                         }
2298
2299                         else
2300                             xpath_rev[len++] = *cp;
2301                     xpath_rev[len++] = '/';
2302                 }
2303                 else if (i == 1)  /* // case */
2304                 {
2305                     xpath_rev[len++] = '.';
2306                     xpath_rev[len++] = '*';
2307                 }
2308             }
2309             xpath_rev[len] = 0;
2310
2311             if (xpath[level].predicate &&
2312                 xpath[level].predicate->which == XPATH_PREDICATE_RELATION &&
2313                 xpath[level].predicate->u.relation.name[0])
2314             {
2315                 char predicate_str[128];
2316
2317                 strcpy (predicate_str,
2318                         xpath[level].predicate->u.relation.name+1);
2319                 if (xpath[level].predicate->u.relation.value)
2320                 {
2321                     strcat (predicate_str, "=");
2322                     strcat (predicate_str,
2323                             xpath[level].predicate->u.relation.value);
2324                 }
2325                 rset_attr = xpath_trunc (
2326                     zh, stream, '0', predicate_str, 3, curAttributeSet);
2327             } 
2328             else 
2329             {
2330                 if (!first_path)
2331                     continue;
2332             }
2333             yaz_log (LOG_LOG, "xpath_rev (%d) = %s", level, xpath_rev);
2334             if (strlen(xpath_rev))
2335             {
2336                 rset_start_tag = xpath_trunc(zh, stream, 
2337                                          '0', xpath_rev, 1, curAttributeSet);
2338             
2339                 rset_end_tag = xpath_trunc(zh, stream,
2340                                        '0', xpath_rev, 2, curAttributeSet);
2341
2342                 parms.key_size = sizeof(struct it_key);
2343                 parms.cmp = key_compare_it;
2344                 parms.rset_l = rset_start_tag;
2345                 parms.rset_m = rset;
2346                 parms.rset_r = rset_end_tag;
2347                 parms.rset_attr = rset_attr;
2348                 parms.printer = key_print_it;
2349                 rset = rset_create (rset_kind_between, &parms);
2350             }
2351             first_path = 0;
2352         }
2353     }
2354
2355     return rset;
2356 }
2357
2358
2359
2360 static RSET rpn_search_APT (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
2361                             oid_value attributeSet, NMEM stream,
2362                             Z_SortKeySpecList *sort_sequence,
2363                             int num_bases, char **basenames)
2364 {
2365     unsigned reg_id;
2366     char *search_type = NULL;
2367     char rank_type[128];
2368     int complete_flag;
2369     int sort_flag;
2370     char termz[IT_MAX_WORD+1];
2371     RSET rset = 0;
2372     int xpath_len;
2373     int xpath_use = 0;
2374     struct xpath_location_step xpath[10];
2375
2376     zebra_maps_attr (zh->reg->zebra_maps, zapt, &reg_id, &search_type,
2377                      rank_type, &complete_flag, &sort_flag);
2378     
2379     logf (LOG_DEBUG, "reg_id=%c", reg_id);
2380     logf (LOG_DEBUG, "complete_flag=%d", complete_flag);
2381     logf (LOG_DEBUG, "search_type=%s", search_type);
2382     logf (LOG_DEBUG, "rank_type=%s", rank_type);
2383
2384     if (zapt_term_to_utf8(zh, zapt, termz))
2385         return 0;
2386
2387     if (sort_flag)
2388         return rpn_sort_spec (zh, zapt, attributeSet, stream, sort_sequence,
2389                               rank_type);
2390     xpath_len = parse_xpath(zh, zapt, attributeSet, xpath, 10, stream);
2391     if (xpath_len >= 0)
2392     {
2393         xpath_use = 1016;
2394         if (xpath[xpath_len-1].part[0] == '@')
2395             xpath_use = 1015;
2396     }
2397
2398     if (!strcmp (search_type, "phrase"))
2399     {
2400         rset = rpn_search_APT_phrase (zh, zapt, termz, attributeSet, stream,
2401                                       reg_id, complete_flag, rank_type,
2402                                       xpath_use,
2403                                       num_bases, basenames);
2404     }
2405     else if (!strcmp (search_type, "and-list"))
2406     {
2407         rset = rpn_search_APT_and_list (zh, zapt, termz, attributeSet, stream,
2408                                         reg_id, complete_flag, rank_type,
2409                                         xpath_use,
2410                                         num_bases, basenames);
2411     }
2412     else if (!strcmp (search_type, "or-list"))
2413     {
2414         rset = rpn_search_APT_or_list (zh, zapt, termz, attributeSet, stream,
2415                                        reg_id, complete_flag, rank_type,
2416                                        xpath_use,
2417                                        num_bases, basenames);
2418     }
2419     else if (!strcmp (search_type, "local"))
2420     {
2421         rset = rpn_search_APT_local (zh, zapt, termz, attributeSet, stream,
2422                                      rank_type);
2423     }
2424     else if (!strcmp (search_type, "numeric"))
2425     {
2426         rset = rpn_search_APT_numeric (zh, zapt, termz, attributeSet, stream,
2427                                        reg_id, complete_flag, rank_type,
2428                                        xpath_use,
2429                                        num_bases, basenames);
2430     }
2431     else if (!strcmp (search_type, "always"))
2432     {
2433         rset = 0;
2434     }
2435     else
2436         zh->errCode = 118;
2437     return rpn_search_xpath (zh, attributeSet, num_bases, basenames,
2438                              stream, rank_type, rset, xpath_len, xpath);
2439 }
2440
2441 static RSET rpn_search_structure (ZebraHandle zh, Z_RPNStructure *zs,
2442                                   oid_value attributeSet, NMEM stream,
2443                                   Z_SortKeySpecList *sort_sequence,
2444                                   int num_bases, char **basenames)
2445 {
2446     RSET r = NULL;
2447     if (zs->which == Z_RPNStructure_complex)
2448     {
2449         Z_Operator *zop = zs->u.complex->roperator;
2450         rset_bool_parms bool_parms;
2451
2452         bool_parms.rset_l = rpn_search_structure (zh, zs->u.complex->s1,
2453                                                   attributeSet, stream,
2454                                                   sort_sequence,
2455                                                   num_bases, basenames);
2456         if (bool_parms.rset_l == NULL)
2457             return NULL;
2458         bool_parms.rset_r = rpn_search_structure (zh, zs->u.complex->s2,
2459                                                   attributeSet, stream,
2460                                                   sort_sequence,
2461                                                   num_bases, basenames);
2462         if (bool_parms.rset_r == NULL)
2463         {
2464             rset_delete (bool_parms.rset_l);
2465             return NULL;
2466         }
2467         bool_parms.key_size = sizeof(struct it_key);
2468         bool_parms.cmp = key_compare_it;
2469
2470         switch (zop->which)
2471         {
2472         case Z_Operator_and:
2473             r = rset_create (rset_kind_and, &bool_parms);
2474             break;
2475         case Z_Operator_or:
2476             r = rset_create (rset_kind_or, &bool_parms);
2477             break;
2478         case Z_Operator_and_not:
2479             r = rset_create (rset_kind_not, &bool_parms);
2480             break;
2481         case Z_Operator_prox:
2482             if (zop->u.prox->which != Z_ProximityOperator_known)
2483             {
2484                 zh->errCode = 132;
2485                 return NULL;
2486             }
2487             if (*zop->u.prox->u.known != Z_ProxUnit_word)
2488             {
2489                 char *val = (char *) nmem_malloc (stream, 16);
2490                 zh->errCode = 132;
2491                 zh->errString = val;
2492                 sprintf (val, "%d", *zop->u.prox->u.known);
2493                 return NULL;
2494             }
2495             else
2496             {
2497                 RSET rsets[2];
2498
2499                 rsets[0] = bool_parms.rset_l;
2500                 rsets[1] = bool_parms.rset_r;
2501                 
2502                 r = rpn_prox (zh, rsets, 2, 
2503                               *zop->u.prox->ordered,
2504                               (!zop->u.prox->exclusion ? 0 :
2505                                *zop->u.prox->exclusion),
2506                               *zop->u.prox->relationType,
2507                               *zop->u.prox->distance);
2508                 rset_delete (rsets[0]);
2509                 rset_delete (rsets[1]);
2510             }
2511             break;
2512         default:
2513             zh->errCode = 110;
2514             return NULL;
2515         }
2516     }
2517     else if (zs->which == Z_RPNStructure_simple)
2518     {
2519         if (zs->u.simple->which == Z_Operand_APT)
2520         {
2521             logf (LOG_DEBUG, "rpn_search_APT");
2522             r = rpn_search_APT (zh, zs->u.simple->u.attributesPlusTerm,
2523                                 attributeSet, stream, sort_sequence,
2524                                 num_bases, basenames);
2525         }
2526         else if (zs->u.simple->which == Z_Operand_resultSetId)
2527         {
2528             logf (LOG_DEBUG, "rpn_search_ref");
2529             r = resultSetRef (zh, zs->u.simple->u.resultSetId);
2530             if (!r)
2531             {
2532                 r = rset_create (rset_kind_null, NULL);
2533                 zh->errCode = 30;
2534                 zh->errString =
2535                     nmem_strdup (stream, zs->u.simple->u.resultSetId);
2536                 return 0;
2537             }
2538             else
2539                 rset_dup(r);
2540         }
2541         else
2542         {
2543             zh->errCode = 3;
2544             return 0;
2545         }
2546     }
2547     else
2548     {
2549         zh->errCode = 3;
2550         return 0;
2551     }
2552     return r;
2553 }
2554
2555
2556 RSET rpn_search (ZebraHandle zh, NMEM nmem,
2557                  Z_RPNQuery *rpn, int num_bases, char **basenames, 
2558                  const char *setname,
2559                  ZebraSet sset)
2560 {
2561     RSET rset;
2562     oident *attrset;
2563     oid_value attributeSet;
2564     Z_SortKeySpecList *sort_sequence;
2565     int sort_status, i;
2566
2567     zh->errCode = 0;
2568     zh->errString = NULL;
2569     zh->hits = 0;
2570
2571     sort_sequence = (Z_SortKeySpecList *)
2572         nmem_malloc (nmem, sizeof(*sort_sequence));
2573     sort_sequence->num_specs = 10;
2574     sort_sequence->specs = (Z_SortKeySpec **)
2575         nmem_malloc (nmem, sort_sequence->num_specs *
2576                      sizeof(*sort_sequence->specs));
2577     for (i = 0; i<sort_sequence->num_specs; i++)
2578         sort_sequence->specs[i] = 0;
2579     
2580     attrset = oid_getentbyoid (rpn->attributeSetId);
2581     attributeSet = attrset->value;
2582     rset = rpn_search_structure (zh, rpn->RPNStructure, attributeSet,
2583                                  nmem, sort_sequence, num_bases, basenames);
2584     if (!rset)
2585         return 0;
2586
2587     if (zh->errCode)
2588         logf (LOG_DEBUG, "search error: %d", zh->errCode);
2589     
2590     for (i = 0; sort_sequence->specs[i]; i++)
2591         ;
2592     sort_sequence->num_specs = i;
2593     if (!i)
2594         resultSetRank (zh, sset, rset);
2595     else
2596     {
2597         logf (LOG_DEBUG, "resultSetSortSingle in rpn_search");
2598         resultSetSortSingle (zh, nmem, sset, rset,
2599                              sort_sequence, &sort_status);
2600         if (zh->errCode)
2601         {
2602             logf (LOG_DEBUG, "resultSetSortSingle status = %d", zh->errCode);
2603         }
2604     }
2605     return rset;
2606 }
2607
2608 struct scan_info_entry {
2609     char *term;
2610     ISAMS_P isam_p;
2611 };
2612
2613 struct scan_info {
2614     struct scan_info_entry *list;
2615     ODR odr;
2616     int before, after;
2617     char prefix[20];
2618 };
2619
2620 static int scan_handle (char *name, const char *info, int pos, void *client)
2621 {
2622     int len_prefix, idx;
2623     struct scan_info *scan_info = (struct scan_info *) client;
2624
2625     len_prefix = strlen(scan_info->prefix);
2626     if (memcmp (name, scan_info->prefix, len_prefix))
2627         return 1;
2628     if (pos > 0)        idx = scan_info->after - pos + scan_info->before;
2629     else
2630         idx = - pos - 1;
2631     scan_info->list[idx].term = (char *)
2632         odr_malloc (scan_info->odr, strlen(name + len_prefix)+1);
2633     strcpy (scan_info->list[idx].term, name + len_prefix);
2634     assert (*info == sizeof(ISAMS_P));
2635     memcpy (&scan_info->list[idx].isam_p, info+1, sizeof(ISAMS_P));
2636     return 0;
2637 }
2638
2639 static void scan_term_untrans (ZebraHandle zh, NMEM stream, int reg_type,
2640                                char **dst, const char *src)
2641 {
2642     char term_src[IT_MAX_WORD];
2643     char term_dst[IT_MAX_WORD];
2644     
2645     term_untrans (zh, reg_type, term_src, src);
2646
2647     if (zh->iconv_from_utf8 != 0)
2648     {
2649         int len;
2650         char *inbuf = term_src;
2651         size_t inleft = strlen(term_src);
2652         char *outbuf = term_dst;
2653         size_t outleft = sizeof(term_dst)-1;
2654         size_t ret;
2655         
2656         ret = yaz_iconv (zh->iconv_from_utf8, &inbuf, &inleft,
2657                          &outbuf, &outleft);
2658         if (ret == (size_t)(-1))
2659             len = 0;
2660         else
2661             len = outbuf - term_dst;
2662         *dst = nmem_malloc (stream, len + 1);
2663         if (len > 0)
2664             memcpy (*dst, term_dst, len);
2665         (*dst)[len] = '\0';
2666     }
2667     else
2668         *dst = nmem_strdup (stream, term_src);
2669 }
2670
2671 static void count_set (RSET r, int *count)
2672 {
2673     int psysno = 0;
2674     int kno = 0;
2675     struct it_key key;
2676     RSFD rfd;
2677     int term_index;
2678
2679     logf (LOG_DEBUG, "count_set");
2680
2681     *count = 0;
2682     rfd = rset_open (r, RSETF_READ);
2683     while (rset_read (r, rfd, &key, &term_index))
2684     {
2685         if (key.sysno != psysno)
2686         {
2687             psysno = key.sysno;
2688             (*count)++;
2689         }
2690         kno++;
2691     }
2692     rset_close (r, rfd);
2693     logf (LOG_DEBUG, "%d keys, %d records", kno, *count);
2694 }
2695
2696 void rpn_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
2697                oid_value attributeset,
2698                int num_bases, char **basenames,
2699                int *position, int *num_entries, ZebraScanEntry **list,
2700                int *is_partial, RSET limit_set, int return_zero)
2701 {
2702     int i;
2703     int pos = *position;
2704     int num = *num_entries;
2705     int before;
2706     int after;
2707     int base_no;
2708     char termz[IT_MAX_WORD+20];
2709     AttrType use;
2710     int use_value;
2711     struct scan_info *scan_info_array;
2712     ZebraScanEntry *glist;
2713     int ords[32], ord_no = 0;
2714     int ptr[32];
2715
2716     int bases_ok = 0;     /* no of databases with OK attribute */
2717     int errCode = 0;      /* err code (if any is not OK) */
2718     char *errString = 0;  /* addinfo */
2719
2720     unsigned reg_id;
2721     char *search_type = NULL;
2722     char rank_type[128];
2723     int complete_flag;
2724     int sort_flag;
2725
2726     *list = 0;
2727
2728     if (attributeset == VAL_NONE)
2729         attributeset = VAL_BIB1;
2730
2731     if (!limit_set)
2732     {
2733         AttrType termset;
2734         int termset_value_numeric;
2735         const char *termset_value_string;
2736         attr_init (&termset, zapt, 8);
2737         termset_value_numeric =
2738             attr_find_ex (&termset, NULL, &termset_value_string);
2739         if (termset_value_numeric != -1)
2740         {
2741             char resname[32];
2742             const char *termset_name = 0;
2743             
2744             if (termset_value_numeric != -2)
2745             {
2746                 
2747                 sprintf (resname, "%d", termset_value_numeric);
2748                 termset_name = resname;
2749             }
2750             else
2751                 termset_name = termset_value_string;
2752             
2753             limit_set = resultSetRef (zh, termset_name);
2754         }
2755     }
2756         
2757     yaz_log (LOG_DEBUG, "position = %d, num = %d set=%d",
2758              pos, num, attributeset);
2759         
2760     attr_init (&use, zapt, 1);
2761     use_value = attr_find (&use, &attributeset);
2762
2763     if (zebra_maps_attr (zh->reg->zebra_maps, zapt, &reg_id, &search_type,
2764                          rank_type, &complete_flag, &sort_flag))
2765     {
2766         *num_entries = 0;
2767         zh->errCode = 113;
2768         return ;
2769     }
2770     yaz_log (LOG_DEBUG, "use_value = %d", use_value);
2771
2772     if (use_value == -1)
2773         use_value = 1016;
2774     for (base_no = 0; base_no < num_bases && ord_no < 32; base_no++)
2775     {
2776         int r;
2777         attent attp;
2778         data1_local_attribute *local_attr;
2779
2780         if ((r=att_getentbyatt (zh, &attp, attributeset, use_value)))
2781         {
2782             logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d",
2783                   attributeset, use_value);
2784             if (r == -1)
2785             {
2786                 char val_str[32];
2787                 sprintf (val_str, "%d", use_value);
2788                 errCode = 114;
2789                 errString = odr_strdup (stream, val_str);
2790             }   
2791             else
2792                 errCode = 121;
2793             continue;
2794         }
2795         if (zebraExplain_curDatabase (zh->reg->zei, basenames[base_no]))
2796         {
2797             zh->errString = basenames[base_no];
2798             zh->errCode = 109; /* Database unavailable */
2799             *num_entries = 0;
2800             return;
2801         }
2802         bases_ok++;
2803         for (local_attr = attp.local_attributes; local_attr && ord_no < 32;
2804              local_attr = local_attr->next)
2805         {
2806             int ord;
2807
2808             ord = zebraExplain_lookupSU (zh->reg->zei, attp.attset_ordinal,
2809                                          local_attr->local);
2810             if (ord > 0)
2811                 ords[ord_no++] = ord;
2812         }
2813     }
2814     if (!bases_ok && errCode)
2815     {
2816         zh->errCode = errCode;
2817         zh->errString = errString;
2818         *num_entries = 0;
2819     }
2820     if (ord_no == 0)
2821     {
2822         char val_str[32];
2823         sprintf (val_str, "%d", use_value);
2824         zh->errCode = 114;
2825         zh->errString = odr_strdup (stream, val_str);
2826
2827         *num_entries = 0;
2828         return;
2829     }
2830     /* prepare dictionary scanning */
2831     before = pos-1;
2832     after = 1+num-pos;
2833     scan_info_array = (struct scan_info *)
2834         odr_malloc (stream, ord_no * sizeof(*scan_info_array));
2835     for (i = 0; i < ord_no; i++)
2836     {
2837         int j, prefix_len = 0;
2838         int before_tmp = before, after_tmp = after;
2839         struct scan_info *scan_info = scan_info_array + i;
2840         struct rpn_char_map_info rcmi;
2841
2842         rpn_char_map_prepare (zh->reg, reg_id, &rcmi);
2843
2844         scan_info->before = before;
2845         scan_info->after = after;
2846         scan_info->odr = stream;
2847
2848         scan_info->list = (struct scan_info_entry *)
2849             odr_malloc (stream, (before+after) * sizeof(*scan_info->list));
2850         for (j = 0; j<before+after; j++)
2851             scan_info->list[j].term = NULL;
2852
2853         prefix_len += key_SU_encode (ords[i], termz + prefix_len);
2854         termz[prefix_len++] = reg_id;
2855         termz[prefix_len] = 0;
2856         strcpy (scan_info->prefix, termz);
2857
2858         if (trans_scan_term (zh, zapt, termz+prefix_len, reg_id))
2859             return ;
2860                     
2861         dict_scan (zh->reg->dict, termz, &before_tmp, &after_tmp,
2862                    scan_info, scan_handle);
2863     }
2864     glist = (ZebraScanEntry *)
2865         odr_malloc (stream, (before+after)*sizeof(*glist));
2866
2867     /* consider terms after main term */
2868     for (i = 0; i < ord_no; i++)
2869         ptr[i] = before;
2870     
2871     *is_partial = 0;
2872     for (i = 0; i<after; i++)
2873     {
2874         int j, j0 = -1;
2875         const char *mterm = NULL;
2876         const char *tst;
2877         RSET rset;
2878         
2879         for (j = 0; j < ord_no; j++)
2880         {
2881             if (ptr[j] < before+after &&
2882                 (tst=scan_info_array[j].list[ptr[j]].term) &&
2883                 (!mterm || strcmp (tst, mterm) < 0))
2884             {
2885                 j0 = j;
2886                 mterm = tst;
2887             }
2888         }
2889         if (j0 == -1)
2890             break;
2891         scan_term_untrans (zh, stream->mem, reg_id,
2892                            &glist[i+before].term, mterm);
2893         rset = rset_trunc (zh, &scan_info_array[j0].list[ptr[j0]].isam_p, 1,
2894                            glist[i+before].term, strlen(glist[i+before].term),
2895                            NULL, 0, zapt->term->which);
2896
2897         ptr[j0]++;
2898         for (j = j0+1; j<ord_no; j++)
2899         {
2900             if (ptr[j] < before+after &&
2901                 (tst=scan_info_array[j].list[ptr[j]].term) &&
2902                 !strcmp (tst, mterm))
2903             {
2904                 rset_bool_parms bool_parms;
2905                 RSET rset2;
2906
2907                 rset2 =
2908                    rset_trunc (zh, &scan_info_array[j].list[ptr[j]].isam_p, 1,
2909                                glist[i+before].term,
2910                                strlen(glist[i+before].term), NULL, 0,
2911                                zapt->term->which);
2912
2913                 bool_parms.key_size = sizeof(struct it_key);
2914                 bool_parms.cmp = key_compare_it;
2915                 bool_parms.rset_l = rset;
2916                 bool_parms.rset_r = rset2;
2917               
2918                 rset = rset_create (rset_kind_or, &bool_parms);
2919
2920                 ptr[j]++;
2921             }
2922         }
2923         if (limit_set)
2924         {
2925             rset_bool_parms bool_parms;
2926
2927             bool_parms.key_size = sizeof(struct it_key);
2928             bool_parms.cmp = key_compare_it;
2929             bool_parms.rset_l = rset;
2930             bool_parms.rset_r = rset_dup(limit_set);
2931
2932             rset = rset_create (rset_kind_and, &bool_parms);
2933         }
2934         count_set (rset, &glist[i+before].occurrences);
2935         rset_delete (rset);
2936     }
2937     if (i < after)
2938     {
2939         *num_entries -= (after-i);
2940         *is_partial = 1;
2941     }
2942
2943     /* consider terms before main term */
2944     for (i = 0; i<ord_no; i++)
2945         ptr[i] = 0;
2946
2947     for (i = 0; i<before; i++)
2948     {
2949         int j, j0 = -1;
2950         const char *mterm = NULL;
2951         const char *tst;
2952         RSET rset;
2953         
2954         for (j = 0; j <ord_no; j++)
2955         {
2956             if (ptr[j] < before &&
2957                 (tst=scan_info_array[j].list[before-1-ptr[j]].term) &&
2958                 (!mterm || strcmp (tst, mterm) > 0))
2959             {
2960                 j0 = j;
2961                 mterm = tst;
2962             }
2963         }
2964         if (j0 == -1)
2965             break;
2966
2967         scan_term_untrans (zh, stream->mem, reg_id,
2968                            &glist[before-1-i].term, mterm);
2969
2970         rset = rset_trunc
2971                (zh, &scan_info_array[j0].list[before-1-ptr[j0]].isam_p, 1,
2972                 glist[before-1-i].term, strlen(glist[before-1-i].term),
2973                 NULL, 0, zapt->term->which);
2974
2975         ptr[j0]++;
2976
2977         for (j = j0+1; j<ord_no; j++)
2978         {
2979             if (ptr[j] < before &&
2980                 (tst=scan_info_array[j].list[before-1-ptr[j]].term) &&
2981                 !strcmp (tst, mterm))
2982             {
2983                 rset_bool_parms bool_parms;
2984                 RSET rset2;
2985
2986                 rset2 = rset_trunc (zh,
2987                          &scan_info_array[j].list[before-1-ptr[j]].isam_p, 1,
2988                                     glist[before-1-i].term,
2989                                     strlen(glist[before-1-i].term), NULL, 0,
2990                                     zapt->term->which);
2991
2992                 bool_parms.key_size = sizeof(struct it_key);
2993                 bool_parms.cmp = key_compare_it;
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.rset_l = rset;
3009             bool_parms.rset_r = rset_dup(limit_set);
3010
3011             rset = rset_create (rset_kind_and, &bool_parms);
3012         }
3013         count_set (rset, &glist[before-1-i].occurrences);
3014         rset_delete (rset);
3015     }
3016     i = before-i;
3017     if (i)
3018     {
3019         *is_partial = 1;
3020         *position -= i;
3021         *num_entries -= i;
3022     }
3023     *list = glist + i;               /* list is set to first 'real' entry */
3024     
3025     logf (LOG_DEBUG, "position = %d, num_entries = %d",
3026           *position, *num_entries);
3027     if (zh->errCode)
3028         logf (LOG_DEBUG, "scan error: %d", zh->errCode);
3029 }
3030