#! /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";

$TargetEvent = 1;

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 ) {
    $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];
}

printf("Reading data in $Dir\n" );

$Hist = $Dir."/_history";

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

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

# Read information from _history
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 ) { last; }
    }
}

close( H );

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.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;
}

system("root \'o32_new.C\(\"$FileInHist\", $TargetEvent, $Nev, \"$ROC_NAME\", \"$CommentOnPlot\", $ROC_TYPE\)\'");
