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

/*      FIND.C  	*/
/*      This module is used to find and display 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 displayed.
**	It calls findrcds.c to do all the work.
*/

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

static struct Sdata disp_screen[MAXFLDS+1];

find(fields, dbname)
struct  Fdata   *fields;
char    *dbname;
{
    struct Fdata *fp;
    struct Sdata *sp;
    char	first[SWIDTH];
    int 	display();
    
    sprintf(first, "Display Records from the %s Data Base", 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, display, first);
    for (sp = disp_screen ; sp->S_title != 0; ++sp) {
	free(sp->S_result);
    }
    return(0);
}


/*ARGSUSED*/
display(fields, rcd, dummy1, dummy2)
struct  Fdata   *fields;
char    *rcd;
FILE	*dummy1;
char    *dummy2;
{
    char	c, save[DBSIZE+1];
    FILE	*filep;
    char	*first = "Selected Records";
    char	*last = "RETURN for next, ESC to abort, CTL-P to print, CTL-B to reverse";
    static      char    fmt[256];
    struct      Sdata   *sp;
    char	*getfield();
    extern char	lastchar;
    
    strcpy(save, rcd);
    getfield(rcd, ":");
    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 == DLE) {		/* CTL-P entered */
	    if ((filep=popen("lp", "w")) == NULL) {
		msg("Unable to open printer");
		continue;
	    }
	    strcpy(rcd, save);
	    putrcd(first, rcd, filep, fmt, PWIDTH, 1);
	    pclose(filep);
	    continue;
	}
	if (c == ESC) {
	    echo();
	    return(1);
	}
	if (c == STX) {		/* CTL-B entered */
	    echo();
	    return(-1);
	}
	rawputchar(BEL);
    } while (c=rawgetchar());
    echo();
    return(0);
}
