#!/usr/bin/perl

sub abort;


#
#
#cat /home/kael/Queries/prod_id.sql | mysql -u penguin domprodtest > newdoms.txt
#
#
# get output of monitor program
#



$step  = $ARGV[0];
if (!defined($step) || (($step ne "step1")&&($step ne "step2"))) {
 print " Before running this script you need to get a list of domids and mainboard ids \n";
 print " If STF has been run on these DOMs then execute this command: \n";
 print " cat /home/kael/Queries/prod_id.sql | mysql -u penguin domprodtest > newdoms.txt";
 print " otherwise, you must create this file some other way \n\n\n";
 print " you must define either step1 or step2 \n";
 print " StartFAT.pl step1 \n";
 print " or \n";
 print " StartFAT.pl step2 \n";
 print "\n";
 abort " StartFAT.pl does not have the necessary arguments \n";
}

$getnames = 0;
$namesfile  = $ARGV[1];
if (defined($namesfile)) {
  $getnames = 1;  
  print "\n Will use names file $namesfile \n";
}

if ($getnames == 1) {

open(IN3,"$namesfile");
@allnames = (<IN3>);
close(IN3);
 
 $first = 1;
 $c = 0;
 $cu = 0;
 $ct = 0;
 foreach (@allnames) {

   $inputline = $_;
   chop $inputline;
   $firstchar = substr($inputline,0,1);
   if ($firstchar eq "\+") {
#      print " found + \n"
   }
   if ($firstchar eq "\|") {
      if ($first == 1) {
        $first = 0; 
      } else {
        $c = $c + 1;
        ($j1,$domname[$c],$domexplanation[$c],$domtheme[$c]) = split('\|',$inputline);
        $domname[$c] =~ s/\s*//g;
        $domexplanation[$c] =~ s/^\s+//; #Trim leading white space
        $domexplanation[$c] =~ s/\s+$//; #Trim trailing whitespace
        $domtheme[$c] =~ s/^\s+//; #Trim leading white space
        $domtheme[$c] =~ s/\s+$//; #Trim trailing whitespace

        $firstnamechar = substr($domname[$c],0,1);
        $fnc[$c] = $firstnamechar;
        if ($firstnamechar le "L") {
          $ab[$c] = "U";
          $cu = $cu + 1;
        } else {
          $ab[$c] = "T";
          $ct = $ct + 1;
        }
      }
   }
 }
}
$totalnames = $c;
$totalts = $ct;
$totalus = $cu;
#print " found $totalnames names in $namesfile, total U DOMs = $totalus,  total T DOMs = $totalts  \n";
$c = 0;
while ($c < $totalnames) {
$c = $c + 1;

print " $ab[$c] $domname[$c] $domexplanation[$c] $domtheme[$c] \n";

}

print " found $totalnames names in $namesfile, total U DOMs = $totalus, total TorA DOMs = $totalts  \n";



open(IN2,"newdoms.txt");
@domprodtestpage = (<IN2>);
close(IN2);

open(IN,"monitor.dat");
@monitorpage = (<IN>);
close(IN);
                                                                                
         
$instr = 1;           
open(OUT,">InitializeNewDoms.SQL");

print OUT "use fat;\n";                                                            
                 
$line = 0;                 
$unknowns = 0;                                                                     
$knowns = 0;
$foundunknowns = 0;
$foundunknownTs = 0;
$foundunknownUs = 0;
$foundunknownAs = 0;
$ct = 0;
$cu = 0;
$c = 0;

foreach (@monitorpage) {
# $line = $line + 1;
# if ($line == 1) {goto Skip};
# ($domid,$mbid) = split(" ",$_);
# $name = "Name";
# print "insert into doms(domid,name,mbid) values('$domid','$name','$mbid')\n";

$name = substr($_,43,20); 
$mbid = substr($_,64,12);

      if ($instr == 1) {
        $instr = 0;
        print "\n\n\n";
        print " When you name DOMs, it is suggested that you \n";
        print "   1) keep names short \n";
        print "   2) use a particular theme so it is easy to know later which DOM came from which FAT \n";
        print "   3) make sure that the name has never been used before \n";
        print "   4) the name should not end in the letters 'ish' \n";
        print "  \n\n";

      }




 print "*$name* *$mbid* \n";


if ($name eq "                    ") {
 print "\n";
 print "  unknown DOM $mbid found in monitor.dat\n";
 $unknowns = $unknowns + 1;

 $line = 0;
 $flag = 0;
 foreach (@domprodtestpage) {
    $line = $line + 1;
    if ($line == 1) {goto Skip1stLine};
    ($dpdomid,$dpmbid) = split(" ",$_);
    if ($dpmbid eq $mbid) {
      print "  found $mbid, $dpdomid from the domid-mbid list ! \n";
      $foundunknowns = $foundunknowns + 1;
      $flag = 1; 
      if ($step eq "step1") { goto SkipIt };

      if ($getnames == 1) {
        if ((substr($dpdomid,0,1) eq "T") || (substr($dpdomid,0,1) eq "A")) {
           $ct = $ct + 1;
           if ($ct > $totalts) { abort "too many new t doms! " };
           $name = $domname[$ct+$totalus];
           $explanation = $domexplanation[$ct+$totalus];
           $theme = $domtheme[$ct+$totalus];
        } elsif (substr($dpdomid,0,1) eq "U") {
           $cu = $cu + 1;
           if ($cu > $totalus) { abort "too many new u doms! " };
           $name = $domname[$cu];
           $explanation = $domexplanation[$cu];
           $theme = $domtheme[$cu];
        }
      } else { 
        print "\nWhat do you want to call this DOM ? ";
        $name = "testname      ";
        $name= <STDIN>;
      }
SkipIt:
      $name =~ s/^\s+//;
      $name =~ s/\s+$//;
      $c = $c + 1;
      $sname[$c] = $name;
      $sdpdomid[$c] = $dpdomid;
      print OUT "insert into doms(domid,name,mbid) values('$dpdomid','$name','$mbid');\n";
      print OUT "insert into domtune
            (mbid,atwd0_trigger_bias,atwd1_trigger_bias,atwd0_ramp_rate,atwd1_ramp_rate"
            .",atwd0_ramp_top,atwd1_ramp_top,atwd_analog_ref,fe_pedestal,fadc_ref,spe_disc,mpe_disc"
            .",hv0,hv1,hv2,hv3,hvmax,hvsetting,thename,lcmode,thedomid,explanation,theme) 
            values ('$mbid',850,850,350,350,2300,2300,2250,2130,800,575,650,0,0,0,0,2047,1,'$name',1,'$dpdomid','$explanation','$theme');\n";

      if (substr($dpdomid,0,1) eq "T") { $foundunknownTs = $foundunknownTs + 1};
      if (substr($dpdomid,0,1) eq "U") { $foundunknownUs = $foundunknownUs + 1};
      if (substr($dpdomid,0,1) eq "A") { $foundunknownAs = $foundunknownAs + 1};
    }       
    Skip1stLine:    
 }
 if ($flag == 0) {
    print " \n\n\n OH NO, DOM not in newdoms.txt $mbid \n\n\n\n";
 }


} else {
 $knowns = $knowns + 1;
}


 Skip:
}

print "total  number of       unknown (monitor)     doms = $unknowns \n";
print "total  number of         known (monitor)     doms = $knowns \n";
print "total  number of found unknown (newdoms.txt) doms = $foundunknowns \n";
print "total  number of found unknown             T doms = $foundunknownTs \n";
print "total  number of found unknown             U doms = $foundunknownUs \n";
print "total  number of found unknown             A doms = $foundunknownAs \n";

#printf ("increment_run_number.pl: new run= %07.7s   old run = %07.7s \n",$newrun,$oldrun);

if ($unknowns != $foundunknowns) {
 
 print "\n";
 print "\n";
 print " NUMBER OF unkown new (monitor) DOMs DOES NOT MATCH number of new DOMS in newdoms.txt !!!!!\n";
 print "\n";
 print "\n";

}

if ($step eq "step2") {

print "\n";
print " found $totalnames names in $namesfile, total U DOMs = $totalus, total TorA DOMs = $totalts  \n";
print "\n";

print "\n LIST OF NEW DOM NAME ASSIGNMENTS: \n";
$c = 0;
while ($c < $unknowns) {
 $c = $c + 1;
 printf(" %-32.32s %10s \n",$sname[$c],$sdpdomid[$c]);
}
}
print "\n";
if ($step ne "step1") {
 print "\n to update: \n\n mysql fat -u tester -h sastrugi -p < InitializeNewDoms.SQL \n";
}

close (OUT);

exit(0);

sub abort {
    my $why = shift;
    die <<EOF;

Sorry, the script failed.  Here's why:

   $why

EOF
;
}

