/* Julia set z^2+c; Postscript image  (ice) */
/* Reinvented by EH, 24 March 1994 */
/* 3-coloring by simple "lightning" method */

#include "cx.h"
#include <stdio.h>
#include <stdlib.h>

/* Defaults */
/*Maximum number of iterations*/
#define ITERLIM 200  

/* Center and radius of image */
#define CENTER {0.0,0.0}
#define RADIUS 1.6

/* Value of C */
#define C {0.377771,0.311349}

/* Lightning radius */
#define LIGHTRAD 2.0
#define LIGHTMULT 0.2

/* Coloring */
#define COLOR 0
#define GRAY 1
#define CMAP GRAY
static int cmap = CMAP;

static int iterlim=ITERLIM;
static double lightrad = LIGHTRAD;
static double lightmult = LIGHTMULT;
static complex c = C;

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

{
	int i,n;

	static complex center = CENTER;
	static double radius = RADIUS;
	int color();
	int idim, jdim;

	for(i=1; i<argc; i++)
	{	if(argv[i][0] != '-') usage();
		switch(argv[i][1])
	{
		case 'c':
		if(argc <= (i+2)) usage();
		sscanf(argv[++i],"%lf",&center.x);
		sscanf(argv[++i],"%lf",&center.y);
		break;

		case 'C':
		if(argc <= (i+2)) usage();
		sscanf(argv[++i],"%lf",&c.x);
		sscanf(argv[++i],"%lf",&c.y);
		break;

		case 'd':
		if(argc <= (i+2)) usage();
		sscanf(argv[++i],"%d",&idim);
		sscanf(argv[++i],"%d",&jdim);
		scan_dim(idim,jdim);
		break;

		case 'h':
		cmap = COLOR;
		break;

		case 'i':
		if(argc <= (i+1)) usage();
		sscanf(argv[++i],"%d",&iterlim);
		break;

		case 'l':
		if(argc <= (i+1)) usage();
		sscanf(argv[++i],"%lf",&lightrad);
		break;

		case 'm':
		if(argc <= (i+1)) usage();
		sscanf(argv[++i],"%lf",&lightmult);
		break;

		case 'r':
		if(argc <= (i+1)) usage();
		sscanf(argv[++i],"%lf",&radius);
		break;

		default:
		usage();
	}
	}
	scan_window(center,radius);
	if(cmap==GRAY)
	{	scan_gray(0,1.0);
		scan_gray(1,0.0);
		scan_gray(2,0.0);
		scan_gray(3,1.0);
	}
	if(cmap==COLOR)
	{	scan_rgb(0,255,255,0);
		scan_rgb(1,255,0,0);
		scan_rgb(2,0,0,255);
		scan_rgb(3,0,0,0);
	}
	scan(color);
	scan_end(argc,argv);
}

usage()
{
	fprintf(stderr,"Usage:  julia [options]\n");
	fprintf(stderr,"  -c [center of window]\n");
	fprintf(stderr,"  -d [n m] nxm raster\n");
	fprintf(stderr,"  -h hued (color) image\n");
	fprintf(stderr,"  -i [iteration limit]\n");
	fprintf(stderr,"  -l [light radius]\n");
	fprintf(stderr,"  -m [light multiple]\n");
	fprintf(stderr,"  -r [radius of window]\n");
	fprintf(stderr,"Raster file is written to stdout.\n");
	exit(1);
}

/* Color according to escape quadrant from a square of */
/* radius lightrad */

color(z)
	complex z;
{
	double rx, ry;
	int i;

	for(i=1; i<iterlim; i++)
	{	rx = (z.x > 0) ? z.x : -z.x;
		ry = (z.y > 0) ? z.y : -z.y;
		if(rx > lightrad || ry > lightrad)
		{	if(rx > lightrad+lightmult*ry*ry) return(1);
			if(ry > lightrad+lightmult*rx*rx) return(2);
			else return (3);
		}
		z = add(mult(z,z),c); 
	}
	return(0);
}
