#!/usr/local/bin/perl

#  4/22/94 by Mark Torrance (torrance@ai.mit.edu)
#
#  Redraws gnuplot graph for a particular mutual fund

$ENV{'PATH'} = "/usr/local/bin:/usr/bin:/bin:/home/pangloss/pbmplus/ppm:/home/pangloss/gnuplot:/usr/ucb";

#$funddir = "/com/doc/web/stocks/funds";
$funddir = "/home/pangloss/public_html/Fund/funds";

sub round
{
    local ($_) = @_;
    ($result)=split(/\./,$_+.5);
    $result;
}

sub floor
{
    local ($_) = @_;
    ($result)=split(/\./);
    $result;
}

while(@ARGV) {
    $fundsym = shift;
    $fl = substr($fundsym,0,1);

#    open (INFILE, "< $funddir/ZZ$fl/$fundsym") ||
    open (INFILE, "< $funddir/$fundsym") ||
	die("No data available for ", $fundsym, "\n");

    # Cruise through the file.  At each new month, store a new pair
    # in an array to serve as the xtics.

    $index = 0;
    $n = 0;
    $numpoints = 0;
    @xtics = ();
    @xindex = ();
    $lowest = 10000;
    $highest = -1;
    while (<INFILE>) {
	$numpoints++;
	($date,$last) = split(/\t/);
	if (($lowest>$last)&&($last>0)) {$lowest=$last};
	if ($highest<$last) {$highest=$last};
	if ($index==0) {
	    $lastdate = $date;
	}
	if ((scalar(substr($date,0,2)) > scalar(substr($lastdate,0,2))) ||
	    (scalar(substr($date,2,2)) > scalar(substr($lastdate,2,2)))) {
	    # new year
	    $xtics[$n]=substr($date,0,4);
	    $xindex[$n++]=$index;
	}

	$index++;
	$lastdate = $date;
    }
    close INFILE;
    
    $highest = $highest*1.03;
    $lowest = $lowest*.97;

    # iterate through possibilities.  If numtics < 25, save as best

    $increment = 32;
    @possibilities = (32, 16, 8, 4, 2, 1, 0.5, 0.25, 0.125);
    foreach $possibility (@possibilities) {
	$numtics = ($highest - $lowest) / $possibility;
	if ($numtics < 20) {$increment = $possibility};
    }
    
    $xmax = $numpoints + 3;

#    open(CONTROL,"| gnuplot 2>/dev/null | ppmtogif 2>/dev/null > $funddir/ZZ$fl/$fundsym.gif") || die("Cannot create graph file.\n");
    open(CONTROL,"| gnuplot | ppmtogif > $funddir/$fundsym.gif") || die("Cannot create graph file.\n");

    print CONTROL <<EOF;
set term pbm small
set size .9,.7
set nozeroaxis
set logscale y 2
set ytics 0,$increment
set yrange [$lowest : $highest]
set noautoscale x
set xrange [-3 : $xmax]
EOF
    print CONTROL "set xtics (\"$xtics[0]\" $xindex[0]";
    $n=0;
    while (++$n <= $#xtics) {
	print CONTROL ", \"$xtics[$n]\" $xindex[$n]";
    }
    print CONTROL ")\n";
    print CONTROL "plot \"$funddir/$fundsym\" using 0:2 title '' with lines\n";
    close CONTROL;

}
