#!/usr/bin/perl -w

use strict;


$|=1;


require File::Basename;
require File::Path;
require Cwd;
require Sys::Hostname;


use strict;

my $_tool_name;
my $_tool_path;
($_tool_name, $_tool_path, undef) = &File::Basename::fileparse($0);

$_tool_path = Cwd::abs_path($_tool_path);
my $_cwd = Cwd::abs_path('.');


my $_info_marker = "$_tool_name :INFO:";
my $_warning_marker = "$_tool_name :WARNING:";
my $_error_marker = "$_tool_name :ERROR:";

my $_ascii_number_format = '%05d'; # 100000 files should be enough

if(@ARGV)
  {
  warn "$_info_marker \@ARGV item per line:\n";
  warn join("\n", @ARGV), "\n";
  warn "$_info_marker end of \@ARGV\n";
  }

warn "$_info_marker started intercepting STDIN\n\n";

my $_dir_for_gnuplot_files = &create_dir_for_gnuplot_files();

#my @_buffer;
my $_number_of_substreams = 0;
my $_data_file_number = 0;
my $_commands_file_number = 0;

my $_session_data_file_start_number;

my $_commands_file;
my $_commands_file_fh;
my $_data_file_fh;


&main_loop();

# comment out the line below if you wish to keep 'gnuplot' files
system("\\rm -rf $_dir_for_gnuplot_files");


warn "$_info_marker finished intercepting STDIN\n";


#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------


################################
sub create_dir_for_gnuplot_files
################################
  {
  my $hostname = &Sys::Hostname::hostname;
  ($hostname) = ($hostname =~ m/^([^\.]*)/); # no domain name - if any at all
  
  # change the following line if you want a different location
  my $dir = "$_cwd/.gnuplot_files.$hostname.$$";

  if(-e $dir)
    {
    system("\\rm -rf $dir");
    }

  system("\\mkdir -p $dir");

  unless(-d $dir)
    {
    die "$_error_marker could not create '$dir' directory";
    }

  $dir; # the returned value
  } # sub create_dir_for_gnuplot_files
  #-----------------------------------


###############
sub run_gnuplot
###############
  {
  my ($commands_file) = @_;

  # you may give full path to 'gnuplot' in the line below
  # if you wish to use particular version
  my $command = "xterm -hold -e gnuplot -persist $commands_file - \&";

  warn "$_info_marker executing ==> $command\n";
  system($command);
  } # sub run_gnuplot
  #------------------


#############
sub main_loop
#############
  {
  outer_while:
  ##################################
  while(defined(my $line = <STDIN>))
  ##################################
    {
    #warn "outer while: \$line=$line";

    unless(defined $_commands_file_fh)
      {
      my $commands_file_ascii_number = sprintf($_ascii_number_format, $_commands_file_number);
      $_commands_file = "$_dir_for_gnuplot_files/commands_file.$commands_file_ascii_number";
      open($_commands_file_fh, '>', $_commands_file) or die "$_error_marker could not open '$_commands_file' file for writing";
      }


    if($line =~ m|^s?plot\s+|)
      {
      #push @_buffer, $line;
      print $_commands_file_fh $line;

      $_session_data_file_start_number = $_data_file_number;

      inner_while:
      ##################################
      while(defined(my $line = <STDIN>))
      ##################################
        {
        #warn "inner while: \$line=$line";

        if($line =~ m|^"-"\s*|)
          {
          my $data_file_number = $_session_data_file_start_number + $_number_of_substreams;
          my $ascii_data_file_number = sprintf($_ascii_number_format, $data_file_number);
          my $data_file = "$_dir_for_gnuplot_files/data_file.$ascii_data_file_number";
          #warn "\$data_file=$data_file";
          $_number_of_substreams++;

          my $line = $line;
          $line =~ s/^"-"/"$data_file"/;

          #push @_buffer, $line;
          print $_commands_file_fh $line;

          next;
          }

        #push @_buffer, $line;

        if(defined $_commands_file_fh)
          {
          print $_commands_file_fh $line;
          }
        else
          {
          print $_data_file_fh $line;
          }

        if($line =~ m/^;/)
          {
          close($_commands_file_fh);
          undef($_commands_file_fh);

          my $ascii_data_file_number = sprintf($_ascii_number_format, $_data_file_number);
          my $data_file = "$_dir_for_gnuplot_files/data_file.$ascii_data_file_number";
          #warn "\$data_file=$data_file";
          open($_data_file_fh, '>', $data_file) or die "$_error_marker could not open '$data_file' for writing";

          next;
          }

        if($line =~ m|^e\s*$|)
          {
          close($_data_file_fh);

          $_number_of_substreams--;
          $_data_file_number++;


          if($_number_of_substreams == 0)
            {
            #warn "\@_buffer=\n";
            #warn join('', @_buffer), "\n";
            #warn "end of \@_buffer\n";
            #@_buffer = ();

            &run_gnuplot($_commands_file);

            $_commands_file_number++;

            last inner_while;
            }

          my $ascii_data_file_number = sprintf($_ascii_number_format, $_data_file_number);
          my $data_file = "$_dir_for_gnuplot_files/data_file.$ascii_data_file_number";
          #warn "\$data_file=$data_file";
          open($_data_file_fh, '>', $data_file) or die "$_error_marker could not open '$data_file' for writing";
          }
        }
      }

    #push @_buffer, $line;
    if(defined $_commands_file_fh)
      {
      print $_commands_file_fh $line;
      }
    } # while(defined(my $line = <STDIN>))
  } # sub main_loop
  #----------------
