#ifndef lint
static char Sccsid[] = "@(#)add.c	3.1    DeltaDate 8/3/90    ExtrDate 10/6/90";
#endif

/*      ADD.C   */
/*      This subroutine is used to add a new record to the
**	data base. It also requests the updating of the
**	alternate key files.
*/

#include <stdio.h>
#include <errno.h>
#include "ascii.h"
#include "cardfile.h"

long    ftell();
char    *malloc();
extern  int     errno;
extern	int	readonly;

add(fields, dbname)
struct  Fdata   fields[];
char    *dbname;
{
    struct      Fdata   *fp;
    struct      Sdata   add_screen[MAXFLDS+1], *sp;
    int 	err;
    char	first[SWIDTH+1];
    char	out_line[DBSIZE+1];
    FILE	*filep;
    char	filename[FNSIZE];
    long	offset;
    char	*buffer;
    
    if (readonly) {
	msg("Database is readonly");
	return(1);
    }
    sprintf(first, "Add Records to %s Data Base", dbname);
    buffer = malloc(BUFSIZE+1);
    buffer[0] = '\0';
    sprintf(filename, "%s%s.db", datadir, dbname);
    if((filep = fopen(filename, "a")) == NULL) {
	if (errno == EACCES) {
	    strcpy(out_line, "You do not have permission to modify this database");
	} else {
	    sprintf(out_line, "Unable to open %s, errno=%d\n", filename, errno);
	}
	msg(out_line);
	return(1);
    }
    for (fp = fields, sp = add_screen ; fp->F_title[0] != 0; ++fp, ++sp) {
	sp->S_title = fp->F_title;
	sp->S_length = fp->F_length;
	sp->S_result = malloc((unsigned)fp->F_length+1);
	sp->S_dfault = 0;
	sp->S_page = fp->F_page;
	sp->S_Lrow = fp->F_Lrow;
	sp->S_Lcol = fp->F_Lcol;
	sp->S_Drow = fp->F_Drow;
	sp->S_Dcol = fp->F_Dcol;
	sp->S_Dfmt = fp->F_Dfmt;
    }
    sp->S_title = 0;
    while (screen(first, add_screen, 0, 0, FALSE) != 0) {
	out_line[0] = '\0';
	err = 0;
	fp = fields;
	sp = add_screen;
	while (sp->S_title) {
	    if (sp->S_result[0] == '\0' && fp->F_required == 'Y') {
		sprintf(out_line, "Required field %s missing", fp->F_title);
		msg(out_line);
		++err;
	    }
	    if (strchr(sp->S_result, ':')) {
		msg("A ':' is not allowed in any field");
		++err;
	    }
	    if (strlen(out_line) + strlen(sp->S_result) >= DBSIZE) {
		msg("Record too long");
		++err;
		break;
	    }
	    strcat(out_line, sp->S_result);
	    strcat(out_line, ":");
	    ++fp;
	    ++sp;
	}
	if (err)
	    continue;
	out_line[strlen(out_line)-1] = '\0';
	offset = ftell(filep);
	fprintf(filep, " :%s\n", out_line);
	buildak(dbname, out_line, offset, fields, buffer);
    }
    sp = add_screen;
    while (sp->S_title) {
	free(sp->S_result);
	++sp;
    }
    fclose(filep);
    writeak(dbname, buffer);
    free(buffer); 
    return(0);
}
