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