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