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