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

#define	USAGE	"usage: dbfadd <file> <field> <field> ...\n"

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

#include "dbf.h"

main(argc, argv)
int	argc;
char	**argv;
{
	dbhead_t 	*dbh;
	dbfield_t	*dbf, *cur_f;
	char	*fnp;
	u_char	*cp, *t_cp;
	int	fd, nfields;
	int	rec_cnt;

	if (argc < 2) {
		printf(USAGE);
		exit(1);
	}
	argv++;	argc--;
	if ((fd = open(*argv, O_RDWR)) < 0) {
		cp = (u_char *)malloc(256);
		strcpy(cp, *argv); strcat(cp, ".dbf");
		free(cp);
		if ((fd = open(cp, O_RDWR)) < 0) {
			perror("open");
			exit(1);
		}
	}
	argv++;	argc--;

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

	nfields = dbh->db_nfields;
	if (nfields != argc) {
		fprintf(stderr, "mismatch of field count, %d vs %d inputs\n",
				nfields, argc);
		exit(1);
	}
	cp = t_cp = (u_char *)malloc(dbh->db_rlen + 1);
	*t_cp++ = VALID_RECORD;

	dbf = dbh->db_fields;
	for (cur_f = dbf; cur_f < &dbf[nfields]; cur_f++, argv++) {
		sprintf(t_cp, cur_f->db_format, *argv);
		t_cp += cur_f->db_flen;
	}
	dbh->db_records++;
	if ( put_dbf_record(dbh, dbh->db_records, cp) < 0 ) {
		fprintf(stderr, "unable to put record at %d\n",
				dbh->db_records);
	}
	if (cp = db_cur_date(NULL)) {
		strncpy(dbh->db_date, cp, 8);
	}
	put_dbf_info(dbh);
}
