/*
 * A file test
 * write chunks of random lengths (constrained to be > 4 in postgres version)
 * read chunks from random positions (constrainted to be == 5 in postgres
 * version) and verify the contents with that originally written.
 */
#ifdef UNIX
#define p_open open
#define p_read read
#define p_write write
#define p_close close
#define p_lseek lseek
#else
#include "tmp/libpq-fs.h"
#endif
#include  <sys/file.h>
#include <stdio.h>

#define max(x,y) ((x) < (y) ? (y) : (x))

void main(argc,argv)
     int argc;       
     char *argv[];
{
    int fd;
    int cnt, total = 0;
    unsigned char buf[128*1024];
    int lastwrite = 0;
    int i;
    int bad = 0;
    int blockboundary = 0;

    PQsetdb(getenv("USER"));
    fd = p_open("a",O_RDWR|O_CREAT);
    printf("%d fd\n",fd);
    srandom(time(0));
    if (fd < 0) {
	printf ("bad open\n");
	exit(1);
    }
    /* write some random bytes, write random lengths */
    for (i = 0; i < sizeof(buf); i++) {
	buf[i] = random()%sizeof(buf);
	if ((random()%4) == 0 && (i-lastwrite+1) >= 1021) {
	    p_write(fd,&buf[lastwrite],i-lastwrite+1);
	    lastwrite = i+1;
	}
    }
    if (i-lastwrite+1 > 0)
      p_write(fd,&buf[lastwrite],max(i-lastwrite+1,10));
#if 0
    p_write(fd,&buf[0],sizeof(buf));
#endif
    /* read some random bytes */
    for (i = 0; i < 500; i++) {
	int loc, n;
	unsigned char tst[5];
	loc = random()%sizeof(buf);
	p_lseek(fd,loc,SEEK_SET);
	if ((loc/1024) != ((loc+5)/1024)) {
	    blockboundary++;
	}
	if ((n = p_read(fd,&tst[0],5)) != 5)
	  printf ("only read %d\n",n);
	{
	    int j, match = 1;
	    for (j = 0; j < 5; j++) {
		if (tst[j] != buf[loc+j]) {
		    match=0;
		    break;
		}
	    }
	    if (!match) {
		printf ("at loc %d, wanted %d, saw %d\n",loc+j,buf[loc+j],
			tst[j]);
		bad++;
	    }
	}
    }
    printf ("%d of 500 bad should be 0.\n",bad);
    printf ("%d block boundaries should be > 0 for a good test\n",
	    blockboundary);
    p_close(fd);
    PQfinish();
}
