/*
#ident "@(#)smail/pd/sdbm:RELEASE-3_2_0_115:dbd.c,v 1.2 2003/03/27 16:49:22 woods Exp"
 */
/*
 * dbd - dump a dbm data file
 */

#include "defs.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>

#if defined(UNIX_SYS5) || defined(POSIX_OS) || defined(USE_FCNTL)
# include <fcntl.h>
#else
# if defined(UNIX_BSD)
#  include <sys/file.h>
# endif
#endif

#include "tune.h"
#include "sdbm.h"

char *progname;
extern int main __P((int, char **));
extern void oops __P((char *, ...));		/* util.c */
extern int okpage __P((char *));		/* util.c */

static void sdump __P((int));
static void dispage __P((char *));


#define empty(page)	(((short *) page)[0] == 0)

int
main(argc, argv)
	int argc;
	char **argv;
{
	size_t n;
	char *p;
	char *name;
	int pagf;

	progname = argv[0];

	if ((p = argv[1])) {
		name = (char *) malloc((n = strlen(p)) + 5);
		strcpy(name, p);
		strcpy(name + n, ".pag");

		if ((pagf = open(name, O_RDONLY)) < 0)
			oops("cannot open %s.", name);

		sdump(pagf);
	}
	else
		oops("usage: %s dbname", progname);

	exit(0);
	/* NOTREACHED */
}

static void
sdump(pagf)
	int pagf;
{
	register int r;
	register int n = 0;
	register int o = 0;
	char pag[PBLKSIZ];

	while ((r = read(pagf, pag, PBLKSIZ)) > 0) {
		if (!okpage(pag))
			fprintf(stderr, "%d: bad page.\n", n);
		else if (empty(pag))
			o++;
		else
			dispage(pag);
		n++;
	}

	if (r == 0)
		fprintf(stderr, "%d pages (%d holes).\n", n, o);
	else
		oops("read failed: block %d", n);
}


#ifdef OLD
dispage(pag)
char *pag;
{
	register i, n;
	register off;
	register short *ino = (short *) pag;

	off = PBLKSIZ;
	for (i = 1; i < ino[0]; i += 2) {
		printf("\t[%d]: ", ino[i]);
		for (n = ino[i]; n < off; n++)
			putchar(pag[n]);
		putchar(' ');
		off = ino[i];
		printf("[%d]: ", ino[i + 1]);
		for (n = ino[i + 1]; n < off; n++)
			putchar(pag[n]);
		off = ino[i + 1];
		putchar('\n');
	}
}
#else
static void
dispage(pag)
	char *pag;
{
	register int i;
	register int n;
	register int off;
	register short *ino = (short *) pag;

	off = PBLKSIZ;
	for (i = 1; i < ino[0]; i += 2) {
		for (n = ino[i]; n < off; n++)
			if (pag[n] != 0)
				putchar(pag[n]);
		putchar('\t');
		off = ino[i];
		for (n = ino[i + 1]; n < off; n++)
			if (pag[n] != 0)
				putchar(pag[n]);
		putchar('\n');
		off = ino[i + 1];
	}
}
#endif
