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

#ifndef CHAR_BIT
# define CHAR_BIT 8
#endif

BOOL write_int_2(FILE *fp, int i)
{
 C int maxpos = ~(~0 << (2*CHAR_BIT-1));
 C int maxneg = ~0 << (2*CHAR_BIT-1);
 if(i > maxpos)
	i = maxpos;
 if(i < maxneg)
	i = maxneg;
 C UCHAR c0 = i&~(~0<<CHAR_BIT);
 C UCHAR c1 = (i>>CHAR_BIT)&~(~0<<CHAR_BIT);

 return putc(c0, fp)!=EOF && putc(c1, fp)!=EOF;
}

BOOL write_long_4(FILE *fp, long i)
{
 UCHAR c[4];
 C unsigned byte = ~(~0<<CHAR_BIT);
 assert(sizeof(long)==4);
 c[0] = (UCHAR)(i&byte);
 i >>= CHAR_BIT;
 c[1] = (UCHAR)(i&byte);
 i >>= CHAR_BIT;
 c[2] = (UCHAR)(i&byte);
 i >>= CHAR_BIT;
 c[3] = (UCHAR)(i&byte);
 return fwrite((char *)c, 1, 4, fp)==4;
}

BOOL write_char_1(FILE *fp, char c)
{
 assert(sizeof(char)==1);
 return putc(c, fp) != EOF;
}

#ifndef write_schar_1

BOOL write_schar_1(FILE *fp, SCHAR c)
{
 return putc(c, fp) != EOF;
}

#endif

BOOL write_uchar_1(FILE *fp, UCHAR c)
{
 return putc(c, fp) != EOF;
}

#ifndef write_schars

BOOL write_schars(FILE *fp, int n, C SCHAR *p)
{
 return fwrite((C char *)p, 1, n, fp) == n;
}
#endif

BOOL write_uchars(FILE *fp, int n, C UCHAR *p)
{
 return fwrite((C char *)p, 1, n, fp) == n;
}

BOOL write_chars(FILE *fp, int n, C char *p)
{
 return fwrite(p, 1, n, fp) == n;
}

BOOL write_charstring(FILE *fp, int n, C char *p)
{
 C int pl = strlen(p);
 int nn = pl<n ? pl : n;
 BOOL ok = fwrite(p, 1, nn, fp)==nn;
 while(ok && nn++<n)
	ok = ok && putc('\0', fp)!=EOF;
 return ok;
}

struct sb	{UCHAR c[2];};

#define WS2BS	1024
BOOL write_shorts_2(FILE *fp, int n, C short *p)
{
 C LOCAL struct sb test = {02, 01};
 C short *ts = (C short *)&test;

 if(*ts == 01*(1<<CHAR_BIT)+02)
 	return fwrite((C char *)p, 2, n, fp)==n;

 assert(*ts == 02*(1<<CHAR_BIT) + 01);

 {
  BOOL Ok = TRUE;
  struct sb buf[WS2BS];
  C struct sb *q = (C struct sb *)p;
  assert(sizeof(struct sb)==sizeof(short));
  while(n > 0)	{
	C int il=(n>WS2BS ? WS2BS : n);
	swab((char *)q, (char *)buf, 2*il);
  	Ok = Ok && fwrite((char *)buf, sizeof(short), il, fp)==il;
	n -= il;
	q += il;
	}
 return Ok;
 }
}

BOOL write_TBOOL_1(FILE *fp, TBOOL c)
{
 return putc(c, fp) != EOF;
}

