#! /usr/bin/perl
#
# Usage: ./o32_plot.pl filename
#    OR  ./o32_plot.pl
#
# If filename is not given, it takes _last_data file.
#
# Auto plot tool.

require "modules/read_setup.pl";

$NevToProcess = 100;

my $testgood = `modules/check_dir.pl | tail -1`;
if ( $testgood != 1 ) {
    printf("Strange directory.\n");
    printf("Please run this script only in Stand1 or Stand2 directory.\n");
    exit;
}

if( $#ARGV == -1 ) {
    printf("No filename given, take _last_data\n");
    $File    = "_last_data";
    $Dir     = "_current";
    $Comment = "-";
} elsif( $#ARGV == 0 ) {
    $File    = $ARGV[0];
    @TEMP    = split( /\//, $File );
    $Dir     = $TEMP[0];
    $Comment = "-";
} elsif( $#ARGV == 1 ) {
    $File    = $ARGV[0];
    @TEMP    = split( /\//, $File );
    $Dir     = $TEMP[0];
    $Comment = $ARGV[1];
}

$Hist = $Dir."/_history";

printf("Reading data in $Dir\n" );
printf("History file is $Hist\n" );

# Parse _setup
( $DIR_NAME, $DATE, $ROC_SERIAL, $ROC_LAYER, $ROC_TYPE, $DCS_SERIAL, $WITH_PIPES, $INITIAL, $TRD_FEE ) = read_setup( $Dir );

$ROC_NAME = "L".$ROC_LAYER."C".$ROC_TYPE."-".$ROC_SERIAL;

# Read information from _history
$found = 0;
open( H, $Hist ) || die "Can not open history file $Hist, please check.";
while( <H> ) {
    if( /^(\S+:)\s+Executed:opt_readout.sh\s+Trigger:(\S+)\s+Nev:(\d+)\s+File:(\S+)\s+Config:(\S+)\s+Comment:(\S*)\s*$/ ) {
	$data_date = $1;
	$trigger   = $2;
	$Nev       = $3;
	$FileInHist= $4;
	$Config    = $5;
	$Comment   = $6;
	if( $File eq $FileInHist ) { 
	    printf("Found one entry in the history.\n");
	    $found = 1;
	    last;
	}
    }
}
close( H );

if( $found == 0 ) {
    printf("File is not found in the _history.\n");
}

if( $File eq "_last_data" ) {
    $FileInHist = $File;
}

printf("Data Taking Date: %s\n",   $data_date);
printf("Process file    : %s\n", $FileInHist);
printf("Nev             : %s\n", $Nev);
printf("Config          : %s\n", $Config);
printf("Comment         : %s\n", $Comment);
printf("ROC name        : %s\n", $ROC_NAME);
printf("ROC Type        : %s\n", $ROC_TYPE);
printf("Hist_File       : %s\n", $Hist);

$CommentOnPlot = sprintf("$Comment Config=$Config Trigger=$trigger NevInData=$Nev");

# Determine Axis Range
$RMS_Range_L  = 0.5;
$RMS_Range_H  = 2.2; # nominaly 2.5
$MEAN_Range_L = 5.0;
$MEAN_Range_H = 15.0;

if( $Config eq "nf" ) { $MEAN_Range_L =    0.0; $MEAN_Range_H =  200.0; }
if( $trigger eq "p" ) { $RMS_Range_L  =    0.0; $RMS_Range_H =   100.0; }

system("root -l \'o32_plot.C\(\"$FileInHist\", $NevToProcess, \"$ROC_NAME\", \"$CommentOnPlot\" , $ROC_TYPE, $RMS_Range_L, $RMS_Range_H, $MEAN_Range_L, $MEAN_Range_H \)\'");
