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