#! /usr/bin/perl


# Usage: newSummaryPage.pl -m M7690-17-2 
# -----

# ----------------------------------------------------------------------
use Getopt::Std;
getopts('m:');

#$testDir = "/home/l_tester/ptr/moduleTestsOld/psi46expert";
#$testDir = "/home/l_tester/ptr/moduleTests/psi46expert";
#$testDir = "/home/l_tester/ptr/merged/psi46expert";
#$testDir = "/home/l_tester/ptr/supervisor/tests";   
 
$tmp1 = $opt_m;
$tmp1 =~ s/\.\.//;
$tmp1 =~ s/\///g;
@ntmp = split(/\-/,$tmp1);
$name= $ntmp[0]."T-".$ntmp[2];

  
$tmp2 = $opt_m;
$tmp2 =~ s/\.\.//;

@mtmp = split(/\//,$tmp2);
$testNr=$mtmp[$#mtmp];  
@ntmp = split(/\-/,$mtmp[$#mtmp-1]);
$moduleNr=$ntmp[0];
$name= $moduleNr."".$testNr;

$redTestNr = substr($testNr,2,3);
$sollTemp  = substr($testNr,1,3);

$ttmp = $testNr;
$ttmp =~ s/T//;
$ttmp =~ s/a/q/;
$ttmp =~ s/b/q/;
$ttmp =~ s/c/q/;
$ttmp =~ s/d/q/;
$ttmp =~ s/e/q/;
$ttmp =~ s/f/q/;
$ttmp =~ s/g/q/;

($temperature, $nada) = split(/q/,$ttmp);

$dbDir   = "/home/l_tester/ptr/moduleDB";
$testDir = $dbDir;

$testFile     = "FullTest.root";
$phCalFile    = "phCalibration_C15.dat";
$ivFile       = "iv.dat";

$meanT=-100.;
$sigmaT=-100.;

$meanC=-100.;
$sigmaC=-100.;

@summaryFiles = `ls -1 $dbDir/$opt_m/summary_*.txt`;
my @trimFiles = ();
@trimFiles    = `ls -1 $dbDir/$opt_m/trimParameters*C15.dat`;

print "\nphpSummary> Trim paramaters  -->  Found the following files\n";

foreach $k (0...$#trimFiles) { 

            @ttmp=split(/\//,$trimFiles[$k]); 
            $theTrimFile[$k]=pop(@ttmp);
            chop($theTrimFile[$k]);
            print "phpSummary> $k: $theTrimFile[$k]\n";
  } 
my $deadTot=0, $maskTot=0, $bumpsTot=0, $trimbitsTot=0, $addressTot=0, $badROCS=0, $badROCS1=0, $badROCS2=0, $rootTot=0;
my $badDEAD1=0, $badMASK1=0, $badBUMPS1=0, $badTRIMBITS1=0, $badADDRESS1=0;
my $badDEAD2=0, $badMASK2=0, $badBUMPS2=0, $badTRIMBITS2=0, $badADDRESS2=0;
my $mSCurve, $sSCurve, $mThr, $sThr, $mGain, $sGain, $mPed, $sPed;
my @SCurve, @Thr, @Gain, @Ped;
my $nSCurve=0, $nThr=0, $nGain=0, $nPed=0;

push(@SCurve, "<FONT COLOR=#009c66> SCurve ");
push(@Thr, " <FONT COLOR=#9900ff> Vcal Thr ");
push(@Gain, "<FONT COLOR=#3366ff> Gain ");
push(@Ped, "<FONT COLOR=#ff9c33> Ped ");

if (-e "$dbDir/$opt_m/summaryTest.txt" ) {system("rm -f $dbDir/$opt_m/summaryTest.txt");}
open(SUMM, ">$dbDir/$opt_m/summaryTest.txt") || die "==> Cannot open $dbDir/$opt_m/summaryTest.txt\n";
if (-e "$dbDir/$opt_m/gradingTest.txt" ) {system("rm -f $dbDir/$opt_m/gradingTest.txt");}
open(GRAD, ">$dbDir/$opt_m/gradingTest.txt") || die "==> Cannot open $dbDir/$opt_m/gradingTest.txt\n";

# -- Loop over all summary files and extract relevant numbers from 

print "\nphpSummary> test-Nr: $redTestNr and Soll-Temp: $sollTemp\n";

$file = "$dbDir/$opt_m/../summaryTemp.txt";
if ( -e $file ) {
    getTemp($file);
}
 
for ($i = 0; $i < $#summaryFiles+1; $i++) {

    $file = "$dbDir/$opt_m/summary_C$i.txt";
    if ( -e $file ) {
	getDefects($file);
    }
}

for ($j = 0; $j < $#summaryFiles+1; $j++) {

    $file = "$dbDir/$opt_m/fits_C$j.txt";
    if ( -e $file ) {
	getFits($file);
    }
}

$mSCurve = $mSCurve/16;
$sSCurve = $sSCurve/16;
$mThr = $mThr/16;
$sThr = $sThr/16;
$mGain = $mGain/16;
$sGain = $sGain/16;
$mPed = $mPed/16;
$sPed = $sPed/16;

push(@SCurve, " ? </FONT>");
push(@Thr, " ? </FONT>");
push(@Gain, " ? </FONT>");
push(@Ped, " ? </FONT>");

&mkSummaryTest;


print "\nphpSummary> $dbDir/$opt_m\/summaryTest.txt produced...\n\n";


# ----------------------------------------------------------------------
sub getDefects() {
    my ($f) = @_;
    
    my $roc, $dead, $mask, $bumps, $trimbits, $address, $root;
    ($bla, $roc) = split(/summary_C/, $f);
    $roc =~ s/\.txt//;
    open(IN, "$f") || die "Cannot open $file\n";
    while (<IN>) {
	if (/nDeadPixel/) {
	    s/nDeadPixel: //g;
	    $dead = $_;
	}

	if (/nDeadTrimbits/) {
	    s/nDeadTrimbits: //g;
	    $trimbits = $_;
	}

	if (/nDeadBumps/) {
	    s/nDeadBumps: //g;
	    $bumps = $_;
	}

	if (/nMaskDefect/) {
	    s/nMaskDefect: //g;
	    $mask = $_;
	}

	if (/nAddressProblems/) {
	    s/nAddressProblems: //g;
	    $address = $_;
	}

	if (/nRootFileProblems/) {
	    s/nRootFileProblems: //g;
	    $root = $_;
	}
    }
      
    $deadTot += $dead;
    $maskTot += $mask;
    $bumps = $bumps - $dead;
    if($bumps<0) {$bumps = 0;}
    $bumpsTot += $bumps;
    $trimbits = $trimbits - 4*$dead;
    if($trimbits<0) {$trimbits = 0;}
    $trimbitsTot += $trimbits;
    $address = $address - $dead;
    if($address<0) {$address = 0;}
    $addressTot += $address;



    if($dead>42 && $dead<168) { $badDEAD1++; }
    if($mask>42 && $mask<168) { $badMASK1++; }
    if($bumps>42 && $bumps<168) { $badBUMPS1++; }
    if($trimbits>42 && $trimbits<168) { $badTRIMBITS1++; }
    if($address>42 && $address<168) { $badADDRESS1++; }

    if($dead>168) { $badDEAD2++; }
    if($mask>168) { $badMASK2++; }
    if($bumps>168) { $badBUMPS2++; }
    if($trimbits>168) { $badTRIMBITS2++; }
    if($address>168) { $badADDRESS2++; }

    if($dead>42 || $mask>42 || $bumps>42 || $trimbits>42 || $address>42) { $badROCS++;} 
    if(($dead>42 || $mask>42 || $bumps>42 || $trimbits>42 || $address>42) &&
       ($dead<168 || $mask<168 || $bumps<168 || $trimbits<168 || $address<168)) { $badROCS1++;} 
    if($dead>168 || $mask>168 || $bumps>168 || $trimbits>168 || $address>168) { $badROCS2++;} 
    $rootTot += $root;

}

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

sub getTemp() {
    my ($f) = @_;

    open(TE, "$f") || die "Cannot open $f\n"; 

    while (<TE>) {
	if (/$redTestNr/) {
	    ($nr, $meanT, $sigmaT) = split(/ /, $_);
	    chop($sigmaT);
	    print "phpSummary> TEMP $meanT $sigmaT\n";
	}

	if (/T-cycl/) {
	    s/T-cycl //g;
	    ($meanC, $sigmaC) = split(/ /, $_);
	    chop($sigmaC);
	    print "phpSummary> CYCL $meanC $sigmaC\n";
	}

    }
}

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

sub getFits() {
    my ($f) = @_;
    
    my $mSCurveChip, $sSCurveChip, $mThrChip, $sThrChip, $mGainChip, $sGainChip, $mPedChip, $sPedChip;
    ($bla, $roc) = split(/fits_/, $f);
    $roc =~ s/\.txt//;
    open(IN, "$f") || die "Cannot open $f\n";
    while (<IN>) {
	if (/SCurve/) {
	    s/SCurve //g;
	    ($mSCurveChip, $sSCurveChip) = split(/ /);
	    chop($sSCurveChip);
	}

	if (/Threshold/) {
	    s/Threshold //g;
	    ($mThrChip, $sThrChip) = split(/ /);
	    chop($sThrChip);
	}

	if (/Gain/) {
	    s/Gain //g;
	    ($mGainChip, $sGainChip) = split(/ /);
	    chop($sGainChip);
	}

	if (/Pedestal/) {
	    s/Pedestal //g;
	    ($mPedChip, $sPedChip) = split(/ /);
	    chop($sPedChip);
	}

    }

    
   # -------> Qualification parameters
    
    if ($mSCurveChip > 250. )  { push(@SCurve, $roc); $nSCurve++; }
    if ((65*$sThrChip) > 200 )     { push(@Thr, $roc); $nThr++; }
    if ($mGainChip != 0) {
      if (($sGainChip/$mGainChip)   > 0.1 )     { push(@Gain, $roc); $nGain++; }
      if ((65*$sPedChip/$mGainChip) > 2500. )   { push(@Ped, $roc);  $nPed++; }
    }

    $mSCurve = $mSCurve + $mSCurveChip;
    $sSCurve += $sSCurveChip;
    $mThr += $mThrChip;
    $sThr += $sThrChip;
    $mGain += $mGainChip;
    $sGain += $sGainChip;
    $mPed += $mPedChip;
    $sPed += $sPedChip;
}

#----------------------------------------------------------------------------------------
sub mkSummaryTest() {

  print GRAD "DEAD $badDEAD1 $badDEAD2\n";
  print GRAD "MASK $badMASK1 $badMASK2\n";
  print GRAD "BUMPS $badBUMPS1 $badBUMPS2\n";
  print GRAD "TRIMBITS $badTRIMBITS1 $badTRIMBITS2\n";
  print GRAD "ADDRESS $badADDRESS1 $badADDRESS2\n";
 
  print SUMM "Directory $opt_m \n";
  print SUMM "ModuleNr TestNr $moduleNr $testNr\n";
  print SUMM "$deadTot $maskTot $bumpsTot $trimbitsTot $addressTot \n";
  print SUMM "ROCS with defects > 1% $badROCS $badROCS1 $badROCS2\n";
  print SUMM "Missing histograms $rootTot\n";
  
  if (`ls -1 $dbDir/$opt_m/$testFile`) {
    $date=getFileDate($dbDir, $testFile); print SUMM "Tested yes on $date\n";
  }               
  else {print SUMM "Tested no\n";}
  
  if (`ls -1 $dbDir/$opt_m/trimParameters*C15.dat`) {
    $date=getFileDate($dbDir, $theTrimFile[0]); print SUMM "Trimming yes on $date\n";
  }
  else {print SUMM "Trimming no\n";}

  if (`ls -1 $dbDir/$opt_m/$phCalFile`) {
      $date=getFileDate($dbDir, $phCalFile); print SUMM "phCalibration yes on $date\n";
  }        
  else {print SUMM "phCalibration no\n";}

  if ( $meanT != -100 && $sigmaT != -100 ) {
      print SUMM "Temp $meanT $sigmaT Soll $sollTemp\n";
  }
  else {
      print SUMM "Temp $sollTemp $sigmaT Soll $sollTemp\n";
  }

  if (`ls -1 $dbDir/$opt_m/../T-10a` && `ls -1 $dbDir/$opt_m/../T-10b`)  {
      
      print SUMM "Thermal cycling yes $meanC $sigmaC\n";
  }               
  else {print SUMM "Thermal cycling no $meanC $sigmaC\n";}
  
  print SUMM "SCurve $mSCurve $sSCurve \n";
  print SUMM "Threshold   $mThr $sThr \n";
  print SUMM "Gain $mGain $sGain \n";
  print SUMM "Pedestal $mPed $sPed \n";

#comments
  if ($nSCurve > 0 ) { print SUMM "@SCurve\n"; }
  else { print SUMM "SCurves good\n"; }
  if ($nThr > 0 )   { print SUMM "@Thr\n"; }
  else { print SUMM "Thresholds good\n"; }
  if ($nGain > 0 )  { print SUMM "@Gain\n"; }
  else { print SUMM "Gains good\n"; }
  if ($nPed > 0 )   { print SUMM "@Ped\n"; }
  else { print SUMM "Peds good\n"; }

   
}

# ----------------------------------------------------------------------
sub getFileDate() {
    local($fileDir, $file) = @_;
    
 ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
       = stat("$fileDir/$opt_m/$file");
       
 $time = localtime($mtime);
  
 return $time;
}
