#!/usr/bin/perl

use GD::Simple;
use Math::Trig;
use Data::Dumper;
require "../cgi-lib.pl";
ReadParse(*params);

$minx = $params->{minx} || -20;
$maxx = $params->{maxx} || 20;
$miny = $params->{miny} || -20;
$maxy = $params->{maxy} || 20;
$step = $params->{step} || 0.05;

$width = (($maxx-$minx)/$step) + 1;
$height = (($maxy-$miny)/$step) + 1;
$img = GD::Simple->new($width,$height,1);
$img->fill(10,5,color(255,255,255));

$pi = 3.14159;

my($sx,$sy) = (0,0);
for($x=$minx;$x<=$maxx;$x+=$step) {
    $sy = 0;
    for($y=$miny;$y<=$maxy;$y+=$step) {
	$newx = $x*$x - $y*$y;
	$newy = 2*$x*$y;

	if(($x-$newx) == 0) {
	    $angle = $pi / 2;
	} else {
	    $angle = atan(($y-$newy)/($x-$newx));
	}

	$red = int(sin($angle)*127.5 + 127.5);
	$green = int(cos($angle)*127.5 + 127.5);

	$dist1 = sqrt($x**2 + $y**2);
	$dist2 = sqrt(($x-$newx)**2 + ($y-$newy)**2);
	if($dist1 == 0) {
	    $blue = 255;
	} else {
	    $blue = int($dist2 / $dist1);
	}
	if($blue > 255) { $blue = 255; }

	$img->setPixel($sx,$sy,color($red,$green,$blue));
	
	$sy++;
    }
    $sx++;
}

open($F,">","complex_out.png");
print $F $img->png();
close $F;

sub color {
    my($r,$g,$b) = @_;
    if(!defined($pal{"$r\_$g\_$b"})) {
        $pal{"$r\_$g\_$b"} = $img->colorAllocate($r,$g,$b);
    }
    return $pal{"$r\_$g\_$b"};
}
