#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;

$| = 1;

my $exe = "/usr/bin/gnuplot";
if ( ! -e $exe ) {
    die "cannot execute $exe!\n";
}

my $time_interval = 1;
my $first_time = 0;
my $start_input;
my $stop_input;
my $out_file;
my @color_f;

my $result = GetOptions(
    'interval=i' => \$time_interval,
    'first=f' => \$first_time,
    'start=f' => \$start_input,
    'stop=f' => \$stop_input,
    'color=i{3}' => \@color_f,
);

if ( !$result or !@ARGV ) {
    print "Usage: $0 [options] 2drms_raw_file\n";
    print "    -start time\n";
    print "    -stop time\n";
    print "    -interval time_interval (default: 1 (ps))\n";
    print "    -first first_time (default: 0 (ps))\n";
    print "    -out out_file\n";
    print "    -color color_formulae(gnuplot) (default: 7 5 15)\n"; 
    exit;
}

if ( scalar(@color_f) == 0 ) {
    @color_f = ( 7, 5, 15 );
}

if ( ! defined $out_file ) {
    $out_file = "$ARGV[0]\.eps";
}

my $data_file = "$ARGV[0].data.tmp";
if ( -e "$data_file" ) {
    die "remove $data_file and run again\n";
}

print "Preparing data file ...";
open PDATA, '>', $data_file;
my $cur_x = $first_time;
open DAT, '<', $ARGV[0];
while ( <DAT> ) {
    /(\S+)\s+(\S+)\s+(\S+)/ or die;
    my $x = $first_time + $1 * $time_interval;
    my $y = $first_time + $2 * $time_interval;
    my $z = $3;
    if ( defined $start_input ) {
        next if ( $x < $start_input || $y < $start_input );
    }
    if ( defined $stop_input ) {
        next if ( $x > $stop_input || $y > $stop_input );
    }
    if ( $cur_x != $x ) {
        print PDATA "\n";
    }
    $cur_x = $x;
    print PDATA "$x $y $z\n";
}
close DAT;
close PDATA;
print " ... Done!\n";

print "Generating plot ...";
open PLOT, "|-", $exe;
print PLOT "set terminal postscript eps color enhanced\n";
print PLOT "set size 1,1\n";
print PLOT "set output '$out_file'\n";
print PLOT "set xlabel 'time (ps)'\n";
print PLOT "set ylabel 'time (ps)'\n";
print PLOT "set style data pm3d\n";
print PLOT "set palette rgbformulae " . join( ',', @color_f ) . "\n";
print PLOT "set pm3d at b\n";
print PLOT "set view map\n";
print PLOT "splot '$data_file' notitle\n";
close PLOT;
print " Done\n";

unlink $data_file;
