#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include <sys/types.h>
#include <time.h>
#include "paulslib.h"
#include "bitmaplib.h"

#define NX 2000
#define NY 2000
#define N 10000000
#define SCALE (NX / 2)

int main(int argc,char **argv)
{
	int i,m,n,ix,iy;
	double c;
	double x=0,y=0,x1,y1;
	double xmin=1e32,ymin=1e32,xmax=-1e32,ymax=-1e32;
	BITMAP *image,white={255,255,255},black={0,0,0};
	BITMAP colour;
	char fname[64];
	FILE *fptr;

	if (argc < 1) {
		fprintf(stderr,"Usage: %s \n",argv[0]);
		exit(-1);
	}

	/* Create the image */
	image = CreateBitmap(NX,NY);
	EraseBitmap(image,NX,NY,white);
	srand(time(NULL));

	for (n=0;n<N;n++) {
		c = drand48();
		if (c < 1/3.0) {
			x1 = (x + y / sqrt(3.0)) / 2;
			y1 = (x / sqrt(3.0) - y) / 2;
		} else if (c < 2/3.0) {
			x1 = (x - y / sqrt(3.0)) / 2 + 1 / 2.0;
			y1 = (-x / sqrt(3.0) - y) / 2 + 1 / (2 * sqrt(3.0));
		} else {
			x1 = (x + y / sqrt(3.0)) / 2 + 1;
			y1 = - (x / sqrt(3.0) - y) / 2;
		}
		x = x1;
		y = y1;
		xmin = MIN(x,xmin);
		ymin = MIN(y,ymin);
		xmax = MAX(x,xmax);
		ymax = MAX(y,ymax);
      if ((n % (N/100)) == 0)
         fprintf(stderr,"%d (%g,%g) - (%g,%g)\n",n,xmin,ymin,xmax,ymax);
		if (n < 100)
			continue;
		ix = x * SCALE + NX/20;
		iy = y * SCALE + NY/2;
      DrawPixel(image,NX,NY,ix,iy,black);
	}

	/* Write the image to a ppm file */
	sprintf(fname,"roger10.tiff");
	if ((fptr = fopen(fname,"w")) == NULL) {
		fprintf(stderr,"Unable to open bitmap file\n");
		exit(0);
	}
	WriteBitmap(fptr,image,NX,NY,5);
	fclose(fptr);
	DestroyBitmap(image);
}

#include "bitmaplib.c"
#include "paulslib.c"
