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