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