//Dan Mayer danmanwointernet@excite.com
//Fractal.cxx
//Gillet Ian Bratt
//1:00
//Creates a drawing based on math

#include <iostream.h>
#include <stdlib.h>
#include <winbgim.h>

const int    LIMIT              = 15;   // Maximum jumps allowed
const int    PIXEL_SIZE         = 401;  // Width & height of screen in pixels 
const double CARTESIAN_MAX      = 2.0;  // Maximum Cartesian coordinate value


double cartesian(int pixel);
// Function to convert a pixel value (in the range from 0 to PIXEL_SIZE-1)
// to its corresponding Cartesian value (in the range from
// -1*CARTESIAN_MAX to CARTESIAN_MAX).

double distance_from_origin(double x, double y);
//checks if distance is
//greater than 2.0

int    escape_time(double x, double y);
//finds the escape time by doing all the jumps

int main (void)
{
    int x=0,y=0;
    initwindow(PIXEL_SIZE, PIXEL_SIZE);    //opens graph
    do    //do while loop to go throught every y value
    {
	x=0;
	do        //do while to go through every x value
	{
	    putpixel(x,y,(escape_time((cartesian(x)),(cartesian(y)))));  //converts values to right graph and tests them
	    x++;   //ups x value
	}while(x<PIXEL_SIZE);
	y++;       //ups y value
	
    }while(y<PIXEL_SIZE);   //ends both loops
    getch();   //lets you see the graph
}


double cartesian(int pixel)         //convert to standard graph
{
    double cartesiansize;
    if(pixel<((PIXEL_SIZE-1)/2))
	cartesiansize=-(CARTESIAN_MAX-(double(pixel)/100));   //for the negative part
    if(pixel==((PIXEL_SIZE-1)/2))
	cartesiansize=0.0;   //for the special case 0
    if(pixel>((PIXEL_SIZE-1)/2))
	cartesiansize=((double(pixel)-((PIXEL_SIZE-1)/2))/100);    //for the positive part of graph
    return cartesiansize;
}


double distance_from_origin(double x, double y)
{
    if( ((x*x)+(y*y))!= 0)               //makes sure it doesnt crash with 0
	return sqrt((x*x)+(y*y));
    else
	return 0.0;                     //returns 0 if distants is 0
}

int    escape_time(double x, double y)              //finds escape time
{
    double moving_x, moving_y,old_moving_x, old_moving_y;
    int jump=0,d;                                             //initiallize variables
    moving_x=x;
    moving_y=y;                               
    
    if((distance_from_origin(moving_x,moving_y))<2.0)  //makes sure if if is already 2.0 distance to stay at 0
    {
	do                  //does math until distance greater than 2
	{
	    old_moving_x=moving_x;
	    old_moving_y=moving_y;
	    moving_x = (((old_moving_x)*(old_moving_x)) - ((old_moving_y)*(old_moving_y)) + x); 
	    moving_y = (2 * (old_moving_x) * (old_moving_y) + y);      //do while that does the math
	    jump++;
	}while(((distance_from_origin(moving_x,moving_y))<CARTESIAN_MAX) && (jump != LIMIT));
    }
    return jump;
}
