#!/usr/local/bin/perl

# Testing Discrete Models of Continuous Systems:
# Simple Population Models
#
# Based on Biophys 702 Lecture/Slide Examples
# (C) WCR 20050305.0003


# Modify the following section depending on if you have
# libGD installed for Perl.  set:
# $outputmode = "graph";
# to plot output to a png, otherwise
# $outputmode = "tab";
# to print $t and $x coordinates;

$outputmode = "graph";  # comment in, or out as appropriate
# $outputmode = "tab";  


$imgXsize = 600;  # these are used for scaling even when not graphing
$imgYsize = 600;

if($outputmode eq "graph")
{
    # this bit of Perl's dirty underthings, brought to you courtesy
    #   of Perl's compile-time checking of dependencies.  Thanks to
    #   Shareef Dabdoub for finding a solution that doesn't require
    #   commenting out the 'use' statement in addition to changing
    #   $outputmode.
#   this doesn't work...
#   use GD;
#
#   This does...
    my $module = "GD";
    eval "use $module";
    die "couldn't load module : $!n" if ($@);


    $scale = 100;
    
    # Set up GD image stuff
    $im = new GD::Image($imgXsize,$imgYsize);
    # allocate some colors
    $white = $im->colorAllocate(255,255,255);
    $black = $im->colorAllocate(0,0,0);
    $red   = $im->colorAllocate(255,0,0);
    $blue  = $im->colorAllocate(0,0,255);
    $green = $im->colorAllocate(0,255,0);

    $oldxpos = $oldypos = 0;

    binmode STDOUT;
    #  draw a rectangle around our plot
    $im->rectangle(5,5,$imgXsize-5,$imgYsize-5,$black);
}

$xt = .000000001;    # The starting size of our population is very small
                     # compared to the carrying capacity - experiment
                     # with this value.

$rt = 2.9;           # tilde_r.  Experiment with different values for this
                     # parameter.  Especially be sure to try values in the
                     # neighborhood of 1, 2, 3, 3.59, and 4

# loop across our image, plotting a value of tilde_x
# for each horizontal pixel as a separate timepoint.
for ($p=1;$p<$imgXsize-10; $p++)
{
    $xb = $rt * $xt * (1-$xt);  # calculate our new tilde_x(t+h)
    $xt = $xb;                  # assign it to $xt, so we can use it in the next iteration
    
    if($outputmode eq "graph")
    {
	$newxpos = $p+5;            # calculate ourselves some drawing coordinates
	$newypos = 590 * $xt;
	
	$im->arc($newxpos,$newypos,3,3,0,360,$red);   # draw a point on the image
	
	# comment out this line of you prefer just points, without lines
	$im->line($oldxpos,$oldypos,$newxpos,$newypos,$red);
	$oldxpos = $newxpos;        # save them for drawing lines the next time
	$oldypos = $newypos;
    }
    if($outputmode eq "tab")
    {
	print "$p\t$xt\n";
    }
}

if($outputmode eq "graph") { print $im->png;}
exit;

