#ifndef lint
static char Sccsid[] = "@(#)delete.c	3.2    DeltaDate 12/9/90    ExtrDate 12/9/90";
#endif

/*	DELETE.C		*/
/*	This module is used to find and delete records
**	in the data base matching the selection criteria.
**	The user may select multiple values of one field
**	which will be or'd and/or multiple fields which will
**	be and'd. In other words, if field 1 is specified
**	as value1:value2 and field3 is specified as value3.
**	Records with field1==(value1 || value2) && field3==value3
**	will be selected for deletion.
**	It calls findrcds.c to do all the work.
**	It does not actually delete records, the flag(first)
**	field is set to 'D'. To physically delete them, the data
**	base must be compressed.
*/

#include "stdio.h"
#include "ascii.h"
#include "cardfile.h"


static struct Sdata disp_screen[MAXFLDS+1];

extern	int	readonly;
char	*malloc(), *getfield();

delete(fields, dbname)
struct  Fdata   fields[];
char    *dbname;
{
    char	first[SWIDTH];
    struct Fdata *fp;
    struct Sdata *sp;
    int 	processd();
    
    if (readonly) {
	msg("Database is readonly");
	return(1);
    }
    sprintf(first, "Select Records from the %s Data Base to be DELETED",
	dbname);
    for (fp = fields, sp = disp_screen ; fp->F_title[0] != 0; ++fp, ++sp) {
	sp->S_title = fp->F_title;
	sp->S_length = fp->F_length;
	sp->S_result = (char*)malloc((unsigned)fp->F_length+1);
	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;

    findrcds(fields, dbname, processd, first);
    for (sp = disp_screen ; sp->S_title != 0; ++sp) {
	free(sp->S_result);
    }
    return(0);
}


/*ARGSUSED*/
processd(fields, rcd, dbfile, dummy)
struct  Fdata   *fields;
char    *rcd;
FILE    *dbfile;
char	*dummy;
{
    char	c, save[DBSIZE+1];
    struct      Sdata   *sp;
    char	*first = "Record to be DELETED";
    char	*last = "RETURN for next, ESC to abort, CTL-D to DELETE, CTL-B to reverse";
    extern char	lastchar;

    strcpy(save, rcd);
    *strchr(save, '\n') = '\0';          /* truncate \n */
    getfield(save, ":");
    for (sp = disp_screen; sp->S_title != 0; ++sp) {
	sp->S_dfault = getfield(NULL, ":");
    }
    screen(first, disp_screen, last, NULL, TRUE);
    noecho();
    c = lastchar;
    do {
	if (c == LF || c == CR)
	    break;
	if (c == EOT) {		/* CTL-D entered */
	    fseek(dbfile, (long)(-strlen(rcd)), 1);
	    putc('D', dbfile);
	    break;
	}
	if (c == ESC) {
	    echo();
	    return(1);
	}
	if (c == STX) {
	    echo();
	    return(-1);
	}
	rawputchar(BEL);
    } while (c=rawgetchar());
    echo();
    return(0);
}
