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

/*      DUMPDB.C        */
/*      This subroutine is used to dump all records from
        the data base and the alternate key files, including
        deleted records.
*/

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

static	FILE	*in, *out;
static	int	quit = 0;
static	SIGRTN	abort();
static	SIGRTN	(*old_sig)();

dumpdb(dbname, ak_data, fields)
char    *dbname;
struct  AKdata  *ak_data;
struct  Fdata   *fields;
{
    char        ptitle[PWIDTH+1];
    int         pnum, lnum;
    char        fname[FNSIZE];
    char        rcd[DBSIZE+1];
    
    if ((out = popen("lp", "w")) == NULL) {
        msg("Unable to open printer");
        return(1);
    }
    sprintf(fname, "%s%s.db", datadir, dbname);
    if ((in = fopen(fname, "r")) == NULL) {
	pclose(out);
        msg("Unable to open DB file");
        return(1);
    }
    /* msg() will leave the cursor at the bottom */
    msg("");
    fputs("DEL to abort dump", stdout);
    old_sig = signal(SIGINT, abort);
    lnum = PLENGTH + 1;                 /* force top-of-page */
    pnum = 1;
    sprintf(ptitle, "Records in %s.db", dbname);
    while( !quit && (fgets(rcd, DBSIZE, in)) != NULL) {   /* print DB file */
        rcd[strlen(rcd)-1] = '\0';      /* truncate \n */
        if (lnum + 3 + (strlen(rcd)+PWIDTH-1)/PWIDTH >= PLENGTH) {
            newpage(&pnum, ptitle);
            lnum = 3;
        }
        fputs(rcd, out);
        putc('\n', out);
        lnum += (strlen(rcd)+PWIDTH-1)/PWIDTH;
    }
    if (quit)
	return(1);
    fclose(in);
    while (ak_data->A_fldnum >= 0) {
	strcpy(fname, datadir);
        strcat(fname, ak_data->A_akname);
        if ((in = fopen(fname, "r")) == NULL) {
            sprintf(ptitle, "Unable to open %s", fname);
            msg(ptitle);
            return(1);
        }
        lnum = PLENGTH + 1;
        pnum = 1;
        sprintf(ptitle, "Records in %s sorted on %s",
            fname, fields[ak_data->A_fldnum].F_title);
	/* print AK file */
        while( !quit && (fgets(rcd, DBSIZE, in)) != NULL) {
            rcd[strlen(rcd)-1] = '\0';  /* truncate \n */
            if (lnum + 3 + (strlen(rcd)+PWIDTH-1)/PWIDTH >= PLENGTH) {
                newpage(&pnum, ptitle);
                lnum = 3;
            }
            fputs(rcd, out);
            putc('\n', out);
            lnum += (strlen(rcd)+PWIDTH-1)/PWIDTH;
        }
	if (quit)
	    return(1);
        fclose(in);
        ++ak_data;
    }
    pclose(out);
    signal(SIGINT, old_sig);
    return(0);
}

newpage(pnum, title)
int     *pnum;
char    *title;
{

    putc(FF, out);
    fprintf(out, "%-69sPAGE %4d\n\n\n", title, *pnum);
    *pnum += 1;
}


static SIGRTN
abort()
{

    signal(SIGINT, old_sig);
    fputs("\n\nOUTPUT ABORTED!\n", out);
    pclose(out);
    fclose(in);
    msg("Dump aborted");
    quit = 1;
}
