/*******************************************************************
*  Amish's I/O package for Type 1 font reading
********************************************************************/

#ifndef T1GST
#include "global.h"
#endif


extern void freefont(char *fbuf);
extern int readfont(char *filename, char **pfbuf, int *pfbuflen);


/* Open the file */
F_FILE *T1Open(char *fn, char *mode)
{
	F_FILE *of;

	if (of = (F_FILE *)xalloc(sizeof(F_FILE)))
	{
		if (readfont(fn, &(of->fbuf), &(of->fbuflen)) >= 0)
		{
			of->curpos = 0;
			return of;
		}

		xfree(of);
		of = NULL;
	}

	return of;
}


/* Read one character */
int T1Getc(F_FILE *f)
{
	if (f->fbuf == NULL)
		return EOF;			/* already closed */

	if (f->curpos == f->fbuflen)
		return EOF;

	return (f->fbuf)[(f->curpos)++];
}


/* Put back one character */
int T1Ungetc(int c, F_FILE *f)
{
	if (f && (c != EOF))
	{
		if (f->curpos > 0)
			(f->curpos)--;
	}

	return c;
}


/* Read n items into caller's buffer */
int T1Read(char *buffP, int size, int n, F_FILE *f)
{
	int acnt, rcnt;

	/* Number of bytes requested */
	rcnt = n * size;

	/* Number of bytes available */
	acnt = f->fbuflen - f->curpos;

	if (rcnt <= acnt)
	{
		memcpy((void *)buffP, (void *)(f->fbuf + f->curpos), rcnt);
		(f->curpos) += rcnt;
		return rcnt;
	}
	else
	{
		memcpy((void *)buffP, (void *)(f->fbuf + f->curpos), acnt);
		(f->curpos) = f->fbuflen;
		return acnt;
	}
}


/* Close the file */
int T1Close(F_FILE *f)
{
	if (f)
	{
		freefont(f->fbuf);
		xfree(f);
	}

	return 1;
}


/**
 * I commented out the following C version of T1eexec() because I have now
 * implemented it in assembly...
 **/

/* Eexec Decryption */
//F_FILE *T1eexec(F_FILE *f)
//{
//	int i, c;
//	unsigned char ch;
//	unsigned char randomP[4];
//	unsigned short r;
//	int pos;
//	static unsigned short c1 = 52845;
//	static unsigned short c2 = 22719;
//
//	/**
//	 * Get and initialize the key
//	 **/
//	randomP[0] = (f->fbuf)[(f->curpos)++];
//	randomP[1] = (f->fbuf)[(f->curpos)++];
//	randomP[2] = (f->fbuf)[(f->curpos)++];
//	randomP[3] = (f->fbuf)[(f->curpos)++];
//	r = 55665;
//	for (i=0; i < 4; i++)
//		r = (randomP[i] + r) * c1 + c2;
//
//	/**
//	 * Store the current file position
//	 **/
//	pos = f->curpos;
//
//	/**
//	 * Decrypt the rest of the file.  NOTE: ascii is not supported at this time
//	 **/
//	while (pos != f->fbuflen)
//	{
//		c = (f->fbuf)[pos];
//		ch = c ^ (r >> 8);
//		r = (c + r) * c1 + c2;
//		(f->fbuf)[pos++] = ch;
//	}
//
//	return f;
//}

