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