//Distributed Chaotic Image Renderer
//Copyright 2005 Jack Carrozzo
//jack _at_ crepinc.com
//http://www.crepinc.com

// x' = sin(a * y) - cos(b * x)
// y' = sin(c * x) - cos(d * y)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define PICSIZE_X 600
#define PICSIZE_Y 600
#define DEBUG     0

int Pixels[PICSIZE_X][PICSIZE_Y]; //main pixel vars
unsigned long int iters=0;
double x,y,xp,yp,a,b,c,d;

void zero_Pixels( void ) {

    int i,j;

    for (i=0;i<PICSIZE_X;i++) { //zero the Pixels var
        for (j=0;j<PICSIZE_Y;j++) {
            Pixels[i][j]=0;
        }
    }
}

void get_abcdxy( void ) {

    srand(time(0)*getpid());

    a=(rand()-1120000000); //dont ask
    b=(rand()-1120000000); 
    c=(rand()-1120000000); 
    d=(rand()-1120000000); 
    x=(rand()-1120000000);
    y=(rand()-1120000000);

    if (DEBUG)
        printf("a = %1.30f\nb = %1.30f\nc = %1.30f\nd = %1.30f\n\n",a,b,c,d);

    while (a>5.0 || a<-5.0)  //normalize a,b,c to be 0<var<5
        a=a/10;

    while (b>5.0 || b<-5.0)
        b=b/10;

    while (c>5.0 || c<-5.0)
        c=c/10;

    while (d>5.0 || d<-5.0)
        d=d/10;

    while (x>5.0 || x<-5.0)
        x=x/10;

    while (y>5.0 || y<-5.0)
        y=y/10;

    //if (DEBUG)
    printf("a = %1.30f\nb = %1.30f\nc = %1.30f\nd = %1.30f\n\n",a,b,c,d);

}

void usage( void ) {

    printf("Usage: ./DCIR <iterations>\n");
    exit(1);
}

void print_array( void ) {

    int i,j;

    for (j=0;j<PICSIZE_Y;j++) {
        for (i=0;i<PICSIZE_X;i++) {
            if (DEBUG)
                printf("point: (%d,%d)\n",i,j);
            printf("%d\n",Pixels[i][j]);
        }
    }

}

int main(int argc, char *argv[]) {

    int xpic,ypic,run;

    printf("DCIR v0.1 by Jack Carrozzo, jack {@} crepinc.com\n\n");

    //if (argc!=1) usage();

    zero_Pixels();
    get_abcdxy();

    run=atoi(argv[1]);

    if (DEBUG)
        printf("Running for %d iterations...\n",run);

    for (iters=0;iters<run;iters++) {
        xp=sin(a*y)-cos(b*x);
        yp=sin(c*x)-cos(d*y);

        x=xp;
        y=yp;

        xpic=(int)((xp*(PICSIZE_X/4))+(PICSIZE_X/2));
        ypic=(int)((yp*(PICSIZE_Y/4))+(PICSIZE_Y/2));

        if (DEBUG)
            printf("point++ @ %1.15f,%1.15f  or  (%d,%d)\n",x,y,xpic,ypic);

        if (xpic<=PICSIZE_X && ypic <=PICSIZE_Y && xpic>=0 && ypic >=0) //for segfault protection, shouldnt need
            Pixels[xpic][ypic]++;
    }

    print_array();

    return 0;
}
