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