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