Avoid crash in ISAMB when isamb_pp_open gets ISAMB_POS = 0. In
[idzebra-moved-to-github.git] / isamb / isamb.c
1 /* $Id: isamb.c,v 1.47.2.3 2004-11-10 21:20:03 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004
3    Index Data Aps
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23 #include <string.h>
24 #include <yaz/xmalloc.h>
25 #include <yaz/log.h>
26 #include <isamb.h>
27 #include <assert.h>
28
29 #ifndef ISAMB_DEBUG
30 #define ISAMB_DEBUG 0
31 #endif
32
33 struct ISAMB_head {
34     int first_block;
35     int last_block;
36     int block_size;
37     int block_max;
38     int free_list;
39 };
40
41 #define ISAMB_DATA_OFFSET 3
42
43 /* maximum size of encoded buffer */
44 #define DST_ITEM_MAX 256
45
46 #define ISAMB_MAX_LEVEL 10
47 /* approx 2*max page + max size of item */
48 #define DST_BUF_SIZE 16840
49
50 #define ISAMB_CACHE_ENTRY_SIZE 4096
51
52 /* CAT_MAX: _must_ be power of 2 */
53 #define CAT_MAX 4
54 #define CAT_MASK (CAT_MAX-1)
55 /* CAT_NO: <= CAT_MAX */
56 #define CAT_NO 4
57
58 /* ISAMB_PTR_CODEC=1 var, =0 fixed */
59 #define ISAMB_PTR_CODEC  0
60
61 struct ISAMB_cache_entry {
62     ISAMB_P pos;
63     unsigned char *buf;
64     int dirty;
65     int hits;
66     struct ISAMB_cache_entry *next;
67 };
68
69 struct ISAMB_file {
70     BFile bf;
71     int head_dirty;
72     struct ISAMB_head head;
73     struct ISAMB_cache_entry *cache_entries;
74 };
75
76 struct ISAMB_s {
77     BFiles bfs;
78     ISAMC_M *method;
79
80     struct ISAMB_file *file;
81     int no_cat;
82     int cache; /* 0=no cache, 1=use cache, -1=dummy isam (for testing only) */
83     int log_io;        /* log level for bf_read/bf_write calls */
84     int log_freelist;  /* log level for freelist handling */
85     int skipped_numbers; /* on a leaf node */
86     int returned_numbers; 
87     int skipped_nodes[ISAMB_MAX_LEVEL]; /* [0]=skipped leaves, 1=higher etc */
88     int accessed_nodes[ISAMB_MAX_LEVEL]; /* nodes we did not skip */
89 };
90
91 struct ISAMB_block {
92     ISAMB_P pos;
93     int cat;
94     int size;
95     int leaf;
96     int dirty;
97     int deleted;
98     int offset;
99     char *bytes;
100     char *cbuf;
101     unsigned char *buf;
102     void *decodeClientData;
103     int log_rw;
104 };
105
106 struct ISAMB_PP_s {
107     ISAMB isamb;
108     ISAMB_P pos;
109     int level;
110     int maxlevel; /* total depth */
111     int total_size;
112     int no_blocks;
113     int skipped_numbers; /* on a leaf node */
114     int returned_numbers; 
115     int skipped_nodes[ISAMB_MAX_LEVEL]; /* [0]=skipped leaves, 1=higher etc */
116     int accessed_nodes[ISAMB_MAX_LEVEL]; /* nodes we did not skip */
117     struct ISAMB_block **block;
118 };
119
120
121 #if ISAMB_PTR_CODEC
122 static void encode_ptr (char **dst, unsigned pos)
123 {
124     unsigned char *bp = (unsigned char*) *dst;
125
126     while (pos > 127)
127     {
128          *bp++ = 128 | (pos & 127);
129          pos = pos >> 7;
130     }
131     *bp++ = pos;
132     *dst = (char *) bp;
133 }
134 #else
135 static void encode_ptr (char **dst, unsigned pos)
136 {
137     memcpy(*dst, &pos, sizeof(pos));
138     (*dst) += sizeof(pos);
139 }
140 #endif
141
142 #if ISAMB_PTR_CODEC
143 static void decode_ptr (char **src1, int *pos)
144 {
145     unsigned char **src = (unsigned char **) src1;
146     unsigned d = 0;
147     unsigned char c;
148     unsigned r = 0;
149
150     while (((c = *(*src)++) & 128))
151     {
152         d += ((c & 127) << r);
153         r += 7;
154     }
155     d += (c << r);
156     *pos = d;
157 }
158 #else
159 static void decode_ptr (char **src, int *pos)
160 {
161      memcpy (pos, *src, sizeof(*pos));
162      (*src) += sizeof(*pos);
163 }
164 #endif
165
166 ISAMB isamb_open (BFiles bfs, const char *name, int writeflag, ISAMC_M *method,
167                   int cache)
168 {
169     ISAMB isamb = xmalloc (sizeof(*isamb));
170     int i, b_size = 32;
171
172     isamb->bfs = bfs;
173     isamb->method = (ISAMC_M *) xmalloc (sizeof(*method));
174     memcpy (isamb->method, method, sizeof(*method));
175     isamb->no_cat = CAT_NO;
176     isamb->log_io = 0;
177     isamb->log_freelist = 0;
178     isamb->cache = cache;
179     isamb->skipped_numbers=0;
180     isamb->returned_numbers=0;
181     for (i=0;i<ISAMB_MAX_LEVEL;i++)
182       isamb->skipped_nodes[i]= isamb->accessed_nodes[i]=0;
183
184     assert (cache == 0);
185     isamb->file = xmalloc (sizeof(*isamb->file) * isamb->no_cat);
186     for (i = 0; i<isamb->no_cat; i++)
187     {
188         char fname[DST_BUF_SIZE];
189         isamb->file[i].cache_entries = 0;
190         isamb->file[i].head_dirty = 0;
191         sprintf (fname, "%s%c", name, i+'A');
192         if (cache)
193             isamb->file[i].bf = bf_open (bfs, fname, ISAMB_CACHE_ENTRY_SIZE,
194                                          writeflag);
195         else
196             isamb->file[i].bf = bf_open (bfs, fname, b_size, writeflag);
197
198         
199         if (!bf_read (isamb->file[i].bf, 0, 0, sizeof(struct ISAMB_head),
200                       &isamb->file[i].head))
201         {
202             isamb->file[i].head.first_block = ISAMB_CACHE_ENTRY_SIZE/b_size+1;
203             isamb->file[i].head.last_block = isamb->file[i].head.first_block;
204             isamb->file[i].head.block_size = b_size;
205             isamb->file[i].head.block_max = b_size - ISAMB_DATA_OFFSET;
206             isamb->file[i].head.free_list = 0;
207         }
208         assert (isamb->file[i].head.block_size >= ISAMB_DATA_OFFSET);
209         isamb->file[i].head_dirty = 0;
210         assert(isamb->file[i].head.block_size == b_size);
211         b_size = b_size * 4;
212     }
213 #if ISAMB_DEBUG
214     logf(LOG_WARN, "isamb debug enabled. Things will be slower than usual");
215 #endif
216     return isamb;
217 }
218
219 static void flush_blocks (ISAMB b, int cat)
220 {
221     while (b->file[cat].cache_entries)
222     {
223         struct ISAMB_cache_entry *ce_this = b->file[cat].cache_entries;
224         b->file[cat].cache_entries = ce_this->next;
225
226         if (ce_this->dirty)
227         {
228             yaz_log (b->log_io, "bf_write: flush_blocks");
229             bf_write (b->file[cat].bf, ce_this->pos, 0, 0, ce_this->buf);
230         }
231         xfree (ce_this->buf);
232         xfree (ce_this);
233     }
234 }
235
236 static int get_block (ISAMB b, ISAMC_P pos, char *userbuf, int wr)
237 {
238     int cat = pos&CAT_MASK;
239     int off = ((pos/CAT_MAX) & 
240                (ISAMB_CACHE_ENTRY_SIZE / b->file[cat].head.block_size - 1))
241         * b->file[cat].head.block_size;
242     int norm = pos / (CAT_MASK*ISAMB_CACHE_ENTRY_SIZE / b->file[cat].head.block_size);
243     int no = 0;
244     struct ISAMB_cache_entry **ce, *ce_this = 0, **ce_last = 0;
245
246     if (!b->cache)
247         return 0;
248
249     assert (ISAMB_CACHE_ENTRY_SIZE >= b->file[cat].head.block_size);
250     for (ce = &b->file[cat].cache_entries; *ce; ce = &(*ce)->next, no++)
251     {
252         ce_last = ce;
253         if ((*ce)->pos == norm)
254         {
255             ce_this = *ce;
256             *ce = (*ce)->next;   /* remove from list */
257             
258             ce_this->next = b->file[cat].cache_entries;  /* move to front */
259             b->file[cat].cache_entries = ce_this;
260             
261             if (wr)
262             {
263                 memcpy (ce_this->buf + off, userbuf, 
264                         b->file[cat].head.block_size);
265                 ce_this->dirty = 1;
266             }
267             else
268                 memcpy (userbuf, ce_this->buf + off,
269                         b->file[cat].head.block_size);
270             return 1;
271         }
272     }
273     if (no >= 40)
274     {
275         assert (no == 40);
276         assert (ce_last && *ce_last);
277         ce_this = *ce_last;
278         *ce_last = 0;  /* remove the last entry from list */
279         if (ce_this->dirty)
280         {
281             yaz_log (b->log_io, "bf_write: get_block");
282             bf_write (b->file[cat].bf, ce_this->pos, 0, 0, ce_this->buf);
283         }
284         xfree (ce_this->buf);
285         xfree (ce_this);
286     }
287     ce_this = xmalloc (sizeof(*ce_this));
288     ce_this->next = b->file[cat].cache_entries;
289     b->file[cat].cache_entries = ce_this;
290     ce_this->buf = xmalloc (ISAMB_CACHE_ENTRY_SIZE);
291     ce_this->pos = norm;
292     yaz_log (b->log_io, "bf_read: get_block");
293     if (!bf_read (b->file[cat].bf, norm, 0, 0, ce_this->buf))
294         memset (ce_this->buf, 0, ISAMB_CACHE_ENTRY_SIZE);
295     if (wr)
296     {
297         memcpy (ce_this->buf + off, userbuf, b->file[cat].head.block_size);
298         ce_this->dirty = 1;
299     }
300     else
301     {
302         ce_this->dirty = 0;
303         memcpy (userbuf, ce_this->buf + off, b->file[cat].head.block_size);
304     }
305     return 1;
306 }
307
308
309 void isamb_close (ISAMB isamb)
310 {
311     int i;
312     for (i=0;isamb->accessed_nodes[i];i++)
313         logf(LOG_DEBUG,"isamb_close  level leaf-%d: %d read, %d skipped",
314              i, isamb->accessed_nodes[i], isamb->skipped_nodes[i]);
315     logf(LOG_DEBUG,"isamb_close returned %d values, skipped %d",
316          isamb->skipped_numbers, isamb->returned_numbers);
317     for (i = 0; i<isamb->no_cat; i++)
318     {
319         flush_blocks (isamb, i);
320         if (isamb->file[i].head_dirty)
321             bf_write (isamb->file[i].bf, 0, 0,
322                       sizeof(struct ISAMB_head), &isamb->file[i].head);
323         
324         bf_close (isamb->file[i].bf);
325     }
326     xfree (isamb->file);
327     xfree (isamb->method);
328     xfree (isamb);
329 }
330
331 static struct ISAMB_block *open_block (ISAMB b, ISAMC_P pos)
332 {
333     int cat = pos&CAT_MASK;
334     struct ISAMB_block *p;
335     if (!pos)
336         return 0;
337     p = xmalloc (sizeof(*p));
338     p->pos = pos;
339     p->cat = pos & CAT_MASK;
340     p->buf = xmalloc (b->file[cat].head.block_size);
341     p->cbuf = 0;
342
343     if (!get_block (b, pos, p->buf, 0))
344     {
345         yaz_log (b->log_io, "bf_read: open_block");
346         if (!bf_read (b->file[cat].bf, pos/CAT_MAX, 0, 0, p->buf))
347         {
348             yaz_log (LOG_FATAL, "isamb: read fail for pos=%ld block=%ld",
349                      (long) pos, (long) pos/CAT_MAX);
350             abort();
351         }
352     }
353     p->bytes = p->buf + ISAMB_DATA_OFFSET;
354     p->leaf = p->buf[0];
355     p->size = (p->buf[1] + 256 * p->buf[2]) - ISAMB_DATA_OFFSET;
356     if (p->size < 0)
357     {
358         yaz_log (LOG_FATAL, "Bad block size %d in pos=%d\n", p->size, pos);
359     }
360     assert (p->size >= 0);
361     p->offset = 0;
362     p->dirty = 0;
363     p->deleted = 0;
364     p->decodeClientData = (*b->method->code_start)(ISAMC_DECODE);
365     yaz_log (LOG_DEBUG, "isamb_open_block: Opened block %d ofs=%d",pos, p->offset);
366     return p;
367 }
368
369 struct ISAMB_block *new_block (ISAMB b, int leaf, int cat)
370 {
371     struct ISAMB_block *p;
372
373     p = xmalloc (sizeof(*p));
374     p->buf = xmalloc (b->file[cat].head.block_size);
375
376     if (!b->file[cat].head.free_list)
377     {
378         int block_no;
379         block_no = b->file[cat].head.last_block++;
380         p->pos = block_no * CAT_MAX + cat;
381     }
382     else
383     {
384         p->pos = b->file[cat].head.free_list;
385         assert((p->pos & CAT_MASK) == cat);
386         if (!get_block (b, p->pos, p->buf, 0))
387         {
388             yaz_log (b->log_io, "bf_read: new_block");
389             if (!bf_read (b->file[cat].bf, p->pos/CAT_MAX, 0, 0, p->buf))
390             {
391                 yaz_log (LOG_FATAL, "isamb: read fail for pos=%ld block=%ld",
392                          (long) p->pos/CAT_MAX, (long) p->pos/CAT_MAX);
393                 abort ();
394             }
395         }
396         yaz_log (b->log_freelist, "got block %d from freelist %d:%d", p->pos,
397                  cat, p->pos/CAT_MAX);
398         memcpy (&b->file[cat].head.free_list, p->buf, sizeof(int));
399     }
400     p->cat = cat;
401     b->file[cat].head_dirty = 1;
402     memset (p->buf, 0, b->file[cat].head.block_size);
403     p->bytes = p->buf + ISAMB_DATA_OFFSET;
404     p->leaf = leaf;
405     p->size = 0;
406     p->dirty = 1;
407     p->deleted = 0;
408     p->offset = 0;
409     p->decodeClientData = (*b->method->code_start)(ISAMC_DECODE);
410     return p;
411 }
412
413 struct ISAMB_block *new_leaf (ISAMB b, int cat)
414 {
415     return new_block (b, 1, cat);
416 }
417
418
419 struct ISAMB_block *new_int (ISAMB b, int cat)
420 {
421     return new_block (b, 0, cat);
422 }
423
424 static void check_block (ISAMB b, struct ISAMB_block *p)
425 {
426     if (p->leaf)
427     {
428         ;
429     }
430     else
431     {
432         /* sanity check */
433         char *startp = p->bytes;
434         char *src = startp;
435         char *endp = p->bytes + p->size;
436         int pos;
437             
438         decode_ptr (&src, &pos);
439         assert ((pos&CAT_MASK) == p->cat);
440         while (src != endp)
441         {
442             int item_len;
443             decode_ptr (&src, &item_len);
444             assert (item_len > 0 && item_len < 30);
445             src += item_len;
446             decode_ptr (&src, &pos);
447             assert ((pos&CAT_MASK) == p->cat);
448         }
449     }
450 }
451
452 void close_block (ISAMB b, struct ISAMB_block *p)
453 {
454     if (!p)
455         return;
456     if (p->deleted)
457     {
458         yaz_log (b->log_freelist, "release block %d from freelist %d:%d",
459                  p->pos, p->cat, p->pos/CAT_MAX);
460         memcpy (p->buf, &b->file[p->cat].head.free_list, sizeof(int));
461         b->file[p->cat].head.free_list = p->pos;
462         if (!get_block (b, p->pos, p->buf, 1))
463         {
464             yaz_log (b->log_io, "bf_write: close_block (deleted)");
465             bf_write (b->file[p->cat].bf, p->pos/CAT_MAX, 0, 0, p->buf);
466         }
467     }
468     else if (p->dirty)
469     {
470         int size = p->size + ISAMB_DATA_OFFSET;
471         assert (p->size >= 0);
472         p->buf[0] = p->leaf;
473         p->buf[1] = size & 255;
474         p->buf[2] = size >> 8;
475         check_block(b, p);
476         if (!get_block (b, p->pos, p->buf, 1))
477         {
478             yaz_log (b->log_io, "bf_write: close_block");
479             bf_write (b->file[p->cat].bf, p->pos/CAT_MAX, 0, 0, p->buf);
480         }
481     }
482     (*b->method->code_stop)(ISAMC_DECODE, p->decodeClientData);
483     xfree (p->buf);
484     xfree (p);
485 }
486
487 int insert_sub (ISAMB b, struct ISAMB_block **p,
488                 void *new_item, int *mode,
489                 ISAMC_I *stream,
490                 struct ISAMB_block **sp,
491                 void *sub_item, int *sub_size,
492                 void *max_item);
493
494 int insert_int (ISAMB b, struct ISAMB_block *p, void *lookahead_item,
495                 int *mode,
496                 ISAMC_I *stream, struct ISAMB_block **sp,
497                 void *split_item, int *split_size, void *last_max_item)
498 {
499     char *startp = p->bytes;
500     char *src = startp;
501     char *endp = p->bytes + p->size;
502     int pos;
503     struct ISAMB_block *sub_p1 = 0, *sub_p2 = 0;
504     char sub_item[DST_ITEM_MAX];
505     int sub_size;
506     int more = 0;
507
508     *sp = 0;
509
510     assert(p->size >= 0);
511     decode_ptr (&src, &pos);
512     while (src != endp)
513     {
514         int item_len;
515         int d;
516         char *src0 = src;
517         decode_ptr (&src, &item_len);
518         d = (*b->method->compare_item)(src, lookahead_item);
519         if (d > 0)
520         {
521             sub_p1 = open_block (b, pos);
522             assert (sub_p1);
523             more = insert_sub (b, &sub_p1, lookahead_item, mode,
524                                stream, &sub_p2, 
525                                sub_item, &sub_size, src);
526             src = src0;
527             break;
528         }
529         src += item_len;
530         decode_ptr (&src, &pos);
531     }
532     if (!sub_p1)
533     {
534         sub_p1 = open_block (b, pos);
535         assert (sub_p1);
536         more = insert_sub (b, &sub_p1, lookahead_item, mode, stream, &sub_p2, 
537                            sub_item, &sub_size, last_max_item);
538     }
539     if (sub_p2)
540     {
541         /* there was a split - must insert pointer in this one */
542         char dst_buf[DST_BUF_SIZE];
543         char *dst = dst_buf;
544
545         assert (sub_size < 30 && sub_size > 1);
546
547         memcpy (dst, startp, src - startp);
548                 
549         dst += src - startp;
550
551         encode_ptr (&dst, sub_size);      /* sub length and item */
552         memcpy (dst, sub_item, sub_size);
553         dst += sub_size;
554
555         encode_ptr (&dst, sub_p2->pos);   /* pos */
556
557         if (endp - src)                   /* remaining data */
558         {
559             memcpy (dst, src, endp - src);
560             dst += endp - src;
561         }
562         p->size = dst - dst_buf;
563         assert (p->size >= 0);
564         if (p->size <= b->file[p->cat].head.block_max)
565         {
566             memcpy (startp, dst_buf, dst - dst_buf);
567         }
568         else
569         {
570             int p_new_size;
571             char *half;
572             src = dst_buf;
573             endp = dst;
574
575             half = src + b->file[p->cat].head.block_size/2;
576             decode_ptr (&src, &pos);
577             while (src <= half)
578             {
579                 decode_ptr (&src, split_size);
580                 src += *split_size;
581                 decode_ptr (&src, &pos);
582             }
583             p_new_size = src - dst_buf;
584             memcpy (p->bytes, dst_buf, p_new_size);
585
586             decode_ptr (&src, split_size);
587             memcpy (split_item, src, *split_size);
588             src += *split_size;
589
590             *sp = new_int (b, p->cat);
591             (*sp)->size = endp - src;
592             memcpy ((*sp)->bytes, src, (*sp)->size);
593
594             p->size = p_new_size;
595         }
596         p->dirty = 1;
597         close_block (b, sub_p2);
598     }
599     close_block (b, sub_p1);
600     return more;
601 }
602
603
604 int insert_leaf (ISAMB b, struct ISAMB_block **sp1, void *lookahead_item,
605                  int *lookahead_mode, ISAMC_I *stream,
606                  struct ISAMB_block **sp2,
607                  void *sub_item, int *sub_size,
608                  void *max_item)
609 {
610     struct ISAMB_block *p = *sp1;
611     char *src = 0, *endp = 0;
612     char dst_buf[DST_BUF_SIZE], *dst = dst_buf;
613     int new_size;
614     void *c1 = (*b->method->code_start)(ISAMC_DECODE);
615     void *c2 = (*b->method->code_start)(ISAMC_ENCODE);
616     int more = 1;
617     int quater = b->file[b->no_cat-1].head.block_max / CAT_MAX;
618     char *cut = dst_buf + quater * 2;
619     char *maxp = dst_buf + b->file[b->no_cat-1].head.block_max;
620     char *half1 = 0;
621     char *half2 = 0;
622     char cut_item_buf[DST_ITEM_MAX];
623     int cut_item_size = 0;
624
625     if (p && p->size)
626     {
627         char file_item_buf[DST_ITEM_MAX];
628         char *file_item = file_item_buf;
629             
630         src = p->bytes;
631         endp = p->bytes + p->size;
632         (*b->method->code_item)(ISAMC_DECODE, c1, &file_item, &src);
633         while (1)
634         {
635             char *dst_item = 0;
636             char *lookahead_next;
637             int d = -1;
638             
639             if (lookahead_item)
640                 d = (*b->method->compare_item)(file_item_buf, lookahead_item);
641             
642             if (d > 0)
643             {
644                 dst_item = lookahead_item;
645                 if (!*lookahead_mode)
646                 {
647                     yaz_log (LOG_WARN, "isamb: Inconsistent register (1)");
648                     assert (*lookahead_mode);
649                 }
650             }
651             else
652                 dst_item = file_item_buf;
653             if (!*lookahead_mode && d == 0)
654             {
655                 p->dirty = 1;
656             }
657             else if (!half1 && dst > cut)
658             {
659                 char *dst_item_0 = dst_item;
660                 half1 = dst; /* candidate for splitting */
661                 
662                 (*b->method->code_item)(ISAMC_ENCODE, c2, &dst, &dst_item);
663                 
664                 cut_item_size = dst_item - dst_item_0;
665                 memcpy (cut_item_buf, dst_item_0, cut_item_size);
666                 
667                 half2 = dst;
668             }
669             else
670                 (*b->method->code_item)(ISAMC_ENCODE, c2, &dst, &dst_item);
671             if (d > 0)  
672             {
673                 if (dst > maxp)
674                     lookahead_item = 0;
675                 else
676                 {
677                     lookahead_next = lookahead_item;
678                     if (!(*stream->read_item)(stream->clientData,
679                                               &lookahead_next,
680                                               lookahead_mode))
681                     {
682                         lookahead_item = 0;
683                         more = 0;
684                     }
685                     if (lookahead_item && max_item &&
686                         (*b->method->compare_item)(max_item, lookahead_item) <= 0)
687                     {
688                         /* max_item 1 */
689                         lookahead_item = 0;
690                     }
691                     
692                     p->dirty = 1;
693                 }
694             }
695             else if (d == 0)
696             {
697                 lookahead_next = lookahead_item;
698                 if (!(*stream->read_item)(stream->clientData,
699                                           &lookahead_next, lookahead_mode))
700                 {
701                     lookahead_item = 0;
702                     more = 0;
703                 }
704                 if (src == endp)
705                     break;
706                 file_item = file_item_buf;
707                 (*b->method->code_item)(ISAMC_DECODE, c1, &file_item, &src);
708             }
709             else
710             {
711                 if (src == endp)
712                     break;
713                 file_item = file_item_buf;
714                 (*b->method->code_item)(ISAMC_DECODE, c1, &file_item, &src);
715             }
716         }
717     }
718     maxp = dst_buf + b->file[b->no_cat-1].head.block_max + quater;
719     while (lookahead_item)
720     {
721         char *dst_item = lookahead_item;
722         char *dst_0 = dst;
723         
724         if (max_item &&
725             (*b->method->compare_item)(max_item, lookahead_item) <= 0)
726         {
727             /* max_item 2 */
728             break;
729         }
730         if (!*lookahead_mode)
731         {
732             yaz_log (LOG_WARN, "isamb: Inconsistent register (2)");
733             abort();
734         }
735         else if (!half1 && dst > cut)   
736         {
737             char *dst_item_0 = dst_item;
738             half1 = dst; /* candidate for splitting */
739             
740             (*b->method->code_item)(ISAMC_ENCODE, c2, &dst, &dst_item);
741             
742             cut_item_size = dst_item - dst_item_0;
743             memcpy (cut_item_buf, dst_item_0, cut_item_size);
744             
745             half2 = dst;
746         }
747         else
748             (*b->method->code_item)(ISAMC_ENCODE, c2, &dst, &dst_item);
749
750         if (dst > maxp)
751         {
752             dst = dst_0;
753             break;
754         }
755         if (p)
756             p->dirty = 1;
757         dst_item = lookahead_item;
758         if (!(*stream->read_item)(stream->clientData, &dst_item,
759                                   lookahead_mode))
760         {
761             lookahead_item = 0;
762             more = 0;
763         }
764     }
765     new_size = dst - dst_buf;
766     if (p && p->cat != b->no_cat-1 && 
767         new_size > b->file[p->cat].head.block_max)
768     {
769         /* non-btree block will be removed */
770         p->deleted = 1;
771         close_block (b, p);
772         /* delete it too!! */
773         p = 0; /* make a new one anyway */
774     }
775     if (!p)
776     {   /* must create a new one */
777         int i;
778         for (i = 0; i < b->no_cat; i++)
779             if (new_size <= b->file[i].head.block_max)
780                 break;
781         if (i == b->no_cat)
782             i = b->no_cat - 1;
783         p = new_leaf (b, i);
784     }
785     if (new_size > b->file[p->cat].head.block_max)
786     {
787         char *first_dst;
788         char *cut_item = cut_item_buf;
789
790         assert (half1);
791         assert (half2);
792
793        /* first half */
794         p->size = half1 - dst_buf;
795         memcpy (p->bytes, dst_buf, half1 - dst_buf);
796
797         /* second half */
798         *sp2 = new_leaf (b, p->cat);
799
800         (*b->method->code_reset)(c2);
801
802         first_dst = (*sp2)->bytes;
803
804         (*b->method->code_item)(ISAMC_ENCODE, c2, &first_dst, &cut_item);
805
806         memcpy (first_dst, half2, dst - half2);
807
808         (*sp2)->size = (first_dst - (*sp2)->bytes) + (dst - half2);
809         (*sp2)->dirty = 1;
810         p->dirty = 1;
811         memcpy (sub_item, cut_item_buf, cut_item_size);
812         *sub_size = cut_item_size;
813     }
814     else
815     {
816         memcpy (p->bytes, dst_buf, dst - dst_buf);
817         p->size = new_size;
818     }
819     (*b->method->code_stop)(ISAMC_DECODE, c1);
820     (*b->method->code_stop)(ISAMC_ENCODE, c2);
821     *sp1 = p;
822     return more;
823 }
824
825 int insert_sub (ISAMB b, struct ISAMB_block **p, void *new_item,
826                 int *mode,
827                 ISAMC_I *stream,
828                 struct ISAMB_block **sp,
829                 void *sub_item, int *sub_size,
830                 void *max_item)
831 {
832     if (!*p || (*p)->leaf)
833         return insert_leaf (b, p, new_item, mode, stream, sp, sub_item, 
834                             sub_size, max_item);
835     else
836         return insert_int (b, *p, new_item, mode, stream, sp, sub_item,
837                            sub_size, max_item);
838 }
839
840 int isamb_unlink (ISAMB b, ISAMC_P pos)
841 {
842     struct ISAMB_block *p1;
843
844     if (!pos)
845         return 0;
846     p1 = open_block(b, pos);
847     p1->deleted = 1;
848     if (!p1->leaf)
849     {
850         int sub_p;
851         int item_len;
852         char *src = p1->bytes + p1->offset;
853
854         decode_ptr(&src, &sub_p);
855         isamb_unlink(b, sub_p);
856         
857         while (src != p1->bytes + p1->size)
858         {
859             decode_ptr(&src, &item_len);
860             src += item_len;
861             decode_ptr(&src, &sub_p);
862             isamb_unlink(b, sub_p);
863         }
864     }
865     close_block(b, p1);
866     return 0;
867 }
868
869 int isamb_merge (ISAMB b, ISAMC_P pos, ISAMC_I *stream)
870 {
871     char item_buf[DST_ITEM_MAX];
872     char *item_ptr;
873     int i_mode;
874     int more;
875
876     if (b->cache < 0)
877     {
878         int more = 1;
879         while (more)
880         {
881             item_ptr = item_buf;
882             more =
883                 (*stream->read_item)(stream->clientData, &item_ptr, &i_mode);
884         }
885         return 1;
886     }
887     item_ptr = item_buf;
888     more = (*stream->read_item)(stream->clientData, &item_ptr, &i_mode);
889     while (more)
890     {
891         struct ISAMB_block *p = 0, *sp = 0;
892         char sub_item[DST_ITEM_MAX];
893         int sub_size;
894         
895         if (pos)
896             p = open_block (b, pos);
897         more = insert_sub (b, &p, item_buf, &i_mode, stream, &sp,
898                             sub_item, &sub_size, 0);
899         if (sp)
900         {    /* increase level of tree by one */
901             struct ISAMB_block *p2 = new_int (b, p->cat);
902             char *dst = p2->bytes + p2->size;
903             
904             encode_ptr (&dst, p->pos);
905             assert (sub_size < 20);
906             encode_ptr (&dst, sub_size);
907             memcpy (dst, sub_item, sub_size);
908             dst += sub_size;
909             encode_ptr (&dst, sp->pos);
910             
911             p2->size = dst - p2->bytes;
912             pos = p2->pos;  /* return new super page */
913             close_block (b, sp);
914             close_block (b, p2);
915         }
916         else
917             pos = p->pos;   /* return current one (again) */
918         close_block (b, p);
919     }
920     return pos;
921 }
922
923 ISAMB_PP isamb_pp_open_x (ISAMB isamb, ISAMB_P pos, int *level)
924 {
925     ISAMB_PP pp = xmalloc (sizeof(*pp));
926     int i;
927
928     pp->isamb = isamb;
929     pp->block = xmalloc (ISAMB_MAX_LEVEL * sizeof(*pp->block));
930
931     pp->pos = pos;
932     pp->level = 0;
933     pp->maxlevel=0;
934     pp->total_size = 0;
935     pp->no_blocks = 0;
936     pp->skipped_numbers=0;
937     pp->returned_numbers=0;
938     for (i = 0; i<ISAMB_MAX_LEVEL; i++)
939         pp->skipped_nodes[i] = pp->accessed_nodes[i] = 0;
940     pp->block[0] = 0;
941     if (pos)
942     {
943         while (1)
944         {
945             struct ISAMB_block *p = open_block (isamb, pos);
946             char *src = p->bytes + p->offset;
947             pp->block[pp->level] = p;
948             
949             pp->total_size += p->size;
950             pp->no_blocks++;
951             if (p->leaf)
952                 break;
953             
954             decode_ptr (&src, &pos);
955             p->offset = src - p->bytes;
956             pp->level++;
957             pp->accessed_nodes[pp->level]++; 
958         }
959     }
960     pp->block[pp->level+1] = 0;
961     pp->maxlevel = pp->level;
962     if (level)
963         *level = pp->level;
964     return pp;
965 }
966
967 ISAMB_PP isamb_pp_open (ISAMB isamb, ISAMB_P pos)
968 {
969     return isamb_pp_open_x (isamb, pos, 0);
970 }
971
972 void isamb_pp_close_x (ISAMB_PP pp, int *size, int *blocks)
973 {
974     int i;
975     if (!pp)
976         return;
977     logf(LOG_DEBUG,"isamb_pp_close lev=%d returned %d values, skipped %d",
978         pp->maxlevel, pp->skipped_numbers, pp->returned_numbers);
979     for (i=pp->maxlevel;i>=0;i--)
980         if ( pp->skipped_nodes[i] || pp->accessed_nodes[i])
981             logf(LOG_DEBUG,"isamb_pp_close  level leaf-%d: %d read, %d skipped", i,
982                  pp->accessed_nodes[i], pp->skipped_nodes[i]);
983     pp->isamb->skipped_numbers += pp->skipped_numbers;
984     pp->isamb->returned_numbers += pp->returned_numbers;
985     for (i=pp->maxlevel;i>=0;i--)
986     {
987         pp->isamb->accessed_nodes[i] += pp->accessed_nodes[i];
988         pp->isamb->skipped_nodes[i] += pp->skipped_nodes[i];
989     }
990     if (size)
991         *size = pp->total_size;
992     if (blocks)
993         *blocks = pp->no_blocks;
994     for (i = 0; i <= pp->level; i++)
995         close_block (pp->isamb, pp->block[i]);
996     xfree (pp->block);
997     xfree (pp);
998 }
999
1000 int isamb_block_info (ISAMB isamb, int cat)
1001 {
1002     if (cat >= 0 && cat < isamb->no_cat)
1003         return isamb->file[cat].head.block_size;
1004     return -1;
1005 }
1006
1007 void isamb_pp_close (ISAMB_PP pp)
1008 {
1009     isamb_pp_close_x (pp, 0, 0);
1010 }
1011
1012 /* simple recursive dumper .. */
1013 static void isamb_dump_r (ISAMB b, ISAMB_P pos, void (*pr)(const char *str),
1014                           int level)
1015 {
1016     char buf[1024];
1017     char prefix_str[1024];
1018     if (pos)
1019     {
1020         struct ISAMB_block *p = open_block (b, pos);
1021         sprintf(prefix_str, "%*s %d cat=%d size=%d max=%d", level*2, "",
1022                 pos, p->cat, p->size, b->file[p->cat].head.block_max);
1023         (*pr)(prefix_str);
1024         sprintf(prefix_str, "%*s %d", level*2, "", pos);
1025         if (p->leaf)
1026         {
1027             while (p->offset < p->size)
1028             {
1029                 char *src = p->bytes + p->offset;
1030                 char *dst = buf;
1031                 (*b->method->code_item)(ISAMC_DECODE, p->decodeClientData,
1032                                         &dst, &src);
1033                 (*b->method->log_item)(LOG_DEBUG, buf, prefix_str);
1034                 p->offset = src - (char*) p->bytes;
1035             }
1036             assert(p->offset == p->size);
1037         }
1038         else
1039         {
1040             char *src = p->bytes + p->offset;
1041             int sub;
1042             int item_len;
1043
1044             decode_ptr (&src, &sub);
1045             p->offset = src - (char*) p->bytes;
1046
1047             isamb_dump_r(b, sub, pr, level+1);
1048             
1049             while (p->offset < p->size)
1050             {
1051                 decode_ptr (&src, &item_len);
1052                 (*b->method->log_item)(LOG_DEBUG, src, prefix_str);
1053                 src += item_len;
1054                 decode_ptr (&src, &sub);
1055                 
1056                 p->offset = src - (char*) p->bytes;
1057                 
1058                 isamb_dump_r(b, sub, pr, level+1);
1059             }           
1060         }
1061         close_block(b,p);
1062     }
1063 }
1064
1065 void isamb_dump (ISAMB b, ISAMB_P pos, void (*pr)(const char *str))
1066 {
1067     isamb_dump_r(b, pos, pr, 0);
1068 }
1069
1070 #if 0
1071 /* Old isamb_pp_read that Adam wrote, kept as a reference in case we need to
1072    debug the more complex pp_read that also forwards. May be deleted near end
1073    of 2004, if it has not shown to be useful */
1074
1075
1076 int isamb_pp_read (ISAMB_PP pp, void *buf)
1077 {
1078     char *dst = buf;
1079     char *src;
1080     struct ISAMB_block *p = pp->block[pp->level];
1081     if (!p)
1082         return 0;
1083
1084     while (p->offset == p->size)
1085     {
1086         int pos, item_len;
1087         while (p->offset == p->size)
1088         {
1089             if (pp->level == 0)
1090                 return 0;
1091             close_block (pp->isamb, pp->block[pp->level]);
1092             pp->block[pp->level] = 0;
1093             (pp->level)--;
1094             p = pp->block[pp->level];
1095             assert (!p->leaf);  
1096         }
1097         src = p->bytes + p->offset;
1098         
1099         decode_ptr (&src, &item_len);
1100         src += item_len;
1101         decode_ptr (&src, &pos);
1102         
1103         p->offset = src - (char*) p->bytes;
1104
1105         ++(pp->level);
1106         
1107         while (1)
1108         {
1109             pp->block[pp->level] = p = open_block (pp->isamb, pos);
1110
1111             pp->total_size += p->size;
1112             pp->no_blocks++;
1113             
1114             if (p->leaf) 
1115             {
1116                 break;
1117             }
1118             src = p->bytes + p->offset;
1119             decode_ptr (&src, &pos);
1120             p->offset = src - (char*) p->bytes;
1121             pp->level++;
1122         }
1123     }
1124     assert (p->offset < p->size);
1125     assert (p->leaf);
1126     src = p->bytes + p->offset;
1127     (*pp->isamb->method->code_item)(ISAMC_DECODE, p->decodeClientData,
1128                                     &dst, &src);
1129     p->offset = src - (char*) p->bytes;
1130     /* key_logdump_txt(LOG_DEBUG,buf, "isamb_pp_read returning 1"); */
1131     return 1;
1132 }
1133
1134 #else
1135 int isamb_pp_read (ISAMB_PP pp, void *buf)
1136 {
1137     return isamb_pp_forward(pp,buf,0);
1138 }
1139 #endif
1140
1141 #define NEW_FORWARD 1
1142
1143 #if NEW_FORWARD == 1
1144
1145 /*
1146 #undef ISAMB_DEBUB
1147 #define ISAMB_DEBUG 1
1148 */
1149 static int isamb_pp_on_right_node(ISAMB_PP pp, int level, const void *untilbuf)
1150 { /* looks one node higher to see if we should be on this node at all */
1151   /* useful in backing off quickly, and in avoiding tail descends */
1152   /* call with pp->level to begin with */
1153     struct ISAMB_block *p;
1154     int cmp;
1155     char *src;
1156     int item_len;
1157     assert(level>=0);
1158     if ( level == 0) {
1159 #if ISAMB_DEBUG
1160             logf(LOG_DEBUG,"isamb_pp_on_right returning true for root");
1161 #endif
1162         return 1; /* we can never skip the root node */
1163     }
1164     level--;
1165     p=pp->block[level];
1166     assert(p->offset <= p->size);
1167     if (p->offset < p->size )
1168     {
1169         assert(p->offset>0); 
1170         src=p->bytes + p->offset;
1171         decode_ptr(&src,&item_len);
1172 #if ISAMB_DEBUG
1173         (*pp->isamb->method->log_item)(LOG_DEBUG,untilbuf,"on_leaf: until");
1174         (*pp->isamb->method->log_item)(LOG_DEBUG,src,"on_leaf: value");
1175 #endif
1176         cmp=(*pp->isamb->method->compare_item)(untilbuf,src);
1177         if (cmp<2) {
1178 #if ISAMB_DEBUG
1179             logf(LOG_DEBUG,"isamb_pp_on_right returning true "
1180                             "cmp=%d lev=%d ofs=%d",cmp,level,p->offset);
1181 #endif
1182             return 1; 
1183         }
1184         else {
1185 #if ISAMB_DEBUG
1186             logf(LOG_DEBUG,"isamb_pp_on_right returning false "
1187                             "cmp=%d lev=%d ofs=%d",cmp,level,p->offset);
1188 #endif
1189             return 0; 
1190         }
1191     }
1192     else {
1193 #if ISAMB_DEBUG
1194         logf(LOG_DEBUG,"isamb_pp_on_right at tail, looking higher "
1195                         "lev=%d",level);
1196 #endif
1197         return isamb_pp_on_right_node(pp, level, untilbuf);
1198     }
1199 } /* isamb_pp_on_right_node */
1200
1201 static int isamb_pp_read_on_leaf(ISAMB_PP pp, void *buf)
1202 { /* reads the next item on the current leaf, returns 0 if end of leaf*/
1203     struct ISAMB_block *p = pp->block[pp->level];
1204     char *dst;
1205     char *src;
1206     assert(pp);
1207     assert(buf);
1208     if (!p || p->offset == p->size) {
1209 #if ISAMB_DEBUG
1210         logf(LOG_DEBUG,"isamb_pp_read_on_leaf returning 0 on node %d",p->pos);
1211 #endif
1212         return 0; /* at end of leaf */
1213     }
1214     src=p->bytes + p->offset;
1215     dst=buf;
1216     (*pp->isamb->method->code_item)
1217            (ISAMC_DECODE, p->decodeClientData,&dst, &src);
1218     p->offset = src - (char*) p->bytes;
1219     /*
1220 #if ISAMB_DEBUG
1221     (*pp->isamb->method->log_item)(LOG_DEBUG, buf, "read_on_leaf returning 1");
1222 #endif
1223 */
1224     return 1;
1225 } /* read_on_leaf */
1226
1227 static int isamb_pp_forward_on_leaf(ISAMB_PP pp, void *buf, const void *untilbuf)
1228 { /* forwards on the current leaf, returns 0 if not found */
1229     int cmp;
1230     int skips=0;
1231     while (1){
1232         if (!isamb_pp_read_on_leaf(pp,buf))
1233             return 0;
1234         /* FIXME - this is an extra function call, inline the read? */
1235         cmp=(*pp->isamb->method->compare_item)(untilbuf,buf);
1236         if (cmp <2){  /* found a good one */
1237 #if ISAMB_DEBUG
1238             if (skips)
1239                 logf(LOG_DEBUG, "isam_pp_fwd_on_leaf skipped %d items",skips);
1240 #endif
1241             pp->returned_numbers++;
1242             return 1;
1243         }
1244         if (!skips)
1245             if (!isamb_pp_on_right_node(pp, pp->level, untilbuf))
1246                 return 0; /* never mind the rest of this leaf */
1247         pp->skipped_numbers++;
1248         skips++;
1249     }
1250 } /* forward_on_leaf */
1251
1252 static int isamb_pp_climb_level(ISAMB_PP pp, int *pos)
1253 { /* climbs higher in the tree, until finds a level with data left */
1254   /* returns the node to (consider to) descend to in *pos) */
1255     struct ISAMB_block *p = pp->block[pp->level];
1256     char *src;
1257     int item_len;
1258 #if ISAMB_DEBUG
1259     logf(LOG_DEBUG,"isamb_pp_climb_level starting "
1260                    "at level %d node %d ofs=%d sz=%d",
1261                     pp->level, p->pos, p->offset, p->size);
1262 #endif
1263     assert(pp->level >= 0);
1264     if (!p)
1265         return 0;
1266     assert(p->offset <= p->size);
1267     if (pp->level==0)
1268     {
1269 #if ISAMB_DEBUG
1270         logf(LOG_DEBUG,"isamb_pp_climb_level returning 0 at root");
1271 #endif
1272         return 0;
1273     }
1274     assert(pp->level>0); 
1275     close_block(pp->isamb, pp->block[pp->level]);
1276     pp->block[pp->level]=0;
1277     (pp->level)--;
1278     p=pp->block[pp->level];
1279 #if ISAMB_DEBUG
1280     logf(LOG_DEBUG,"isamb_pp_climb_level climbed to level %d node %d ofs=%d",
1281                     pp->level, p->pos, p->offset);
1282 #endif
1283     assert(!p->leaf);
1284     assert(p->offset <= p->size);
1285     if (p->offset == p->size ) {
1286         /* we came from the last pointer, climb on */
1287         if (!isamb_pp_climb_level(pp,pos))
1288             return 0;
1289         p=pp->block[pp->level];
1290     }
1291     else
1292     {
1293         /* skip the child we just came from */
1294 #if ISAMB_DEBUG
1295         logf(LOG_DEBUG,"isam_pp_climb_level: skipping lev=%d ofs=%d sz=%d", 
1296                         pp->level, p->offset, p->size);
1297 #endif
1298         assert (p->offset < p->size );
1299         src=p->bytes + p->offset;
1300         decode_ptr(&src, &item_len);
1301         src += item_len;
1302         decode_ptr(&src, pos);
1303         p->offset=src - (char *)p->bytes;
1304             
1305     }
1306     return 1;
1307 } /* climb_level */
1308
1309
1310 static int isamb_pp_forward_unode(ISAMB_PP pp, int pos, const void *untilbuf)
1311 { /* scans a upper node until it finds a child <= untilbuf */
1312   /* pp points to the key value, as always. pos is the child read from */
1313   /* the buffer */
1314   /* if all values are too small, returns the last child in the node */
1315   /* FIXME - this can be detected, and avoided by looking at the */
1316   /* parent node, but that gets messy. Presumably the cost is */
1317   /* pretty low anyway */
1318     struct ISAMB_block *p = pp->block[pp->level];
1319     char *src = p->bytes + p->offset;
1320     int item_len;
1321     int cmp;
1322     int nxtpos;
1323 #if ISAMB_DEBUG
1324     int skips = 0;
1325     if (p)
1326         logf(LOG_DEBUG,"isamb_pp_forward_unode starting "
1327              "at level %d node %d ofs=%di sz=%d",
1328              pp->level, p->pos, p->offset, p->size);
1329 #endif
1330     assert(!p->leaf);
1331     assert(p->offset <= p->size);
1332     if (p->offset == p->size) {
1333 #if ISAMB_DEBUG
1334         logf(LOG_DEBUG,"isamb_pp_forward_unode returning at end "
1335              "at level %d node %d ofs=%di sz=%d",
1336              pp->level, p->pos, p->offset, p->size);
1337 #endif
1338         return pos; /* already at the end of it */
1339     }
1340     while(p->offset < p->size)
1341     {
1342         decode_ptr(&src,&item_len);
1343         cmp=(*pp->isamb->method->compare_item)(untilbuf,src);
1344         src+=item_len;
1345         decode_ptr(&src,&nxtpos);
1346         if (cmp<2)
1347         {
1348 #if ISAMB_DEBUG
1349             logf(LOG_DEBUG,"isamb_pp_forward_unode returning a hit "
1350                  "at level %d node %d ofs=%d sz=%d",
1351                  pp->level, p->pos, p->offset, p->size);
1352 #endif
1353             return pos;
1354         } /* found one */
1355         pos=nxtpos;
1356         p->offset=src-(char*)p->bytes;
1357         (pp->skipped_nodes[pp->maxlevel - pp->level -1])++;
1358 #if ISAMB_DEBUG
1359         skips++;
1360 #endif
1361     }
1362 #if ISAMB_DEBUG
1363             logf(LOG_DEBUG,"isamb_pp_forward_unode returning at tail "
1364                    "at level %d node %d ofs=%d sz=%d skips=%d",
1365                     pp->level, p->pos, p->offset, p->size, skips);
1366 #endif
1367     return pos; /* that's the last one in the line */
1368     
1369 } /* forward_unode */
1370
1371 static void isamb_pp_descend_to_leaf(ISAMB_PP pp, int pos, const void *untilbuf)
1372 { /* climbs down the tree, from pos, to the leftmost leaf */
1373     struct ISAMB_block *p = pp->block[pp->level];
1374     char *src;
1375     assert(!p->leaf);
1376 #if ISAMB_DEBUG
1377     logf(LOG_DEBUG,"isamb_pp_descend_to_leaf "
1378                    "starting at lev %d node %d ofs=%d lf=%d u=%p", 
1379                    pp->level, p->pos, p->offset, p->leaf, untilbuf);
1380 #endif
1381     if (untilbuf)
1382         pos=isamb_pp_forward_unode(pp,pos,untilbuf);
1383     ++(pp->level);
1384     assert(pos);
1385     p = open_block(pp->isamb, pos);
1386     pp->block[pp->level] = p;
1387     ++(pp->accessed_nodes[pp->maxlevel-pp->level]);
1388     ++(pp->no_blocks);
1389 #if ISAMB_DEBUG
1390     logf(LOG_DEBUG,"isamb_pp_descend_to_leaf "
1391                    "got lev %d node %d lf=%d", 
1392                    pp->level, p->pos, p->leaf);
1393 #endif
1394     if (p->leaf)
1395         return;
1396     assert (p->offset==0);
1397     src = p->bytes + p->offset;
1398     decode_ptr(&src, &pos);
1399     p->offset = src-(char*)p->bytes;
1400     isamb_pp_descend_to_leaf(pp,pos,untilbuf);
1401 #if ISAMB_DEBUG
1402     logf(LOG_DEBUG,"isamb_pp_descend_to_leaf "
1403                    "returning at lev %d node %d ofs=%d lf=%d", 
1404                    pp->level, p->pos, p->offset, p->leaf);
1405 #endif
1406 } /* descend_to_leaf */
1407
1408 static int isamb_pp_find_next_leaf(ISAMB_PP pp)
1409 { /* finds the next leaf by climbing up and down */
1410     int pos;
1411     if (!isamb_pp_climb_level(pp,&pos))
1412         return 0;
1413     isamb_pp_descend_to_leaf(pp, pos,0);
1414     return 1;
1415 }
1416
1417 static int isamb_pp_climb_desc(ISAMB_PP pp, void *buf, const void *untilbuf)
1418 { /* climbs up and descends to a leaf where values >= *untilbuf are found */
1419     int pos;
1420 #if ISAMB_DEBUG
1421     struct ISAMB_block *p = pp->block[pp->level];
1422     logf(LOG_DEBUG,"isamb_pp_climb_desc starting "
1423                    "at level %d node %d ofs=%d sz=%d",
1424                     pp->level, p->pos, p->offset, p->size);
1425 #endif
1426     if (!isamb_pp_climb_level(pp,&pos))
1427         return 0;
1428     /* see if it would pay to climb one higher */
1429     if (!isamb_pp_on_right_node(pp, pp->level, untilbuf))
1430         if (!isamb_pp_climb_level(pp,&pos))
1431             return 0;
1432     isamb_pp_descend_to_leaf(pp, pos,untilbuf);
1433 #if ISAMB_DEBUG
1434     p = pp->block[pp->level];
1435     logf(LOG_DEBUG,"isamb_pp_climb_desc done "
1436                    "at level %d node %d ofs=%d sz=%d",
1437                     pp->level, p->pos, p->offset, p->size);
1438 #endif
1439     return 1;
1440 } /* climb_desc */
1441
1442 int isamb_pp_forward (ISAMB_PP pp, void *buf, const void *untilbuf)
1443 {
1444 #if ISAMB_DEBUG
1445     struct ISAMB_block *p = pp->block[pp->level];
1446     if (p)
1447     {
1448         assert(p->leaf);
1449         logf(LOG_DEBUG,"isamb_pp_forward starting "
1450              "at level %d node %d ofs=%d sz=%d u=%p",
1451              pp->level, p->pos, p->offset, p->size,untilbuf);
1452     }
1453 #endif
1454     if (untilbuf) {
1455         if (isamb_pp_forward_on_leaf( pp, buf, untilbuf)) {
1456 #if ISAMB_DEBUG
1457             if (p)
1458                 logf(LOG_DEBUG,"isamb_pp_forward (f) returning (A) "
1459                      "at level %d node %d ofs=%d sz=%d",
1460                     pp->level, p->pos, p->offset, p->size);
1461 #endif
1462             return 1;
1463         }
1464         if (! isamb_pp_climb_desc( pp, buf, untilbuf)) {
1465 #if ISAMB_DEBUG
1466             if (p)
1467                 logf(LOG_DEBUG,"isamb_pp_forward (f) returning notfound (B) "
1468                      "at level %d node %d ofs=%d sz=%d",
1469                      pp->level, p->pos, p->offset, p->size);
1470 #endif
1471             return 0; /* could not find a leaf */
1472         }
1473         do {
1474             if (isamb_pp_forward_on_leaf( pp, buf, untilbuf)) {
1475 #if ISAMB_DEBUG
1476                 if(p)
1477                     logf(LOG_DEBUG,"isamb_pp_forward (f) returning (C) "
1478                          "at level %d node %d ofs=%d sz=%d",
1479                          pp->level, p->pos, p->offset, p->size);
1480 #endif
1481                 return 1;
1482             }
1483         } while (isamb_pp_find_next_leaf(pp));
1484         return 0; /* could not find at all */
1485     }
1486     else { /* no untilbuf, a straight read */
1487         /* FIXME - this should be moved
1488          * directly into the pp_read */
1489         /* keeping here now, to keep same
1490          * interface as the old fwd */
1491         if (isamb_pp_read_on_leaf( pp, buf)) {
1492 #if ISAMB_DEBUG
1493             if (p)
1494                 logf(LOG_DEBUG,"isamb_pp_forward (read) returning (D) "
1495                      "at level %d node %d ofs=%d sz=%d",
1496                      pp->level, p->pos, p->offset, p->size);
1497 #endif
1498             return 1;
1499         }
1500         if (isamb_pp_find_next_leaf(pp)) {
1501 #if ISAMB_DEBUG
1502             if (p)
1503                 logf(LOG_DEBUG,"isamb_pp_forward (read) returning (E) "
1504                      "at level %d node %d ofs=%d sz=%d",
1505                     pp->level, p->pos, p->offset, p->size);
1506 #endif
1507             return isamb_pp_read_on_leaf(pp, buf);
1508         }
1509         else
1510             return 0;
1511     }
1512 } /* isam_pp_forward (new version) */
1513
1514 #elif NEW_FORWARD == 0
1515
1516 int isamb_pp_forward (ISAMB_PP pp, void *buf, const void *untilbuf)
1517 {
1518     /* pseudocode:
1519      *   while 1
1520      *     while at end of node
1521      *       climb higher. If out, return 0
1522      *     while not on a leaf (and not at its end)
1523      *       decode next
1524      *       if cmp
1525      *         descend to node
1526      *     decode next
1527      *     if cmp
1528      *       return 1
1529      */
1530      /* 
1531       * The upper nodes consist of a sequence of nodenumbers and keys
1532       * When opening a block,  the first node number is read in, and
1533       * offset points to the first key, which is the upper limit of keys
1534       * in the node just read.
1535       */
1536     char *dst = buf;
1537     char *src;
1538     struct ISAMB_block *p = pp->block[pp->level];
1539     int cmp;
1540     int item_len;
1541     int pos;
1542     int nxtpos;
1543     int descending=0; /* used to prevent a border condition error */
1544     if (!p)
1545         return 0;
1546 #if ISAMB_DEBUG
1547     logf(LOG_DEBUG,"isamb_pp_forward starting [%p] p=%d",pp,p->pos);
1548     
1549     (*pp->isamb->method->log_item)(LOG_DEBUG, untilbuf, "until");
1550     (*pp->isamb->method->log_item)(LOG_DEBUG, buf, "buf");
1551 #endif
1552
1553     while (1)
1554     {
1555         while ( (p->offset == p->size) && !descending )
1556         {  /* end of this block - climb higher */
1557             assert (p->offset <= p->size);
1558 #if ISAMB_DEBUG
1559             logf(LOG_DEBUG,"isamb_pp_forward climbing from l=%d",
1560                             pp->level);
1561 #endif
1562             if (pp->level == 0)
1563             {
1564 #if ISAMB_DEBUG
1565                 logf(LOG_DEBUG,"isamb_pp_forward returning 0 at root");
1566 #endif
1567                 return 0; /* at end of the root, nothing left */
1568             }
1569             close_block(pp->isamb, pp->block[pp->level]);
1570             pp->block[pp->level]=0;
1571             (pp->level)--;
1572             p=pp->block[pp->level];
1573 #if ISAMB_DEBUG
1574             logf(LOG_DEBUG,"isamb_pp_forward climbed to node %d off=%d",
1575                             p->pos, p->offset);
1576 #endif
1577             assert(!p->leaf);
1578             assert(p->offset <= p->size);
1579             /* skip the child we have handled */
1580             if (p->offset != p->size)
1581             { 
1582                 src = p->bytes + p->offset;
1583                 decode_ptr(&src, &item_len);
1584 #if ISAMB_DEBUG         
1585                 (*pp->isamb->method->log_item)(LOG_DEBUG, src,
1586                                                " isamb_pp_forward "
1587                                                "climb skipping old key");
1588 #endif
1589                 src += item_len;
1590                 decode_ptr(&src,&pos);
1591                 p->offset = src - (char*) p->bytes;
1592                 break; /* even if this puts us at the end of the block, we
1593                           need to descend to the last pos. UGLY coding,
1594                           clean up some day */
1595             }
1596         }
1597         if (!p->leaf)
1598         { 
1599             src = p->bytes + p->offset;
1600             if (p->offset == p->size)
1601                 cmp=-2 ; /* descend to the last node, as we have
1602                             no value to cmp */
1603             else
1604             {
1605                 decode_ptr(&src, &item_len);
1606 #if ISAMB_DEBUG
1607                 logf(LOG_DEBUG,"isamb_pp_forward (B) on a high node. "
1608                      "ofs=%d sz=%d nxtpos=%d ",
1609                         p->offset,p->size,pos);
1610                 (*pp->isamb->method->log_item)(LOG_DEBUG, src, "");
1611 #endif
1612                 if (untilbuf)
1613                     cmp=(*pp->isamb->method->compare_item)(untilbuf,src);
1614                 else
1615                     cmp=-2;
1616                 src += item_len;
1617                 decode_ptr(&src,&nxtpos);
1618             }
1619             if (cmp<2)
1620             { 
1621 #if ISAMB_DEBUG
1622                 logf(LOG_DEBUG,"isambb_pp_forward descending l=%d p=%d ",
1623                             pp->level, pos);
1624 #endif
1625                 descending=1; /* prevent climbing for a while */
1626                 ++(pp->level);
1627                 p = open_block(pp->isamb,pos);
1628                 pp->block[pp->level] = p ;
1629                 pp->total_size += p->size;
1630                 (pp->accessed_nodes[pp->maxlevel - pp->level])++;
1631                 pp->no_blocks++;
1632                 if ( !p->leaf)
1633                 { /* block starts with a pos */
1634                     src = p->bytes + p->offset;
1635                     decode_ptr(&src,&pos);
1636                     p->offset=src-(char*) p->bytes;
1637 #if ISAMB_DEBUG
1638                     logf(LOG_DEBUG,"isamb_pp_forward: block %d starts with %d",
1639                                     p->pos, pos);
1640 #endif
1641                 } 
1642             } /* descend to the node */
1643             else
1644             { /* skip the node */
1645                 p->offset = src - (char*) p->bytes;
1646                 pos=nxtpos;
1647                 (pp->skipped_nodes[pp->maxlevel - pp->level -1])++;
1648 #if ISAMB_DEBUG
1649                 logf(LOG_DEBUG,
1650                     "isamb_pp_forward: skipping block on level %d, noting "
1651                      "on %d (%d)",
1652                     pp->level, pp->maxlevel - pp->level-1 , 
1653                     pp->skipped_nodes[pp->maxlevel - pp->level-1 ]);
1654 #endif
1655                 /* 0 is always leafs, 1 is one level above leafs etc, no
1656                  * matter how high tree */
1657             }
1658         } /* not on a leaf */
1659         else
1660         { /* on a leaf */
1661             if (p->offset == p->size) { 
1662                 descending = 0;
1663             }
1664             else
1665             {
1666                 assert (p->offset < p->size);
1667                 src = p->bytes + p->offset;
1668                 dst=buf;
1669                 (*pp->isamb->method->code_item)(ISAMC_DECODE, p->decodeClientData,
1670                                                 &dst, &src);
1671                 p->offset = src - (char*) p->bytes;
1672                 if (untilbuf)
1673                     cmp=(*pp->isamb->method->compare_item)(untilbuf,buf);
1674                 else
1675                     cmp=-2;
1676 #if ISAMB_DEBUG
1677                 logf(LOG_DEBUG,"isamb_pp_forward on a leaf. cmp=%d", 
1678                      cmp);
1679                 (*pp->isamb->method->log_item)(LOG_DEBUG, buf, "");
1680 #endif
1681                 if (cmp <2)
1682                 {
1683 #if ISAMB_DEBUG
1684                     if (untilbuf)
1685                     {
1686                         (*pp->isamb->method->log_item)(
1687                             LOG_DEBUG, buf,  "isamb_pp_forward returning 1");
1688                     }
1689                     else
1690                     {
1691                         (*pp->isamb->method->log_item)(
1692                             LOG_DEBUG, buf, "isamb_pp_read returning 1 (fwd)");
1693                     }
1694 #endif
1695                     pp->returned_numbers++;
1696                     return 1;
1697                 }
1698                 else
1699                     pp->skipped_numbers++;
1700             }
1701         } /* leaf */
1702     } /* main loop */
1703 }
1704
1705 #elif NEW_FORWARD == 2
1706
1707 int isamb_pp_forward (ISAMB_PP pp, void *buf, const void *untilb)
1708 {
1709     char *dst = buf;
1710     char *src;
1711     struct ISAMB_block *p = pp->block[pp->level];
1712     if (!p)
1713         return 0;
1714
1715 again:
1716     while (p->offset == p->size)
1717     {
1718         int pos, item_len;
1719         while (p->offset == p->size)
1720         {
1721             if (pp->level == 0)
1722                 return 0;
1723             close_block (pp->isamb, pp->block[pp->level]);
1724             pp->block[pp->level] = 0;
1725             (pp->level)--;
1726             p = pp->block[pp->level];
1727             assert (!p->leaf);  
1728         }
1729
1730         assert(!p->leaf);
1731         src = p->bytes + p->offset;
1732         
1733         decode_ptr (&src, &item_len);
1734         src += item_len;
1735         decode_ptr (&src, &pos);
1736         
1737         p->offset = src - (char*) p->bytes;
1738
1739         src = p->bytes + p->offset;
1740
1741         while(1)
1742         {
1743             if (!untilb || p->offset == p->size)
1744                 break;
1745             assert(p->offset < p->size);
1746             decode_ptr (&src, &item_len);
1747             if ((*pp->isamb->method->compare_item)(untilb, src) <= 1)
1748                 break;
1749             src += item_len;
1750             decode_ptr (&src, &pos);
1751             p->offset = src - (char*) p->bytes;
1752         }
1753
1754         pp->level++;
1755
1756         while (1)
1757         {
1758             pp->block[pp->level] = p = open_block (pp->isamb, pos);
1759
1760             pp->total_size += p->size;
1761             pp->no_blocks++;
1762             
1763             if (p->leaf) 
1764             {
1765                 break;
1766             }
1767             
1768             src = p->bytes + p->offset;
1769             while(1)
1770             {
1771                 decode_ptr (&src, &pos);
1772                 p->offset = src - (char*) p->bytes;
1773                 
1774                 if (!untilb || p->offset == p->size)
1775                     break;
1776                 assert(p->offset < p->size);
1777                 decode_ptr (&src, &item_len);
1778                 if ((*pp->isamb->method->compare_item)(untilb, src) <= 1)
1779                     break;
1780                 src += item_len;
1781             }
1782             pp->level++;
1783         }
1784     }
1785     assert (p->offset < p->size);
1786     assert (p->leaf);
1787     while(1)
1788     {
1789         char *dst0 = dst;
1790         src = p->bytes + p->offset;
1791         (*pp->isamb->method->code_item)(ISAMC_DECODE, p->decodeClientData,
1792                                     &dst, &src);
1793         p->offset = src - (char*) p->bytes;
1794         if (!untilb || (*pp->isamb->method->compare_item)(untilb, dst0) <= 1)
1795             break;
1796         dst = dst0;
1797         if (p->offset == p->size) goto again;
1798     }
1799     /* key_logdump_txt(LOG_DEBUG,buf, "isamb_pp_read returning 1"); */
1800     return 1;
1801 }
1802
1803 #endif
1804
1805 int isamb_pp_num (ISAMB_PP pp)
1806 {
1807     return 1;
1808 }
1809
1810 static void isamb_pp_leaf_pos( ISAMB_PP pp, 
1811                                int *current, int *total, void *dummybuf )
1812 {
1813     struct ISAMB_block *p = pp->block[pp->level];
1814     char *src=p->bytes;
1815     char *end=p->bytes+p->size;
1816     char *cur=p->bytes+p->offset;
1817     char *dst;
1818     assert(p->offset <= p->size);
1819     assert(cur <= end);
1820     assert(p->leaf);
1821     *current=0;
1822     *total=0;
1823
1824     while(src < end) {
1825         dst=dummybuf;
1826         (*pp->isamb->method->code_item)
1827            (ISAMC_DECODE, p->decodeClientData,&dst, &src);
1828         assert(dst<(char*) dummybuf+100); /*FIXME */
1829         (*total)++;
1830         if (src<=cur)
1831              (*current)++;
1832     }
1833     logf(LOG_DEBUG, "isamb_pp_leaf_pos: cur=%d tot=%d ofs=%d sz=%d lev=%d",
1834                     *current, *total, p->offset, p->size, pp->level);
1835     assert(src==end);
1836 }
1837
1838 static void isamb_pp_upper_pos( ISAMB_PP pp, int *current, int *total, 
1839                                 int size, int level )
1840 { /* estimates total/current occurrences from here up, excl leaf */
1841     struct ISAMB_block *p = pp->block[level];
1842     char *src=p->bytes;
1843     char *end=p->bytes+p->size;
1844     char *cur=p->bytes+p->offset;
1845     int item_size;
1846     int child;
1847     assert(level>=0);
1848     assert(!p->leaf);
1849     logf(LOG_DEBUG,"isamb_pp_upper_pos at beginning     l=%d "
1850                    "cur=%d tot=%d ofs=%d sz=%d pos=%d", 
1851                    level, *current, *total, p->offset, p->size, p->pos);
1852     assert (p->offset <= p->size);
1853         decode_ptr (&src, &child ); /* first child */
1854     while(src < end) {
1855         if (src!=cur) {
1856             *total += size;
1857             if (src < cur)
1858                 *current +=size;
1859         }
1860             decode_ptr (&src, &item_size ); 
1861         assert(src+item_size<=end);
1862         src += item_size;
1863             decode_ptr (&src, &child );
1864     }
1865     if (level>0)
1866         isamb_pp_upper_pos(pp, current, total, *total, level-1);
1867 } /* upper_pos */
1868
1869 void isamb_pp_pos( ISAMB_PP pp, int *current, int *total )
1870 { /* return an estimate of the current position and of the total number of */
1871   /* occureences in the isam tree, based on the current leaf */
1872     struct ISAMB_block *p = pp->block[pp->level];
1873     char dummy[100]; /* 100 bytes/entry must be enough */
1874     assert(total);
1875     assert(current);
1876     assert(p->leaf);
1877     isamb_pp_leaf_pos(pp,current, total, dummy);
1878     if (pp->level>0)
1879         isamb_pp_upper_pos(pp, current, total, *total, pp->level-1);
1880     /*
1881     logf(LOG_DEBUG,"isamb_pp_pos: C=%d T=%d =%6.2f%%",
1882                     *current, *total, 100.0*(*current)/(*total));
1883     */
1884 }