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