280b16754dcf97596c6e06de6a9653b8edc8a9ff
[idzebra-moved-to-github.git] / index / zrpn.c
1 /*
2  * Copyright (C) 1995-1998, Index Data
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: zrpn.c,v $
7  * Revision 1.85  1998-09-22 10:03:43  adam
8  * Changed result sets to be persistent in the sense that they can
9  * be re-searched if needed.
10  * Fixed memory leak in rsm_or.
11  *
12  * Revision 1.84  1998/09/18 12:41:00  adam
13  * Fixed bug with numerical relations.
14  *
15  * Revision 1.83  1998/09/02 13:53:19  adam
16  * Extra parameter decode added to search routines to implement
17  * persistent queries.
18  *
19  * Revision 1.82  1998/06/26 11:16:40  quinn
20  * Added support (un-optimised) for left and left/right truncation
21  *
22  * Revision 1.81  1998/06/24 12:16:14  adam
23  * Support for relations on text operands. Open range support in
24  * DFA module (i.e. [-j], [g-]).
25  *
26  * Revision 1.80  1998/06/23 15:33:34  adam
27  * Added feature to specify sort criteria in query (type 7 specifies
28  * sort flags).
29  *
30  * Revision 1.79  1998/06/22 11:35:09  adam
31  * Minor changes.
32  *
33  * Revision 1.78  1998/06/08 14:43:17  adam
34  * Added suport for EXPLAIN Proxy servers - added settings databasePath
35  * and explainDatabase to facilitate this. Increased maximum number
36  * of databases and attributes in one register.
37  *
38  * Revision 1.77  1998/05/20 10:12:22  adam
39  * Implemented automatic EXPLAIN database maintenance.
40  * Modified Zebra to work with ASN.1 compiled version of YAZ.
41  *
42  * Revision 1.76  1998/04/02 14:35:29  adam
43  * First version of Zebra that works with compiled ASN.1.
44  *
45  * Revision 1.75  1998/03/05 08:45:13  adam
46  * New result set model and modular ranking system. Moved towards
47  * descent server API. System information stored as "SGML" records.
48  *
49  * Revision 1.74  1998/02/10 12:03:06  adam
50  * Implemented Sort.
51  *
52  * Revision 1.73  1998/01/29 13:40:11  adam
53  * Better logging for scan service.
54  *
55  * Revision 1.72  1998/01/07 13:53:41  adam
56  * Queries using simple ranked operands returns right number of hits.
57  *
58  * Revision 1.71  1997/12/18 10:54:24  adam
59  * New method result set method rs_hits that returns the number of
60  * hits in result-set (if known). The ranked result set returns real
61  * number of hits but only when not combined with other operands.
62  *
63  * Revision 1.70  1997/10/31 12:34:43  adam
64  * Changed a few log statements.
65  *
66  * Revision 1.69  1997/10/29 12:05:02  adam
67  * Server produces diagnostic "Unsupported Attribute Set" when appropriate.
68  *
69  * Revision 1.68  1997/10/27 14:33:06  adam
70  * Moved towards generic character mapping depending on "structure"
71  * field in abstract syntax file. Fixed a few memory leaks. Fixed
72  * bug with negative integers when doing searches with relational
73  * operators.
74  *
75  * Revision 1.67  1997/09/29 09:06:10  adam
76  * Removed one static var in order to make this module thread safe.
77  *
78  * Revision 1.66  1997/09/25 14:58:03  adam
79  * Windows NT port.
80  *
81  * Revision 1.65  1997/09/22 12:39:06  adam
82  * Added get_pos method for the ranked result sets.
83  *
84  * Revision 1.64  1997/09/18 08:59:20  adam
85  * Extra generic handle for the character mapping routines.
86  *
87  * Revision 1.63  1997/09/17 12:19:18  adam
88  * Zebra version corresponds to YAZ version 1.4.
89  * Changed Zebra server so that it doesn't depend on global common_resource.
90  *
91  * Revision 1.62  1997/09/05 15:30:09  adam
92  * Changed prototype for chr_map_input - added const.
93  * Added support for C++, headers uses extern "C" for public definitions.
94  *
95  * Revision 1.61  1997/02/10 10:21:14  adam
96  * Bug fix: in search terms character (^) wasn't observed.
97  *
98  * Revision 1.60  1997/01/31 11:10:34  adam
99  * Bug fix: Leading and trailing white space weren't removed in scan tokens.
100  *
101  * Revision 1.59  1997/01/17 11:31:46  adam
102  * Bug fix: complete phrase search didn't work.
103  *
104  * Revision 1.58  1996/12/23 15:30:45  adam
105  * Work on truncation.
106  * Bug fix: result sets weren't deleted after server shut down.
107  *
108  * Revision 1.57  1996/11/11 13:38:02  adam
109  * Added proximity support in search.
110  *
111  * Revision 1.56  1996/11/08 11:10:32  adam
112  * Buffers used during file match got bigger.
113  * Compressed ISAM support everywhere.
114  * Bug fixes regarding masking characters in queries.
115  * Redesigned Regexp-2 queries.
116  *
117  * Revision 1.55  1996/11/04 14:07:44  adam
118  * Moved truncation code to trunc.c.
119  *
120  * Revision 1.54  1996/10/29 14:09:52  adam
121  * Use of cisam system - enabled if setting isamc is 1.
122  *
123  * Revision 1.53  1996/06/26 09:21:43  adam
124  * Bug fix: local attribute set wasn't obeyed in scan.
125  *
126  * Revision 1.52  1996/06/17  14:26:20  adam
127  * Function gen_regular_rel changed to handle negative numbers.
128  *
129  * Revision 1.51  1996/06/11 10:54:15  quinn
130  * Relevance work
131  *
132  * Revision 1.50  1996/06/07  08:51:53  adam
133  * Bug fix: Character mapping was broken (introducued by last revision).
134  *
135  * Revision 1.49  1996/06/04  10:18:11  adam
136  * Search/scan uses character mapping module.
137  *
138  * Revision 1.48  1996/05/28  15:15:01  adam
139  * Bug fix: Didn't handle unknown database correctly.
140  *
141  * Revision 1.47  1996/05/15  18:36:28  adam
142  * Function trans_term transforms unsearchable characters to blanks.
143  *
144  * Revision 1.46  1996/05/15  11:57:56  adam
145  * Fixed bug introduced by set/field mapping in search operations.
146  *
147  * Revision 1.45  1996/05/14  11:34:00  adam
148  * Scan support in multiple registers/databases.
149  *
150  * Revision 1.44  1996/05/14  06:16:44  adam
151  * Compact use/set bytes used in search service.
152  *
153  * Revision 1.43  1996/05/09 09:54:43  adam
154  * Server supports maps from one logical attributes to a list of physical
155  * attributes.
156  * The extraction process doesn't make space consuming 'any' keys.
157  *
158  * Revision 1.42  1996/05/09  07:28:56  quinn
159  * Work towards phrases and multiple registers
160  *
161  * Revision 1.41  1996/03/20  09:36:43  adam
162  * Function dict_lookup_grep got extra parameter, init_pos, which marks
163  * from which position in pattern approximate pattern matching should occur.
164  * Approximate pattern matching is used in relevance=re-2.
165  *
166  * Revision 1.40  1996/02/02  13:44:44  adam
167  * The public dictionary functions simply use char instead of Dict_char
168  * to represent search strings. Dict_char is used internally only.
169  *
170  * Revision 1.39  1996/01/03  16:22:13  quinn
171  * operator->roperator
172  *
173  * Revision 1.38  1995/12/11  09:12:55  adam
174  * The rec_get function returns NULL if record doesn't exist - will
175  * happen in the server if the result set records have been deleted since
176  * the creation of the set (i.e. the search).
177  * The server saves a result temporarily if it is 'volatile', i.e. the
178  * set is register dependent.
179  *
180  * Revision 1.37  1995/12/06  15:05:28  adam
181  * More verbose in count_set.
182  *
183  * Revision 1.36  1995/12/06  12:41:27  adam
184  * New command 'stat' for the index program.
185  * Filenames can be read from stdin by specifying '-'.
186  * Bug fix/enhancement of the transformation from terms to regular
187  * expressons in the search engine.
188  *
189  * Revision 1.35  1995/11/27  09:29:00  adam
190  * Bug fixes regarding conversion to regular expressions.
191  *
192  * Revision 1.34  1995/11/16  17:00:56  adam
193  * Better logging of rpn query.
194  *
195  * Revision 1.33  1995/11/01  13:58:28  quinn
196  * Moving data1 to yaz/retrieval
197  *
198  * Revision 1.32  1995/10/27  14:00:11  adam
199  * Implemented detection of database availability.
200  *
201  * Revision 1.31  1995/10/17  18:02:10  adam
202  * New feature: databases. Implemented as prefix to words in dictionary.
203  *
204  * Revision 1.30  1995/10/16  09:32:38  adam
205  * More work on relational op.
206  *
207  * Revision 1.29  1995/10/13  16:01:49  adam
208  * Work on relations.
209  *
210  * Revision 1.28  1995/10/13  12:26:43  adam
211  * Optimization of truncation.
212  *
213  * Revision 1.27  1995/10/12  17:07:22  adam
214  * Truncation works.
215  *
216  * Revision 1.26  1995/10/12  12:40:54  adam
217  * Bug fixes in rpn_prox.
218  *
219  * Revision 1.25  1995/10/10  13:59:24  adam
220  * Function rset_open changed its wflag parameter to general flags.
221  *
222  * Revision 1.24  1995/10/09  16:18:37  adam
223  * Function dict_lookup_grep got extra client data parameter.
224  *
225  * Revision 1.23  1995/10/06  16:33:37  adam
226  * Use attribute mappings.
227  *
228  * Revision 1.22  1995/10/06  15:07:39  adam
229  * Structure 'local-number' handled.
230  *
231  * Revision 1.21  1995/10/06  13:52:06  adam
232  * Bug fixes. Handler may abort further scanning.
233  *
234  * Revision 1.20  1995/10/06  11:06:33  adam
235  * Scan entries include 'occurrences' now.
236  *
237  * Revision 1.19  1995/10/06  10:43:56  adam
238  * Scan added. 'occurrences' in scan entries not set yet.
239  *
240  * Revision 1.18  1995/10/04  16:57:20  adam
241  * Key input and merge sort in one pass.
242  *
243  * Revision 1.17  1995/10/04  12:55:17  adam
244  * Bug fix in ranked search. Use=Any keys inserted.
245  *
246  * Revision 1.16  1995/10/02  16:24:40  adam
247  * Use attribute actually used in search requests.
248  *
249  * Revision 1.15  1995/10/02  15:18:52  adam
250  * New member in recRetrieveCtrl: diagnostic.
251  *
252  * Revision 1.14  1995/09/28  12:10:32  adam
253  * Bug fixes. Field prefix used in queries.
254  *
255  * Revision 1.13  1995/09/18  14:17:50  adam
256  * Minor changes.
257  *
258  * Revision 1.12  1995/09/15  14:45:21  adam
259  * Retrieve control.
260  * Work on truncation.
261  *
262  * Revision 1.11  1995/09/14  11:53:27  adam
263  * First work on regular expressions/truncations.
264  *
265  * Revision 1.10  1995/09/11  15:23:26  adam
266  * More work on relevance search.
267  *
268  * Revision 1.9  1995/09/11  13:09:35  adam
269  * More work on relevance feedback.
270  *
271  * Revision 1.8  1995/09/08  14:52:27  adam
272  * Minor changes. Dictionary is lower case now.
273  *
274  * Revision 1.7  1995/09/07  13:58:36  adam
275  * New parameter: result-set file descriptor (RSFD) to support multiple
276  * positions within the same result-set.
277  * Boolean operators: and, or, not implemented.
278  * Result-set references.
279  *
280  * Revision 1.6  1995/09/06  16:11:18  adam
281  * Option: only one word key per file.
282  *
283  * Revision 1.5  1995/09/06  10:33:04  adam
284  * More work on present. Some log messages removed.
285  *
286  * Revision 1.4  1995/09/05  15:28:40  adam
287  * More work on search engine.
288  *
289  * Revision 1.3  1995/09/04  15:20:22  adam
290  * Minor changes.
291  *
292  * Revision 1.2  1995/09/04  12:33:43  adam
293  * Various cleanup. YAZ util used instead.
294  *
295  * Revision 1.1  1995/09/04  09:10:40  adam
296  * More work on index add/del/update.
297  * Merge sort implemented.
298  * Initial work on z39 server.
299  *
300  */
301 #include <stdio.h>
302 #include <assert.h>
303 #ifdef WINDOWS
304 #include <io.h>
305 #else
306 #include <unistd.h>
307 #endif
308 #include <ctype.h>
309
310 #include "zserver.h"
311
312 #include <charmap.h>
313 #include <rstemp.h>
314 #include <rsnull.h>
315 #include <rsbool.h>
316
317 struct rpn_char_map_info {
318     ZebraMaps zm;
319     int reg_type;
320 };
321
322 static const char **rpn_char_map_handler (void *vp, const char **from, int len)
323 {
324     struct rpn_char_map_info *p = vp;
325     return zebra_maps_input (p->zm, p->reg_type, from, len);
326 }
327
328 static void rpn_char_map_prepare (ZebraHandle zh, int reg_type,
329                                   struct rpn_char_map_info *map_info)
330 {
331     map_info->zm = zh->zebra_maps;
332     map_info->reg_type = reg_type;
333     dict_grep_cmap (zh->dict, map_info, rpn_char_map_handler);
334 }
335
336 typedef struct {
337     int type;
338     int major;
339     int minor;
340     Z_AttributesPlusTerm *zapt;
341 } AttrType;
342
343 static int attr_find (AttrType *src, oid_value *attributeSetP)
344 {
345     int num_attributes;
346
347 #ifdef ASN_COMPILED
348     num_attributes = src->zapt->attributes->num_attributes;
349 #else
350     num_attributes = src->zapt->num_attributes;
351 #endif
352     while (src->major < num_attributes)
353     {
354         Z_AttributeElement *element;
355
356 #ifdef ASN_COMPILED
357         element = src->zapt->attributes->attributes[src->major];
358 #else
359         element = src->zapt->attributeList[src->major];
360 #endif
361         if (src->type == *element->attributeType)
362         {
363             switch (element->which) 
364             {
365             case Z_AttributeValue_numeric:
366                 ++(src->major);
367                 if (element->attributeSet && attributeSetP)
368                 {
369                     oident *attrset;
370
371                     attrset = oid_getentbyoid (element->attributeSet);
372                     *attributeSetP = attrset->value;
373                 }
374                 return *element->value.numeric;
375                 break;
376             case Z_AttributeValue_complex:
377                 if (src->minor >= element->value.complex->num_list ||
378                     element->value.complex->list[src->minor]->which !=  
379                     Z_StringOrNumeric_numeric)
380                     break;
381                 ++(src->minor);
382                 if (element->attributeSet && attributeSetP)
383                 {
384                     oident *attrset;
385
386                     attrset = oid_getentbyoid (element->attributeSet);
387                     *attributeSetP = attrset->value;
388                 }
389                 return *element->value.complex->list[src->minor-1]->u.numeric;
390             default:
391                 assert (0);
392             }
393         }
394         ++(src->major);
395     }
396     return -1;
397 }
398
399 static void attr_init (AttrType *src, Z_AttributesPlusTerm *zapt,
400                        int type)
401 {
402     src->zapt = zapt;
403     src->type = type;
404     src->major = 0;
405     src->minor = 0;
406 }
407
408 #define TERM_COUNT        
409        
410 struct grep_info {        
411 #ifdef TERM_COUNT        
412     int *term_no;        
413 #endif        
414     ISAM_P *isam_p_buf;
415     int isam_p_size;        
416     int isam_p_indx;
417     ZebraHandle zh;
418     int reg_type;
419 };        
420
421 static void term_untrans  (ZebraHandle zh, int reg_type,
422                            char *dst, const char *src)
423 {
424     while (*src)
425     {
426         const char *cp = zebra_maps_output (zh->zebra_maps, reg_type, &src);
427         while (*cp)
428             *dst++ = *cp++;
429     }
430     *dst = '\0';
431 }
432
433 static void add_isam_p (const char *name, const char *info,
434                         struct grep_info *p)
435 {
436     if (p->isam_p_indx == p->isam_p_size)
437     {
438         ISAM_P *new_isam_p_buf;
439 #ifdef TERM_COUNT        
440         int *new_term_no;        
441 #endif
442         p->isam_p_size = 2*p->isam_p_size + 100;
443         new_isam_p_buf = xmalloc (sizeof(*new_isam_p_buf) *
444                                   p->isam_p_size);
445         if (p->isam_p_buf)
446         {
447             memcpy (new_isam_p_buf, p->isam_p_buf,
448                     p->isam_p_indx * sizeof(*p->isam_p_buf));
449             xfree (p->isam_p_buf);
450         }
451         p->isam_p_buf = new_isam_p_buf;
452
453 #ifdef TERM_COUNT
454         new_term_no = xmalloc (sizeof(*new_term_no) *
455                                   p->isam_p_size);
456         if (p->term_no)
457         {
458             memcpy (new_term_no, p->isam_p_buf,
459                     p->isam_p_indx * sizeof(*p->term_no));
460             xfree (p->term_no);
461         }
462         p->term_no = new_term_no;
463 #endif
464     }
465     assert (*info == sizeof(*p->isam_p_buf));
466     memcpy (p->isam_p_buf + p->isam_p_indx, info+1, sizeof(*p->isam_p_buf));
467
468 #if 0
469     term_untrans  (p->zh, p->reg_type, term_tmp, name+2);
470     logf (LOG_DEBUG, "grep: %s", term_tmp);
471 #endif
472     (p->isam_p_indx)++;
473 }
474
475 static int grep_handle (char *name, const char *info, void *p)
476 {
477     add_isam_p (name, info, p);
478     return 0;
479 }
480
481 static int term_pre (ZebraMaps zebra_maps, int reg_type, const char **src,
482                      const char *ct1, const char *ct2)
483 {
484     const char *s1, *s0 = *src;
485     const char **map;
486
487     /* skip white space */
488     while (*s0)
489     {
490         if (ct1 && strchr (ct1, *s0))
491             break;
492         if (ct2 && strchr (ct2, *s0))
493             break;
494         s1 = s0;
495         map = zebra_maps_input (zebra_maps, reg_type, &s1, strlen(s1));
496         if (**map != *CHR_SPACE)
497             break;
498         s0 = s1;
499     }
500     *src = s0;
501     return *s0;
502 }
503
504 static int term_100 (ZebraMaps zebra_maps, int reg_type,
505                      const char **src, char *dst, int space_split,
506                      char *dst_term)
507 {
508     const char *s0, *s1;
509     const char **map;
510     int i = 0;
511     int j = 0;
512
513     if (!term_pre (zebra_maps, reg_type, src, NULL, NULL))
514         return 0;
515     s0 = *src;
516     while (*s0)
517     {
518         s1 = s0;
519         map = zebra_maps_input (zebra_maps, reg_type, &s0, strlen(s0));
520         if (space_split && **map == *CHR_SPACE)
521             break;
522         while (s1 < s0)
523         {
524             if (!isalnum (*s1) && *s1 != '-')
525                 dst[i++] = '\\';
526             dst_term[j++] = *s1;
527             dst[i++] = *s1++;
528         }
529     }
530     dst[i] = '\0';
531     dst_term[j] = '\0';
532     *src = s0;
533     return i;
534 }
535
536 static int term_101 (ZebraMaps zebra_maps, int reg_type,
537                      const char **src, char *dst, int space_split,
538                      char *dst_term)
539 {
540     const char *s0, *s1;
541     const char **map;
542     int i = 0;
543     int j = 0;
544
545     if (!term_pre (zebra_maps, reg_type, src, "#", "#"))
546         return 0;
547     s0 = *src;
548     while (*s0)
549     {
550         if (*s0 == '#')
551         {
552             dst[i++] = '.';
553             dst[i++] = '*';
554             dst_term[j++] = *s0++;
555         }
556         else
557         {
558             s1 = s0;
559             map = zebra_maps_input (zebra_maps, reg_type, &s0, strlen(s0));
560             if (space_split && **map == *CHR_SPACE)
561                 break;
562             while (s1 < s0)
563             {
564                 if (!isalnum (*s1))
565                     dst[i++] = '\\';
566                 dst_term[j++] = *s1;
567                 dst[i++] = *s1++;
568             }
569         }
570     }
571     dst[i] = '\0';
572     dst_term[j++] = '\0';
573     *src = s0;
574     return i;
575 }
576
577
578 static int term_103 (ZebraMaps zebra_maps, int reg_type, const char **src,
579                      char *dst, int *errors, int space_split,
580                      char *dst_term)
581 {
582     int i = 0;
583     int j = 0;
584     const char *s0, *s1;
585     const char **map;
586
587     if (!term_pre (zebra_maps, reg_type, src, "^\\()[].*+?|", "("))
588         return 0;
589     s0 = *src;
590     if (errors && *s0 == '+' && s0[1] && s0[2] == '+' && s0[3] &&
591         isdigit (s0[1]))
592     {
593         *errors = s0[1] - '0';
594         s0 += 3;
595         if (*errors > 3)
596             *errors = 3;
597     }
598     while (*s0)
599     {
600         if (strchr ("^\\()[].*+?|-", *s0))
601         {
602             dst_term[j++] = *s0;
603             dst[i++] = *s0++;
604         }
605         else
606         {
607             s1 = s0;
608             map = zebra_maps_input (zebra_maps, reg_type, &s0, strlen(s0));
609             if (**map == *CHR_SPACE)
610                 break;
611             while (s1 < s0)
612             {
613                 if (!isalnum (*s1))
614                     dst[i++] = '\\';
615                 dst_term[j++] = *s1;
616                 dst[i++] = *s1++;
617             }
618         }
619     }
620     dst[i] = '\0';
621     dst_term[j] = '\0';
622     *src = s0;
623     return i;
624 }
625
626 static int term_102 (ZebraMaps zebra_maps, int reg_type, const char **src,
627                      char *dst, int space_split, char *dst_term)
628 {
629     return term_103 (zebra_maps, reg_type, src, dst, NULL, space_split,
630                      dst_term);
631 }
632
633 /* gen_regular_rel - generate regular expression from relation
634  *  val:     border value (inclusive)
635  *  islt:    1 if <=; 0 if >=.
636  */
637 static void gen_regular_rel (char *dst, int val, int islt)
638 {
639     int dst_p;
640     int w, d, i;
641     int pos = 0;
642     char numstr[20];
643
644     logf (LOG_DEBUG, "gen_regular_rel. val=%d, islt=%d", val, islt);
645     if (val >= 0)
646     {
647         if (islt)
648             strcpy (dst, "(-[0-9]+|(");
649         else
650             strcpy (dst, "((");
651     } 
652     else
653     {
654         if (!islt)
655         {
656             strcpy (dst, "([0-9]+|-(");
657             dst_p = strlen (dst);
658             islt = 1;
659         }
660         else
661         {
662             strcpy (dst, "(-(");
663             islt = 0;
664         }
665         val = -val;
666     }
667     dst_p = strlen (dst);
668     sprintf (numstr, "%d", val);
669     for (w = strlen(numstr); --w >= 0; pos++)
670     {
671         d = numstr[w];
672         if (pos > 0)
673         {
674             if (islt)
675             {
676                 if (d == '0')
677                     continue;
678                 d--;
679             } 
680             else
681             {
682                 if (d == '9')
683                     continue;
684                 d++;
685             }
686         }
687         
688         strcpy (dst + dst_p, numstr);
689         dst_p = strlen(dst) - pos - 1;
690
691         if (islt)
692         {
693             if (d != '0')
694             {
695                 dst[dst_p++] = '[';
696                 dst[dst_p++] = '0';
697                 dst[dst_p++] = '-';
698                 dst[dst_p++] = d;
699                 dst[dst_p++] = ']';
700             }
701             else
702                 dst[dst_p++] = d;
703         }
704         else
705         {
706             if (d != '9')
707             { 
708                 dst[dst_p++] = '[';
709                 dst[dst_p++] = d;
710                 dst[dst_p++] = '-';
711                 dst[dst_p++] = '9';
712                 dst[dst_p++] = ']';
713             }
714             else
715                 dst[dst_p++] = d;
716         }
717         for (i = 0; i<pos; i++)
718         {
719             dst[dst_p++] = '[';
720             dst[dst_p++] = '0';
721             dst[dst_p++] = '-';
722             dst[dst_p++] = '9';
723             dst[dst_p++] = ']';
724         }
725         dst[dst_p++] = '|';
726     }
727     dst[dst_p] = '\0';
728     if (islt)
729     {
730         for (i=1; i<pos; i++)
731             strcat (dst, "[0-9]?");
732     }
733     else
734     {
735         for (i = 0; i <= pos; i++)
736             strcat (dst, "[0-9]");
737         strcat (dst, "[0-9]*");
738     }
739     strcat (dst, "))");
740 }
741
742 void string_rel_add_char (char **term_p, const char *src, int *indx)
743 {
744     if (src[*indx] == '\\')
745         *(*term_p)++ = src[(*indx)++];
746     *(*term_p)++ = src[(*indx)++];
747 }
748
749 /*
750  *   >  abc     ([b-].*|a[c-].*|ab[d-].*|abc.+)
751  *              ([^-a].*|a[^-b].*ab[^-c].*|abc.+)
752  *   >= abc     ([b-].*|a[c-].*|ab[c-].*)
753  *              ([^-a].*|a[^-b].*|ab[c-].*)
754  *   <  abc     ([-0].*|a[-a].*|ab[-b].*)
755  *              ([^a-].*|a[^b-].*|ab[^c-].*)
756  *   <= abc     ([-0].*|a[-a].*|ab[-b].*|abc)
757  *              ([^a-].*|a[^b-].*|ab[^c-].*|abc)
758  */
759 static int string_relation (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
760                             const char **term_sub, char *term_dict,
761                             oid_value attributeSet,
762                             int reg_type, int space_split, char *term_dst)
763 {
764     AttrType relation;
765     int relation_value;
766     int i;
767     char *term_tmp = term_dict + strlen(term_dict);
768     char term_component[256];
769
770     attr_init (&relation, zapt, 2);
771     relation_value = attr_find (&relation, NULL);
772
773     logf (LOG_DEBUG, "string relation value=%d", relation_value);
774     switch (relation_value)
775     {
776     case 1:
777         if (!term_100 (zh->zebra_maps, reg_type, term_sub, term_component,
778                        space_split, term_dst))
779             return 0;
780         logf (LOG_DEBUG, "Relation <");
781         
782         *term_tmp++ = '(';
783         for (i = 0; term_component[i]; )
784         {
785             int j = 0;
786
787             if (i)
788                 *term_tmp++ = '|';
789             while (j < i)
790                 string_rel_add_char (&term_tmp, term_component, &j);
791
792             *term_tmp++ = '[';
793
794             *term_tmp++ = '^';
795             string_rel_add_char (&term_tmp, term_component, &i);
796             *term_tmp++ = '-';
797
798             *term_tmp++ = ']';
799             *term_tmp++ = '.';
800             *term_tmp++ = '*';
801         }
802         *term_tmp++ = ')';
803         *term_tmp = '\0';
804         break;
805     case 2:
806         if (!term_100 (zh->zebra_maps, reg_type, term_sub, term_component,
807                        space_split, term_dst))
808             return 0;
809         logf (LOG_DEBUG, "Relation <=");
810
811         *term_tmp++ = '(';
812         for (i = 0; term_component[i]; )
813         {
814             int j = 0;
815
816             while (j < i)
817                 string_rel_add_char (&term_tmp, term_component, &j);
818             *term_tmp++ = '[';
819
820             *term_tmp++ = '^';
821             string_rel_add_char (&term_tmp, term_component, &i);
822             *term_tmp++ = '-';
823
824             *term_tmp++ = ']';
825             *term_tmp++ = '.';
826             *term_tmp++ = '*';
827
828             *term_tmp++ = '|';
829         }
830         for (i = 0; term_component[i]; )
831             string_rel_add_char (&term_tmp, term_component, &i);
832         *term_tmp++ = ')';
833         *term_tmp = '\0';
834         break;
835     case 5:
836         if (!term_100 (zh->zebra_maps, reg_type, term_sub, term_component,
837                        space_split, term_dst))
838             return 0;
839         logf (LOG_DEBUG, "Relation >");
840
841         *term_tmp++ = '(';
842         for (i = 0; term_component[i];)
843         {
844             int j = 0;
845
846             while (j < i)
847                 string_rel_add_char (&term_tmp, term_component, &j);
848             *term_tmp++ = '[';
849             
850             *term_tmp++ = '^';
851             *term_tmp++ = '-';
852             string_rel_add_char (&term_tmp, term_component, &i);
853
854             *term_tmp++ = ']';
855             *term_tmp++ = '.';
856             *term_tmp++ = '*';
857
858             *term_tmp++ = '|';
859         }
860         for (i = 0; term_component[i];)
861             string_rel_add_char (&term_tmp, term_component, &i);
862         *term_tmp++ = '.';
863         *term_tmp++ = '+';
864         *term_tmp++ = ')';
865         *term_tmp = '\0';
866         break;
867     case 4:
868         if (!term_100 (zh->zebra_maps, reg_type, term_sub, term_component,
869                        space_split, term_dst))
870             return 0;
871         logf (LOG_DEBUG, "Relation >=");
872
873         *term_tmp++ = '(';
874         for (i = 0; term_component[i];)
875         {
876             int j = 0;
877
878             if (i)
879                 *term_tmp++ = '|';
880             while (j < i)
881                 string_rel_add_char (&term_tmp, term_component, &j);
882             *term_tmp++ = '[';
883
884             if (term_component[i+1])
885             {
886                 *term_tmp++ = '^';
887                 *term_tmp++ = '-';
888                 string_rel_add_char (&term_tmp, term_component, &i);
889             }
890             else
891             {
892                 string_rel_add_char (&term_tmp, term_component, &i);
893                 *term_tmp++ = '-';
894             }
895             *term_tmp++ = ']';
896             *term_tmp++ = '.';
897             *term_tmp++ = '*';
898         }
899         *term_tmp++ = ')';
900         *term_tmp = '\0';
901         break;
902     case 3:
903     default:
904         logf (LOG_DEBUG, "Relation =");
905         if (!term_100 (zh->zebra_maps, reg_type, term_sub, term_component,
906                        space_split, term_dst))
907             return 0;
908         strcat (term_tmp, "(");
909         strcat (term_tmp, term_component);
910         strcat (term_tmp, ")");
911     }
912     return 1;
913 }
914
915 static int string_term (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
916                         const char **term_sub, 
917                         oid_value attributeSet, struct grep_info *grep_info,
918                         int reg_type, int complete_flag,
919                         int num_bases, char **basenames,
920                         char *term_dst)
921 {
922     char term_dict[2*IT_MAX_WORD+4000];
923     int j, r, base_no;
924     AttrType truncation;
925     int truncation_value;
926     AttrType use;
927     int use_value;
928     oid_value curAttributeSet = attributeSet;
929     const char *termp;
930     struct rpn_char_map_info rcmi;
931     int space_split = complete_flag ? 0 : 1;
932
933     rpn_char_map_prepare (zh, reg_type, &rcmi);
934     attr_init (&use, zapt, 1);
935     use_value = attr_find (&use, &curAttributeSet);
936     logf (LOG_DEBUG, "string_term, use value %d", use_value);
937     attr_init (&truncation, zapt, 5);
938     truncation_value = attr_find (&truncation, NULL);
939     logf (LOG_DEBUG, "truncation value %d", truncation_value);
940
941     if (use_value == -1)
942         use_value = 1016;
943
944     for (base_no = 0; base_no < num_bases; base_no++)
945     {
946         attent attp;
947         data1_local_attribute *local_attr;
948         int max_pos, prefix_len = 0;
949
950         termp = *term_sub;
951         if ((r=att_getentbyatt (zh, &attp, curAttributeSet, use_value)))
952         {
953             logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d r=%d",
954                   curAttributeSet, use_value, r);
955             if (r == -1)
956                 zh->errCode = 114;
957             else
958                 zh->errCode = 121;
959             return -1;
960         }
961         if (zebraExplain_curDatabase (zh->zei, basenames[base_no]))
962         {
963             zh->errCode = 109; /* Database unavailable */
964             zh->errString = basenames[base_no];
965             return -1;
966         }
967         for (local_attr = attp.local_attributes; local_attr;
968              local_attr = local_attr->next)
969         {
970             int ord;
971             char ord_buf[32];
972             int i, ord_len;
973
974             ord = zebraExplain_lookupSU (zh->zei, attp.attset_ordinal,
975                                           local_attr->local);
976             if (ord < 0)
977                 continue;
978             if (prefix_len)
979                 term_dict[prefix_len++] = '|';
980             else
981                 term_dict[prefix_len++] = '(';
982
983             ord_len = key_SU_code (ord, ord_buf);
984             for (i = 0; i<ord_len; i++)
985             {
986                 term_dict[prefix_len++] = 1;
987                 term_dict[prefix_len++] = ord_buf[i];
988             }
989         }
990         if (!prefix_len)
991         {
992             zh->errCode = 114;
993             return -1;
994         }
995         term_dict[prefix_len++] = ')';        
996         term_dict[prefix_len++] = 1;
997         term_dict[prefix_len++] = reg_type;
998         logf (LOG_DEBUG, "reg_type = %d", term_dict[prefix_len-1]);
999         term_dict[prefix_len] = '\0';
1000         j = prefix_len;
1001         switch (truncation_value)
1002         {
1003         case -1:         /* not specified */
1004         case 100:        /* do not truncate */
1005             if (!string_relation (zh, zapt, &termp, term_dict,
1006                                   attributeSet,
1007                                   reg_type, space_split, term_dst))
1008                 return 0;
1009             logf (LOG_DEBUG, "dict_lookup_grep: %s", term_dict+prefix_len);
1010             r = dict_lookup_grep (zh->dict, term_dict, 0, grep_info, &max_pos,
1011                                   0, grep_handle);
1012             if (r)
1013                 logf (LOG_WARN, "dict_lookup_grep fail, rel=gt: %d", r);
1014             break;
1015         case 1:          /* right truncation */
1016             term_dict[j++] = '(';
1017             if (!term_100 (zh->zebra_maps, reg_type,
1018                            &termp, term_dict + j, space_split, term_dst))
1019                 return 0;
1020             strcat (term_dict, ".*)");
1021             dict_lookup_grep (zh->dict, term_dict, 0, grep_info,
1022                               &max_pos, 0, grep_handle);
1023             break;
1024         case 2:          /* keft truncation */
1025             term_dict[j++] = '('; term_dict[j++] = '.'; term_dict[j++] = '*';
1026             if (!term_100 (zh->zebra_maps, reg_type,
1027                            &termp, term_dict + j, space_split, term_dst))
1028                 return 0;
1029             strcat (term_dict, ")");
1030             dict_lookup_grep (zh->dict, term_dict, 0, grep_info,
1031                               &max_pos, 0, grep_handle);
1032             break;
1033         case 3:          /* left&right truncation */
1034             term_dict[j++] = '('; term_dict[j++] = '.'; term_dict[j++] = '*';
1035             if (!term_100 (zh->zebra_maps, reg_type,
1036                            &termp, term_dict + j, space_split, term_dst))
1037                 return 0;
1038             strcat (term_dict, ".*)");
1039             dict_lookup_grep (zh->dict, term_dict, 0, grep_info,
1040                               &max_pos, 0, grep_handle);
1041             break;
1042             zh->errCode = 120;
1043             return -1;
1044         case 101:        /* process # in term */
1045             term_dict[j++] = '(';
1046             if (!term_101 (zh->zebra_maps, reg_type,
1047                            &termp, term_dict + j, space_split, term_dst))
1048                 return 0;
1049             strcat (term_dict, ")");
1050             r = dict_lookup_grep (zh->dict, term_dict, 0, grep_info,
1051                                   &max_pos, 0, grep_handle);
1052             if (r)
1053                 logf (LOG_WARN, "dict_lookup_grep err, trunc=#: %d", r);
1054             break;
1055         case 102:        /* Regexp-1 */
1056             term_dict[j++] = '(';
1057             if (!term_102 (zh->zebra_maps, reg_type,
1058                            &termp, term_dict + j, space_split, term_dst))
1059                 return 0;
1060             strcat (term_dict, ")");
1061             logf (LOG_DEBUG, "Regexp-1 tolerance=%d", r);
1062             r = dict_lookup_grep (zh->dict, term_dict, 0, grep_info,
1063                                   &max_pos, 0, grep_handle);
1064             if (r)
1065                 logf (LOG_WARN, "dict_lookup_grep err, trunc=regular: %d",
1066                       r);
1067             break;
1068         case 103:       /* Regexp-2 */
1069             r = 1;
1070             term_dict[j++] = '(';
1071             if (!term_103 (zh->zebra_maps, reg_type,
1072                            &termp, term_dict + j, &r, space_split, term_dst))
1073                 return 0;
1074             strcat (term_dict, ")");
1075             logf (LOG_DEBUG, "Regexp-2 tolerance=%d", r);
1076             r = dict_lookup_grep (zh->dict, term_dict, r, grep_info,
1077                                   &max_pos, 2, grep_handle);
1078             if (r)
1079                 logf (LOG_WARN, "dict_lookup_grep err, trunc=eregular: %d",
1080                       r);
1081             break;
1082         }
1083     }
1084     *term_sub = termp;
1085     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
1086     return 1;
1087 }
1088
1089 static void trans_term (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1090                         char *termz)
1091 {
1092     size_t sizez;
1093     Z_Term *term = zapt->term;
1094
1095     sizez = term->u.general->len;
1096     if (sizez > IT_MAX_WORD-1)
1097         sizez = IT_MAX_WORD-1;
1098     memcpy (termz, term->u.general->buf, sizez);
1099     termz[sizez] = '\0';
1100 }
1101
1102 static void trans_scan_term (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1103                              char *termz, int reg_type)
1104 {
1105     Z_Term *term = zapt->term;
1106     const char **map;
1107     const char *cp = (const char *) term->u.general->buf;
1108     const char *cp_end = cp + term->u.general->len;
1109     const char *src;
1110     int i = 0;
1111     const char *space_map = NULL;
1112     int len;
1113     
1114     while ((len = (cp_end - cp)) > 0)
1115     {
1116         map = zebra_maps_input (zh->zebra_maps, reg_type, &cp, len);
1117         if (**map == *CHR_SPACE)
1118             space_map = *map;
1119         else
1120         {
1121             if (i && space_map)
1122                 for (src = space_map; *src; src++)
1123                     termz[i++] = *src;
1124             space_map = NULL;
1125             for (src = *map; *src; src++)
1126                 termz[i++] = *src;
1127         }
1128     }
1129     termz[i] = '\0';
1130 }
1131
1132 static RSET rpn_proximity (ZebraHandle zh, RSET rset1, RSET rset2,
1133                            int ordered,
1134                            int exclusion, int relation, int distance)
1135 {
1136     int i;
1137     RSFD rsfd1, rsfd2;
1138     int  more1, more2;
1139     struct it_key buf1, buf2;
1140     RSFD rsfd_result;
1141     RSET result;
1142     rset_temp_parms parms;
1143     int term_index;
1144     
1145     rsfd1 = rset_open (rset1, RSETF_READ);
1146     more1 = rset_read (rset1, rsfd1, &buf1, &term_index);
1147     
1148     rsfd2 = rset_open (rset2, RSETF_READ);
1149     more2 = rset_read (rset2, rsfd2, &buf2, &term_index);
1150
1151     parms.key_size = sizeof (struct it_key);
1152     parms.temp_path = res_get (zh->res, "setTmpDir");
1153     result = rset_create (rset_kind_temp, &parms);
1154     rsfd_result = rset_open (result, RSETF_WRITE);
1155    
1156     logf (LOG_DEBUG, "rpn_proximity  excl=%d ord=%d rel=%d dis=%d",
1157           exclusion, ordered, relation, distance);
1158     while (more1 && more2)
1159     {
1160         int cmp = key_compare_it (&buf1, &buf2);
1161         if (cmp < -1)
1162             more1 = rset_read (rset1, rsfd1, &buf1, &term_index);
1163         else if (cmp > 1)
1164             more2 = rset_read (rset2, rsfd2, &buf2, &term_index);
1165         else
1166         {
1167             int sysno = buf1.sysno;
1168             int seqno[500];
1169             int n = 0;
1170
1171             seqno[n++] = buf1.seqno;
1172             while ((more1 = rset_read (rset1, rsfd1, &buf1, &term_index)) &&
1173                    sysno == buf1.sysno)
1174                 if (n < 500)
1175                     seqno[n++] = buf1.seqno;
1176             do
1177             {
1178                 for (i = 0; i<n; i++)
1179                 {
1180                     int diff = buf2.seqno - seqno[i];
1181                     int excl = exclusion;
1182                     if (!ordered && diff < 0)
1183                         diff = -diff;
1184                     switch (relation)
1185                     {
1186                     case 1:      /* < */
1187                         if (diff < distance)
1188                             excl = !excl;
1189                         break;
1190                     case 2:      /* <= */
1191                         if (diff <= distance)
1192                             excl = !excl;
1193                         break;
1194                     case 3:      /* == */
1195                         if (diff == distance)
1196                             excl = !excl;
1197                         break;
1198                     case 4:      /* >= */
1199                         if (diff >= distance)
1200                             excl = !excl;
1201                         break;
1202                     case 5:      /* > */
1203                         if (diff > distance)
1204                             excl = !excl;
1205                         break;
1206                     case 6:      /* != */
1207                         if (diff != distance)
1208                             excl = !excl;
1209                         break;
1210                     }
1211                     if (excl)
1212                         rset_write (result, rsfd_result, &buf2);
1213                 }
1214             } while ((more2 = rset_read (rset2, rsfd2, &buf2, &term_index)) &&
1215                       sysno == buf2.sysno);
1216         }
1217     }
1218     rset_close (result, rsfd_result);
1219     rset_close (rset1, rsfd1);
1220     rset_close (rset2, rsfd2);
1221     return result;
1222 }
1223
1224 static RSET rpn_prox (ZebraHandle zh, RSET *rset, int rset_no)
1225 {
1226     int i;
1227     RSFD *rsfd;
1228     int  *more;
1229     struct it_key **buf;
1230     RSET result;
1231     char prox_term[1024];
1232     int length_prox_term = 0;
1233     int min_nn = 10000000;
1234     int term_index;
1235     const char *flags = NULL;
1236     
1237     rsfd = xmalloc (sizeof(*rsfd)*rset_no);
1238     more = xmalloc (sizeof(*more)*rset_no);
1239     buf = xmalloc (sizeof(*buf)*rset_no);
1240
1241     for (i = 0; i<rset_no; i++)
1242     {
1243         int j;
1244         buf[i] = xmalloc (sizeof(**buf));
1245         rsfd[i] = rset_open (rset[i], RSETF_READ);
1246         if (!(more[i] = rset_read (rset[i], rsfd[i], buf[i], &term_index)))
1247             break;
1248         for (j = 0; j<rset[i]->no_rset_terms; j++)
1249         {
1250             const char *nflags = rset[i]->rset_terms[j]->flags;
1251             char *term = rset[i]->rset_terms[j]->name;
1252             int lterm = strlen(term);
1253             if (length_prox_term)
1254                 prox_term[length_prox_term++] = ' ';
1255             strcpy (prox_term + length_prox_term, term);
1256             length_prox_term += lterm;
1257             if (min_nn > rset[i]->rset_terms[j]->nn)
1258                 min_nn = rset[i]->rset_terms[j]->nn;
1259             flags = nflags;
1260         }
1261     }
1262     if (i != rset_no)
1263     {
1264         rset_null_parms parms;
1265
1266         while (i >= 0)
1267         {
1268             rset_close (rset[i], rsfd[i]);
1269             xfree (buf[i]);
1270             --i;
1271         }
1272         parms.rset_term = rset_term_create (prox_term, -1, flags);
1273         parms.rset_term->nn = 0;
1274         result = rset_create (rset_kind_null, &parms);
1275     }
1276     else
1277     {
1278         rset_temp_parms parms;
1279         RSFD rsfd_result;
1280
1281         parms.rset_term = rset_term_create (prox_term, -1, flags);
1282         parms.rset_term->nn = min_nn;
1283         parms.key_size = sizeof (struct it_key);
1284         parms.temp_path = res_get (zh->res, "setTmpDir");
1285         result = rset_create (rset_kind_temp, &parms);
1286         rsfd_result = rset_open (result, RSETF_WRITE);
1287         
1288         while (*more)
1289         {
1290             for (i = 1; i<rset_no; i++)
1291             {
1292                 int cmp;
1293                 
1294                 if (!more[i])
1295                 {
1296                     *more = 0;
1297                     break;
1298                 }
1299                 cmp = key_compare_it (buf[i], buf[i-1]);
1300                 if (cmp > 1)
1301                 {
1302                     more[i-1] = rset_read (rset[i-1], rsfd[i-1],
1303                                            buf[i-1], &term_index);
1304                     break;
1305                 }
1306                 else if (cmp == 1)
1307                 {
1308                     if (buf[i-1]->seqno+1 != buf[i]->seqno)
1309                     {
1310                         more[i-1] = rset_read (rset[i-1], rsfd[i-1],
1311                                                buf[i-1], &term_index);
1312                         break;
1313                     }
1314                 }
1315                 else
1316                 {
1317                     more[i] = rset_read (rset[i], rsfd[i], buf[i],
1318                                          &term_index);
1319                     break;
1320                 }
1321             }
1322             if (i == rset_no)
1323             {
1324                 rset_write (result, rsfd_result, buf[0]);
1325                 more[0] = rset_read (*rset, *rsfd, *buf, &term_index);
1326             }
1327         }
1328         
1329         for (i = 0; i<rset_no; i++)
1330         {
1331             rset_close (rset[i], rsfd[i]);
1332             xfree (buf[i]);
1333         }
1334         rset_close (result, rsfd_result);
1335     }
1336     xfree (buf);
1337     xfree (more);
1338     xfree (rsfd);
1339     return result;
1340 }
1341
1342 static RSET rpn_search_APT_phrase (ZebraHandle zh,
1343                                    Z_AttributesPlusTerm *zapt,
1344                                    const char *termz,
1345                                    oid_value attributeSet,
1346                                    int reg_type, int complete_flag,
1347                                    const char *rank_type,
1348                                    int num_bases, char **basenames)
1349 {
1350     char term_dst[IT_MAX_WORD+1];
1351     const char *termp = termz;
1352     RSET rset[60], result;
1353     int i, r, rset_no = 0;
1354     struct grep_info grep_info;
1355
1356 #ifdef TERM_COUNT
1357     grep_info.term_no = 0;
1358 #endif
1359     grep_info.isam_p_size = 0;
1360     grep_info.isam_p_buf = NULL;
1361     grep_info.zh = zh;
1362     grep_info.reg_type = reg_type;
1363
1364     while (1)
1365     { 
1366         logf (LOG_DEBUG, "APT_phrase termp=%s", termp);
1367         grep_info.isam_p_indx = 0;
1368         r = string_term (zh, zapt, &termp, attributeSet, &grep_info,
1369                         reg_type, complete_flag, num_bases, basenames,
1370                         term_dst);
1371         if (r < 1)
1372             break;
1373         logf (LOG_DEBUG, "term: %s", term_dst);
1374         rset[rset_no] = rset_trunc (zh, grep_info.isam_p_buf,
1375                                     grep_info.isam_p_indx, term_dst,
1376                                     strlen(term_dst), rank_type);
1377         assert (rset[rset_no]);
1378         if (++rset_no >= sizeof(rset)/sizeof(*rset))
1379             break;
1380     }
1381 #ifdef TERM_COUNT
1382     xfree(grep_info.term_no);
1383 #endif
1384     xfree (grep_info.isam_p_buf);
1385     if (rset_no == 0)
1386     {
1387         rset_null_parms parms;
1388         
1389         parms.rset_term = rset_term_create (term_dst, -1, rank_type);
1390         return rset_create (rset_kind_null, &parms);
1391     }
1392     else if (rset_no == 1)
1393         return (rset[0]);
1394     result = rpn_prox (zh, rset, rset_no);
1395     for (i = 0; i<rset_no; i++)
1396         rset_delete (rset[i]);
1397     return result;
1398 }
1399
1400 static RSET rpn_search_APT_or_list (ZebraHandle zh,
1401                                     Z_AttributesPlusTerm *zapt,
1402                                     const char *termz,
1403                                     oid_value attributeSet,
1404                                     int reg_type, int complete_flag,
1405                                     const char *rank_type,
1406                                     int num_bases, char **basenames)
1407 {
1408     char term_dst[IT_MAX_WORD+1];
1409     const char *termp = termz;
1410     RSET rset[60], result;
1411     int i, r, rset_no = 0;
1412     struct grep_info grep_info;
1413
1414 #ifdef TERM_COUNT
1415     grep_info.term_no = 0;
1416 #endif
1417     grep_info.isam_p_size = 0;
1418     grep_info.isam_p_buf = NULL;
1419     grep_info.zh = zh;
1420     grep_info.reg_type = reg_type;
1421
1422     while (1)
1423     { 
1424         logf (LOG_DEBUG, "APT_or_list termp=%s", termp);
1425         grep_info.isam_p_indx = 0;
1426         r = string_term (zh, zapt, &termp, attributeSet, &grep_info,
1427                         reg_type, complete_flag, num_bases, basenames,
1428                         term_dst);
1429         if (r < 1)
1430             break;
1431         logf (LOG_DEBUG, "term: %s", term_dst);
1432         rset[rset_no] = rset_trunc (zh, grep_info.isam_p_buf,
1433                                     grep_info.isam_p_indx, term_dst,
1434                                     strlen(term_dst), rank_type);
1435         assert (rset[rset_no]);
1436         if (++rset_no >= sizeof(rset)/sizeof(*rset))
1437             break;
1438     }
1439 #ifdef TERM_COUNT
1440     xfree(grep_info.term_no);
1441 #endif
1442     xfree (grep_info.isam_p_buf);
1443     if (rset_no == 0)
1444     {
1445         rset_null_parms parms;
1446         
1447         parms.rset_term = rset_term_create (term_dst, -1, rank_type);
1448         return rset_create (rset_kind_null, &parms);
1449     }
1450     result = rset[0];
1451     for (i = 1; i<rset_no; i++)
1452     {
1453         rset_bool_parms bool_parms;
1454
1455         bool_parms.rset_l = result;
1456         bool_parms.rset_r = rset[i];
1457         bool_parms.key_size = sizeof(struct it_key);
1458         bool_parms.cmp = key_compare_it;
1459         result = rset_create (rset_kind_or, &bool_parms);
1460     }
1461     return result;
1462 }
1463
1464 static RSET rpn_search_APT_and_list (ZebraHandle zh,
1465                                      Z_AttributesPlusTerm *zapt,
1466                                      const char *termz,
1467                                      oid_value attributeSet,
1468                                      int reg_type, int complete_flag,
1469                                      const char *rank_type,
1470                                      int num_bases, char **basenames)
1471 {
1472     char term_dst[IT_MAX_WORD+1];
1473     const char *termp = termz;
1474     RSET rset[60], result;
1475     int i, r, rset_no = 0;
1476     struct grep_info grep_info;
1477
1478 #ifdef TERM_COUNT
1479     grep_info.term_no = 0;
1480 #endif
1481     grep_info.isam_p_size = 0;
1482     grep_info.isam_p_buf = NULL;
1483     grep_info.zh = zh;
1484     grep_info.reg_type = reg_type;
1485
1486     while (1)
1487     { 
1488         logf (LOG_DEBUG, "APT_and_list termp=%s", termp);
1489         grep_info.isam_p_indx = 0;
1490         r = string_term (zh, zapt, &termp, attributeSet, &grep_info,
1491                         reg_type, complete_flag, num_bases, basenames,
1492                         term_dst);
1493         if (r < 1)
1494             break;
1495         logf (LOG_DEBUG, "term: %s", term_dst);
1496         rset[rset_no] = rset_trunc (zh, grep_info.isam_p_buf,
1497                                     grep_info.isam_p_indx, term_dst,
1498                                     strlen(term_dst), rank_type);
1499         assert (rset[rset_no]);
1500         if (++rset_no >= sizeof(rset)/sizeof(*rset))
1501             break;
1502     }
1503 #ifdef TERM_COUNT
1504     xfree(grep_info.term_no);
1505 #endif
1506     xfree (grep_info.isam_p_buf);
1507     if (rset_no == 0)
1508     {
1509         rset_null_parms parms;
1510         
1511         parms.rset_term = rset_term_create (term_dst, -1, rank_type);
1512         return rset_create (rset_kind_null, &parms);
1513     }
1514     result = rset[0];
1515     for (i = 1; i<rset_no; i++)
1516     {
1517         rset_bool_parms bool_parms;
1518
1519         bool_parms.rset_l = result;
1520         bool_parms.rset_r = rset[i];
1521         bool_parms.key_size = sizeof(struct it_key);
1522         bool_parms.cmp = key_compare_it;
1523         result = rset_create (rset_kind_and, &bool_parms);
1524     }
1525     return result;
1526 }
1527
1528 static int numeric_relation (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1529                              const char **term_sub,
1530                              char *term_dict,
1531                              oid_value attributeSet,
1532                              struct grep_info *grep_info,
1533                              int *max_pos,
1534                              int reg_type,
1535                              char *term_dst)
1536 {
1537     AttrType relation;
1538     int relation_value;
1539     int term_value;
1540     int r;
1541     char *term_tmp = term_dict + strlen(term_dict);
1542
1543     attr_init (&relation, zapt, 2);
1544     relation_value = attr_find (&relation, NULL);
1545
1546     logf (LOG_DEBUG, "numeric relation value=%d", relation_value);
1547
1548     if (!term_100 (zh->zebra_maps, reg_type, term_sub, term_tmp, 1,
1549                    term_dst))
1550         return 0;
1551     term_value = atoi (term_tmp);
1552     switch (relation_value)
1553     {
1554     case 1:
1555         logf (LOG_DEBUG, "Relation <");
1556         gen_regular_rel (term_tmp, term_value-1, 1);
1557         break;
1558     case 2:
1559         logf (LOG_DEBUG, "Relation <=");
1560         gen_regular_rel (term_tmp, term_value, 1);
1561         break;
1562     case 4:
1563         logf (LOG_DEBUG, "Relation >=");
1564         gen_regular_rel (term_tmp, term_value, 0);
1565         break;
1566     case 5:
1567         logf (LOG_DEBUG, "Relation >");
1568         gen_regular_rel (term_tmp, term_value+1, 0);
1569         break;
1570     case 3:
1571     default:
1572         logf (LOG_DEBUG, "Relation =");
1573         sprintf (term_tmp, "(0*%d)", term_value);
1574     }
1575     logf (LOG_DEBUG, "dict_lookup_grep: %s", term_tmp);
1576     r = dict_lookup_grep (zh->dict, term_dict, 0, grep_info, max_pos,
1577                           0, grep_handle);
1578     if (r)
1579         logf (LOG_WARN, "dict_lookup_grep fail, rel=gt: %d", r);
1580     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
1581     return 1;
1582 }
1583
1584 static int numeric_term (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1585                          const char **term_sub, 
1586                          oid_value attributeSet, struct grep_info *grep_info,
1587                          int reg_type, int complete_flag,
1588                          int num_bases, char **basenames,
1589                          char *term_dst)
1590 {
1591     char term_dict[2*IT_MAX_WORD+2];
1592     int r, base_no;
1593     AttrType use;
1594     int use_value;
1595     oid_value curAttributeSet = attributeSet;
1596     const char *termp;
1597     struct rpn_char_map_info rcmi;
1598
1599     rpn_char_map_prepare (zh, reg_type, &rcmi);
1600     attr_init (&use, zapt, 1);
1601     use_value = attr_find (&use, &curAttributeSet);
1602     logf (LOG_DEBUG, "numeric_term, use value %d", use_value);
1603
1604     if (use_value == -1)
1605         use_value = 1016;
1606
1607     for (base_no = 0; base_no < num_bases; base_no++)
1608     {
1609         attent attp;
1610         data1_local_attribute *local_attr;
1611         int max_pos, prefix_len = 0;
1612
1613         termp = *term_sub;
1614         if ((r=att_getentbyatt (zh, &attp, curAttributeSet, use_value)))
1615         {
1616             logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d r=%d",
1617                   curAttributeSet, use_value, r);
1618             if (r == -1)
1619                 zh->errCode = 114;
1620             else
1621                 zh->errCode = 121;
1622             return -1;
1623         }
1624         if (zebraExplain_curDatabase (zh->zei, basenames[base_no]))
1625         {
1626             zh->errCode = 109; /* Database unavailable */
1627             zh->errString = basenames[base_no];
1628             return -1;
1629         }
1630         for (local_attr = attp.local_attributes; local_attr;
1631              local_attr = local_attr->next)
1632         {
1633             int ord;
1634             char ord_buf[32];
1635             int i, ord_len;
1636
1637             ord = zebraExplain_lookupSU (zh->zei, attp.attset_ordinal,
1638                                           local_attr->local);
1639             if (ord < 0)
1640                 continue;
1641             if (prefix_len)
1642                 term_dict[prefix_len++] = '|';
1643             else
1644                 term_dict[prefix_len++] = '(';
1645
1646             ord_len = key_SU_code (ord, ord_buf);
1647             for (i = 0; i<ord_len; i++)
1648             {
1649                 term_dict[prefix_len++] = 1;
1650                 term_dict[prefix_len++] = ord_buf[i];
1651             }
1652         }
1653         if (!prefix_len)
1654         {
1655             zh->errCode = 114;
1656             return -1;
1657         }
1658         term_dict[prefix_len++] = ')';        
1659         term_dict[prefix_len++] = 1;
1660         term_dict[prefix_len++] = reg_type;
1661         logf (LOG_DEBUG, "reg_type = %d", term_dict[prefix_len-1]);
1662         term_dict[prefix_len] = '\0';
1663         if (!numeric_relation (zh, zapt, &termp, term_dict,
1664                                attributeSet, grep_info, &max_pos, reg_type,
1665                                term_dst))
1666             return 0;
1667     }
1668     *term_sub = termp;
1669     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
1670     return 1;
1671 }
1672
1673 static RSET rpn_search_APT_numeric (ZebraHandle zh,
1674                                     Z_AttributesPlusTerm *zapt,
1675                                     const char *termz,
1676                                     oid_value attributeSet,
1677                                     int reg_type, int complete_flag,
1678                                     const char *rank_type,
1679                                     int num_bases, char **basenames)
1680 {
1681     char term_dst[IT_MAX_WORD+1];
1682     const char *termp = termz;
1683     RSET rset[60], result;
1684     int i, r, rset_no = 0;
1685     struct grep_info grep_info;
1686
1687 #ifdef TERM_COUNT
1688     grep_info.term_no = 0;
1689 #endif
1690     grep_info.isam_p_size = 0;
1691     grep_info.isam_p_buf = NULL;
1692     grep_info.zh = zh;
1693     grep_info.reg_type = reg_type;
1694
1695     while (1)
1696     { 
1697         logf (LOG_DEBUG, "APT_numeric termp=%s", termp);
1698         grep_info.isam_p_indx = 0;
1699         r = numeric_term (zh, zapt, &termp, attributeSet, &grep_info,
1700                           reg_type, complete_flag, num_bases, basenames,
1701                           term_dst);
1702         if (r < 1)
1703             break;
1704         logf (LOG_DEBUG, "term: %s", term_dst);
1705         rset[rset_no] = rset_trunc (zh, grep_info.isam_p_buf,
1706                                     grep_info.isam_p_indx, term_dst,
1707                                     strlen(term_dst), rank_type);
1708         assert (rset[rset_no]);
1709         if (++rset_no >= sizeof(rset)/sizeof(*rset))
1710             break;
1711     }
1712 #ifdef TERM_COUNT
1713     xfree(grep_info.term_no);
1714 #endif
1715     xfree (grep_info.isam_p_buf);
1716     if (rset_no == 0)
1717     {
1718         rset_null_parms parms;
1719         
1720         parms.rset_term = rset_term_create (term_dst, -1, rank_type);
1721         return rset_create (rset_kind_null, &parms);
1722     }
1723     result = rset[0];
1724     for (i = 1; i<rset_no; i++)
1725     {
1726         rset_bool_parms bool_parms;
1727
1728         bool_parms.rset_l = result;
1729         bool_parms.rset_r = rset[i];
1730         bool_parms.key_size = sizeof(struct it_key);
1731         bool_parms.cmp = key_compare_it;
1732         result = rset_create (rset_kind_and, &bool_parms);
1733     }
1734     return result;
1735 }
1736
1737 static RSET rpn_search_APT_local (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1738                                   const char *termz,
1739                                   oid_value attributeSet,
1740                                   const char *rank_type)
1741 {
1742     RSET result;
1743     RSFD rsfd;
1744     struct it_key key;
1745     rset_temp_parms parms;
1746
1747     parms.rset_term = rset_term_create (termz, -1, rank_type);
1748     parms.key_size = sizeof (struct it_key);
1749     parms.temp_path = res_get (zh->res, "setTmpDir");
1750     result = rset_create (rset_kind_temp, &parms);
1751     rsfd = rset_open (result, RSETF_WRITE);
1752
1753     key.sysno = atoi (termz);
1754     key.seqno = 1;
1755     if (key.sysno <= 0)
1756         key.sysno = 1;
1757     rset_write (result, rsfd, &key);
1758     rset_close (result, rsfd);
1759     return result;
1760 }
1761
1762 static RSET rpn_sort_spec (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1763                            oid_value attributeSet, NMEM stream,
1764                            Z_SortKeySpecList *sort_sequence,
1765                            const char *rank_type)
1766 {
1767     rset_null_parms parms;    
1768     int i;
1769     int sort_relation_value;
1770     AttrType sort_relation_type;
1771     int use_value;
1772     AttrType use_type;
1773     Z_SortKeySpec *sks;
1774     Z_SortKey *sk;
1775     Z_AttributeElement *ae;
1776     int oid[OID_SIZE];
1777     oident oe;
1778     
1779     attr_init (&sort_relation_type, zapt, 7);
1780     sort_relation_value = attr_find (&sort_relation_type, &attributeSet);
1781
1782     attr_init (&use_type, zapt, 1);
1783     use_value = attr_find (&use_type, &attributeSet);
1784
1785     if (!sort_sequence->specs)
1786     {
1787         sort_sequence->num_specs = 10;
1788         sort_sequence->specs = nmem_malloc (stream, sort_sequence->num_specs *
1789                                             sizeof(*sort_sequence->specs));
1790         for (i = 0; i<sort_sequence->num_specs; i++)
1791             sort_sequence->specs[i] = 0;
1792     }
1793     if (zapt->term->which != Z_Term_general)
1794         i = 0;
1795     else
1796         i = atoi_n (zapt->term->u.general->buf, zapt->term->u.general->len);
1797     if (i >= sort_sequence->num_specs)
1798         i = 0;
1799
1800     oe.proto = PROTO_Z3950;
1801     oe.oclass = CLASS_ATTSET;
1802     oe.value = attributeSet;
1803     if (!oid_ent_to_oid (&oe, oid))
1804         return 0;
1805
1806     sks = nmem_malloc (stream, sizeof(*sks));
1807     sks->sortElement = nmem_malloc (stream, sizeof(*sks->sortElement));
1808     sks->sortElement->which = Z_SortElement_generic;
1809     sk = sks->sortElement->u.generic = nmem_malloc (stream, sizeof(*sk));
1810     sk->which = Z_SortKey_sortAttributes;
1811     sk->u.sortAttributes = nmem_malloc (stream, sizeof(*sk->u.sortAttributes));
1812
1813     sk->u.sortAttributes->id = oid;
1814     sk->u.sortAttributes->list =
1815         nmem_malloc (stream, sizeof(*sk->u.sortAttributes->list));
1816     sk->u.sortAttributes->list->num_attributes = 1;
1817     sk->u.sortAttributes->list->attributes =
1818         nmem_malloc (stream, sizeof(*sk->u.sortAttributes->list->attributes));
1819     ae = *sk->u.sortAttributes->list->attributes =
1820         nmem_malloc (stream, sizeof(**sk->u.sortAttributes->list->attributes));
1821     ae->attributeSet = 0;
1822     ae->attributeType = nmem_malloc (stream, sizeof(*ae->attributeType));
1823     *ae->attributeType = 1;
1824     ae->which = Z_AttributeValue_numeric;
1825     ae->value.numeric = nmem_malloc (stream, sizeof(*ae->value.numeric));
1826     *ae->value.numeric = use_value;
1827
1828     sks->sortRelation = nmem_malloc (stream, sizeof(*sks->sortRelation));
1829     if (sort_relation_value == 1)
1830         *sks->sortRelation = Z_SortRelation_ascending;
1831     else if (sort_relation_value == 2)
1832         *sks->sortRelation = Z_SortRelation_descending;
1833     else 
1834         *sks->sortRelation = Z_SortRelation_ascending;
1835
1836     sks->caseSensitivity = nmem_malloc (stream, sizeof(*sks->caseSensitivity));
1837     *sks->caseSensitivity = 0;
1838
1839     sks->missingValueAction = 0;
1840
1841     sort_sequence->specs[i] = sks;
1842
1843     parms.rset_term = rset_term_create ("", -1, rank_type);
1844     return rset_create (rset_kind_null, &parms);
1845 }
1846
1847
1848 static RSET rpn_search_APT (ZebraHandle zh, Z_AttributesPlusTerm *zapt,
1849                             oid_value attributeSet, NMEM stream,
1850                             Z_SortKeySpecList *sort_sequence,
1851                             int num_bases, char **basenames)
1852 {
1853     unsigned reg_id;
1854     char *search_type = NULL;
1855     char *rank_type = NULL;
1856     int complete_flag;
1857     int sort_flag;
1858     char termz[IT_MAX_WORD+1];
1859
1860     zebra_maps_attr (zh->zebra_maps, zapt, &reg_id, &search_type,
1861                      &rank_type, &complete_flag, &sort_flag);
1862     
1863     logf (LOG_DEBUG, "reg_id=%c", reg_id);
1864     logf (LOG_DEBUG, "complete_flag=%d", complete_flag);
1865     logf (LOG_DEBUG, "search_type=%s", search_type);
1866     logf (LOG_DEBUG, "rank_type=%s", rank_type);
1867
1868     if (zapt->term->which != Z_Term_general)
1869     {
1870         zh->errCode = 124;
1871         return NULL;
1872     }
1873     trans_term (zh, zapt, termz);
1874
1875     if (sort_flag)
1876         return rpn_sort_spec (zh, zapt, attributeSet, stream, sort_sequence,
1877                               rank_type);
1878
1879     if (!strcmp (search_type, "phrase"))
1880     {
1881         return rpn_search_APT_phrase (zh, zapt, termz, attributeSet,
1882                                       reg_id, complete_flag, rank_type,
1883                                       num_bases, basenames);
1884     }
1885     else if (!strcmp (search_type, "and-list"))
1886     {
1887         return rpn_search_APT_and_list (zh, zapt, termz, attributeSet,
1888                                         reg_id, complete_flag, rank_type,
1889                                         num_bases, basenames);
1890     }
1891     else if (!strcmp (search_type, "or-list"))
1892     {
1893         return rpn_search_APT_or_list (zh, zapt, termz, attributeSet,
1894                                        reg_id, complete_flag, rank_type,
1895                                        num_bases, basenames);
1896     }
1897     else if (!strcmp (search_type, "local"))
1898     {
1899         return rpn_search_APT_local (zh, zapt, termz, attributeSet,
1900                                      rank_type);
1901     }
1902     else if (!strcmp (search_type, "numeric"))
1903     {
1904         return rpn_search_APT_numeric (zh, zapt, termz, attributeSet,
1905                                        reg_id, complete_flag, rank_type,
1906                                        num_bases, basenames);
1907     }
1908     zh->errCode = 118;
1909     return NULL;
1910 }
1911
1912 static RSET rpn_search_structure (ZebraHandle zh, Z_RPNStructure *zs,
1913                                   oid_value attributeSet, NMEM stream,
1914                                   Z_SortKeySpecList *sort_sequence,
1915                                   int num_bases, char **basenames)
1916 {
1917     RSET r = NULL;
1918     if (zs->which == Z_RPNStructure_complex)
1919     {
1920         Z_Operator *zop = zs->u.complex->roperator;
1921         rset_bool_parms bool_parms;
1922
1923         bool_parms.rset_l = rpn_search_structure (zh, zs->u.complex->s1,
1924                                                   attributeSet, stream,
1925                                                   sort_sequence,
1926                                                   num_bases, basenames);
1927         if (bool_parms.rset_l == NULL)
1928             return NULL;
1929         bool_parms.rset_r = rpn_search_structure (zh, zs->u.complex->s2,
1930                                                   attributeSet, stream,
1931                                                   sort_sequence,
1932                                                   num_bases, basenames);
1933         if (bool_parms.rset_r == NULL)
1934         {
1935             rset_delete (bool_parms.rset_l);
1936             return NULL;
1937         }
1938         bool_parms.key_size = sizeof(struct it_key);
1939         bool_parms.cmp = key_compare_it;
1940
1941         switch (zop->which)
1942         {
1943         case Z_Operator_and:
1944             r = rset_create (rset_kind_and, &bool_parms);
1945             break;
1946         case Z_Operator_or:
1947             r = rset_create (rset_kind_or, &bool_parms);
1948             break;
1949         case Z_Operator_and_not:
1950             r = rset_create (rset_kind_not, &bool_parms);
1951             break;
1952         case Z_Operator_prox:
1953 #ifdef ASN_COMPILED
1954             if (zop->u.prox->which != Z_ProximityOperator_known)
1955             {
1956                 zh->errCode = 132;
1957                 return NULL;
1958             }
1959 #else
1960             if (zop->u.prox->which != Z_ProxCode_known)
1961             {
1962                 zh->errCode = 132;
1963                 return NULL;
1964             }
1965 #endif
1966
1967 #ifdef ASN_COMPILED
1968             if (*zop->u.prox->u.known != Z_ProxUnit_word)
1969             {
1970                 char *val = nmem_malloc (stream, 16);
1971                 zh->errCode = 132;
1972                 zh->errString = val;
1973                 sprintf (val, "%d", *zop->u.prox->u.known);
1974                 return NULL;
1975             }
1976 #else
1977             if (*zop->u.prox->proximityUnitCode != Z_ProxUnit_word)
1978             {
1979                 char *val = nmem_malloc (stream, 16);
1980                 zh->errCode = 132;
1981                 zh->errString = val;
1982                 sprintf (val, "%d", *zop->u.prox->proximityUnitCode);
1983                 return NULL;
1984             }
1985 #endif
1986             r = rpn_proximity (zh, bool_parms.rset_l, bool_parms.rset_r,
1987                                *zop->u.prox->ordered,
1988                                (!zop->u.prox->exclusion ? 0 :
1989                                          *zop->u.prox->exclusion),
1990                                *zop->u.prox->relationType,
1991                                *zop->u.prox->distance);
1992             break;
1993         default:
1994             zh->errCode = 110;
1995             return NULL;
1996         }
1997     }
1998     else if (zs->which == Z_RPNStructure_simple)
1999     {
2000         if (zs->u.simple->which == Z_Operand_APT)
2001         {
2002             logf (LOG_DEBUG, "rpn_search_APT");
2003             r = rpn_search_APT (zh, zs->u.simple->u.attributesPlusTerm,
2004                                 attributeSet, stream, sort_sequence,
2005                                 num_bases, basenames);
2006         }
2007         else if (zs->u.simple->which == Z_Operand_resultSetId)
2008         {
2009             logf (LOG_DEBUG, "rpn_search_ref");
2010             r = resultSetRef (zh, zs->u.simple->u.resultSetId);
2011             if (!r)
2012                 r = rset_create (rset_kind_null, NULL);
2013         }
2014         else
2015         {
2016             zh->errCode = 3;
2017             return NULL;
2018         }
2019     }
2020     else
2021     {
2022         zh->errCode = 3;
2023         return NULL;
2024     }
2025     return r;
2026 }
2027
2028
2029 RSET rpn_search (ZebraHandle zh, NMEM nmem,
2030                  Z_RPNQuery *rpn, int num_bases, char **basenames, 
2031                  const char *setname,
2032                  ZebraSet sset)
2033 {
2034     RSET rset;
2035     oident *attrset;
2036     oid_value attributeSet;
2037     Z_SortKeySpecList *sort_sequence;
2038     int sort_status, i;
2039
2040     zlog_rpn (rpn);
2041
2042     zh->errCode = 0;
2043     zh->errString = NULL;
2044     zh->hits = 0;
2045
2046     sort_sequence = nmem_malloc (nmem, sizeof(*sort_sequence));
2047     sort_sequence->num_specs = 10;
2048     sort_sequence->specs = nmem_malloc (nmem, sort_sequence->num_specs *
2049                                        sizeof(*sort_sequence->specs));
2050     for (i = 0; i<sort_sequence->num_specs; i++)
2051         sort_sequence->specs[i] = 0;
2052     
2053     attrset = oid_getentbyoid (rpn->attributeSetId);
2054     attributeSet = attrset->value;
2055     rset = rpn_search_structure (zh, rpn->RPNStructure, attributeSet,
2056                                  nmem, sort_sequence, num_bases, basenames);
2057     if (!rset)
2058         return 0;
2059
2060     if (zh->errCode)
2061         logf (LOG_DEBUG, "search error: %d", zh->errCode);
2062     
2063     for (i = 0; sort_sequence->specs[i]; i++)
2064         ;
2065     sort_sequence->num_specs = i;
2066     if (!i)
2067         resultSetRank (zh, sset, rset);
2068     else
2069     {
2070         logf (LOG_DEBUG, "resultSetSortSingle in rpn_search");
2071         resultSetSortSingle (zh, nmem, sset, rset,
2072                              sort_sequence, &sort_status);
2073         if (zh->errCode)
2074         {
2075             logf (LOG_DEBUG, "resultSetSortSingle status = %d", zh->errCode);
2076         }
2077     }
2078     return rset;
2079 }
2080
2081 struct scan_info_entry {
2082     char *term;
2083     ISAM_P isam_p;
2084 };
2085
2086 struct scan_info {
2087     struct scan_info_entry *list;
2088     ODR odr;
2089     int before, after;
2090     char prefix[20];
2091 };
2092
2093 static int scan_handle (char *name, const char *info, int pos, void *client)
2094 {
2095     int len_prefix, idx;
2096     struct scan_info *scan_info = client;
2097
2098     len_prefix = strlen(scan_info->prefix);
2099     if (memcmp (name, scan_info->prefix, len_prefix))
2100         return 1;
2101     if (pos > 0)
2102         idx = scan_info->after - pos + scan_info->before;
2103     else
2104         idx = - pos - 1;
2105     scan_info->list[idx].term = odr_malloc (scan_info->odr,
2106                                             strlen(name + len_prefix)+1);
2107     strcpy (scan_info->list[idx].term, name + len_prefix);
2108     assert (*info == sizeof(ISAM_P));
2109     memcpy (&scan_info->list[idx].isam_p, info+1, sizeof(ISAM_P));
2110     return 0;
2111 }
2112
2113 static void scan_term_untrans (ZebraHandle zh, NMEM stream, int reg_type,
2114                                char **dst, const char *src)
2115 {
2116     char term_dst[1024];
2117     
2118     term_untrans (zh, reg_type, term_dst, src);
2119     
2120     *dst = nmem_malloc (stream, strlen(term_dst)+1);
2121     strcpy (*dst, term_dst);
2122 }
2123
2124 static void count_set (RSET r, int *count)
2125 {
2126     int psysno = 0;
2127     int kno = 0;
2128     struct it_key key;
2129     RSFD rfd;
2130     int term_index;
2131
2132     logf (LOG_DEBUG, "count_set");
2133
2134     *count = 0;
2135     rfd = rset_open (r, RSETF_READ);
2136     while (rset_read (r, rfd, &key, &term_index))
2137     {
2138         if (key.sysno != psysno)
2139         {
2140             psysno = key.sysno;
2141             (*count)++;
2142         }
2143         kno++;
2144     }
2145     rset_close (r, rfd);
2146     logf (LOG_DEBUG, "%d keys, %d records", kno, *count);
2147 }
2148
2149 void rpn_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
2150                oid_value attributeset,
2151                int num_bases, char **basenames,
2152                int *position, int *num_entries, ZebraScanEntry **list,
2153                int *is_partial)
2154 {
2155     int i;
2156     int pos = *position;
2157     int num = *num_entries;
2158     int before;
2159     int after;
2160     int base_no;
2161     char termz[IT_MAX_WORD+20];
2162     AttrType use;
2163     int use_value;
2164     struct scan_info *scan_info_array;
2165     ZebraScanEntry *glist;
2166     int ords[32], ord_no = 0;
2167     int ptr[32];
2168
2169     unsigned reg_id;
2170     char *search_type = NULL;
2171     char *rank_type = NULL;
2172     int complete_flag;
2173     int sort_flag;
2174
2175     if (attributeset == VAL_NONE)
2176         attributeset = VAL_BIB1;
2177
2178     zlog_scan (zapt, attributeset);
2179     logf (LOG_DEBUG, "position = %d, num = %d", pos, num);
2180         
2181     attr_init (&use, zapt, 1);
2182     use_value = attr_find (&use, &attributeset);
2183
2184     if (zebra_maps_attr (zh->zebra_maps, zapt, &reg_id, &search_type,
2185                          &rank_type, &complete_flag, &sort_flag))
2186     {
2187         zh->errCode = 113;
2188         return ;
2189     }
2190
2191     if (use_value == -1)
2192         use_value = 1016;
2193     for (base_no = 0; base_no < num_bases && ord_no < 32; base_no++)
2194     {
2195         int r;
2196         attent attp;
2197         data1_local_attribute *local_attr;
2198
2199         if ((r=att_getentbyatt (zh, &attp, attributeset, use_value)))
2200         {
2201             logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d",
2202                   attributeset, use_value);
2203             if (r == -1)
2204                 zh->errCode = 114;
2205             else
2206                 zh->errCode = 121;
2207         }
2208         if (zebraExplain_curDatabase (zh->zei, basenames[base_no]))
2209         {
2210             zh->errString = basenames[base_no];
2211             zh->errCode = 109; /* Database unavailable */
2212             return;
2213         }
2214         for (local_attr = attp.local_attributes; local_attr && ord_no < 32;
2215              local_attr = local_attr->next)
2216         {
2217             int ord;
2218
2219             ord = zebraExplain_lookupSU (zh->zei, attp.attset_ordinal,
2220                                          local_attr->local);
2221             if (ord > 0)
2222                 ords[ord_no++] = ord;
2223         }
2224     }
2225     if (ord_no == 0)
2226     {
2227         zh->errCode = 113;
2228         return;
2229     }
2230     /* prepare dictionary scanning */
2231     before = pos-1;
2232     after = 1+num-pos;
2233     scan_info_array = odr_malloc (stream, ord_no * sizeof(*scan_info_array));
2234     for (i = 0; i < ord_no; i++)
2235     {
2236         int j, prefix_len = 0;
2237         int before_tmp = before, after_tmp = after;
2238         struct scan_info *scan_info = scan_info_array + i;
2239         struct rpn_char_map_info rcmi;
2240
2241         rpn_char_map_prepare (zh, reg_id, &rcmi);
2242
2243         scan_info->before = before;
2244         scan_info->after = after;
2245         scan_info->odr = stream;
2246
2247         scan_info->list = odr_malloc (stream, (before+after)*
2248                                       sizeof(*scan_info->list));
2249         for (j = 0; j<before+after; j++)
2250             scan_info->list[j].term = NULL;
2251
2252         prefix_len += key_SU_code (ords[i], termz + prefix_len);
2253         termz[prefix_len++] = reg_id;
2254         termz[prefix_len] = 0;
2255         strcpy (scan_info->prefix, termz);
2256
2257         trans_scan_term (zh, zapt, termz+prefix_len, reg_id);
2258                     
2259         dict_scan (zh->dict, termz, &before_tmp, &after_tmp, scan_info,
2260                    scan_handle);
2261     }
2262     glist = odr_malloc (stream, (before+after)*sizeof(*glist));
2263
2264     /* consider terms after main term */
2265     for (i = 0; i < ord_no; i++)
2266         ptr[i] = before;
2267     
2268     *is_partial = 0;
2269     for (i = 0; i<after; i++)
2270     {
2271         int j, j0 = -1;
2272         const char *mterm = NULL;
2273         const char *tst;
2274         RSET rset;
2275         
2276         for (j = 0; j < ord_no; j++)
2277         {
2278             if (ptr[j] < before+after &&
2279                 (tst=scan_info_array[j].list[ptr[j]].term) &&
2280                 (!mterm || strcmp (tst, mterm) < 0))
2281             {
2282                 j0 = j;
2283                 mterm = tst;
2284             }
2285         }
2286         if (j0 == -1)
2287             break;
2288         scan_term_untrans (zh, stream->mem, reg_id,
2289                            &glist[i+before].term, mterm);
2290         rset = rset_trunc (zh, &scan_info_array[j0].list[ptr[j0]].isam_p, 1,
2291                            glist[i+before].term, strlen(glist[i+before].term),
2292                            NULL);
2293
2294         ptr[j0]++;
2295         for (j = j0+1; j<ord_no; j++)
2296         {
2297             if (ptr[j] < before+after &&
2298                 (tst=scan_info_array[j].list[ptr[j]].term) &&
2299                 !strcmp (tst, mterm))
2300             {
2301                 rset_bool_parms bool_parms;
2302                 RSET rset2;
2303
2304                 rset2 =
2305                    rset_trunc (zh, &scan_info_array[j].list[ptr[j]].isam_p, 1,
2306                                glist[i+before].term,
2307                                strlen(glist[i+before].term), NULL);
2308
2309                 bool_parms.key_size = sizeof(struct it_key);
2310                 bool_parms.cmp = key_compare_it;
2311                 bool_parms.rset_l = rset;
2312                 bool_parms.rset_r = rset2;
2313               
2314                 rset = rset_create (rset_kind_or, &bool_parms);
2315
2316                 ptr[j]++;
2317             }
2318         }
2319         count_set (rset, &glist[i+before].occurrences);
2320         rset_delete (rset);
2321     }
2322     if (i < after)
2323     {
2324         *num_entries -= (after-i);
2325         *is_partial = 1;
2326     }
2327
2328     /* consider terms before main term */
2329     for (i = 0; i<ord_no; i++)
2330         ptr[i] = 0;
2331
2332     for (i = 0; i<before; i++)
2333     {
2334         int j, j0 = -1;
2335         const char *mterm = NULL;
2336         const char *tst;
2337         RSET rset;
2338         
2339         for (j = 0; j <ord_no; j++)
2340         {
2341             if (ptr[j] < before &&
2342                 (tst=scan_info_array[j].list[before-1-ptr[j]].term) &&
2343                 (!mterm || strcmp (tst, mterm) > 0))
2344             {
2345                 j0 = j;
2346                 mterm = tst;
2347             }
2348         }
2349         if (j0 == -1)
2350             break;
2351
2352         scan_term_untrans (zh, stream->mem, reg_id,
2353                            &glist[before-1-i].term, mterm);
2354
2355         rset = rset_trunc
2356                (zh, &scan_info_array[j0].list[before-1-ptr[j0]].isam_p, 1,
2357                 glist[before-1-i].term, strlen(glist[before-1-i].term),
2358                 NULL);
2359
2360         ptr[j0]++;
2361
2362         for (j = j0+1; j<ord_no; j++)
2363         {
2364             if (ptr[j] < before &&
2365                 (tst=scan_info_array[j].list[before-1-ptr[j]].term) &&
2366                 !strcmp (tst, mterm))
2367             {
2368                 rset_bool_parms bool_parms;
2369                 RSET rset2;
2370
2371                 rset2 = rset_trunc (zh,
2372                          &scan_info_array[j].list[before-1-ptr[j]].isam_p, 1,
2373                                     glist[before-1-i].term,
2374                                     strlen(glist[before-1-i].term), NULL);
2375
2376                 bool_parms.key_size = sizeof(struct it_key);
2377                 bool_parms.cmp = key_compare_it;
2378                 bool_parms.rset_l = rset;
2379                 bool_parms.rset_r = rset2;
2380               
2381                 rset = rset_create (rset_kind_or, &bool_parms);
2382
2383                 ptr[j]++;
2384             }
2385         }
2386         count_set (rset, &glist[before-1-i].occurrences);
2387         rset_delete (rset);
2388     }
2389     i = before-i;
2390     if (i)
2391     {
2392         *is_partial = 1;
2393         *position -= i;
2394         *num_entries -= i;
2395     }
2396     *list = glist + i;               /* list is set to first 'real' entry */
2397     
2398     logf (LOG_DEBUG, "position = %d, num_entries = %d",
2399           *position, *num_entries);
2400     if (zh->errCode)
2401         logf (LOG_DEBUG, "scan error: %d", zh->errCode);
2402 }
2403