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