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

#define NX 1000
#define NY 1000
#define N 10000000
#define SCALE (NX / 4)

int main(int argc,char **argv)
{
   int i,ix,iy;
   double x=0.5,y=0.75,r=2,r0,w;
   double xmin=1e32,ymin=1e32,xmax=-1e32,ymax=-1e32;
   BITMAP *image,white={255,255,255,0},black={0,0,0,0};
   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);
   srand48((int)time(NULL));

   for (i=0;i<N;i++) {
      r0 = sqrt(x*x+y*y);
      switch ((int)(drand48()*4)) {
      case 0:
         w = atan2(y,x-1);
         y = -r0 * cos(w) / r + 1;
         x = -r0 * sin(w) / r;
         break;
      case 1:
         w = atan2(y-SQRT3/2,x+0.5);
         y = -r0 * cos(w) / r - 0.5;
         x = -r0 * sin(w) / r + SQRT3/2;
         break;
      case 2:
         w = atan2(y+SQRT3/2,x+0.5);
         y = -r0 * cos(w) / r - 0.5;
         x = -r0 * sin(w) / r - SQRT3/2;
         break;
      case 3:
         w = atan2(y,x);
         y = -r0 * cos(w) / r;
         x = -r0 * sin(w) / r;
         break;
      }
      xmin = MIN(x,xmin);
      ymin = MIN(y,ymin);
      xmax = MAX(x,xmax);
      ymax = MAX(y,ymax);
      if ((i % (N/100)) == 0)
         fprintf(stderr,"%d (%g,%g) -> (%g,%g)\n",i,xmin,ymin,xmax,ymax);
      if (i < 100)
         continue;
      ix = x * SCALE + NX/2;
      iy = y * SCALE + NY/2;
      DrawPixel(image,NX,NY,ix,iy,black);
   }

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

