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

/*      COMPRESS.C      */
/*	This function will remove all records with a flag
**	byte of 'D' from the data base.  The alternate key
**	files MUST be rebuilt after it finishes.
*/

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

compress(dbname)
char    *dbname;
{
    FILE	*in, *out;
    char	fname[FNSIZE];
    char	tempname[FNSIZE];
    char	rcd[DBSIZE+1];
    
    sprintf(tempname, "%snewdb.$$$", datadir);
    if ((out = fopen(tempname, "w")) == NULL) {
	msg("Unable to create temporary file");
	getout();
    }
    sprintf(fname, "%s%s.db", datadir, dbname);
    if ((in = fopen(fname, "r")) == NULL) {
	unlink(tempname);
	msg("Unable to read DB file");
	getout();
    }
    while (fgets(rcd, DBSIZE, in) != NULL) {
	if (feof(in))
	    break;
	if (*rcd == 'D')        /* record to be deleted */
	    continue;
	if(fputs(rcd, out) == EOF) {
	    unlink(tempname);
	    msg("Unable to write to temporary file");
	    getout();
	}
    }
    fclose(in);
    fclose(out);
    unlink(fname);
    link(tempname, fname);
    unlink(tempname);
}
