/* zzpk.m,
 *
 * Emulates some PACKFILE functions for ZZIP_FILEs.
 */

#ifndef NO_ZZIP

#include <assert.h>
#include <stdio.h>
#include "zzpk.h"


/* zzpk_getc:
 *  Read a byte from a file, returning EOF if the end of file was reached.
 */
int zzpk_getc(ZZIP_FILE *f)
{
   unsigned char c;

   if (zzip_fread(&c, sizeof(c), 1, f) == 1)
      return c;
   else
      return EOF;
}

/* zzpk_ungetc:
 *  Unread a byte from a file.
 */
int zzpk_ungetc(int c, ZZIP_FILE *f)
{
    zzip_seek(f, -1, SEEK_CUR);
    return c;
}

/* zzpk_igetw:
 *  Reads a 16 bit word from a file, using intel byte ordering.
 */
int zzpk_igetw(ZZIP_FILE *f)
{
   int b1, b2;
   assert(f);

   if ((b1 = zzpk_getc(f)) != EOF)
      if ((b2 = zzpk_getc(f)) != EOF)
	 return ((b2 << 8) | b1);

   return EOF;
}

/* zzpk_igetl:
 *  Reads a 32 bit long from a file, using intel byte ordering.
 */
long zzpk_igetl(ZZIP_FILE *f)
{
   int b1, b2, b3, b4;
   assert(f);

   if ((b1 = zzpk_getc(f)) != EOF)
      if ((b2 = zzpk_getc(f)) != EOF)
	 if ((b3 = zzpk_getc(f)) != EOF)
	    if ((b4 = zzpk_getc(f)) != EOF)
	       return (((long)b4 << 24) | ((long)b3 << 16) |
		       ((long)b2 << 8) | (long)b1);

   return EOF;
}

/* zzpk_fread:
 *  Reads n bytes from f and stores them at memory location p. Returns the 
 *  number of items read, which will be less than n if EOF is reached or an 
 *  error occurs. Error codes are stored in errno.
 */
long zzpk_fread(void *p, long n, ZZIP_FILE *f)
{
   return zzip_fread(p, 1, n, f);
}

#endif
