#!/usr/local/bin/perl -w

# jrock: perl to dump everything about mps digitals

# first do this:
#      . /usr/local/lcls/epics/setup/oracleSetup.bash
# before running this perl script

use DBI qw(:sql_types);
use Switch;

my $boFile;
my $mbboFile;
my $biFile;
my $mbbiFile;

my $PRIM;
my $MICRO;
my $UNIT;
my $COMP;
my $blanks = "                    ";
my $dummyVal = " \"\" ";

    my @IBSDs = ();
    my @OBSDs = ();
    my @SEVRs = ();
    # this is for DIDNs
    my @SEVMs = ();
    my $SEVM1;
    my @PULSEs = ();
    my @statesPerComponent = ();
    my @componentNames = ();
    my @stateNames = ();
    my $primImod;
    my @primImods = ();
    my $primIchan;
    my @primIchans = ();
    my $primOchan;
    my @primOchans = ();

    my %primHash;
 

    my $numComponents = 0;
    my $numIBits = 0;
    my $numOBits = 0;
    my $dbh;
    my $egu_dbh;
    my $dig_row;
    my $dim_row;
    my $secn;
    my $unit;
    my $micro;
    my $local_index;
    my $value;
    my %DIMHash; # key is DIM unit; value is CRATE:MODULE
    my @DIMModArr;
    my @DIMCrateArr;

    my $DOMModule;
    my $DOMCrate;

    my $i;
    my $j;
    my $arrLen;

    my @comps;

    # this is the map of all bit values, bits used and not used (16 for input, 8 for output)
    my @allIBitVals;
    my @allOBitVals;

    # these are parallel arrays of bits+modules used and their values for the state in question
    # to be output-ed
    my @IBits=();
    my @IBitVals=();
    my @IModules=();
    my @ISevrs=();
    my @OBits=();
    my @OModules=();
    my @OBitVals=();
    my @OPulses=();

    # attributes output for Zero and One input and output states
    my $ZstateName;
    my $ZsevrStr;
    my $Zcrate=();
    my $Zmod=();
    my $Zbit=();
    my $Zpulse=();
    my $OstateName;
    my $OsevrStr;
    my $Ocrate=();
    my $Omod=();
    my $Obit=();
    my $Opulse=();
   
    my $ZstateNameOut;
    my $ZbitOut;
    my $OstateNameOut;
    my $ObitOut;

    my $domCrate;
    my $domMod;

    my $hasBIBits = 0;
    my $hasBOBits = 0;
    my $hasMBBIBits = 0;
    my $hasMBBOBits = 0;

    my $ORIGPRIM;
#===============================================================
sub setDIDNSevrs
#===============================================================
{
# for severities, DIDN-based digitals have a different method than normal digitals.
# querying Oracle, for the micros in question, all DIDN-based severities were
# found to be either NO_ALARM or MINOR.
# "
#  select distinct value from slc_data_view_all
#  where prim='ACCS' and secn = 'SEVM' and local_index > 1 and
#  (micro like 'LI2%' or micro='LI30' or micro='AB01' or micro='CB00' or
#  micro='CA11' or micro='CA01' or micro='MC00') and
#  value not like '%0000'
# "
# yielded 0 rows.
# the only severity in the database is MINOR, which is the first SEVM, captured in
# $sevrMask;  it will tell us which name and states are MINOR.  the rest are
# NO_ALARM.

# bit by bit:
# for each bit, high bits tell us whether this bit has an alarm status
# for each bit, low bits tell us which value is BAD
print "=============\nENTERING setDIDNsevrs\n";
#my $sevMask = shift;
print "in setDIDNSevrs\n";
my $sevMask = $SEVM1;
print "SEVRMASK: $sevMask: ";

my $hiBits = hex (substr($sevMask, 0, 2));
my $loBits = hex (substr($sevMask, 2));
print "hibits: $hiBits, lobits: $loBits\n";

my $numBits = $numComponents*2;

print "NUMBITS = $numBits\n";
my $i;
for ($i = 0; $i < $numBits; ++$i)
   {
   # default
   $SEVRs[$i*2] = "0";
   $SEVRs[($i*2)+1] = "0";

   if (((2**$i) & $hiBits))
      {
      # if this bit is important
      # then set its "bad" and "good" states
      print "use this bit: $i\n";
      my $bitVal = ($loBits & (2**$i));
      print "val of bit $i is $bitVal\n";
      if ($bitVal == 0)
         { print "setting val +1 to 1\n"; $SEVRs[($i*2)+1] = "1"; }
      else
         { print "setting val to 1\n"; $SEVRs[($i*2)] = "1"; }
      }
   else
      {   
      print "DON'T use this bit: $i\n";
      }
   }
print "=============\nLEAVING setDIDNsevrs\n";
}


#===============================================================
sub grabIBits ($$)
#===============================================================
{
   my $bits = shift;
   my $sevr = shift;

   my $maxBit;
   my $offset;
   my $i;
   my $pos = 0;


#   print "grabbing BI bits from $bits\n";

   $maxBit = 3;
   $offset = 4; 

   # all the set values, whether used or not
   # need to modify this so that it is more general
   for ($i = $maxBit + $offset; $i > $maxBit; --$i)
      {
      my $decBits = hex substr($bits,$i,1);
      whichSetIBits($decBits, $pos);
      ++$pos;
      } 

   $pos = 0;
   for ($i = $maxBit; $i >= 0; --$i)
      {
      my $decBits = hex substr($bits,$i,1);
      whichUseIBits($decBits, $sevr, $pos);
      ++$pos;
      } 
} 

#===============================================================
sub grabOBits ($$)
#===============================================================
{
   my $bits = shift;
   my $pulse = shift;

   my $maxBit;
   my $offset;
   my $i;
   my $pos = 0;


#   print "grabbing BO bits from $bits\n";

   $maxBit = 1; 
   $offset = 2;

   # all the set values, whether used or not
   # need to modify this so that it is more general
   for ($i = $maxBit + $offset; $i > $maxBit; --$i)
      {
      my $decBits = hex substr($bits,$i,1);
      whichSetOBits($decBits, $pos);
      ++$pos;
      } 

   $pos = 0;
   for ($i = $maxBit; $i >= 0; --$i)
      {
      my $decBits = hex substr($bits,$i,1);
      whichUseOBits($decBits, $pulse, $pos);
      ++$pos;
      } 
} 

#===============================================================
sub whichUseIBits ($$$)
#===============================================================
{
   my $decBits = shift;
   my $sevr = shift;
   my $pos = shift;
   my $bitUsed;

   my $i;
   for ($i=3; $i>=0; --$i)
      {
      $bitUsed = $i + (4 * $pos);
      if (($decBits & (2**$i)) == 0)
         { 
         next; 
         }
# the next step is:
#   O: if the bit is used, then push the bit number onto OBits.  
# and the step after that is to push the bit value onto IBitVals and OBitVals, but that's another adventure.
print "BIT USED IS $bitUsed\n";
      
      push @IModules, $primImods[$bitUsed];
      push @IBits, $primIchans[$bitUsed];
      push @IBitVals, $allIBitVals[$bitUsed];
      push @ISevrs, $sevr;

#      print "    BI: bit $bitUsed is used; module: $primImods[$bitUsed]  chan: $primIchans[$bitUsed]\n";

      }
}

#===============================================================
sub whichUseOBits ($$$)
#===============================================================
{
   my $decBits = shift;
   my $pulse = shift;
   my $pos = shift;
   my $bitUsed;

   my $i;
   for ($i=3; $i>=0; --$i)
      {
      $bitUsed = $i + (4 * $pos);
      if (($decBits & (2**$i)) == 0)
         { 
         next; 
         }
# the next step is:
#   O: if the bit is used, then push the bit number onto OBits.  
# and the step after that is to push the bit value onto IBitVals and OBitVals, but that's another adventure.
      
      push @OModules, $primHash{"DOM"};
      push @OBits, $primOchans[$bitUsed];
      push @OBitVals, $allOBitVals[$bitUsed];
      push @OPulses, $pulse;

# JROCK TESTING
my $numO = scalar @OModules;
print "pushed OModule count is $numO\n";

#      print "    BO: bit $bitUsed is used; module: $primHash{DOM}  chan: $primOchans[$bitUsed]\n";

      }
}

#===============================================================
sub whichSetIBits ($$)
#===============================================================
{
   my $decBits = shift;
   my $pos = shift;
   my $bitUsed;
   my $i;
   for ($i=3; $i>=0; --$i)
      {
      $bitUsed = $i + (4 * $pos);
      $allIBitVals[$bitUsed] = 0; 
      if (($decBits & (2**$i)) == 0)
         { next; }
      else
         { 
         $allIBitVals[$bitUsed] = 1; 
         #print "$bitUsed is 1\n";
         }

      }
}

#===============================================================
sub whichSetOBits ($$)
#===============================================================
{
   my $decBits = shift;
   my $pos = shift;
   my $bitUsed;
   my $i;
   for ($i=3; $i>=0; --$i)
      {
      $bitUsed = $i + (4 * $pos);
      $allOBitVals[$bitUsed] = 0; 
      if (($decBits & (2**$i)) == 0)
         { next; }
      else
         { 
         $allOBitVals[$bitUsed] = 1; 
         #print "$bitUsed is 1\n";
         }

      }
}

#===============================================================
sub getIModAndChan($$)
#===============================================================
{
  my $DIMunit = shift;
  my $micro = shift;
 
  if (defined ($DIMHash{$DIMunit}))
     { return; }

    my $select_dim_sql =  "select rtrim(micro) micro, ";
       $select_dim_sql .= "       rtrim(module) module, "; 
       $select_dim_sql .= "       rtrim(secn) secn, "; 
       $select_dim_sql .= "       rtrim(value) value, "; 
       $select_dim_sql .= "       rtrim(crate) crate "; 
       $select_dim_sql .= " from slc_data_view_all ";
       $select_dim_sql .= "where prim = 'DIM' and ";
       $select_dim_sql .= "      unit = $DIMunit and ";
       $select_dim_sql .= "      (secn = 'CTLW' or secn = 'MODT') and ";
       $select_dim_sql .= "      micro = '$micro ' ";
#print "dim select is $select_dim_sql\n";
    eval {
        $select_dim_st = $dbh->prepare($select_dim_sql);
        $select_dim_st->execute();
    };
    if ($@) {
        print "error in select from slc_data_view_all for DIM $DIMunit:$@\n";
        exit;
    }

    my $i = 0;
    my $crate = 0;
    my $module = 0;
    my $dimType = "N";

    while ($dim_row = $select_dim_st->fetchrow_hashref) {
        ++$i;

        my $thisSecn = $dim_row->{secn};
        my $thisVal = $dim_row->{value};
        
        if ($thisSecn eq "CTLW")
           {
           $crate = $dim_row->{crate};
           $module = $dim_row->{module};
           }
        else
           {
           # MODT gives module type
           if ($thisVal eq "1")
              { $dimType = "LDIM"; }
           else
              { $dimType = "IDIM"; }
           }
    }
    # assemble here
    $DIMHash{$DIMunit} = $crate . ":" . $module . ":" . $dimType;
    push @DIMModArr, $module; 
    push @DIMCrateArr, $crate;
}

#===============================================================
sub getOModAndChan($$)
#===============================================================
{
  my $DOMunit = shift;
  my $micro = shift;
 
    my $select_dom_sql =  "select rtrim(micro) micro, ";
       $select_dom_sql .= "       rtrim(module) module, "; 
       $select_dom_sql .= "       rtrim(crate) crate "; 
       $select_dom_sql .= " from slc_data_view_all ";
       $select_dom_sql .= "where prim = 'DOM' and ";
       $select_dom_sql .= "      unit = $DOMunit and ";
       $select_dom_sql .= "      secn = 'CTLW' and ";
       $select_dom_sql .= "      micro = '$micro ' ";
print "dom select is $select_dom_sql\n";
    eval {
        $select_dom_st = $dbh->prepare($select_dom_sql);
        $select_dom_st->execute();
    };
    if ($@) {
        print "error in select from slc_data_view_all for DOM $DOMunit:$@\n";
        exit;
    }

    my $i = 0;
    while ($dom_row = $select_dom_st->fetchrow_hashref) {
        ++$i;
        my $thisSecn = $dom_row->{secn};
        my $crate = $dom_row->{crate};
        my $module = $dom_row->{module};
     #print "DOM $DOMunit: $crate $module\n";
        $DOMModule = $module;
        $DOMCrate = $crate;
    }
}

#===============================================================
sub strPad($$)
#===============================================================
{
  my $strToPad = shift;
  my $len = shift;

  my $currLen = length($strToPad);
  if ($currLen >= $len)
     { return $strToPad; }
  else
     { return $strToPad . substr($blanks, 1, $len-$currLen); }
}

#===============================================================
sub IsubstFileLine($$$)
#===============================================================
{
# this adds on info for each state
my $stateName = shift;
my $sevr = shift;
my $stateCount = shift;

my $stateStr; # to return

my $crate; 
my $mod;
my $bit;
my $val;
my $pulse;
my $sevrStr;

my $zcrate; 
my $zmod;
my $zbit;
my $zval;
my $zpulse;
my $zsevrStr;

my $ocrate; 
my $omod;
my $obit;
my $oval;
my $opulse;
my $osevrStr;

my $numBits = @IModules;
switch ($sevr) 
   {
   case 0 { $sevrStr = "NO_ALARM"; }
   case 1 { $sevrStr = "MINOR"; }
   case 2 { $sevrStr = "MAJOR"; }
   }

$stateName = strPad($stateName, 8);
$sevrStr = strPad($sevrStr, 8);

$stateStr = ""; 
my $modType;

if ($numBits > 0)
   { $stateStr = " $stateName, $sevrStr, ";  } 

for ($i=0; $i<$numBits; ++$i)
   { 
      if (defined ($DIMHash{$IModules[$i]})) 
         { 
         ($crate, $mod, $modType) = split /:/, $DIMHash{$IModules[$i]}; 
         }
      else
         { $crate = -1; $mod = -1; } 

      $crate = strPad($crate, 2);
      $mod = strPad($mod, 4);
      $bit = strPad($IBits[$i], 3);
      $val = strPad($IBitVals[$i], 3);

      if ($stateCount != 2)
         {
         # this is an MBBI with > 2 states
         # also handles possible really strange 0 or 1-state situations
         $hasMBBIBits = 1;
         if ($i > 0)
            { $stateStr .= ","; }
         $stateStr .= $crate . ", " . $mod . ", " . $bit . ", " . $val ;
         }
      else
         {
         $hasBIBits = 1;
         # this is a BI
         # since these come from VMS in any old order, store them for output as a single string
         # in the correct order: Z before O
         if ($val =~ /0/)
            { 
           # $ZstateStr = $stateStr . $crate . " " . $mod . " " . $bit; 
            $ZstateName = $stateName;
            $ZsevrStr = $sevrStr;
            $Zcrate = $crate;
            $Zmod = $mod;
            $Zbit = $bit; 
            }
         else
            { 
           # $OstateStr = $stateStr . $crate . " " . $mod . " " . $bit; 
            $OstateName = $stateName;
            $OsevrStr = $sevrStr;
            $Ocrate = $crate;
            $Omod = $mod;
            $Obit = $bit; 
            }
         }
 
   }

   return $stateStr;
}
#===============================================================
sub OsubstFileLine($$$)
#===============================================================
{
# this adds on info for each state
my $stateName = shift;
my $pulse = shift;
my $stateCount = shift;

my $stateStr; # to return

my $crate; 
my $mod;
my $bit;
my $val;

my $zcrate; 
my $zmod;
my $zbit;
my $zval;
my $zpulse;
my $zsevrStr;

my $ocrate; 
my $omod;
my $obit;
my $oval;
my $opulse;
my $osevrStr;

$componentName = strPad($componentName, 8);
$stateName = strPad($stateName, 9);

$stateStr = ""; 

$numBits = @OModules;

if (defined ($DOMCrate) && defined ($DOMModule))
{
print "DOMCrate: $DOMCrate   DOMModule: $DOMModule\n";

if ($numBits > 0)
   { $stateStr = " $stateName, "; } 

for ($i=0; $i<$numBits; ++$i)
   {
   $bit = strPad($OBits[$i], 4);
   $val = strPad($OBitVals[$i], 4);
   $pulse = strPad($OPulses[$i], 4);

   # if this is a spare bit then don't use it
   if ($bit == -1)
      { $ZbitOut = -1; next; }

print "BIT TO OUTPUT: $bit $val $pulse\n";
   if ($stateCount != 2)
      { 
      $hasMBBOBits = 1;
      if ($i > 0)
        { $stateStr .= ","; }
      $stateStr .= " $bit, $val, $pulse"; 
      }
   else
      {
      $hasBOBits = 1;
      # this is a BO
      # since these come from VMS in any old order, store them for output as a single string
      # in the correct order: Z before O
print "VAL IS $val: ";
      if ($val =~ /0/)
         { 
print "GETTING ZPULSE $pulse\n";
         $ZstateNameOut = $stateName;
         $ZbitOut = $bit; 
         $Zpulse = $pulse
         }
      else
         { 
print "GETTING OPULSE $pulse\n";
         $OstateNameOut = $stateName;
         $ObitOut = $bit; 
         $Opulse = $pulse; 
         }
      }
   }
if (($numBits == 1) && ($stateCount != 2))
   { $stateStr .= "MBBO Extra Bit";   }
}
return $stateStr;

}

#===============================================================
sub db_connect 
#===============================================================
{
    #connect to database
    my $dbh;

    # Look up connection parameters in external db.properties file.
    # If a decryption key has been supplied, use blowfish algorithm
    # to decrypt the contents of the file.
    # SLACDEV NOW HAS MANUALLY UPDATABLE TABLES, FOR THIS PROJECT!

    my $db_host = "slac-oracle02";
    my $db_database = "SLACDEV";
    my $db_user = "nlcdev";
    my $db_password = "do~boson4";

    # Get db vendor-specific DBI connect string
    my $dsn = get_dbi_dsn($db_database, $db_host);

    eval {
        $dbh = DBI->connect($dsn,$db_user,$db_password,
                            {AutoCommit=>0, RaiseError=>1, PrintError=>0,
                             FetchHashKeyName=>'NAME_lc'});
    };
    if ($@) {
        print "Unable to connect to db $@\n";
        print "Exiting...\n";
        exit;
    }

    return $dbh;
}

#===============================================================
sub get_dbi_dsn 
#===============================================================
{
    my $db_database = $_[0];
    my $db_host = $_[1];

    return "DBI:Oracle:$db_database";
}

   
# get one device's stuff
# THIS IS FOR OUTPUT FOR SPREADSHEET, WHICH WILL BE USED TO GENERATE THE SUBST FILES
sub stuffForOneDevice($$$)
{
   my $PRIM = $_[0];
   my $MICRO = $_[1];
   my $UNIT = $_[2];

   my $didnBitNum = 0;

    %primHash = ();

    @IBSDs = ();
    @OBSDs = ();
    @SEVRs = ();
    @PULSEs = ();
    @statesPerComponent = ();
    @componentNames = ();
    @stateNames = ();
    @primImods = ();
    @primIchans = ();
    @primOchans = ();

    my %componentHash;

    $numComponents = 0;
    $numIBits = 0;
    $numOBits = 0;
print "getting STUFF FOR $PRIM $MICRO $UNIT\n";

    # ==========================================================
    # first the DEVICE PRIMARY
    my $select_ioc_sql =  "select rtrim(micro) micro, ";
       $select_ioc_sql .= "       rtrim(prim) prim, "; 
       $select_ioc_sql .= "       rtrim(unit) unit, "; 
       $select_ioc_sql .= "       rtrim(secn) secn, "; 
       $select_ioc_sql .= "       rtrim(value) value, "; 
       $select_ioc_sql .= "       local_index "; 
       $select_ioc_sql .= " from slc_data_view_all ";
       $select_ioc_sql .= "where prim = '$PRIM' and ";
       $select_ioc_sql .= "      unit = $UNIT and ";
       $select_ioc_sql .= "      micro = '$MICRO' ";
       $select_ioc_sql .= "order by secn, local_index"; 
#print "device select is $select_ioc_sql\n";
    eval {
        $select_ioc_st = $dbh->prepare($select_ioc_sql);
        $select_ioc_st->execute();
    };
    if ($@) {
        print "error in select from slc_data_view_all for $PRIM $MICRO $UNIT:$@\n";
        exit;
    }

    #outputTop();
    $i = 0;
    $SEVM1 = "0000";
    # get all rows for this device
    while ($dig_row = $select_ioc_st->fetchrow_hashref) {
        ++$i;

        $micro = $dig_row->{micro};
        $unit = $dig_row->{unit};

        $secn = $dig_row->{secn};
        $local_index = $dig_row->{local_index};
        $value = $dig_row->{value};

        if ($secn eq "IBIT")
           {
           if ($local_index%2 == 1)
              { push @primImods, $value; }
           else
              { push @primIchans, $value; }           
           }
        elsif ($secn eq "SEVM")
           { 
            push @SEVMs, substr($value, 21); 
            # capture the first value for use later
            if ($local_index == 1)
               {
               $SEVM1 = substr($value, 21);
               print "SEVM1: $SEVM1\n"; 
               }
           }
        elsif ($secn eq "OBIT")
           { push @primOchans, $value; }
        elsif ($secn eq "DIDN")
           { $primHash{"DODN"} = $value; }
        elsif ($secn eq "UNIT")
           { 
           switch ($local_index)
              {
              case 1 { $primHash{"DODN"} = $value; }
              case 2 { $primHash{"DODD"} = $value; }
              case 3 { $primHash{"DOM"} = $value; }
              }
           }
        #else
        #   { $primHash{$secn} = $value; }
    }
    if ($i == 0)
       { 
       print  "no data found for $PRIM $MICRO $UNIT\n";
       die "no data found for $PRIM $MICRO $UNIT\n"; 
       }

    # ==========================================================
    # now get the module and channel numbers for the i/o modules
    # DIMs:
    if (defined $primHash{DOM})
       {
       getOModAndChan($primHash{DOM}, $MICRO);
       }
    foreach my $dimUnit (@primImods)
       {
       if ($dimUnit > -1)
          { getIModAndChan($dimUnit, $MICRO) };
       }


    # ==========================================================

if (defined $primHash{DODD})
    {
    # next the DODD
    my $select_dodd_sql =  "select rtrim(micro) micro, ";
       $select_dodd_sql .= "       rtrim(prim) prim, "; 
       $select_dodd_sql .= "       rtrim(unit) unit, "; 
       $select_dodd_sql .= "       rtrim(secn) secn, "; 
       $select_dodd_sql .= "       rtrim(value) value, "; 
       $select_dodd_sql .= "       local_index "; 
       $select_dodd_sql .= " from slc_data_view_all ";
       $select_dodd_sql .= "where prim = 'DODD' and ";
       $select_dodd_sql .= "      unit = $primHash{DODD} and ";
       $select_dodd_sql .= "      micro = '$MICRO' ";
       $select_dodd_sql .= "order by secn, local_index"; 
#print "dodd select is: $select_dodd_sql\n";
    eval {
        $select_dodd_st = $dbh->prepare($select_dodd_sql);
        $select_dodd_st->execute();
    };
    if ($@) {
        print "error in select from slc_data_view_all for $PRIM $MICRO $UNIT:$@\n";
        exit;
    }

    #outputTop();
    while ($dodd_row = $select_dodd_st->fetchrow_hashref) {
        ++$i;

        $micro = $dodd_row->{micro};
        $secn = $dodd_row->{secn};
        $unit = $dodd_row->{unit};
        $local_index = $dodd_row->{local_index};
        $value = $dodd_row->{value};
#        print "$i: $secn $local_index $value\n";

        if ($secn eq "IBSD")
           { push @IBSDs, substr($value, 17); }
        elsif ($secn eq "OBSD")
           { push @OBSDs, substr($value, 21); }
        elsif ($secn eq "SEV")
           { push @SEVRs, substr($value, 24); }
        elsif ($secn eq "PLSE")
           { push @PULSEs, $value; }
        elsif ($secn eq "NSV")
           { push @statesPerComponent, $value; }
        elsif ($secn eq "NSC")
           { $numComponents = $value; }
        elsif ($secn eq "NIB")
           { $numIBits = $value; }
        elsif ($secn eq "NOB")
           { $numOBits = $value; }
    }
}

    # ==========================================================
#if (defined $primHash{DODD})
#{
    # next the DODN
my $dodnPRIM; if ($PRIM =~ /ACCS/)
   { $dodnPRIM = "DIDN"; }
else
   { $dodnPRIM = "DODN"; }
print "***** PRIM = $PRIM,  dodnPRIM = $dodnPRIM\n";
   
    my $select_dodn_sql =  "select rtrim(micro) micro, ";
       $select_dodn_sql .= "       rtrim(prim) prim, "; 
       $select_dodn_sql .= "       rtrim(unit) unit, "; 
       $select_dodn_sql .= "       rtrim(secn) secn, "; 
       $select_dodn_sql .= "       rtrim(value) value, "; 
       $select_dodn_sql .= "       local_index "; 
       $select_dodn_sql .= " from slc_data_view_all ";
       $select_dodn_sql .= "where prim = '" . $dodnPRIM. "' and ";
       $select_dodn_sql .= "      unit = $primHash{DODN} and ";
       $select_dodn_sql .= "      micro = 'VX30' ";
       $select_dodn_sql .= "order by secn, local_index"; 
print "didn select is: $select_dodn_sql\n";
    eval {
        $select_dodn_st = $dbh->prepare($select_dodn_sql);
        $select_dodn_st->execute();
    };
    if ($@) {
        print "error in select from slc_data_view_all for $PRIM $MICRO $UNIT:$@\n";
        exit;
    }

    #outputTop();
    while ($dodn_row = $select_dodn_st->fetchrow_hashref) {
        ++$i;

        $micro = $dodn_row->{micro};
        $secn = $dodn_row->{secn};
        $unit = $dodn_row->{unit};
        $local_index = $dodn_row->{local_index};
        $value = $dodn_row->{value};
# ====== DIDN CHANGES =================
# if it's a DIDN, fake out the component and state stuff
# AH HA!!!  FOR EACH STATE, SET IBSD TO 0001, 0002, 0004, 0008 depending on which of the states it is
if ($dodnPRIM eq "DIDN")
        {
        if ($secn eq "INAM")
           { 
           # for DIDNs, the list of modules/bits is parallel to the list of states.
           my $bitMask = 2**$didnBitNum;
           ++$didnBitNum;

           push @componentNames, $value; 
           push @statesPerComponent, "2"; 
           push @IBSDs, "000" . $bitMask . "000" . $bitMask; 
           push @OBSDs, "none"; 
           push @SEVRs, "0"; 
           push @PULSEs, "0"; 
           push @IBSDs, "000" . $bitMask . "0000"; 
           push @OBSDs, "none"; 
           push @SEVRs, "0"; 
           push @PULSEs, "0"; 

           $numIBits = 1;
           ++$numComponents; 
           }
        elsif ($secn eq "ILBL")
           { push @stateNames, $value; }
   }
else
   {   
        if ($secn eq "SCNM")
           { push @componentNames, $value; }
        elsif ($secn eq "SVNM")
           { push @stateNames, $value; }
   }
# ====== END =================
    }
#}
    $arrLen = @componentNames;
    # ==========================================================
    # now combine all into the hash structure for clarity
#    print "creating hash...\n";
    my $startState = 0;
    my $bits = "";

# get severities for DIDNs
# I THINK I NEED TO SET ANOTHER ARRAY HERE, THEN GRAB THE SEVRS LATER.
# @IBits doesn't work yet - it's defined later
    if ($dodnPRIM eq "DIDN")
       { 
print "running setDIDNSevrs\n";
       setDIDNSevrs;
       }

    for ($i = 0; $i < $numComponents; ++$i)
       {
       for ($j = 0; $j < $statesPerComponent[$i]; ++$j)
          {
          if (defined $componentNames[$i])
             { 
             if (!($IBSDs[$j+$startState] eq "00000000"))
                { $bits .= "I"; }
             if (!($OBSDs[$j+$startState] eq "0000"))
                { $bits .= "O"; }

             $bits .= ":I" . $IBSDs[$j+$startState]; 
             $bits .= ":O" . $OBSDs[$j+$startState]; 
             if (defined ($stateNames[$j+$startState]))
                {
                print "COMPONENT: $componentNames[$i]  STATE: $stateNames[$j+$startState]  ";
                print "   bits $bits; sevr $SEVRs[$j+$startState]; pulse $PULSEs[$j+$startState]\n";
                print "   DOMModule: $DOMModule   DOMCrate: $DOMCrate\n";

                #decode severity
                my $svr = $SEVRs[$j+$startState];
                my $svrStr;
                switch ($svr) 
                {
                case 0 { $svrStr = "NO_ALARM"; }
                case 1 { $svrStr = "MINOR"; }
                case 2 { $svrStr = "MAJOR"; }
                }

#my $DIGLine = "$MICRO,$PRIM,$UNIT,$componentNames[$i],$stateNames[$j+$startState],$bits,$svrStr,$PULSEs[$j+$startState]";
my $DIGLine0;

if ($dodnPRIM eq "DODN")
   { $DIGLineO = "OUT," . "$MICRO,$PRIM,$UNIT,$componentNames[$i],$statesPerComponent[$i],$stateNames[$j+$startState],$bits,$PULSEs[$j+$startState]"; }

my $DIGLineI = "INP," . "$MICRO,$PRIM,$UNIT,$componentNames[$i],$statesPerComponent[$i],$stateNames[$j+$startState],$bits,$svrStr";
#now decode bits for the state 
            my $stateName = $stateNames[$j+$startState];
            my $sevrStr;
            # reinitialize bit arrays 
            @IBits=();
            @IBitVals=();
            @IModules=();
            @ISevrs=();
            @OBits=();
            @OModules=();
            @OBitVals=();
            @OPulses=();

print "STATENAME   $stateName\n ";
#            $stateBitsAll = $componentHash{$compName}{$stateName};
#print "STATEBITSALL: $stateBitsAll\n";
            my ($IorO, $inBits, $outBits, $sevr, $pulse) = split/:/, $bits;
            #print "SEE THIS:  IO: $IorO  IB: $inBits  OB: $outBits  S: $sevr  P: $pulse\n";

            # find out which bits are used and their value
            # populate IBits, IModules, IBitVals
            $inBits = substr($inBits, 1);  # remove the leading "I"

print "INBITS is $inBits\n";
            grabIBits($inBits, $sevr);
print "AFTER grabIBits m:@IModules  b:@IBits  v:@IBitVals\n";

            # populate OBits, OModules, OBitVals
            $outBits = substr($outBits, 1);  # remove the leading "O"
if (defined ($pulse))
{
            $pulse = substr($pulse, 1);  # remove the leading "P"
}
else 
{$pulse = 0;}
#=================== DIDN CHANGE
if ($dodnPRIM eq "DODN")
{
            grabOBits($outBits, $pulse);
}

# now output the dims and doms
my $numIB = 0;
my $numOB = 0;
$numIB = scalar @IModules;
$numOB = scalar @OModules;
#my $numDIMs = scalar @DIMModArr;
#print "NUM DIMS is $numDIMs\n";

#$DIGLine .= ",DOM:$numOB";
my $c = 0;
my $modUnit;
#my $bitsLine;
my $bitsLineO;
my $bitsLineI;
my $howManyOBits = 0;
my $howManyIBits = 0;
my $modType;

# NEW: THIS IS FOR OUTPUT BITS
for ($c=0; $c<$numOBits; ++$c)
   {
   if (defined ($OBits[$c]))
      {
         $bit = $OBits[$c];
         $val = $OBitVals[$c];
         $bitsLineO .= ",DOM:$primHash{DOM},$DOMCrate,$DOMModule,$bit,$val";
         ++$howManyOBits;
      # CHANGE: only output if defined!
      print "OUTPUT BIT $bit VAL $val\n";
      }
   }

$c = 0;
#$DIGLine .= ",I:$numIB";
for ($c=0; $c<$numIBits; ++$c)
   {
#     if (defined ($DIMHash{$IModules[$c]}))
# set to -1, in case they're not defined (IBIT = -1)
     if (defined ($IModules[$c]))
         {
         # get the DIM crate and module, except if they are -1 (i.e. IBIT = -1)
         if (defined ($DIMHash{$IModules[$c]}))
            {
            ($crate, $mod, $modType) = split /:/, $DIMHash{$IModules[$c]};
            $modUnit = $IModules[$c];
            }
         else
            {
            $crate = -1;
            $mod = -1;
            $modUnit = -1;
            }

         $bit = $IBits[$c];
         $val = $IBitVals[$c];
         $bitsLineI .= ",$modType:$modUnit,$crate,$mod,$bit,$val";
         ++$howManyIBits;
print "INPUT CRATE $crate MOD $mod BIT $bit VAL $val\n";
         }
      else
         { $crate = -1; $mod = -1; }

#         $bit = $IBits[$c];
#         $val = $IBitVals[$c];
#         $DIGLine .= ",$crate,$mod,$bit,$val";
#print "INPUT CRATE $crate MOD $mod BIT $bit VAL $val\n";
   }
print "num O bits: $howManyOBits   num I bits: $howManyIBits\n";
$DIGLineO .= ",$howManyOBits";
$DIGLineI .= ",$howManyIBits";
if ($howManyOBits > 0)
   { $DIGLineO .= "$bitsLineO\n"; } 
if ($howManyIBits > 0)
   { $DIGLineI .= "$bitsLineI\n"; }  

if ($howManyIBits > 0)
   { print DIGLIST $DIGLineI; }
if ($howManyOBits > 0)
   { print DIGLIST $DIGLineO; }

                $componentHash{$componentNames[$i]}{$stateNames[$j+$startState]} = $bits . ":S" . $SEVRs[$j+$startState] . ":" . "P" . $PULSEs[$j+$startState]; }
                } 
             $bits = "";
          }
          $startState += $statesPerComponent[$i];
       } 
}

#===============================================================
# main code starts here
#===============================================================
print "STARTING\n";
if ($#ARGV == 1) 
   {
   my $which = $ARGV[0];
   my $substFilePrefix = $ARGV[1];
print "$which $substFilePrefix\n";
   if ($which eq "TOP")
      { outputTops($substFilePrefix); exit; }

   if ($which eq "END")
      { outputEnds($substFilePrefix); exit; }

   die "Please specify TOP or END with filename, or output filename, primary, micro, unit, list of components\nExiting!\n"; 
   }

#if ($#ARGV < 4) { die "Please specify output filename, primary, micro, unit, list of components\nExiting!\n"; }

#   my $substFilePrefix = $ARGV[0];
#   $PRIM = $ARGV[1];
#   $MICRO = $ARGV[2];
#   $UNIT = $ARGV[3];
#   $COMP = "ALL";
print "====================================================================\n";
#print "$PRIM:$MICRO:$UNIT\n";
# for original names output
#$ORIGPRIM = $PRIM;
#   if ($#ARGV > 3)
#      { 
#      @comps = splice @ARGV, 4;
#      #$COMP = $ARGV[4]; 
#      }
#die "Could not open output file\n" unless (open(DIGLIST,'>'. "DIGList2030.txt"));
die "Could not open output file\n" unless (open(DIGLIST,'>'. "DIGList1718.txt"));

    if (!$dbh) {
        $dbh = db_connect();
    }
    if (!$egu_dbh) {
        $egu_dbh = db_connect();
    }

    # get all digital device pmus
    # assumption:  all digital devices have an IBIT secondary
    my $dev_row;
    my $select_pmu_sql;
    my $select_pmu_st;
    $select_pmu_sql =  "select distinct rtrim(micro) micro, ";
       $select_pmu_sql .= "       rtrim(prim) prim, ";
       $select_pmu_sql .= "       rtrim(unit) unit ";
       $select_pmu_sql .= " from slc_data_view_all ";
       $select_pmu_sql .= " where secn = 'IBIT' and ";
#       $select_pmu_sql .= "       prim = 'ACCS' and ";
#       $select_pmu_sql .= "      (micro like 'LI2%' or micro like 'LI30%') ";
       $select_pmu_sql .= "      (micro = 'LI17' or micro = 'LI18') ";
#       $select_pmu_sql .= "      micro like 'LI21' ";
       $select_pmu_sql .= "order by micro, prim";
print "device select is $select_pmu_sql\n";
    eval {
        $select_pmu_st = $dbh->prepare($select_pmu_sql);
        $select_pmu_st->execute();
    };
    if ($@) {
        print "error in select from slc_data_view_all for devices:$@\n";
        exit;
    }

    #outputTop();
    $i = 0;
# get all rows for all micros, prims

    while ($dev_row = $select_pmu_st->fetchrow_hashref) 
       {
       $MICRO = $dev_row->{micro};
       $UNIT = $dev_row->{unit};
       $PRIM = $dev_row->{prim};

       print "gathering data for $PRIM $MICRO $UNIT\n";
       $DOMModule = -1;
       $DOMCrate = -1;
       %DIMHash = ();

       @DIMModArr = ();
       @DIMCrateArr = ();

print "$MICRO $PRIM $UNIT\n";
       stuffForOneDevice($PRIM, $MICRO, $UNIT);
       }

    $dbh->rollback();
    $dbh->disconnect();
    
    print "Done\n";

