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