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

require "modules/read_setup.pl";

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");

system("root \'o32_dump.C\(\"$FileInHist\"\'");

# EOF
