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

/*	RBUILDAK.C      */
/*	This module will rebuild the alternate key files.
**	It requires only the DEF and DB files. It must be
**	used after a compress, if the DB file has been edited,
**	or if the DEF file is changed affecting the key fields.
*/
#include "stdio.h"
#include "cardfile.h"

rbuildak(dbname, ak_data, fields)
char    *dbname;
struct  AKdata  *ak_data;
struct  Fdata   *fields;
{
    FILE	*dbfile, *akfile;
    char	fname[FNSIZE], rec[DBSIZE];
    long	offset, ftell();
    char	*buffer, *malloc();
    
    while (ak_data->A_fldnum >= 0) {
	sprintf(fname, "%s%s", datadir, ak_data->A_akname);
	if ((akfile=fopen(fname, "w")) == NULL) {;   /* truncate file */
	    msg("Unable to write the database");
	    getout();
	}
	fclose(akfile);
	++ak_data;
    }
    sprintf(fname, "%s%s.db", datadir, dbname);
    dbfile = fopen(fname, "r");
    buffer = malloc(BUFSIZE);
    if (buffer == NULL) {
	msg("Unable to allocate buffer space");
	getout();
    }
    *buffer = '\0';
    while ((offset = ftell(dbfile)) >= 0L &&
	fgets(rec, DBSIZE, dbfile) != NULL) {
	if (feof(dbfile))
	    break;
	rec[strlen(rec)-1] = '\0';      /* truncate new-line */
	buildak(dbname, strchr(rec,':')+1, offset, fields, buffer);
    }
    fclose(dbfile);
    writeak(dbname, buffer);
    free(buffer);
}
