#include <ToolUtils.h>
#include <Files.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "macbf.h"

/* Add double checking to file functions */
int main(void)
{
	FILE *f;
	char bf[1000];
	char bf2[1000];
	int w;
	int i;
	int r;

	printf("Test fprintf test.txt\n");
	f = fopen("test.txt","w");
	for (i=0; i<1000; i++) {
		fprintf(f,"%d\n",i);
	}
	fclose(f);
	
	
	printf("Test fgets test.txt\n");
	f = fopen("test.txt","r");
	for (i=0; i<2000; i++) {
		if (fgets(bf,100,f)==NULL) break;
		if (atoi(bf)!=i) goto failed;
	}
	printf("Last text line read %d %d\n",i,feof(f));
	fclose(f);


	printf("Test writing 5000 7 byte records to test.dat\n");
	f = fopen("test.dat","wb");
	for (i=0; i<5000; i++) {
		sprintf(bf,"%7d",i);
		if (fwrite(bf,1,7,f)!=7) goto failed;
	}
	fclose(f);

	printf("Test reading 5000 7 byte records to test.dat\n");
	f = fopen("test.dat","rb");
	for (i=0; i<5000; i++) {
		if (fread(bf,1,7,f)!=7) goto failed;
		sprintf(bf2,"%7d",i);
		if (strcmp(bf2,bf)!=0) {printf("Match failed (%s) (%s) \n",bf2,bf); goto failed; }
	}
	fclose(f);

	printf("Test mixed reading and writing\n");
	f = fopen("test.dat","r+");
	for (i=0; i<25000; i++) {
		w = (i * 15 % 5000)/7;
		fseek(f,w*7,SEEK_SET);
		/* Check it was ok */
		if (fread(bf,1,7,f)!=7) goto failed;
		sprintf(bf2,"%7d",w);
		if (strcmp(bf2,bf)!=0) {printf("Match failed (%s) (%s) \n",bf2,bf); goto failed; }

		/* Write it again  */
		fseek(f,w*7,SEEK_SET);
		if (fwrite(bf,1,7,f)!=7) goto failed;
		sprintf(bf2,"%7d",w);
		if (strcmp(bf2,bf)!=0) {printf("Match failed (%s) (%s) \n",bf2,bf); goto failed; }
	}
	fclose(f);

	
	printf("check that file test.dat\n");
	f = fopen("test.dat","rb");
	for (i=0; i<6000 ; i++) {
		r = fread(bf,1,7,f);
		if (feof(f)) { printf("End of file at %d\n",i); break;}
		if (r!=7) {printf("read failed record %d\n",i,r ); goto failed;}
		sprintf(bf2,"%7d",i);
		if (strcmp(bf2,bf)!=0) {printf("Match failed (%s) (%s) \n",bf2,bf); goto failed; }
	}
	fclose(f);
	
	printf("Finished\n");
	return 0;
failed:
	printf("PANIC, SOMETHING FAILED\n");\
	return 0;
}
