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