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