#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 x=0.5,y=0.5,x1,y1,r,denom;
   BITMAP *image,white={255,255,255,0},black={0,0,0,0};
   BITMAP c[6] = {255,0,0,0,     0,255,0,0,     0,0,255,0,
                  255,255,0,0,   255,0,255,0,   0,255,255,0};
   BITMAP colour;
   FILE *fptr;

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

   r = 1 / (1 + SQRT2);
   for (n=0;n<N;n++) {
      denom = x*x + y*y;
      m = rand() % 6;
      switch (m) {
      case 0:
         x1 = 2 * x * y / denom;
         y1 = (x*x - y*y) / denom;
         break;
      case 1:
         x1 = x * r - r;
         y1 = y * r - r;
         break;
      case 2:
         x1 = x * r + r;
         y1 = y * r + rek;
      case 3:
         x1 = x * r + r;
         y1 = y * r - r;
         break;
      case 4:
         x1 = x * r - r;
         y1 = y * r + r;
         break;
      case 5:
         x1 = (x*x - y*y) / denom;
         y1 = 2 * x * y / denom;
         break;
      }
      x = x1;
      y = y1;
      if (n < 100)
         continue;
      ix = x * SCALE + NX/2;
      iy = y * SCALE + NY/2;
      DrawPixel(image,NX,NY,ix,iy,c[m]);
   }

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

