#include <gpk_std.h>
#include <stdio.h>
#include <readwrite.h>
#include <math.h>
#include <assert.h>

extern "C" int unlink(const char *);



C char f[] = "foo.test";

main()
{
 FILE *fp = fopen(f, "w+");
 C static int spc[] = {0, 32767, 32768, -32767, -32768, -32769, 32766,
							126, 127, 128, 129, 130,
							-126, -127, -128, -129, -130, 1, -1};

 int err = 0;
 int i;
 int ok = 0;
 assert(fp);
 for(i=0;i<10000;i++)	{
	int j = i<sizeof(spc)/sizeof(*spc) ? spc[i] : (int)(40000.*cos(i));
	int k;
	rewind(fp);
    BOOL okw = write_int_2(fp, j);
	fflush(fp);
	if(!okw)	{
		fprintf(stderr, "okw false at i=%d, j=%d\n", i, j);
		err = 1;
		}
	rewind(fp);
	BOOL okr = read_int_2(fp, &k);
	if(!okr)	{
		fprintf(stderr, "okr false at i=%d, j=%d\n", i, j);
		err  = 1;
		}
	fflush(fp);
	if(j!=k && ((k!=32767 && k!=-32767-1) || (j>0)!=(k>0)))	{
		fprintf(stderr, "rw mismatch, j=%d, k=%d\n", j, k);
		err = 1;
		}
	else ok++;
	}

 for(i=0;i<10000;i++)	{
	long j = i<sizeof(spc)/sizeof(*spc) ? spc[i] : (int)(4000000.*cos(i));
	long k;
	rewind(fp);
    BOOL okw = write_long_4(fp, j);
	fflush(fp);
	if(!okw)	{
		fprintf(stderr, "okw false at i=%d, j=%d\n", i, j);
		err = 1;
		}
	rewind(fp);
	BOOL okr = read_long_4(fp, &k);
	if(!okr)	{
		fprintf(stderr, "okr false at i=%d, j=%d\n", i, j);
		err  = 1;
		}
	fflush(fp);
	if(j!=k && ((k!=32767 && k!=-32767-1) || (j>0)!=(k>0)))	{
		fprintf(stderr, "rw mismatch, j=%d, k=%d\n", j, k);
		err = 1;
		}
	else ok++;
	}

 fclose(fp);
 unlink(f);
 printf("OK: %d tests\n", ok);
 return err;
}
