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