#!/usr/bin/perl

use Tk;                       # Tk-specific initializations

use constant SIZE => 100;
use constant LEFT => -2;
use constant RIGHT => 0.5; # was 1
use constant TOP => 1.25;  # was 1
use constant BOTTOM => -1.25; # was -1
use constant ITERATIONS => 20;

my $top = new MainWindow;
$top->title('Mandelbrot Set');
my $drawarea = $top->Frame();
$drawarea->pack(-side => 'top', -fill => 'both');
my $canvas = $drawarea->Canvas(-relief => 'ridge', -width => SIZE,
        -height => SIZE, -borderwidth => 4);
$canvas->pack(-side => 'left');

use Math::Complex;

# For each pixel, calculate color and plot.
for ($y = 0; $y < SIZE; $y++) {
    for ($x = 0; $x < SIZE; $x++) {

        $z = Math::Complex->make(0, 0);
        $c = Math::Complex->make(LEFT + $x * (RIGHT - LEFT) / SIZE,
                                 TOP  + $y * (BOTTOM - TOP) / SIZE);
        $norm = (abs $z) ** 2;

        for ($count = 0;
             $norm <= 4.0 && $count < ITERATIONS;
             $count++) {
            $z = Math::Complex->make($z->Re * $z->Re -
                                     $z->Im * $z->Im + $c->Re,
                                     $z->Im * $z->Re * 2 + $c->Im);
            $norm = (abs $z) ** 2;
        }
        if ($norm <= .05) {
            $canvas->create('text', $x, $y, -fill => 'black', -text => '.');
        } elsif ($norm <= .10) {
            $canvas->create('text', $x, $y, -fill => 'green', -text => '.');
        } elsif ($norm <= .15) {
            $canvas->create('text', $x, $y, -fill => 'blue', -text => '.');
        } elsif ($norm <= .20) {
            $canvas->create('text', $x, $y, -fill => 'red', -text => '.');
        } elsif ($norm <= .25) {
            $canvas->create('text', $x, $y, -fill => 'yellow', -text => '.');
        } elsif ($norm <= .3) {
            $canvas->create('text', $x, $y, -fill => 'gray', -text => '.');
        }
    }
}

MainLoop;
