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