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

/*
 * display selected records of the database in question to the stdout
 */
#include <stdio.h>
#include <fcntl.h>

#define	USAGE	"usage: dbfget [-v] <file> [<record> <record>...]\n"

#include "dbf.h"

main(argc, argv)
int	argc;
char	**argv;
{
	dbhead_t 	*dbh;
	dbfield_t	*dbf, *cur_f;
	char	*fnp;
	u_char	*cp;
	int	fd, nfields;
	int	rec_cnt, i;
	extern int optind;
	extern char *optarg;
	int	verbose = 0;

	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 += optind;
	if ((fd = open(*argv, O_RDONLY)) < 0) {
		cp = (u_char *)malloc(256);
		strcpy(cp, *argv); strcat(cp, ".dbf");
		if ((fd = open(cp, O_RDONLY)) < 0) {
			perror("open");
			exit(1);
		}
		free(cp);
	}
	argv++; argc--;

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

	nfields = dbh->db_nfields;
	if (verbose)
	  	printf("# fields: %d, record len: %d, total records %d\n",
			nfields, dbh->db_rlen, dbh->db_records);

	dbf = dbh->db_fields;

	if (verbose) {
		for (cur_f = dbf; cur_f < &dbf[nfields] ; cur_f++) {
			printf("# %s, %c, %d, %d\n", cur_f->db_fname,
				cur_f->db_type, cur_f->db_flen, cur_f->db_fdc);
		}
	}

	/* put out the field headings */
	printf(" ");
	for (cur_f = dbf; cur_f < &dbf[nfields] ; cur_f++) {
		fnp = (char *)strdup(cur_f->db_fname);
		if (strlen(fnp) > cur_f->db_flen) {
			fnp[cur_f->db_flen] = 0;
		}
		printf(" ");
		printf(cur_f->db_format, fnp);
		free((char *)fnp);
	}
	printf("\n");

	/* step thru the records */
	while (argc-- > 0) {
		rec_cnt = strtol(*argv++, NULL, 0);
		if ((cp = get_dbf_record(dbh, rec_cnt)) == NULL) {
			printf("tried to read bad record %d\n", rec_cnt);
			break;
		}
		out_rec(dbh, dbf, cp);
		free(cp);
	}
}

/*
 * output a record
 */
out_rec(dbh, dbf, cp)
dbhead_t	*dbh;
dbfield_t	*dbf;
char	*cp;
{
	dbfield_t	*cur_f;
	int	nfields = dbh->db_nfields;
	char	*fnp = (char *)alloca(dbh->db_rlen);

	printf("%c", *cp++);
	for (cur_f = dbf; cur_f < &dbf[nfields] ; cur_f++) {
		printf(" ");
		strncpy(fnp, cp, cur_f->db_flen);
		fnp[cur_f->db_flen] = 0;
		printf(cur_f->db_format, fnp);
		cp += cur_f->db_flen;
	}
	printf("\n");
}
