#@x=(0, 0.3, 0.6, 1 );
#@y=(0, 0.08, 0.8, 1 );
#@x=(0,1); @y=(0,1);


@x=(0, 0.08, 0.1, 0.3,  0.48, 0.49,  0.6,  0.63, 0.72, 0.85, 0.92, 1);
@y=(0, 0.002, 0.017, 0.17, 0.51, 0.64,  0.85, 0.88, 0.90, 0.915,0.95, 1);
#&runner;
if ($ARGV[0] eq "ppm") {
  &ppm;
}
elsif ($ARGV[0] eq "test") {
  &test2;
}else {
  &runner;
}
sub runner{
#    while(1){
$x=`cview`;
exit 1 unless $x;
exit 1 unless $x =~ m,TOTALS.*?(\d+) / (\d+)\s*$,;
$_=1-$1/$2;
$color=&color2(m1($_));
$time=time();
$date=`date`;
print "$1 / $2 = $_ $color $time $date";

`xsetroot -solid $color`;
sleep 1; #to prevent it accidentally from being called continuously
#}
}

sub ppm {
  $reps=100;
  $wid=1000;
  print "P3\n$wid $reps\n255\n";
  for (1..$reps-5) {
    for $j (1..$wid) {
      $i=$j/$wid;
      $l=&m1($i);
      $s=&color2($l);
      die unless @COL=($s=~m,rgbi:(.*)/(.*)/(.*),);
      for (@COL) {
        print int($_*255)," ";
      }
      print "\n";
    }
  }
  for (1..5) {
    for $j (1..$wid) {
      if ($j%100==0) {
        print "0 255 0\n";
      }
      elsif ($j%10==0) {
        print "255 0 0\n";
      }
      else {
        print "255 255 255\n";
      }
    }
  }
}

sub test2{
$cc=0;
for ($i=0.0;$i<1;$i+=0.0300001) {
  $cc++;
  #$s=&color2($i);
  $l=&m1($i);
  $s=&color2($l);
  print "$cc $i $l $s\n";
  `xsetroot -solid $s`;
  sleep 1;
}
}
sub test1{
for ($i=0;$i<1;$i+=0.01) {
  $s=&color2($i);
  #$s=&m1($i);
  print "$i $s\n";
}
}
sub m1 {
  my($t)=@_;
  my $m=-1;
  for $i(1..$#x) {
    #print "you $t $x[$i]\n";
    if ($t<=$x[$i]) {
      $m=$y[$i-1]+($y[$i]-$y[$i-1])*($t-$x[$i-1])/($x[$i]-$x[$i-1]);
      last;
    }
  }
  die unless $m>=0;
  $m;
}
  

sub color2{
#blueblack..green..yellow..red..magenta
  my ($x)=@_;
  my $t;
  my $blue=0.01;
  $x*=3.3;
  #print "x=$x\n";
  if ($x<0) {
    "rgbi:0/0/$blue";
  }
  elsif ($x<1) {
    $t=$blue*(1-$x);
    die if ($t>1);
    die if ($t<0);
    die if ($x>1);
    die if ($x<0);
    "rgbi:0/$x/$t";
  }
  elsif ($x<2) {
    $t=$x-1;
    die if ($t>1);
    die if ($t<0);
    "rgbi:$t/1/0";
  }
  elsif ($x<3) {
    $t=3-$x;
    die $t if ($t>1);
    die $t if ($t<0);
    "rgbi:1/$t/0";
  }
  elsif ($x<3.3) {
    $t=$x-3;
    #print "hey $t\n";

    die $t if ($t>1);
    die $t if ($t<0);
    "rgbi:1/0/$t";
  }
  else {
    "rgbi:1/0/0.3";
  }
}
