+#define HEADER_SIZE 256
+
+BFile bf_xopen(BFiles bfs, const char *name, int block_size, int wrflag,
+ const char *magic, int *read_version,
+ const char **more_info)
+{
+ char read_magic[40];
+ int l = 0;
+ int i = 0;
+ char *hbuf;
+ zint pos = 0;
+ BFile bf = bf_open(bfs, name, block_size, wrflag);
+
+ if (!bf)
+ return 0;
+ /* HEADER_SIZE is considered enough for our header */
+ if (bf->block_size < HEADER_SIZE)
+ bf->alloc_buf_size = HEADER_SIZE;
+ else
+ bf->alloc_buf_size = bf->block_size;
+
+ hbuf = bf->alloc_buf = xmalloc(bf->alloc_buf_size);
+
+ /* fill-in default values */
+ bf->free_list = 0;
+ bf->root_block = bf->last_block = HEADER_SIZE / bf->block_size + 1;
+ bf->magic = xstrdup(magic);
+
+ if (!bf_read(bf, pos, 0, 0, hbuf + pos * bf->block_size))
+ {
+ if (wrflag)
+ bf->header_dirty = 1;
+ return bf;
+ }
+ while(hbuf[pos * bf->block_size + i] != '\0')
+ {
+ if (i == bf->block_size)
+ { /* end of block at pos reached .. */
+ if (bf->alloc_buf_size < (pos+1) * bf->block_size)
+ {
+ /* not room for all in alloc_buf_size */
+ yaz_log(YLOG_WARN, "bad header for %s (3)", magic);
+ bf_close(bf);
+ return 0;
+ }
+ /* read next block in header */
+ pos++;
+ if (!bf_read(bf, pos, 0, 0, hbuf + pos * bf->block_size))
+ {
+ yaz_log(YLOG_WARN, "missing header block %s (4)", magic);
+ bf_close(bf);
+ return 0;
+ }
+ i = 0; /* pos within block is reset */
+ }
+ else
+ i++;
+ }
+ if (sscanf(hbuf, "%39s %d " ZINT_FORMAT " " ZINT_FORMAT "%n",
+ read_magic, read_version, &bf->last_block,
+ &bf->free_list, &l) < 4 && l) /* if %n is counted, it's 5 */
+ {
+ yaz_log(YLOG_WARN, "bad header for %s (1)", magic);
+ bf_close(bf);
+ return 0;
+ }
+ if (strcmp(read_magic, magic))
+ {
+ yaz_log(YLOG_WARN, "bad header for %s (2)", magic);
+ bf_close(bf);
+ return 0;
+ }
+ if (hbuf[l] == ' ')
+ l++;
+ if (more_info)
+ *more_info = hbuf + l;
+ return bf;
+}
+
+int bf_xclose (BFile bf, int version, const char *more_info)
+{
+ if (bf->header_dirty)
+ {
+ zint pos = 0;
+ assert(bf->alloc_buf);
+ assert(bf->magic);
+ sprintf(bf->alloc_buf, "%s %d " ZINT_FORMAT " " ZINT_FORMAT " ",
+ bf->magic, version, bf->last_block, bf->free_list);
+ if (more_info)
+ strcat(bf->alloc_buf, more_info);
+ while (1)
+ {
+ bf_write(bf, pos, 0, 0, bf->alloc_buf + pos * bf->block_size);
+ pos++;
+ if (pos * bf->block_size > strlen(bf->alloc_buf))
+ break;
+ }
+ }
+ return bf_close(bf);
+}
+