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

/*	UPDAK.C		*/
/*	These subroutines are used to update the alternate key files
**	after the DB file has been changed.
*/

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

char    *bufend;

buildak(dbname, recd, addr, fp, buffer)
char	*dbname, *recd;
long	addr;
struct	Fdata *fp;
char	*buffer;
{
    char	*fld, *fld2;
    char	temp[AKSIZE];
    char	*getfield();

    if (*buffer == '\0')	/* first time */
	bufend = buffer;
    for ( ; fp->F_title[0] != '\0' ; ++fp) {
	if ((fld = getfield(recd, ":")) == 0)
	    continue;
	recd += strlen(fld) + 1;
	if (fp->F_key != 'N' && *fld != '\0') { /* AK record required */
	    while((fld2 = getfield(fld, fp->F_seps)) != NULL) {
		fld = 0;
		sprintf(temp, "%c:%s:%ld\n", fp->F_key, fld2, addr);
		/* check if buffer full */
		if (bufend+strlen(temp)+1 >= buffer+BUFSIZE) {
		    writeak(dbname, buffer);
		}
		strcpy(bufend, temp);
		bufend += strlen(temp);
	    }
	}
    }
}


writeak(dbname, buffer)		/* sort the lines in buffer then merge */
char    *dbname;		/* them in with the appropriate AK file*/
char    *buffer;
{
    char	*line[400];
    int 	nlines, i;
    char	fnum, akname[FNSIZE];
    FILE	*akfile;
    char	*strchr();
    int		compar();
    void	qsort();

    nlines = 0;
    bufend = buffer;		/* reset end of buffer pointer */
    while(*buffer != '\0') {    /* Build file to be sorted */
	line[nlines++] = buffer;
	buffer = strchr(buffer, '\n') + 1;
	if (buffer == (char*)1)		/* test for missing '\n' */
	    break;
    }
    if (nlines == 0)    /* no records to add */
	return;
    qsort((char*)line, (unsigned)nlines, sizeof(int), compar);
    fnum = ' ';
    for (i=0; i<nlines; ++i) {
	if (*(line[i]) != fnum) {	/* check for same file */
	    if (fnum != ' ') {  /* not first time */
		fclose(akfile);
	    }
	    fnum = *line[i];
	    sprintf(akname, "%s%s.ak%c", datadir, dbname, fnum);
	    if((akfile = fopen(akname, "a+")) == NULL) {
		msg(strcat("Unable to open file ", akname));
		getout();
	    }
	}
	fwrite(line[i]+2, strchr(line[i], '\n')-line[i]-2, 1, akfile);
	putc('\n', akfile);
    }
    fclose(akfile);
}


compar(str1, str2)
char	**str1, **str2;
{
    return(keycmp(*str1, *str2, AKSIZE));
}

keycmp(s1, s2, len)
register char	*s1, *s2;
register int	len;
{

#ifdef BSD_STRING
register char	c1, c2;
    while (1) {
	if (isupper(*s1))
	    c1 = tolower(*s1);
	else
	    c1 = *s1;
	if (isupper(*s2))
	    c2 = tolower(*s2);
	else
	    c2 = *s2;
	if (c1 != c2 || len-- == 0)
	    break;
	if (c1 == '\0')
	    return(0);
	++s1;
	++s2;
    }
    return(c1 - c2);
#else
    while (tolower(*s1) == tolower(*s2) && len--) {
	if (*s1 == '\0')
	    return(0);
	++s1;
	++s2;
    }
    return(tolower(*s1) - tolower(*s2));
#endif
}
