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