/* checksum.c
 * ----------
 * Provides a function for reading the checksum of a tfm- and a pk-file.
 * (Derived from Nelson Beebe's dviXXX driver family.)
 */

#include <stdio.h>
#include "checksum.h"

#ifdef AMIGA
char *	index();
char *	strcmp();
#else
#include <string.h>
#endif

static unsigned long
nosignex(fp, n)	/* return n byte quantity from file fd */
FILE *fp;	/* file pointer    */
int n;	/* number of bytes (1..4) */
{
    unsigned long number;	/* number being constructed */

    number = 0;
    while (n--)
    {
	number <<= 8;
	number |= getc(fp);
    }
    return(number);
}

#define warning(msg) fprintf(stderr, msg)
#define PKPRE  247
#define PKID 89 

/* readfile() returns (iff succesfull) the checksum of a tfm-file
 * or a pk-file. Other TeXfiles (gf and pxl) are not supported.
 */
 
int
readfile(name, checksum)	/* return 0 on success, otherwise errorcode */
char *name; unsigned long *checksum;
{
    FILE *fontfp; char * ext;

    if (strcmp(name+strlen(name)-4, ".tfm") ==0) {
        if ((fontfp= fopen(name, "r")) == NULL) {
	    return NOFILE;
        }        
    	
        if (fseek(fontfp, 24L, 0))
        {
	    fclose(fontfp);
	    return WRONGTFMFILE;
        }
        *checksum = nosignex(fontfp,4);	/* checksum */
        fclose(fontfp);
        return NOERROR;
    }

    if (strcmp(name+strlen(name)-2, "pk") ==0)
    {	
        if ((fontfp= fopen(name, "r")) == NULL) {
	    return NOFILE;
        }        
    	
        if (((int)nosignex(fontfp,1) != PKPRE) ||
            ((int)nosignex(fontfp,1) != PKID)  ||
    	    (fseek(fontfp,(long)nosignex(fontfp,1)+4L,1)))
    	{ 
	        fclose(fontfp);
	        return WRONGPKFILE;
        }

    	*checksum = nosignex(fontfp,4);	/* checksum */
    	fclose(fontfp);
    	return NOERROR;
    }        
    return NOTFMORPK;

}
