Work on truncation.
[idzebra-moved-to-github.git] / index / zrpn.c
1 /*
2  * Copyright (C) 1994-1996, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: zrpn.c,v $
7  * Revision 1.58  1996-12-23 15:30:45  adam
8  * Work on truncation.
9  * Bug fix: result sets weren't deleted after server shut down.
10  *
11  * Revision 1.57  1996/11/11 13:38:02  adam
12  * Added proximity support in search.
13  *
14  * Revision 1.56  1996/11/08 11:10:32  adam
15  * Buffers used during file match got bigger.
16  * Compressed ISAM support everywhere.
17  * Bug fixes regarding masking characters in queries.
18  * Redesigned Regexp-2 queries.
19  *
20  * Revision 1.55  1996/11/04 14:07:44  adam
21  * Moved truncation code to trunc.c.
22  *
23  * Revision 1.54  1996/10/29 14:09:52  adam
24  * Use of cisam system - enabled if setting isamc is 1.
25  *
26  * Revision 1.53  1996/06/26 09:21:43  adam
27  * Bug fix: local attribute set wasn't obeyed in scan.
28  *
29  * Revision 1.52  1996/06/17  14:26:20  adam
30  * Function gen_regular_rel changed to handle negative numbers.
31  *
32  * Revision 1.51  1996/06/11 10:54:15  quinn
33  * Relevance work
34  *
35  * Revision 1.50  1996/06/07  08:51:53  adam
36  * Bug fix: Character mapping was broken (introducued by last revision).
37  *
38  * Revision 1.49  1996/06/04  10:18:11  adam
39  * Search/scan uses character mapping module.
40  *
41  * Revision 1.48  1996/05/28  15:15:01  adam
42  * Bug fix: Didn't handle unknown database correctly.
43  *
44  * Revision 1.47  1996/05/15  18:36:28  adam
45  * Function trans_term transforms unsearchable characters to blanks.
46  *
47  * Revision 1.46  1996/05/15  11:57:56  adam
48  * Fixed bug introduced by set/field mapping in search operations.
49  *
50  * Revision 1.45  1996/05/14  11:34:00  adam
51  * Scan support in multiple registers/databases.
52  *
53  * Revision 1.44  1996/05/14  06:16:44  adam
54  * Compact use/set bytes used in search service.
55  *
56  * Revision 1.43  1996/05/09 09:54:43  adam
57  * Server supports maps from one logical attributes to a list of physical
58  * attributes.
59  * The extraction process doesn't make space consuming 'any' keys.
60  *
61  * Revision 1.42  1996/05/09  07:28:56  quinn
62  * Work towards phrases and multiple registers
63  *
64  * Revision 1.41  1996/03/20  09:36:43  adam
65  * Function dict_lookup_grep got extra parameter, init_pos, which marks
66  * from which position in pattern approximate pattern matching should occur.
67  * Approximate pattern matching is used in relevance=re-2.
68  *
69  * Revision 1.40  1996/02/02  13:44:44  adam
70  * The public dictionary functions simply use char instead of Dict_char
71  * to represent search strings. Dict_char is used internally only.
72  *
73  * Revision 1.39  1996/01/03  16:22:13  quinn
74  * operator->roperator
75  *
76  * Revision 1.38  1995/12/11  09:12:55  adam
77  * The rec_get function returns NULL if record doesn't exist - will
78  * happen in the server if the result set records have been deleted since
79  * the creation of the set (i.e. the search).
80  * The server saves a result temporarily if it is 'volatile', i.e. the
81  * set is register dependent.
82  *
83  * Revision 1.37  1995/12/06  15:05:28  adam
84  * More verbose in count_set.
85  *
86  * Revision 1.36  1995/12/06  12:41:27  adam
87  * New command 'stat' for the index program.
88  * Filenames can be read from stdin by specifying '-'.
89  * Bug fix/enhancement of the transformation from terms to regular
90  * expressons in the search engine.
91  *
92  * Revision 1.35  1995/11/27  09:29:00  adam
93  * Bug fixes regarding conversion to regular expressions.
94  *
95  * Revision 1.34  1995/11/16  17:00:56  adam
96  * Better logging of rpn query.
97  *
98  * Revision 1.33  1995/11/01  13:58:28  quinn
99  * Moving data1 to yaz/retrieval
100  *
101  * Revision 1.32  1995/10/27  14:00:11  adam
102  * Implemented detection of database availability.
103  *
104  * Revision 1.31  1995/10/17  18:02:10  adam
105  * New feature: databases. Implemented as prefix to words in dictionary.
106  *
107  * Revision 1.30  1995/10/16  09:32:38  adam
108  * More work on relational op.
109  *
110  * Revision 1.29  1995/10/13  16:01:49  adam
111  * Work on relations.
112  *
113  * Revision 1.28  1995/10/13  12:26:43  adam
114  * Optimization of truncation.
115  *
116  * Revision 1.27  1995/10/12  17:07:22  adam
117  * Truncation works.
118  *
119  * Revision 1.26  1995/10/12  12:40:54  adam
120  * Bug fixes in rpn_prox.
121  *
122  * Revision 1.25  1995/10/10  13:59:24  adam
123  * Function rset_open changed its wflag parameter to general flags.
124  *
125  * Revision 1.24  1995/10/09  16:18:37  adam
126  * Function dict_lookup_grep got extra client data parameter.
127  *
128  * Revision 1.23  1995/10/06  16:33:37  adam
129  * Use attribute mappings.
130  *
131  * Revision 1.22  1995/10/06  15:07:39  adam
132  * Structure 'local-number' handled.
133  *
134  * Revision 1.21  1995/10/06  13:52:06  adam
135  * Bug fixes. Handler may abort further scanning.
136  *
137  * Revision 1.20  1995/10/06  11:06:33  adam
138  * Scan entries include 'occurrences' now.
139  *
140  * Revision 1.19  1995/10/06  10:43:56  adam
141  * Scan added. 'occurrences' in scan entries not set yet.
142  *
143  * Revision 1.18  1995/10/04  16:57:20  adam
144  * Key input and merge sort in one pass.
145  *
146  * Revision 1.17  1995/10/04  12:55:17  adam
147  * Bug fix in ranked search. Use=Any keys inserted.
148  *
149  * Revision 1.16  1995/10/02  16:24:40  adam
150  * Use attribute actually used in search requests.
151  *
152  * Revision 1.15  1995/10/02  15:18:52  adam
153  * New member in recRetrieveCtrl: diagnostic.
154  *
155  * Revision 1.14  1995/09/28  12:10:32  adam
156  * Bug fixes. Field prefix used in queries.
157  *
158  * Revision 1.13  1995/09/18  14:17:50  adam
159  * Minor changes.
160  *
161  * Revision 1.12  1995/09/15  14:45:21  adam
162  * Retrieve control.
163  * Work on truncation.
164  *
165  * Revision 1.11  1995/09/14  11:53:27  adam
166  * First work on regular expressions/truncations.
167  *
168  * Revision 1.10  1995/09/11  15:23:26  adam
169  * More work on relevance search.
170  *
171  * Revision 1.9  1995/09/11  13:09:35  adam
172  * More work on relevance feedback.
173  *
174  * Revision 1.8  1995/09/08  14:52:27  adam
175  * Minor changes. Dictionary is lower case now.
176  *
177  * Revision 1.7  1995/09/07  13:58:36  adam
178  * New parameter: result-set file descriptor (RSFD) to support multiple
179  * positions within the same result-set.
180  * Boolean operators: and, or, not implemented.
181  * Result-set references.
182  *
183  * Revision 1.6  1995/09/06  16:11:18  adam
184  * Option: only one word key per file.
185  *
186  * Revision 1.5  1995/09/06  10:33:04  adam
187  * More work on present. Some log messages removed.
188  *
189  * Revision 1.4  1995/09/05  15:28:40  adam
190  * More work on search engine.
191  *
192  * Revision 1.3  1995/09/04  15:20:22  adam
193  * Minor changes.
194  *
195  * Revision 1.2  1995/09/04  12:33:43  adam
196  * Various cleanup. YAZ util used instead.
197  *
198  * Revision 1.1  1995/09/04  09:10:40  adam
199  * More work on index add/del/update.
200  * Merge sort implemented.
201  * Initial work on z39 server.
202  *
203  */
204 #include <stdio.h>
205 #include <assert.h>
206 #include <unistd.h>
207 #include <ctype.h>
208
209 #include "zserver.h"
210 #include "attribute.h"
211
212 #include <charmap.h>
213 #include <rstemp.h>
214 #include <rsnull.h>
215 #include <rsbool.h>
216 #include <rsrel.h>
217
218 typedef struct {
219     int type;
220     int major;
221     int minor;
222     Z_AttributesPlusTerm *zapt;
223 } AttrType;
224
225 static int attr_find (AttrType *src, oid_value *attributeSetP)
226 {
227     while (src->major < src->zapt->num_attributes)
228     {
229         Z_AttributeElement *element;
230
231         element = src->zapt->attributeList[src->major];
232         if (src->type == *element->attributeType)
233         {
234             switch (element->which) 
235             {
236             case Z_AttributeValue_numeric:
237                 ++(src->major);
238                 if (element->attributeSet && attributeSetP)
239                 {
240                     oident *attrset;
241
242                     attrset = oid_getentbyoid (element->attributeSet);
243                     *attributeSetP = attrset->value;
244                 }
245                 return *element->value.numeric;
246                 break;
247             case Z_AttributeValue_complex:
248                 if (src->minor >= element->value.complex->num_list ||
249                     element->value.complex->list[src->minor]->which !=  
250                     Z_StringOrNumeric_numeric)
251                     break;
252                 ++(src->minor);
253                 if (element->attributeSet && attributeSetP)
254                 {
255                     oident *attrset;
256
257                     attrset = oid_getentbyoid (element->attributeSet);
258                     *attributeSetP = attrset->value;
259                 }
260                 return *element->value.complex->list[src->minor-1]->u.numeric;
261             default:
262                 assert (0);
263             }
264         }
265         ++(src->major);
266     }
267     return -1;
268 }
269
270 static void attr_init (AttrType *src, Z_AttributesPlusTerm *zapt,
271                        int type)
272 {
273     src->zapt = zapt;
274     src->type = type;
275     src->major = 0;
276     src->minor = 0;
277 }
278
279 #define TERM_COUNT        
280        
281 struct grep_info {        
282 #ifdef TERM_COUNT        
283     int *term_no;        
284 #endif        
285     ISAM_P *isam_p_buf;        
286     int isam_p_size;        
287     int isam_p_indx;        
288 };        
289
290 static void add_isam_p (const char *info, struct grep_info *p)
291 {
292     if (p->isam_p_indx == p->isam_p_size)
293     {
294         ISAM_P *new_isam_p_buf;
295 #ifdef TERM_COUNT        
296         int *new_term_no;        
297 #endif        
298         
299         p->isam_p_size = 2*p->isam_p_size + 100;
300         new_isam_p_buf = xmalloc (sizeof(*new_isam_p_buf) *
301                                   p->isam_p_size);
302         if (p->isam_p_buf)
303         {
304             memcpy (new_isam_p_buf, p->isam_p_buf,
305                     p->isam_p_indx * sizeof(*p->isam_p_buf));
306             xfree (p->isam_p_buf);
307         }
308         p->isam_p_buf = new_isam_p_buf;
309
310 #ifdef TERM_COUNT
311         new_term_no = xmalloc (sizeof(*new_term_no) *
312                                   p->isam_p_size);
313         if (p->term_no)
314         {
315             memcpy (new_term_no, p->isam_p_buf,
316                     p->isam_p_indx * sizeof(*p->term_no));
317             xfree (p->term_no);
318         }
319         p->term_no = new_term_no;
320 #endif
321     }
322     assert (*info == sizeof(*p->isam_p_buf));
323     memcpy (p->isam_p_buf + p->isam_p_indx, info+1, sizeof(*p->isam_p_buf));
324     (p->isam_p_indx)++;
325 }
326
327 static int grep_handle (char *name, const char *info, void *p)
328 {
329     add_isam_p (info, p);
330     return 0;
331 }
332
333 static int term_pre (char **src, const char *ct1, const char *ct2)
334 {
335     char *s1, *s0 = *src;
336     char **map;
337
338     /* skip white space */
339     while (*s0)
340     {
341         if (ct1 && strchr (ct1, *s0))
342             break;
343         if (ct2 && strchr (ct2, *s0))
344             break;
345         s1 = s0;
346         map = map_chrs_input (&s1, strlen(s1));
347         if (**map != *CHR_SPACE)
348             break;
349         s0 = s1;
350     }
351     *src = s0;
352     return *s0;
353 }
354
355 static int term_100 (char **src, char *dst)
356 {
357     char *s0, *s1, **map;
358     int i = 0;
359
360     if (!term_pre (src, NULL, NULL))
361         return 0;
362     s0 = *src;
363     while (*s0)
364     {
365         s1 = s0;
366         map = map_chrs_input (&s0, strlen(s0));
367         if (**map == *CHR_SPACE)
368             break;
369         while (s1 < s0)
370         {
371             if (!isalnum (*s1))
372                 dst[i++] = '\\';
373             dst[i++] = *s1++;
374         }
375     }
376     dst[i] = '\0';
377     *src = s0;
378     return i;
379 }
380
381 static int term_101 (char **src, char *dst)
382 {
383     char *s0, *s1, **map;
384     int i = 0;
385
386     if (!term_pre (src, "#", "#"))
387         return 0;
388     s0 = *src;
389     while (*s0)
390     {
391         if (*s0 == '#')
392         {
393             dst[i++] = '.';
394             dst[i++] = '*';
395             s0++;
396         }
397         else
398         {
399             s1 = s0;
400             map = map_chrs_input (&s0, strlen(s0));
401             if (**map == *CHR_SPACE)
402                 break;
403             while (s1 < s0)
404             {
405                 if (!isalnum (*s1))
406                     dst[i++] = '\\';
407                 dst[i++] = *s1++;
408             }
409         }
410     }
411     dst[i] = '\0';
412     *src = s0;
413     return i;
414 }
415
416
417 static int term_103 (char **src, char *dst, int *errors)
418 {
419     int i = 0;
420     char *s0, *s1, **map;
421
422     if (!term_pre (src, "\\()[].*+?|", "("))
423         return 0;
424     s0 = *src;
425     if (errors && *s0 == '+' && s0[1] && s0[2] == '+' && s0[3] &&
426         isdigit (s0[1]))
427     {
428         *errors = s0[1] - '0';
429         s0 += 3;
430         if (*errors > 3)
431             *errors = 3;
432     }
433     while (*s0)
434     {
435         if (strchr ("\\()[].*+?|-", *s0))
436             dst[i++] = *s0++;
437         else
438         {
439             s1 = s0;
440             map = map_chrs_input (&s0, strlen(s0));
441             if (**map == *CHR_SPACE)
442                 break;
443             while (s1 < s0)
444             {
445                 if (!isalnum (*s1))
446                     dst[i++] = '\\';
447                 dst[i++] = *s1++;
448             }
449         }
450     }
451     dst[i] = '\0';
452     *src = s0;
453     return i;
454 }
455
456 static int term_102 (char **src, char *dst)
457 {
458     return term_103 (src, dst, NULL);
459 }
460
461 /* gen_regular_rel - generate regular expression from relation
462  *  val:     border value (inclusive)
463  *  islt:    1 if <=; 0 if >=.
464  */
465 static void gen_regular_rel (char *dst, int val, int islt)
466 {
467     int dst_p;
468     int w, d, i;
469     int pos = 0;
470     char numstr[20];
471
472     logf (LOG_DEBUG, "gen_regular_rel. val=%d, islt=%d", val, islt);
473     if (val >= 0)
474     {
475         if (islt)
476             strcpy (dst, "(-[0-9]+|");
477         else
478             strcpy (dst, "(");
479     } 
480     else
481     {
482         if (!islt)
483         {
484             strcpy (dst, "([0-9]+|-");
485             dst_p = strlen (dst);
486             islt = 1;
487         }
488         else
489         {
490             strcpy (dst, "(-");
491             islt = 0;
492         }
493         val = -val;
494     }
495     dst_p = strlen (dst);
496     sprintf (numstr, "%d", val);
497     for (w = strlen(numstr); --w >= 0; pos++)
498     {
499         d = numstr[w];
500         if (pos > 0)
501         {
502             if (islt)
503             {
504                 if (d == '0')
505                     continue;
506                 d--;
507             } 
508             else
509             {
510                 if (d == '9')
511                     continue;
512                 d++;
513             }
514         }
515         
516         strcpy (dst + dst_p, numstr);
517         dst_p = strlen(dst) - pos - 1;
518
519         if (islt)
520         {
521             if (d != '0')
522             {
523                 dst[dst_p++] = '[';
524                 dst[dst_p++] = '0';
525                 dst[dst_p++] = '-';
526                 dst[dst_p++] = d;
527                 dst[dst_p++] = ']';
528             }
529             else
530                 dst[dst_p++] = d;
531         }
532         else
533         {
534             if (d != '9')
535             { 
536                 dst[dst_p++] = '[';
537                 dst[dst_p++] = d;
538                 dst[dst_p++] = '-';
539                 dst[dst_p++] = '9';
540                 dst[dst_p++] = ']';
541             }
542             else
543                 dst[dst_p++] = d;
544         }
545         for (i = 0; i<pos; i++)
546         {
547             dst[dst_p++] = '[';
548             dst[dst_p++] = '0';
549             dst[dst_p++] = '-';
550             dst[dst_p++] = '9';
551             dst[dst_p++] = ']';
552         }
553         dst[dst_p++] = '|';
554     }
555     dst[dst_p] = '\0';
556     if (islt)
557     {
558         for (i=1; i<pos; i++)
559             strcat (dst, "[0-9]?");
560     }
561     else
562     {
563         for (i = 0; i <= pos; i++)
564             strcat (dst, "[0-9]");
565         strcat (dst, "[0-9]*");
566     }
567     strcat (dst, ")");
568 }
569
570 static int relational_term (ZServerInfo *zi, Z_AttributesPlusTerm *zapt,
571                             char **term_sub,
572                             char *term_dict,
573                             oid_value attributeSet,
574                             struct grep_info *grep_info,
575                             int *max_pos)
576 {
577     AttrType relation;
578     int relation_value;
579     int term_value;
580     int r;
581
582     attr_init (&relation, zapt, 2);
583     relation_value = attr_find (&relation, NULL);
584
585     switch (relation_value)
586     {
587     case 1:
588         if (!term_100 (term_sub, term_dict))
589             return 0;
590         term_value = atoi (term_dict);
591         if (term_value <= 0)
592             return 1;
593         logf (LOG_DEBUG, "Relation <");
594         gen_regular_rel (term_dict + strlen(term_dict), term_value-1, 1);
595         break;
596     case 2:
597         if (!term_100 (term_sub, term_dict))
598             return 0;
599         term_value = atoi (term_dict);
600         if (term_value < 0)
601             return 1;
602         logf (LOG_DEBUG, "Relation <=");
603         gen_regular_rel (term_dict + strlen(term_dict), term_value, 1);
604         break;
605     case 4:
606         if (!term_100 (term_sub, term_dict))
607             return 0;
608         term_value = atoi (term_dict);
609         if (term_value < 0)
610             term_value = 0;
611         logf (LOG_DEBUG, "Relation >=");
612         gen_regular_rel (term_dict + strlen(term_dict), term_value, 0);
613         break;
614     case 5:
615         if (!term_100 (term_sub, term_dict))
616             return 0;
617         term_value = atoi (term_dict);
618         if (term_value < 0)
619             term_value = 0;
620         logf (LOG_DEBUG, "Relation >");
621         gen_regular_rel (term_dict + strlen(term_dict), term_value+1, 0);
622         break;
623     default:
624         return 0;
625     }
626     logf (LOG_DEBUG, "dict_lookup_grep: %s", term_dict);
627     r = dict_lookup_grep (zi->dict, term_dict, 0, grep_info, max_pos,
628                           0, grep_handle);
629     if (r)
630         logf (LOG_WARN, "dict_lookup_grep fail, rel=gt: %d", r);
631     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
632     return 1;
633 }
634
635 static int field_term (ZServerInfo *zi, Z_AttributesPlusTerm *zapt,
636                        char **term_sub, int regType,
637                        oid_value attributeSet, struct grep_info *grep_info,
638                        int num_bases, char **basenames)
639 {
640     char term_dict[2*IT_MAX_WORD+2];
641     int j, r, base_no;
642     AttrType truncation;
643     int truncation_value;
644     AttrType use;
645     int use_value;
646     oid_value curAttributeSet = attributeSet;
647     char *termp;
648
649     attr_init (&use, zapt, 1);
650     use_value = attr_find (&use, &curAttributeSet);
651     logf (LOG_DEBUG, "use value %d", use_value);
652     attr_init (&truncation, zapt, 5);
653     truncation_value = attr_find (&truncation, NULL);
654     logf (LOG_DEBUG, "truncation value %d", truncation_value);
655
656     if (use_value == -1)
657         use_value = 1016;
658
659     for (base_no = 0; base_no < num_bases; base_no++)
660     {
661         attent *attp;
662         data1_local_attribute *local_attr;
663         int max_pos, prefix_len = 0;
664
665         termp = *term_sub;
666         attp = att_getentbyatt (curAttributeSet, use_value);
667         if (!attp)
668         {
669             logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d",
670                   curAttributeSet, use_value);
671             zi->errCode = 114;
672             return -1;
673         }
674         if (zebTargetInfo_curDatabase (zi->zti, basenames[base_no]))
675         {
676             zi->errCode = 109; /* Database unavailable */
677             zi->errString = basenames[base_no];
678             return -1;
679         }
680         for (local_attr = attp->local_attributes; local_attr;
681              local_attr = local_attr->next)
682         {
683             int ord;
684
685             ord = zebTargetInfo_lookupSU (zi->zti, attp->attset_ordinal,
686                                           local_attr->local);
687             if (ord < 0)
688                 continue;
689             if (prefix_len)
690                 term_dict[prefix_len++] = '|';
691             else
692                 term_dict[prefix_len++] = '(';
693             term_dict[prefix_len++] = 1;
694             term_dict[prefix_len++] = ord;
695         }
696         if (!prefix_len)
697         {
698             zi->errCode = 114;
699             return -1;
700         }
701         term_dict[prefix_len++] = ')';        
702         term_dict[prefix_len++] = 1;
703         term_dict[prefix_len++] = regType;
704         term_dict[prefix_len] = '\0';
705         if (!relational_term (zi, zapt, &termp, term_dict,
706                               attributeSet, grep_info, &max_pos))
707         {
708             j = prefix_len;
709             switch (truncation_value)
710             {
711             case -1:         /* not specified */
712             case 100:        /* do not truncate */
713                 term_dict[j++] = '(';
714                 if (!term_100 (&termp, term_dict + j))
715                     return 0;
716                 strcat (term_dict, ")");
717                 r = dict_lookup_grep (zi->dict, term_dict, 0, grep_info,
718                                       &max_pos, 0, grep_handle);
719                 if (r)
720                     logf (LOG_WARN, "dict_lookup_grep err, trunc=none:%d", r);
721                 break;
722             case 1:          /* right truncation */
723                 term_dict[j++] = '(';
724                 if (!term_100 (&termp, term_dict + j))
725                     return 0;
726                 strcat (term_dict, ".*)");
727                 dict_lookup_grep (zi->dict, term_dict, 0, grep_info,
728                                   &max_pos, 0, grep_handle);
729                 break;
730             case 2:          /* left truncation */
731             case 3:          /* left&right truncation */
732                 zi->errCode = 120;
733                 return -1;
734             case 101:        /* process # in term */
735                 term_dict[j++] = '(';
736                 if (!term_101 (&termp, term_dict + j))
737                     return 0;
738                 strcat (term_dict, ")");
739                 r = dict_lookup_grep (zi->dict, term_dict, 0, grep_info,
740                                       &max_pos, 0, grep_handle);
741                 if (r)
742                     logf (LOG_WARN, "dict_lookup_grep err, trunc=#: %d", r);
743                 break;
744             case 102:        /* Regexp-1 */
745                 term_dict[j++] = '(';
746                 if (!term_102 (&termp, term_dict + j))
747                     return 0;
748                 strcat (term_dict, ")");
749                 logf (LOG_DEBUG, "Regexp-1 tolerance=%d", r);
750                 r = dict_lookup_grep (zi->dict, term_dict, 0, grep_info,
751                                       &max_pos, 0, grep_handle);
752                 if (r)
753                     logf (LOG_WARN, "dict_lookup_grep err, trunc=regular: %d",
754                           r);
755                 break;
756              case 103:       /* Regexp-1 */
757                 r = 1;
758                 term_dict[j++] = '(';
759                 if (!term_103 (&termp, term_dict + j, &r))
760                     return 0;
761                 strcat (term_dict, ")");
762                 logf (LOG_DEBUG, "Regexp-2 tolerance=%d", r);
763                 r = dict_lookup_grep (zi->dict, term_dict, r, grep_info,
764                                       &max_pos, 2, grep_handle);
765                 if (r)
766                     logf (LOG_WARN, "dict_lookup_grep err, trunc=eregular: %d",
767                           r);
768                 break;
769             }
770         }
771     }
772     *term_sub = termp;
773     logf (LOG_DEBUG, "%d positions", grep_info->isam_p_indx);
774     return 1;
775 }
776
777 static void trans_term (ZServerInfo *zi, Z_AttributesPlusTerm *zapt,
778                         char *termz)
779 {
780     size_t sizez;
781     Z_Term *term = zapt->term;
782
783     sizez = term->u.general->len;
784     if (sizez > IT_MAX_WORD-1)
785         sizez = IT_MAX_WORD-1;
786     memcpy (termz, term->u.general->buf, sizez);
787     termz[sizez] = '\0';
788 }
789
790 static void trans_scan_term (ZServerInfo *zi, Z_AttributesPlusTerm *zapt,
791                              char *termz)
792 {
793     Z_Term *term = zapt->term;
794     char **map;
795     char *cp = (char*) term->u.general->buf;
796     const char *cp_end = cp + term->u.general->len;
797     const char *src;
798     int i = 0;
799     int prev_space = 0;
800     int len;
801     
802     while ((len = (cp_end - cp)) > 0)
803     {
804         map = map_chrs_input (&cp, len);
805         if (**map == *CHR_SPACE)
806         {
807             if (prev_space)
808                 continue;
809             prev_space = 1;
810         } 
811         else
812             prev_space = 0;
813         for (src = *map; *src; src++)
814             termz[i++] = *src;
815     }
816     termz[i] = '\0';
817 }
818
819 static RSET rpn_search_APT_relevance (ZServerInfo *zi, 
820                                       Z_AttributesPlusTerm *zapt,
821                                       oid_value attributeSet,
822                                       int num_bases, char **basenames)
823 {
824     rset_relevance_parms parms;
825     char termz[IT_MAX_WORD+1];
826     char *termp = termz;
827     struct grep_info grep_info;
828     RSET result;
829     int term_index = 0;
830     int r;
831
832     parms.key_size = sizeof(struct it_key);
833     parms.max_rec = 100;
834     parms.cmp = key_compare_it;
835     parms.is = zi->isam;
836     parms.isc = zi->isamc;
837     parms.no_terms = 0;
838
839     if (zapt->term->which != Z_Term_general)
840     {
841         zi->errCode = 124;
842         return NULL;
843     }
844     trans_term (zi, zapt, termz);
845
846 #ifdef TERM_COUNT
847     grep_info.term_no = 0;
848 #endif
849     grep_info.isam_p_indx = 0;
850     grep_info.isam_p_size = 0;
851     grep_info.isam_p_buf = NULL;
852     while (1)
853     {
854         r = field_term (zi, zapt, &termp, 'w', attributeSet, &grep_info,
855                         num_bases, basenames);
856         if (r <= 0)
857             break;
858 #ifdef TERM_COUNT
859         for (; term_index < grep_info.isam_p_indx; term_index++)
860             grep_info.term_no[term_index] = parms.no_terms;
861         parms.no_terms++;
862 #endif
863     }
864     parms.term_no = grep_info.term_no;
865     parms.isam_positions = grep_info.isam_p_buf;
866     parms.no_isam_positions = grep_info.isam_p_indx;
867     if (grep_info.isam_p_indx > 0)
868         result = rset_create (rset_kind_relevance, &parms);
869     else
870         result = rset_create (rset_kind_null, NULL);
871 #ifdef TERM_COUNT
872     xfree(grep_info.term_no);
873 #endif
874     xfree (grep_info.isam_p_buf);
875     return result;
876 }
877
878 static RSET rpn_search_APT_cphrase (ZServerInfo *zi,
879                                     Z_AttributesPlusTerm *zapt,
880                                     oid_value attributeSet,
881                                     int num_bases, char **basenames)
882 {
883     char termz[IT_MAX_WORD+1];
884     struct grep_info grep_info;
885     RSET result;
886     char *termp = termz;
887     int r;
888
889     if (zapt->term->which != Z_Term_general)
890     {
891         zi->errCode = 124;
892         return NULL;
893     }
894     trans_term (zi, zapt, termz);
895
896 #ifdef TERM_COUNT
897     grep_info.term_no = 0;
898 #endif
899     grep_info.isam_p_indx = 0;
900     grep_info.isam_p_size = 0;
901     grep_info.isam_p_buf = NULL;
902
903     r = field_term (zi, zapt, &termp, 'p', attributeSet, &grep_info,
904                     num_bases, basenames);
905     result = rset_trunc (zi, grep_info.isam_p_buf, grep_info.isam_p_indx);
906 #ifdef TERM_COUNT
907     xfree(grep_info.term_no);
908 #endif
909     xfree (grep_info.isam_p_buf);
910     return result;
911 }
912
913 static RSET rpn_proximity (RSET rset1, RSET rset2, int ordered,
914                            int exclusion, int relation, int distance)
915 {
916     int i;
917     RSFD rsfd1, rsfd2;
918     int  more1, more2;
919     struct it_key buf1, buf2;
920     RSFD rsfd_result;
921     RSET result;
922     rset_temp_parms parms;
923     
924     rsfd1 = rset_open (rset1, RSETF_READ|RSETF_SORT_SYSNO);
925     more1 = rset_read (rset1, rsfd1, &buf1);
926     
927     rsfd2 = rset_open (rset2, RSETF_READ|RSETF_SORT_SYSNO);
928     more2 = rset_read (rset2, rsfd2, &buf2);
929
930     parms.key_size = sizeof (struct it_key);
931     result = rset_create (rset_kind_temp, &parms);
932     rsfd_result = rset_open (result, RSETF_WRITE|RSETF_SORT_SYSNO);
933    
934     logf (LOG_DEBUG, "rpn_proximity  excl=%d ord=%d rel=%d dis=%d",
935           exclusion, ordered, relation, distance);
936     while (more1 && more2)
937     {
938         int cmp = key_compare_it (&buf1, &buf2);
939         if (cmp < -1)
940             more1 = rset_read (rset1, rsfd1, &buf1);
941         else if (cmp > 1)
942             more2 = rset_read (rset2, rsfd2, &buf2);
943         else
944         {
945             int sysno = buf1.sysno;
946             int seqno[500];
947             int n = 0;
948
949             seqno[n++] = buf1.seqno;
950             while ((more1 = rset_read (rset1, rsfd1, &buf1)) &&
951                    sysno == buf1.sysno)
952                 if (n < 500)
953                     seqno[n++] = buf1.seqno;
954             do
955             {
956                 for (i = 0; i<n; i++)
957                 {
958                     int diff = buf2.seqno - seqno[i];
959                     int excl = exclusion;
960                     if (!ordered && diff < 0)
961                         diff = -diff;
962                     logf (LOG_DEBUG, "l = %d r = %d", seqno[i], buf2.seqno);
963                     switch (relation)
964                     {
965                     case 1:      /* < */
966                         if (diff < distance)
967                             excl = !excl;
968                         break;
969                     case 2:      /* <= */
970                         if (diff <= distance)
971                             excl = !excl;
972                         break;
973                     case 3:      /* == */
974                         if (diff == distance)
975                             excl = !excl;
976                         break;
977                     case 4:      /* >= */
978                         if (diff >= distance)
979                             excl = !excl;
980                         break;
981                     case 5:      /* > */
982                         if (diff > distance)
983                             excl = !excl;
984                         break;
985                     case 6:      /* != */
986                         if (diff != distance)
987                             excl = !excl;
988                         break;
989                     }
990                     if (excl)
991                     {
992                         logf (LOG_DEBUG, " match");
993                         rset_write (result, rsfd_result, &buf2);
994                     }
995                 }
996             } while ((more2 = rset_read (rset2, rsfd2, &buf2)) &&
997                       sysno == buf2.sysno);
998         }
999     }
1000     rset_close (result, rsfd_result);
1001     rset_close (rset1, rsfd1);
1002     rset_close (rset2, rsfd2);
1003     return result;
1004 }
1005
1006 static RSET rpn_prox (RSET *rset, int rset_no)
1007 {
1008     int i;
1009     RSFD *rsfd;
1010     int  *more;
1011     struct it_key **buf;
1012     RSFD rsfd_result;
1013     RSET result;
1014     rset_temp_parms parms;
1015     
1016     rsfd = xmalloc (sizeof(*rsfd)*rset_no);
1017     more = xmalloc (sizeof(*more)*rset_no);
1018     buf = xmalloc (sizeof(*buf)*rset_no);
1019
1020     for (i = 0; i<rset_no; i++)
1021     {
1022         buf[i] = xmalloc (sizeof(**buf));
1023         rsfd[i] = rset_open (rset[i], RSETF_READ|RSETF_SORT_SYSNO);
1024         if (!(more[i] = rset_read (rset[i], rsfd[i], buf[i])))
1025         {
1026             while (i >= 0)
1027             {
1028                 rset_close (rset[i], rsfd[i]);
1029                 xfree (buf[i]);
1030                 --i;
1031             }
1032             xfree (rsfd);
1033             xfree (more);
1034             xfree (buf);
1035             return rset_create (rset_kind_null, NULL);
1036         }
1037     }
1038     parms.key_size = sizeof (struct it_key);
1039     result = rset_create (rset_kind_temp, &parms);
1040     rsfd_result = rset_open (result, RSETF_WRITE|RSETF_SORT_SYSNO);
1041     
1042     while (*more)
1043     {
1044         for (i = 1; i<rset_no; i++)
1045         {
1046             int cmp;
1047             
1048             if (!more[i])
1049             {
1050                 *more = 0;
1051                 break;
1052             }
1053             cmp = key_compare_it (buf[i], buf[i-1]);
1054             if (cmp > 1)
1055             {
1056                 more[i-1] = rset_read (rset[i-1], rsfd[i-1], buf[i-1]);
1057                 break;
1058             }
1059             else if (cmp == 1)
1060             {
1061                 if (buf[i-1]->seqno+1 != buf[i]->seqno)
1062                 {
1063                     more[i-1] = rset_read (rset[i-1], rsfd[i-1], buf[i-1]);
1064                     break;
1065                 }
1066             }
1067             else
1068             {
1069                 more[i] = rset_read (rset[i], rsfd[i], buf[i]);
1070                 break;
1071             }
1072         }
1073         if (i == rset_no)
1074         {
1075             rset_write (result, rsfd_result, buf[0]);
1076             more[0] = rset_read (*rset, *rsfd, *buf);
1077         }
1078     }
1079     
1080     for (i = 0; i<rset_no; i++)
1081     {
1082         rset_close (rset[i], rsfd[i]);
1083         xfree (buf[i]);
1084     }
1085     rset_close (result, rsfd_result);
1086     xfree (buf);
1087     xfree (more);
1088     xfree (rsfd);
1089     return result;
1090 }
1091
1092 static RSET rpn_search_APT_phrase (ZServerInfo *zi,
1093                                    Z_AttributesPlusTerm *zapt,
1094                                    oid_value attributeSet,
1095                                    int num_bases, char **basenames)
1096 {
1097     char termz[IT_MAX_WORD+1];
1098     char *termp = termz;
1099     RSET rset[60], result;
1100     int i, r, rset_no = 0;
1101     struct grep_info grep_info;
1102
1103     if (zapt->term->which != Z_Term_general)
1104     {
1105         zi->errCode = 124;
1106         return NULL;
1107     }
1108     trans_term (zi, zapt, termz);
1109
1110 #ifdef TERM_COUNT
1111     grep_info.term_no = 0;
1112 #endif
1113     grep_info.isam_p_size = 0;
1114     grep_info.isam_p_buf = NULL;
1115
1116     while (1)
1117     {
1118         grep_info.isam_p_indx = 0;
1119         r = field_term (zi, zapt, &termp, 'w', attributeSet, &grep_info,
1120                         num_bases, basenames);
1121         if (r < 1)
1122             break;
1123         rset[rset_no] = rset_trunc (zi, grep_info.isam_p_buf,
1124                                     grep_info.isam_p_indx);
1125         assert (rset[rset_no]);
1126         if (++rset_no >= sizeof(rset)/sizeof(*rset))
1127             break;
1128     }
1129 #ifdef TERM_COUNT
1130     xfree(grep_info.term_no);
1131 #endif
1132     xfree (grep_info.isam_p_buf);
1133     if (rset_no == 0)
1134         return rset_create (rset_kind_null, NULL);
1135     else if (rset_no == 1)
1136         return (rset[0]);
1137     result = rpn_prox (rset, rset_no);
1138     for (i = 0; i<rset_no; i++)
1139         rset_delete (rset[i]);
1140     return result;
1141 }
1142
1143 static RSET rpn_search_APT_local (ZServerInfo *zi, Z_AttributesPlusTerm *zapt,
1144                                   oid_value attributeSet)
1145 {
1146     RSET result;
1147     RSFD rsfd;
1148     struct it_key key;
1149     rset_temp_parms parms;
1150     char termz[IT_MAX_WORD+1];
1151
1152     if (zapt->term->which != Z_Term_general)
1153     {
1154         zi->errCode = 124;
1155         return NULL;
1156     }
1157     parms.key_size = sizeof (struct it_key);
1158     result = rset_create (rset_kind_temp, &parms);
1159     rsfd = rset_open (result, RSETF_WRITE|RSETF_SORT_SYSNO);
1160
1161     trans_term (zi, zapt, termz);
1162
1163     key.sysno = atoi (termz);
1164     if (key.sysno <= 0)
1165         key.sysno = 1;
1166     rset_write (result, rsfd, &key);
1167     rset_close (result, rsfd);
1168     return result;
1169 }
1170
1171 static RSET rpn_search_APT (ZServerInfo *zi, Z_AttributesPlusTerm *zapt,
1172                             oid_value attributeSet,
1173                             int num_bases, char **basenames)
1174 {
1175     AttrType relation;
1176     AttrType structure;
1177     AttrType completeness;
1178     int relation_value, structure_value, completeness_value;
1179
1180     attr_init (&relation, zapt, 2);
1181     attr_init (&structure, zapt, 4);
1182     attr_init (&completeness, zapt, 6);
1183     
1184     relation_value = attr_find (&relation, NULL);
1185     structure_value = attr_find (&structure, NULL);
1186     completeness_value = attr_find (&completeness, NULL);
1187     switch (structure_value)
1188     {
1189     case -1:
1190         if (relation_value == 102) /* relevance relation */
1191             return rpn_search_APT_relevance (zi, zapt, attributeSet,
1192                                              num_bases, basenames);
1193         if (completeness_value == 2 || completeness_value == 3)
1194             return rpn_search_APT_cphrase (zi, zapt, attributeSet,
1195                                            num_bases, basenames);
1196         return rpn_search_APT_phrase (zi, zapt, attributeSet,
1197                                       num_bases, basenames);
1198     case 1: /* phrase */
1199         if (relation_value == 102) /* relevance relation */
1200             return rpn_search_APT_relevance (zi, zapt, attributeSet,
1201                                              num_bases, basenames);
1202         if (completeness_value == 2 || completeness_value == 3)
1203             return rpn_search_APT_cphrase (zi, zapt, attributeSet,
1204                                            num_bases, basenames);
1205         return rpn_search_APT_phrase (zi, zapt, attributeSet,
1206                                       num_bases, basenames);
1207         break;
1208     case 2: /* word */
1209         if (relation_value == 102) /* relevance relation */
1210             return rpn_search_APT_relevance (zi, zapt, attributeSet,
1211                                              num_bases, basenames);
1212         if (completeness_value == 2 || completeness_value == 3)
1213             return rpn_search_APT_cphrase (zi, zapt, attributeSet,
1214                                            num_bases, basenames);
1215         return rpn_search_APT_phrase (zi, zapt, attributeSet,
1216                                       num_bases, basenames);
1217     case 3: /* key */
1218         break;
1219     case 4: /* year */
1220         break;
1221     case 5: /* date - normalized */
1222         break;
1223     case 6: /* word list */
1224         return rpn_search_APT_relevance (zi, zapt, attributeSet,
1225                                          num_bases, basenames);
1226     case 100: /* date - un-normalized */
1227         break;
1228     case 101: /* name - normalized */
1229         break;
1230     case 102: /* date - un-normalized */
1231         break;
1232     case 103: /* structure */
1233         break;
1234     case 104: /* urx */
1235         break;
1236     case 105: /* free-form-text */
1237         return rpn_search_APT_relevance (zi, zapt, attributeSet,
1238                                          num_bases, basenames);
1239     case 106: /* document-text */
1240         return rpn_search_APT_relevance (zi, zapt, attributeSet,
1241                                          num_bases, basenames);
1242     case 107: /* local-number */
1243         return rpn_search_APT_local (zi, zapt, attributeSet);
1244     case 108: /* string */ 
1245         return rpn_search_APT_phrase (zi, zapt, attributeSet,
1246                                       num_bases, basenames);
1247     case 109: /* numeric string */
1248         break;
1249     }
1250     zi->errCode = 118;
1251     return NULL;
1252 }
1253
1254 static RSET rpn_search_ref (ZServerInfo *zi, Z_ResultSetId *resultSetId)
1255 {
1256     ZServerSet *s;
1257
1258     if (!(s = resultSetGet (zi, resultSetId)))
1259         return rset_create (rset_kind_null, NULL);
1260     return s->rset;
1261 }
1262
1263 static RSET rpn_search_structure (ZServerInfo *zi, Z_RPNStructure *zs,
1264                                   oid_value attributeSet,
1265                                   int num_bases, char **basenames)
1266 {
1267     RSET r = NULL;
1268     if (zs->which == Z_RPNStructure_complex)
1269     {
1270         Z_Operator *zop = zs->u.complex->roperator;
1271         rset_bool_parms bool_parms;
1272         int soft = 0;
1273          
1274
1275         bool_parms.rset_l = rpn_search_structure (zi, zs->u.complex->s1,
1276                                                   attributeSet,
1277                                                   num_bases, basenames);
1278         if (bool_parms.rset_l == NULL)
1279             return NULL;
1280         if (rset_is_ranked(bool_parms.rset_l))
1281             soft = 1;
1282         bool_parms.rset_r = rpn_search_structure (zi, zs->u.complex->s2,
1283                                                   attributeSet,
1284                                                   num_bases, basenames);
1285         if (bool_parms.rset_r == NULL)
1286         {
1287             rset_delete (bool_parms.rset_l);
1288             return NULL;
1289         }
1290         if (rset_is_ranked(bool_parms.rset_r))
1291             soft = 1;
1292         bool_parms.key_size = sizeof(struct it_key);
1293         bool_parms.cmp = key_compare_it;
1294
1295         switch (zop->which)
1296         {
1297         case Z_Operator_and:
1298             r = rset_create (soft ? rset_kind_sand:rset_kind_and, &bool_parms);
1299             break;
1300         case Z_Operator_or:
1301             r = rset_create (soft ? rset_kind_sor:rset_kind_or, &bool_parms);
1302             break;
1303         case Z_Operator_and_not:
1304             r = rset_create (soft ? rset_kind_snot:rset_kind_not, &bool_parms);
1305             break;
1306         case Z_Operator_prox:
1307             if (zop->u.prox->which != Z_ProxCode_known)
1308             {
1309                 zi->errCode = 132;
1310                 return NULL;
1311             }
1312             if (*zop->u.prox->proximityUnitCode != Z_ProxUnit_word)
1313             {
1314                 static char val[16];
1315                 zi->errCode = 132;
1316                 zi->errString = val;
1317                 sprintf (val, "%d", *zop->u.prox->proximityUnitCode);
1318                 return NULL;
1319             }
1320             r = rpn_proximity (bool_parms.rset_l, bool_parms.rset_r,
1321                                *zop->u.prox->ordered,
1322                                (!zop->u.prox->exclusion ? 0 :
1323                                          *zop->u.prox->exclusion),
1324                                *zop->u.prox->relationType,
1325                                *zop->u.prox->distance);
1326             break;
1327         default:
1328             zi->errCode = 110;
1329             return NULL;
1330         }
1331     }
1332     else if (zs->which == Z_RPNStructure_simple)
1333     {
1334         if (zs->u.simple->which == Z_Operand_APT)
1335         {
1336             logf (LOG_DEBUG, "rpn_search_APT");
1337             r = rpn_search_APT (zi, zs->u.simple->u.attributesPlusTerm,
1338                                 attributeSet, num_bases, basenames);
1339         }
1340         else if (zs->u.simple->which == Z_Operand_resultSetId)
1341         {
1342             logf (LOG_DEBUG, "rpn_search_ref");
1343             r = rpn_search_ref (zi, zs->u.simple->u.resultSetId);
1344         }
1345         else
1346         {
1347             zi->errCode = 3;
1348             return NULL;
1349         }
1350     }
1351     else
1352     {
1353         zi->errCode = 3;
1354         return NULL;
1355     }
1356     return r;
1357 }
1358
1359 void count_set_save (RSET *r, int *count)
1360 {
1361     int psysno = 0;
1362     int kno = 0;
1363     struct it_key key;
1364     RSFD rfd, wfd;
1365     RSET w;
1366     rset_temp_parms parms;
1367
1368     logf (LOG_DEBUG, "count_set_save");
1369     *count = 0;
1370     parms.key_size = sizeof(struct it_key);
1371     w = rset_create (rset_kind_temp, &parms);
1372     wfd = rset_open (w, RSETF_WRITE|RSETF_SORT_SYSNO);
1373     rfd = rset_open (*r, RSETF_READ|RSETF_SORT_SYSNO);
1374     while (rset_read (*r, rfd, &key))
1375     {
1376         if (key.sysno != psysno)
1377         {
1378             if (*count < 400)
1379                 rset_write (w, wfd, &key);
1380             (*count)++;
1381             psysno = key.sysno;
1382         }
1383         kno++;
1384     }
1385     rset_close (*r, rfd);
1386     rset_delete (*r);
1387     rset_close (w, wfd);
1388     *r = w;
1389     logf (LOG_DEBUG, "%d keys, %d distinct sysnos", kno, *count);
1390 }
1391
1392 static void count_set (RSET r, int *count)
1393 {
1394     int psysno = 0;
1395     int kno = 0;
1396     struct it_key key;
1397     RSFD rfd;
1398
1399     logf (LOG_DEBUG, "count_set");
1400     *count = 0;
1401     rfd = rset_open (r, RSETF_READ|RSETF_SORT_SYSNO);
1402     while (rset_read (r, rfd, &key))
1403     {
1404         if (key.sysno != psysno)
1405         {
1406             psysno = key.sysno;
1407             (*count)++;
1408         }
1409         kno++;
1410     }
1411     rset_close (r, rfd);
1412     logf (LOG_DEBUG, "%d keys, %d distinct sysnos", kno, *count);
1413 }
1414
1415 int rpn_search (ZServerInfo *zi,
1416                 Z_RPNQuery *rpn, int num_bases, char **basenames, 
1417                 const char *setname, int *hits)
1418 {
1419     RSET rset;
1420     oident *attrset;
1421     oid_value attributeSet;
1422
1423     dict_grep_cmap (zi->dict, map_chrs_input);
1424     zlog_rpn (rpn);
1425
1426     zi->errCode = 0;
1427     zi->errString = NULL;
1428
1429     attrset = oid_getentbyoid (rpn->attributeSetId);
1430     attributeSet = attrset->value;
1431     rset = rpn_search_structure (zi, rpn->RPNStructure, attributeSet,
1432                                  num_bases, basenames);
1433     if (!rset)
1434         return zi->errCode;
1435     if (rset_is_volatile(rset))
1436         count_set_save(&rset,hits);
1437     else
1438         count_set (rset, hits);
1439     resultSetAdd (zi, setname, 1, rset);
1440     if (zi->errCode)
1441         logf (LOG_DEBUG, "search error: %d", zi->errCode);
1442     return zi->errCode;
1443 }
1444
1445 struct scan_info_entry {
1446     char *term;
1447     ISAM_P isam_p;
1448 };
1449
1450 struct scan_info {
1451     struct scan_info_entry *list;
1452     ODR odr;
1453     int before, after;
1454     char prefix[20];
1455 };
1456
1457 static int scan_handle (char *name, const char *info, int pos, void *client)
1458 {
1459     int len_prefix, idx;
1460     struct scan_info *scan_info = client;
1461
1462     len_prefix = strlen(scan_info->prefix);
1463     if (memcmp (name, scan_info->prefix, len_prefix))
1464         return 1;
1465     if (pos > 0)
1466         idx = scan_info->after - pos + scan_info->before;
1467     else
1468         idx = - pos - 1;
1469     logf (LOG_DEBUG, "%-3d %s", idx, name+len_prefix);
1470     scan_info->list[idx].term = odr_malloc (scan_info->odr,
1471                                             strlen(name + len_prefix)+1);
1472     strcpy (scan_info->list[idx].term, name + len_prefix);
1473     assert (*info == sizeof(ISAM_P));
1474     memcpy (&scan_info->list[idx].isam_p, info+1, sizeof(ISAM_P));
1475     return 0;
1476 }
1477
1478
1479 static void scan_term_untrans (ODR odr, char **dstp, const char *src)
1480 {    
1481     char *dst = odr_malloc (odr, strlen(src)*2+1);
1482     *dstp = dst;
1483
1484     while (*src)
1485     {
1486         const char *cp = map_chrs_output (&src);
1487         while (*cp)
1488             *dst++ = *cp++;
1489     }
1490     *dst = '\0';
1491 }
1492
1493 int rpn_scan (ZServerInfo *zi, Z_AttributesPlusTerm *zapt,
1494               oid_value attributeset,
1495               int num_bases, char **basenames,
1496               int *position, int *num_entries, struct scan_entry **list,
1497               int *status)
1498 {
1499     int i;
1500     int pos = *position;
1501     int num = *num_entries;
1502     int before;
1503     int after;
1504     int base_no;
1505     char termz[IT_MAX_WORD+20];
1506     AttrType use;
1507     int use_value;
1508     AttrType completeness;
1509     int completeness_value;
1510     struct scan_info *scan_info_array;
1511     struct scan_entry *glist;
1512     int ords[32], ord_no = 0;
1513     int ptr[32];
1514
1515     logf (LOG_DEBUG, "scan, position = %d, num = %d", pos, num);
1516
1517     if (attributeset == VAL_NONE)
1518         attributeset = VAL_BIB1;
1519         
1520     attr_init (&use, zapt, 1);
1521     use_value = attr_find (&use, &attributeset);
1522     logf (LOG_DEBUG, "use value %d", use_value);
1523
1524     attr_init (&completeness, zapt, 6);
1525     completeness_value = attr_find (&completeness, NULL);
1526     logf (LOG_DEBUG, "completeness value %d", completeness_value);
1527
1528     if (use_value == -1)
1529         use_value = 1016;
1530     for (base_no = 0; base_no < num_bases && ord_no < 32; base_no++)
1531     {
1532         attent *attp;
1533         data1_local_attribute *local_attr;
1534
1535         attp = att_getentbyatt (attributeset, use_value);
1536         if (!attp)
1537         {
1538             logf (LOG_DEBUG, "att_getentbyatt fail. set=%d use=%d",
1539                   attributeset, use_value);
1540             return zi->errCode = 114;
1541         }
1542         if (zebTargetInfo_curDatabase (zi->zti, basenames[base_no]))
1543         {
1544             zi->errString = basenames[base_no];
1545             return zi->errCode = 109; /* Database unavailable */
1546         }
1547         for (local_attr = attp->local_attributes; local_attr && ord_no < 32;
1548              local_attr = local_attr->next)
1549         {
1550             int ord;
1551
1552             ord = zebTargetInfo_lookupSU (zi->zti, attp->attset_ordinal,
1553                                           local_attr->local);
1554             if (ord > 0)
1555                 ords[ord_no++] = ord;
1556         }
1557     }
1558     if (ord_no == 0)
1559         return zi->errCode = 113;
1560     before = pos-1;
1561     after = 1+num-pos;
1562     scan_info_array = odr_malloc (zi->odr, ord_no * sizeof(*scan_info_array));
1563     for (i = 0; i < ord_no; i++)
1564     {
1565         int j, prefix_len = 0;
1566         int before_tmp = before, after_tmp = after;
1567         struct scan_info *scan_info = scan_info_array + i;
1568
1569         scan_info->before = before;
1570         scan_info->after = after;
1571         scan_info->odr = zi->odr;
1572
1573         scan_info->list = odr_malloc (zi->odr, (before+after)*
1574                                       sizeof(*scan_info->list));
1575         for (j = 0; j<before+after; j++)
1576             scan_info->list[j].term = NULL;
1577         termz[prefix_len++] = ords[i];
1578         termz[prefix_len++] =
1579             (completeness_value==2 || completeness_value==3) ? 'p': 'w';
1580         termz[prefix_len] = 0;
1581         strcpy (scan_info->prefix, termz);
1582
1583         trans_scan_term (zi, zapt, termz+prefix_len);
1584                     
1585         dict_scan (zi->dict, termz, &before_tmp, &after_tmp, scan_info,
1586                    scan_handle);
1587     }
1588     glist = odr_malloc (zi->odr, (before+after)*sizeof(*glist));
1589     for (i = 0; i < ord_no; i++)
1590         ptr[i] = before;
1591     
1592     *status = BEND_SCAN_SUCCESS;
1593     for (i = 0; i<after; i++)
1594     {
1595         int j, j0 = -1;
1596         const char *mterm = NULL;
1597         const char *tst;
1598         RSET rset;
1599         
1600         for (j = 0; j < ord_no; j++)
1601         {
1602             if (ptr[j] < before+after &&
1603                 (tst=scan_info_array[j].list[ptr[j]].term) &&
1604                 (!mterm || strcmp (tst, mterm) < 0))
1605             {
1606                 j0 = j;
1607                 mterm = tst;
1608             }
1609         }
1610         if (j0 == -1)
1611             break;
1612         scan_term_untrans (zi->odr, &glist[i+before].term, mterm);
1613         rset = rset_trunc (zi, &scan_info_array[j0].list[ptr[j0]].isam_p, 1);
1614
1615         ptr[j0]++;
1616         for (j = j0+1; j<ord_no; j++)
1617         {
1618             if (ptr[j] < before+after &&
1619                 (tst=scan_info_array[j].list[ptr[j]].term) &&
1620                 !strcmp (tst, mterm))
1621             {
1622                 rset_bool_parms bool_parms;
1623                 RSET rset2;
1624
1625                 rset2 =
1626                    rset_trunc (zi, &scan_info_array[j].list[ptr[j]].isam_p, 1);
1627
1628                 bool_parms.key_size = sizeof(struct it_key);
1629                 bool_parms.cmp = key_compare_it;
1630                 bool_parms.rset_l = rset;
1631                 bool_parms.rset_r = rset2;
1632               
1633                 rset = rset_create (rset_kind_or, &bool_parms);
1634
1635                 ptr[j]++;
1636             }
1637         }
1638         count_set (rset, &glist[i+before].occurrences);
1639         rset_delete (rset);
1640     }
1641     if (i < after)
1642     {
1643         *num_entries -= (after-i);
1644         *status = BEND_SCAN_PARTIAL;
1645     }
1646
1647     for (i = 0; i<ord_no; i++)
1648         ptr[i] = 0;
1649
1650     for (i = 0; i<before; i++)
1651     {
1652         int j, j0 = -1;
1653         const char *mterm = NULL;
1654         const char *tst;
1655         RSET rset;
1656         
1657         for (j = 0; j <ord_no; j++)
1658         {
1659             if (ptr[j] < before &&
1660                 (tst=scan_info_array[j].list[before-1-ptr[j]].term) &&
1661                 (!mterm || strcmp (tst, mterm) > 0))
1662             {
1663                 j0 = j;
1664                 mterm = tst;
1665             }
1666         }
1667         if (j0 == -1)
1668             break;
1669
1670         scan_term_untrans (zi->odr, &glist[before-1-i].term, mterm);
1671
1672         rset = rset_trunc
1673                (zi, &scan_info_array[j0].list[before-1-ptr[j0]].isam_p, 1);
1674
1675         ptr[j0]++;
1676
1677         for (j = j0+1; j<ord_no; j++)
1678         {
1679             if (ptr[j] < before &&
1680                 (tst=scan_info_array[j].list[before-1-ptr[j]].term) &&
1681                 !strcmp (tst, mterm))
1682             {
1683                 rset_bool_parms bool_parms;
1684                 RSET rset2;
1685
1686                 rset2 = rset_trunc (zi,
1687                          &scan_info_array[j].list[before-1-ptr[j]].isam_p, 1);
1688
1689                 bool_parms.key_size = sizeof(struct it_key);
1690                 bool_parms.cmp = key_compare_it;
1691                 bool_parms.rset_l = rset;
1692                 bool_parms.rset_r = rset2;
1693               
1694                 rset = rset_create (rset_kind_or, &bool_parms);
1695
1696                 ptr[j]++;
1697             }
1698         }
1699         count_set (rset, &glist[before-1-i].occurrences);
1700         rset_delete (rset);
1701     }
1702     i = before-i;
1703     if (i)
1704     {
1705         *status = BEND_SCAN_PARTIAL;
1706         *position -= i;
1707         *num_entries -= i;
1708     }
1709     *list = glist + i;               /* list is set to first 'real' entry */
1710     
1711     logf (LOG_DEBUG, "position = %d, num_entries = %d",
1712           *position, *num_entries);
1713     if (zi->errCode)
1714         logf (LOG_DEBUG, "scan error: %d", zi->errCode);
1715     return zi->errCode;
1716 }
1717