/*
 * Copyright (c) 1993 Brad Eacker,
 *              (Music, Intuition, Software, and Computers)
 * All Rights Reserved
 */

#define	USAGE	"usage: dbfndx [-v] <ndx file>\n"

/*
 * list the records in question to std out using the specified
 * index file.
 */
#include <stdio.h>
#include <fcntl.h>

#include "dbf.h"
#include "dbf_ndx.h"

main(argc, argv)
int	argc;
char	**argv;
{
	ndx_header_t 	*ndh;
	char	*fnp;
	u_char	*cp;
	int	fd, i;
	extern int optind;
	extern char *optarg;
	int	verbose = 0;
	ndx_record_t	*rp;

	if (argc < 2) {
		printf(USAGE);
		exit(1);
	}
	while ((i = getopt(argc, argv, "v")) != EOF) {
		switch (i) {
		    case 'v':
			verbose++;
			break;
		    default:
			printf(USAGE);
			exit(1);
		}
	}
	argc -= optind;  argv = &argv[optind];
	cp = (u_char *)malloc(256);
	if ((fd = open(*argv, O_RDONLY)) < 0) {
		strcpy(cp, *argv); strcat(cp, ".ndx");
		if ((fd = open(cp, O_RDONLY)) < 0) {
			perror("open");
			exit(1);
		}
	}

	if ((ndh = ndx_get_header(fd)) == 0) {
		fprintf(stderr, "Unable to get header\n");
		exit(1);
	}

	if (verbose) {
		fprintf(stderr, "# starting page %d, total pages %d\n",
			ndh->ndx_start_pg, ndh->ndx_total_pgs);
		fprintf(stderr, "# key length %d, keys/page %d, key size %d\n",
			ndh->ndx_key_len, ndh->ndx_keys_ppg,
			ndh->ndx_key_size);
		fprintf(stderr, "# key type %d, unique %d\n",
			ndh->ndx_key_type, ndh->ndx_unique);
		fprintf(stderr, "# key name '%s'\n", ndh->ndx_key_name);
	}
	rp = ndx_get_first_rec(ndh);
	while (rp) {
		if ( !verbose )
			printf("%d\n", rp->ndxr_rec);
		else {
			strncpy(cp, rp->ndxr_key_data, ndh->ndx_key_len);
			printf("%d : '%s'\n", rp->ndxr_rec, cp);
		}
		rp = ndx_get_next_rec(ndh, rp);
	}
}
