#include <stdio.h>
#include <assert.h>
#include <readwrite.h>
#include <stdlib.h>

#ifndef CHAR_BIT
# define CHAR_BIT 8
#endif

#define D	if(0)

BOOL read_short_2(FILE *fp, short *p)
{
 UCHAR c[2];
 BOOL ok = fread((char *)c, 1, 2, fp)==2;
 assert(p);
 if(ok)
	*p= (short)(c[0]) | (((SCHAR)c[1])<<CHAR_BIT);
return ok;
}

BOOL read_int_2(FILE *fp, int *p)
{
 UCHAR c[2];
 BOOL ok = fread((char *)c, 1, 2, fp)==2;
 assert(p);
 assert(ok);
 if(ok)
	*p = (unsigned)c[0] | ((int)(SCHAR)c[1]<<CHAR_BIT);
 return ok;
}

BOOL read_long_4(FILE *fp, long *p)
{
 UCHAR c[4];
 BOOL ok = fread((char *)c, 1, 4, fp)==4;
 assert(p);
 if(ok)	{
	*p = (int)(SCHAR)c[3];
	*p = (*p<<CHAR_BIT) | (unsigned)c[2];
	*p = (*p<<CHAR_BIT) | (unsigned)c[1];
	*p = (*p<<CHAR_BIT) | (unsigned)c[0];
 	}
 return ok;
}

BOOL read_TBOOL_1(FILE *fp, TBOOL *p)
{
 char tmp;
 if(fread(&tmp, 1, 1, fp) == 1)	{
 	*p = tmp;
	return TRUE;
	}
 return FALSE;
}

BOOL read_char_1(FILE *fp, char *p)
{
 C int c = getc(fp);

 if(c != EOF)	{
 	*p = c;
	return TRUE;
	}
 return FALSE;
}

BOOL read_uchar_1(FILE *fp, UCHAR *p)
{
 C int c = getc(fp);

 if(c != EOF)	{
 	*p = c;
	return TRUE;
	}
 return FALSE;
}

#ifndef read_schar_1

BOOL read_schar_1(FILE *fp, SCHAR *p)
{
 C int c = getc(fp);

 if(c != EOF)	{
 	*p = c;
	return TRUE;
	}
 return FALSE;
}
#endif

BOOL read_chars(FILE *fp, int n, char *p)
{
 return fread(p, 1, n, fp) == n;
}

#ifndef read_schars

BOOL read_schars(FILE *fp, int n, SCHAR *p)
{
 return fread(p, 1, n, fp) == n;
}
#endif

union u_sbs	{
	UCHAR c[2];
	short sh;
	};

#define WS2BS	1024
BOOL read_shorts_2(FILE *fp, int n, short *p)
{
 D fprintf(stderr, "Entering read_shorts_2\n");
 {
 union u_sbs test2;
 test2.c[0] = 02;
 test2.c[1] = 01;

 if(test2.sh == 01*256+02)	{
	D fprintf(stderr, "reading %d shorts into p at %p\n", n, p);
 	return fread((char *)p, 2, n, fp)==n;
	}
 assert(test2.sh == 02*256 + 01);
 }


 {
  BOOL Ok = TRUE;
  short buf[WS2BS];
  char *q = (char *)p;
  assert(2 == sizeof(short));
  while(n > 0)	{
	C int il=(n>WS2BS ? WS2BS : n);
	D fprintf(stderr, "reading %d shorts into buf at %p\n", il, buf);
  	Ok = Ok && fread((char *)buf, sizeof(short), il, fp)==il;
	D fprintf(stderr, "swab %d bytes from %p to %p\n", il*sizeof(short),
					buf, q);
	swab((char*)buf, q, sizeof(short)*il);
	n -= il;
	q += il*sizeof(short);
	}
 return Ok;
 }
}
