#!/usr/bin/perl -w
# v0.2 2 October 2008
use Getopt::Long;
use vars qw/$opt_help $opt_batch $opt_s $opt_xy $opt_xlab $opt_ylab $opt_t
 $opt_xmin $opt_xmax $opt_ymin $opt_ymax $opt_lw/;
GetOptions("help","batch","s","xy",  "xlab:s", "ylab:s" , "t:s", "xmin:f" , "xmax:f",
  "ymin:f" , "ymax:f" , "lw:i");
my($x, $y);
if (defined $opt_help){
  print "
usage example for 2-D plot: 

hashplot.pl nn_b.dat 2 4 nn.png -xy -s -xlab 'predicted value'\
 -ylab 'target value' -t 'column 4 versus 2 from nn_b.dat'

usage example for 3-D plot, useful for overlapping binned data:

hashplot.pl nn_b.dat 2 4 nn.png -xlab 'predicted value'\
 -ylab 'target value' -t 'column 4 versus 2 from nn_b.dat'

";
exit(0);  
}

($infile,$xc,$yc,$pngfile)=@ARGV;
($xl,$xr,$yb,$yt)=('','','','');
$xl=$opt_xmin if defined($opt_xmin);
$xr=$opt_xmax if defined($opt_xmax);
$yb=$opt_ymin if defined($opt_ymin);
$yt=$opt_ymax if defined($opt_ymax);
#($xl,$xr,$yb,$yt)=($opt_xmin,$opt_xmax,$opt_ymin,$opt_ymax);
($xl,$xr,$yb,$yt)=(-1,1,-1,1) if $opt_s;
$pngfile='temp.png' unless defined($pngfile);
$pngfile='temp.png' unless $pngfile=~m/\.png$/;
open IN,"<$infile";
open OUT,">temp_hashplot.dat";
while ($line=<IN>){
  next if $line=~m/^\s*\#/;
  chomp($line);
  $line=~s/^\s+//;
  $line=~s/\s+$//;
  @v=split /\s+/,$line;
  $x=$v[$xc-1];
  $y=$v[$yc-1];
  $n{$x}{$y}++;
}

$themax=0;
for $kx (sort keys %n){
for $ky (sort keys %{$n{$kx}}){
  print OUT "$kx $ky $n{$kx}{$ky}\n";
  $themax=$n{$kx}{$ky} if $n{$kx}{$ky}>$themax;
}
}
close OUT;
$opt_xlab="predicted value" unless defined($opt_xlab); 
$opt_ylab="target value" unless defined($opt_ylab); 
$opt_t="columns $yc versus $xc in $infile" unless defined($opt_t);
$opt_lw=1 unless defined($opt_lw);
$plotter="splot [$xl:$xr][$yb:$yt][0:$themax] 'temp_hashplot.dat'  with i lw $opt_lw";
#following make red, good for web and png
$plotter="plot [$xl:$xr][$yb:$yt][0:$themax] 'temp_hashplot.dat' with points pt 1 ps .2" if $opt_xy;
#following makes black and white:
#$plotter="plot [$xl:$xr][$yb:$yt][0:$themax] 'temp_hashplot.dat' with points 7 " if $opt_xy;
$size='';
$size='1.4,2' if $opt_xy;
$size='2,2' unless $opt_xy;
open GNU,">temp.gnu";
print GNU "#!/usr/bin/gnuplot 
set term png giant size 800,600 
set output '$pngfile'
set title '$opt_t'
set xlabel '$opt_xlab'
set ylabel '$opt_ylab'
set nokey
set ticslevel 0
#set noztics
#set size $size
set size square 
set view 45,10,1,1
$plotter
#EOF
";
close GNU;
system('gnuplot temp.gnu');
system("display $pngfile ") unless $opt_batch;
