#!/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 $MICRO;
my $ldimCount = 0;
my $idimCount = 0;


#===============================================================
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~higgs3";

    # 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";
}

#===============================================================
sub addLeadingZero($)
#===============================================================
{
   my $inStr = shift;
   $strLen = length $inStr;

   if (($strLen == 0) || ($strLen > 1))
      { return $inStr; }

   return "0" . $inStr;
}

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

   # print "RPAD: $strToPad\n";
   my $blanks = "                                                                       ";

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

   return $strToPad;
}
   
#===============================================================
sub checkModuleType($)
#===============================================================
{
   my $mUnit = shift;

   if ($mUnit eq "") { return; }

   my ($moduleType,$moduleUnit) = split/:/, $mUnit;

   if ($moduleType =~ /LDIM/)
      { ++$ldimCount; }
   if ($moduleType =~ /IDIM/)
      { ++$idimCount; }
} 

#===============================================================
sub outputTops ()
#  dev area unit attr lims1 lims2 scal1 scal2 egu
#===============================================================
{
    # CAMACFILE
    # IDIMPORT
    # IDIMCHAN
    # B1S2
    # B2S2
    # B2S3
    # B2S4

   print CAMACFILE "# camac info\n";
   print CAMACFILE "file ../../Common/camacModule.template\n";
   print CAMACFILE "{\n";
   print CAMACFILE "pattern { LOCA,  CRAT, SLOT,  CRLOC, MODEL, NSLOT, NCHAN  }\n";

   print IDIMPORT "# idim port info\n";
   print IDIMPORT "file ../../DigitalIn/idimPort.template\n";
   print IDIMPORT "{\n";
   print IDIMPORT "pattern { MICRO,  CRAT, SLOT,  ADDR  }\n";

   print IDIMCHAN "# idim channel info\n";
   print IDIMCHAN "file ../../DigitalIn/idimChannel.template\n";
   print IDIMCHAN "{\n";
   print IDIMCHAN "pattern { MICRO,  CRAT, SLOT,  CHAN,  ALIAS  }\n";

   print B1S2 "# 1 bit 2 state\n";
   print B1S2 "file ../../DigitalIn/digitalIn1Bit2State.template\n";
   print B1S2 "{\n";
   print B1S2 "pattern { ";
   print B1S2 "PRIM, ";
   print B1S2 "LOCA, ";
   print B1S2 "UNIT, ";
   print B1S2 "ATTR, ";
   print B1S2 "DPRIM, ";
   print B1S2 "MICRO, ";
   print B1S2 "DUNIT, ";
   print B1S2 "DNAME, ";
   print B1S2 "CRAT, ";
   print B1S2 "SLOT, ";
   print B1S2 "ADDR, ";
   print B1S2 "BITX, ";
   print B1S2 "ZNAM, ";
   print B1S2 "ZSEV, ";
   print B1S2 "ONAM, ";
   print B1S2 "OSEV ";
   print B1S2 "}\n";

   print B2S2 "# 2 bit 2 state\n";
   print B2S2 "file ../../DigitalIn/digitalIn2Bit2State.template\n";
   print B2S2 "{\n";
   print B2S2 "pattern { ";
   print B2S2 "PRIM,  ";
   print B2S2 "LOCA,  ";
   print B2S2 "UNIT,  ";
   print B2S2 "ATTR,  ";
   print B2S2 "DPRIM,  ";
   print B2S2 "MICRO,  ";
   print B2S2 "DUNIT,  ";
   print B2S2 "DNAME,  ";
   print B2S2 "CRAT1,  ";
   print B2S2 "SLOT1,  ";
   print B2S2 "ADDR1,  ";
   print B2S2 "BIT1X,  ";
   print B2S2 "CRAT2,  ";
   print B2S2 "SLOT2,  ";
   print B2S2 "ADDR2,  ";
   print B2S2 "BIT2X,  ";

   print B2S2 "STATE1,  ";
   print B2S2 "SEVR1,  ";
   print B2S2 "S1VAL1,  ";
   print B2S2 "S1VAL2,  ";

   print B2S2 "STATE2,  ";
   print B2S2 "SEVR2,  ";
   print B2S2 "S2VAL1,  ";
   print B2S2 "S2VAL2  ";

   print B2S2 " }\n";

   print B2S3 "# 2 bit 3 state\n";
   print B2S3 "file ../../DigitalIn/digitalIn2Bit3State.template\n";
   print B2S3 "{\n";
   print B2S3 "pattern { ";
   print B2S3 "PRIM,  ";
   print B2S3 "LOCA,  ";
   print B2S3 "UNIT,  ";
   print B2S3 "ATTR,  ";
   print B2S3 "DPRIM,  ";
   print B2S3 "MICRO,  ";
   print B2S3 "DUNIT,  ";
   print B2S3 "DNAME,  ";
   print B2S3 "CRAT1,  ";
   print B2S3 "SLOT1,  ";
   print B2S3 "ADDR1,  ";
   print B2S3 "BIT1X,  ";
   print B2S3 "CRAT2,  ";
   print B2S3 "SLOT2,  ";
   print B2S3 "ADDR2,  ";
   print B2S3 "BIT2X,  ";

   print B2S3 "STATE1,  ";
   print B2S3 "SEVR1,  ";
   print B2S3 "S1VAL1,  ";
   print B2S3 "S1VAL2,  ";

   print B2S3 "STATE2,  ";
   print B2S3 "SEVR2,  ";
   print B2S3 "S2VAL1,  ";
   print B2S3 "S2VAL2,  ";

   print B2S3 "STATE3,  ";
   print B2S3 "SEVR3,  ";
   print B2S3 "S3VAL1,  ";
   print B2S3 "S3VAL2  ";

   print B2S3 " }\n";

   print B2S4 "# 2 bit 4 state\n";
   print B2S4 "file ../../DigitalIn/digitalIn2Bit4State.template\n";
   print B2S4 "{\n";
   print B2S4 "pattern { ";
   print B2S4 "PRIM,  ";
   print B2S4 "LOCA,  ";
   print B2S4 "UNIT,  ";
   print B2S4 "ATTR,  ";
   print B2S4 "DPRIM,  ";
   print B2S4 "MICRO,  ";
   print B2S4 "DUNIT,  ";
   print B2S4 "DNAME,  ";
   print B2S4 "CRAT1,  ";
   print B2S4 "SLOT1,  ";
   print B2S4 "ADDR1,  ";
   print B2S4 "BIT1X,  ";
   print B2S4 "CRAT2,  ";
   print B2S4 "SLOT2,  ";
   print B2S4 "ADDR2,  ";
   print B2S4 "BIT2X,  ";

   print B2S4 "STATE1,  ";
   print B2S4 "SEVR1,  ";
   print B2S4 "S1VAL1,  ";
   print B2S4 "S1VAL2,  ";

   print B2S4 "STATE2,  ";
   print B2S4 "SEVR2,  ";
   print B2S4 "S2VAL1,  ";
   print B2S4 "S2VAL2,  ";

   print B2S4 "STATE3,  ";
   print B2S4 "SEVR3,  ";
   print B2S4 "S3VAL1,  ";
   print B2S4 "S3VAL2,  ";

   print B2S4 "STATE4,  ";
   print B2S4 "SEVR4,  ";
   print B2S4 "S4VAL1,  ";
   print B2S4 "S4VAL2  ";

   print B2S4 " }\n";

   print B3S2 "# 3 bit 2 state\n";
   print B3S2 "file ../../DigitalIn/digitalIn3Bit2State.template\n";
   print B3S2 "{\n";
   print B3S2 "pattern { ";
   print B3S2 "PRIM,  ";
   print B3S2 "LOCA,  ";
   print B3S2 "UNIT,  ";
   print B3S2 "ATTR,  ";
   print B3S2 "DPRIM,  ";
   print B3S2 "MICRO,  ";
   print B3S2 "DUNIT,  ";
   print B3S2 "DNAME,  ";
   print B3S2 "CRAT1,  ";
   print B3S2 "SLOT1,  ";
   print B3S2 "ADDR1,  ";
   print B3S2 "BIT1X,  ";
   print B3S2 "CRAT2,  ";
   print B3S2 "SLOT2,  ";
   print B3S2 "ADDR2,  ";
   print B3S2 "BIT2X,  ";
   print B3S2 "CRAT3,  ";
   print B3S2 "SLOT3,  ";
   print B3S2 "ADDR3,  ";
   print B3S2 "BIT3X,  ";

   print B3S2 "STATE1,  ";
   print B3S2 "SEVR1,  ";
   print B3S2 "S1VAL1,  ";
   print B3S2 "S1VAL2,  ";
   print B3S2 "S1VAL3,  ";

   print B3S2 "STATE2,  ";
   print B3S2 "SEVR2,  ";
   print B3S2 "S2VAL1,  ";
   print B3S2 "S2VAL2  ";
   print B3S2 "S2VAL3  ";

   print B3S2 " }\n";

   print KLYSMAG "# KlysMag\n";
   print KLYSMAG "file ../../DigitalIn/digitalInKlysMagBulk.template\n";
   print KLYSMAG "{\n";
   print KLYSMAG "pattern { ";
   print KLYSMAG "PRIM,  ";
   print KLYSMAG "LOCA,  ";
   print KLYSMAG "UNIT,  ";
   print KLYSMAG "ATTR,  ";
   print KLYSMAG "DPRIM,  ";
   print KLYSMAG "MICRO,  ";
   print KLYSMAG "DUNIT,  ";
   print KLYSMAG "DNAME  ";

   print KLYSMAG " }\n";

}

#===============================================================
sub outputEnds ()
#===============================================================
{
    # CAMACFILE
    # IDIMPORT
    # IDIMCHAN
    # B1S2
    # B2S2
    # B2S3
    # B2S4

   print CAMACFILE "}\n\n";
   print IDIMPORT "}\n\n";
   print IDIMCHAN "}\n\n";
   print B1S2 "}\n\n";
   print B2S2 "}\n\n";
   print B2S3 "}\n\n";
   print B2S4 "}\n\n";
   print B3S2 "}\n\n";
   print KLYSMAG "}\n\n";

}

#===============================================================
# main code starts here
#===============================================================
print "STARTING\n";

if ($#ARGV < 1) { die "Please specify cvs filename and micro!\n"; }

   die "Could not open csv file\n" unless (open(CSV, $ARGV[0]));
   $MICRO = $ARGV[1];

   print "generating files for micro $MICRO from file $ARGV[0]\n";

   my @lines = <CSV>;
   my $line;
   close(CSV);

   $TFname = $MICRO . "camacModuleDig" . ".substitutions";
   die "Could not open $TFname\n" unless (open(CAMACFILE, '>'.$TFname));
   $TFname = $MICRO . "idimPort" . ".substitutions";
   die "Could not open $TFname\n" unless (open(IDIMPORT, '>'.$TFname));
   $TFname = $MICRO . "idimChannel" . ".substitutions";
   die "Could not open $TFname\n" unless (open(IDIMCHAN, '>'.$TFname));
   $TFname = $MICRO . "digital1Bit2State" . ".substitutions";
   die "Could not open $TFname\n" unless (open(B1S2, '>'.$TFname));
   $TFname = $MICRO . "digital2Bit2State" . ".substitutions";
   die "Could not open $TFname\n" unless (open(B2S2, '>'.$TFname));
   $TFname = $MICRO . "digital2Bit3State" . ".substitutions";
   die "Could not open $TFname\n" unless (open(B2S3, '>'.$TFname));
   $TFname = $MICRO . "digital2Bit4State" . ".substitutions";
   die "Could not open $TFname\n" unless (open(B2S4, '>'.$TFname));
   $TFname = $MICRO . "digital3Bit2State" . ".substitutions";
   die "Could not open $TFname\n" unless (open(B3S2, '>'.$TFname));
   $TFname = $MICRO . "digitalInKlysMagBulk" . ".substitutions";
   die "Could not open $TFname\n" unless (open(KLYSMAG, '>'.$TFname));

   my $lineCount = 0;
  
   outputTops;

   my $currMicro = "none";
   my $currSprim = "none";
   my $currSunit = "none";
   my $currcomponent = "none";
   my $compNum = 0;
   my $stateNum = 0;

   my $currNumStates = 0;
   my $currNumBits = 0;

   my $outFile;
   my $outType = "NONE";
   my $componentLine = "";
   my $componentEName = "";
   my $badComponent = 0;
   my $badMsg = "BAD MSG ";

   my %moduleHash = ();
   my %bitHash = ();
   my %allBitsHash = ();
   my $i;

   my $currKlysMag = "none";
   my $thisKlysMag = "none";

   my $moduleDescr1 = "none";
   my $moduleDescr2 = "none";
   my $moduleDescr3 = "none";
   my $bitDescr1 = "none";
   my $bitDescr2 = "none";
   my $bitDescr3 = "none";

   my $bit1x;
   my $bit2x;
   my $bit3x;

   # bad component and bad msg is set if:
   #   - number of bits/states differs amongst the states for the component
   #   - number of bits/states doesn't correspond to a known bit/state configuration (i.e. template file) 
   #   - module/slot/bitnums differ amongst the states: THIS ONE IS NOT DONE YET

# there is one file-line per state, so multiple file-lines per component
# file is sorted by: micro, prim, unit, component, value1 (so that for 1 bit 2 state components, the 0 will come first)
# (i.e. ZNAM before ONAM)
### PROCESS EACH INPUT LINE ###
   foreach $line (@lines)
      {
      ++$lineCount;
      if ($lineCount == 1)
         { next; }
      chomp $line;
      #print "$line\n";

# example:
#OLD: INP,LI17,ACCC,16,DC,OFF,KLYS,LI17,1,FOCUSBULK_STATE,OFF,YES,MAJOR,2,IO:I00080000:O0101,MAJOR,1,IDIM:106,1,6,19,0,,,,,,,,,,

#NEW: INP,LI17,ACCC,16,DC,OFF,KLYS,LI17,1,FOCUSBULK_STATE,OFF,YES,2,IO:I00080000:O0101,MAJOR,1,IDIM:106,1,6,19,0,,,,,,,,,,

# new:
      my($IorO,$micro,$Sprim,$Sunit,$component,$stateStr,$Eprim,$Elocation,$Eunit,$attribute,$EState,$in_use,$numStates,$IOString,$SevrPls,$numBits,$Munit1,$crate1,$slot1,$bit1,$value1,$Munit2,$crate2,$slot2,$bit2,$value2,$Munit3,$crate3,$slot3,$bit3,$value3) = split/,/, $line;

      # first things first: add leading 0's to slot
      $slot1 = addLeadingZero($slot1);
      $slot2 = addLeadingZero($slot2);
      $slot3 = addLeadingZero($slot3);
      # print "SLOTS $slot1 $slot2 $slot3\n";

      # create mod 16 hex bits
      $bit1x = 0;
      $bit1x = sprintf("%X", $bit1%16);
      if (!($bit2 eq "")) { $bit2x = sprintf("%X", $bit2%16); } else { $bit2x = 0; }
      if (!($bit3 eq "")) { $bit3x = sprintf("%X", $bit3%16); } else { $bit3x = 0; }
      # print "HEX BITS $bit1x $bit2x $bit3x\n";

print "READ: $micro $Sprim $Sunit\n";
      # FIRST DO OMISSIONS AND SPECIAL CASE (KMAG)
      # process only inputs
      # input file must be sorted by In-or-Out
#      if ($IorO eq "OUT")
      # skip if OUTPUT, or if not the micro of current interest, or in_use is not yes
      if ($IorO eq "OUT")
         { print "output chan; skipping\n"; next; }
      if (!($micro eq $MICRO))
         { print "not doing this micro now; skipping\n"; next; }
      if ($in_use eq "NO")
         { print "not in use; skipping\n"; next; }
       
print "Processing...\n";
      # klystron magnet bulk supply interlock status (in_use=KMAG)
      # assuming one spreadsheet row (one component) per KMAG only
      if ($in_use eq "KMAG")
         {
         $thisKlysMag = $Eprim.":".$Elocation.":".$Eunit.":".$attribute.":".$Sprim.":".$micro.":".$Sunit.":".$component;
         if (!($thisKlysMag eq $currKlysMag))
            {
            print KLYSMAG "        { ";
            print KLYSMAG "$Eprim,  ";
            print KLYSMAG "$Elocation,  ";
            print KLYSMAG "$Eunit,  ";
            print KLYSMAG "$attribute,  ";
            print KLYSMAG "$Sprim,  ";
            print KLYSMAG "$micro,  ";
            print KLYSMAG "$Sunit,  ";
            print KLYSMAG "$component  ";
            print KLYSMAG " }\n";
            
            $currKlysMag = $thisKlysMag;
            }
         next;
         }

      ### ACCUMULATE COMPONENT LEVEL ###
      # if micro, prim, unit and component has changed, then we're in a new component
      if (!($micro eq $currMicro) ||
          !($Sprim eq $currSprim) ||
          !($Sunit eq $currSunit) ||
          !($component eq $currcomponent))
         {
         # check the previous component for accumulated errors over all states
         if ($ldimCount > 0 && $idimCount > 0)
            {$badComponent = 1; $badMsg .= "both IDIM and LDIM in this component. "; }

         if (scalar(keys %allBitsHash) > 1)
            {$badComponent = 1; $badMsg .= "More than one set of bits used by states. "; }

         # then, output the previous component, or error message if it is BAAAD for some reason.
         if ($badComponent == 1)
            { print "BAD COMPONENT! $currMicro $currSprim $currSunit $currcomponent:  $badMsg\n"; }
         else
            {
            if ($compNum > 0)
               { print $outFile "$componentLine }\n"; }
            }

         # reset variables for the current component
         ++$compNum;
         $badComponent = 0;
         $badMsg = "BAD MSG ";
         $stateNum = 0; 
         $ldimCount = 0; $idimCount = 0;
         %allBitsHash = ();
         
         # figure out which template to use, based on number of bits and states
         if ($numBits == 1)
            { 
            switch($numStates)
               {
               case 2 { $outFile = *B1S2; $outType = "B1S2"; }
               else { $badMsg .= "$numBits bits and $numStates states: no file for this case!  "; $badComponent = 1; }
               }
            }
         elsif ($numBits == 2)
            { 
            switch($numStates)
               {
               case 2 { $outFile = *B2S2; $outType = "B2S2"; }
               case 3 { $outFile = *B2S3; $outType = "B2S3"; }
               case 4 { $outFile = *B2S4; $outType = "B2S4"; }
               else { $badMsg .= "$numBits bits and $numStates states: no file for this case!  "; $badComponent = 1; }
               }
            }
         elsif ($numBits == 3)
            { 
            switch($numStates)
               {
               case 2 { $outFile = *B3S2; $outType = "B3S2"; }
               else { $badMsg .= "$numBits bits and $numStates states: no file for this case!  "; $badComponent = 1; }
               }
            }
         else 
            { $badMsg .= "$numBits bits and $numStates states: no file for this case!  "; $badComponent = 1; }

         # print "$Eprim, $Elocation, $Eunit, $component $stateStr NUM BITS: $numBits   NUM STATES: $numStates\n";

         # gather the things that are component-specific
         $currMicro = $micro;
         $currSprim = $Sprim;
         $currSunit = $Sunit;
         $currcomponent = $component;
         $currNumBits = $numBits;
         $currNumStates = $numStates;

         # and start accumulating the component line 
         #for reference, from above      my($IorO,$micro,$Sprim,$Sunit,$component,$stateStr,$Eprim,$Elocation,$Eunit,$attribute,$EState,$in_use,$numStates,$IOString,$SevrPls,$numBits,$Munit1,$crate1,$slot1,$bit1,$value1,$Munit2,$crate2,$slot2,$bit2,$value2,$Munit3,$crate3,$slot3,$bit3,$value3) = split/,/, $line;
         $componentLine = "        { $Eprim, $Elocation, $Eunit,  $attribute, $Sprim, $micro,  $Sunit, $component "; 
         $componentEName = $Eprim . ":" . $Elocation . ":" . $Eunit . ":" . $attribute;
         }

      ### ACCUMULATE MICRO LEVEL MODULE INFO - check and record each file line's module  ###
      # module and bit hashes are used to output this micro's idim*.substitution files at the end.
      # these hashes are accumulated for the entire micro
      # so, add to module hashes, if this is the first time we've seen this module
      # and initialize 32 spare bits for each newly encountered module
      $moduleDescr1 = "none";
      $moduleDescr2 = "none";
      $moduleDescr3 = "none";
      $bitDescr1 = "none";
      $bitDescr2 = "none";
      $bitDescr3 = "none";

      my $moduleDescr1 = $micro . ":" . $crate1 . ":" . $slot1;
      # print "MODULE1 : $moduleDescr1\n";
      if (!(defined $moduleHash{$moduleDescr1}))
         { 
         $moduleHash{$moduleDescr1} = "defined"; 
         for ($i=0; $i<32; ++$i)
            {
            my $bitDescr = $moduleDescr1 . ":" . $i;
            $bitHash{$bitDescr} = "SPARE";
            }
         }

      if (!($crate2 eq ""))
         { 
         $moduleDescr2 = $micro . ":" . $crate2 . ":" . $slot2; 
         # print "MODULE2 : $moduleDescr2\n";
         if (!(defined $moduleHash{$moduleDescr2}))
            { 
            $moduleHash{$moduleDescr2} = "defined"; 
            for ($i=0; $i<32; ++$i)
               {
               my $bitDescr = $moduleDescr2 . ":" . $i;
               $bitHash{$bitDescr} = "SPARE";
               }
            }
         }

      if (!($crate3 eq ""))
         { 
         $moduleDescr3 = $micro . ":" . $crate3 . ":" . $slot2; 
         # print "MODULE3 : $moduleDescr3\n";
         if (!(defined $moduleHash{$moduleDescr3}))
            {  
            $moduleHash{$moduleDescr3} = "defined"; 
            for ($i=0; $i<32; ++$i)
               {
               my $bitDescr = $moduleDescr3 . ":" . $i;
               $bitHash{$bitDescr} = "SPARE";
               }
            }
         }

      ### ACCUMULATE STATE LEVEL ###
      # NOW, the state stuff (each file-line)
      ++$stateNum;

      # check for LDIM and IDIM in the same component (bad)
      checkModuleType($Munit1);
      checkModuleType($Munit2);
      checkModuleType($Munit3);

      # output the state-specific info.
      my $addr1 = 0;
      my $addr2 = 0;
      my $addr3 = 0;
 
      if ($bit1 < 16) { $addr1 = 0; } else { $addr1 = 1; }

      $bitDescr1 = $moduleDescr1 . ":" . $bit1;
      $bitHash{$bitDescr1} = $componentEName;

      # print "STATESTR DEBUG *$stateStr*  *$EState*\n";
      # BIT 1
      if ($outType eq "B1S2")
         { 
         # if it's 1B2S don't output value.
         # if it's the second state, don't output crate/slot/bit numbers
         if ($stateNum == 1)
            { $componentLine .= ", $crate1, $slot1, $addr1, $bit1x "; }
         $componentLine .= ", \"$EState\", $SevrPls "; 
         }
      else 
         { 
         # first crate/module/slot/addr/bitnum for each bit
         # output all bit1 info
         # BIT 1 loc

         if ($stateNum == 1)
            { $componentLine .= ", $crate1, $slot1, $addr1, $bit1x "; }

         # BIT 2 loc, if it exists
         my $blen2 = length($bit2);
         # print "BIT2  $blen2  *$bit2*\n";
         if ($blen2 != 0)
            {
            if ($bit2 < 16) { $addr2 = 0; } else { $addr2 = 1; }
            $bitDescr2 = $moduleDescr2 . ":" . $bit2;
            $bitHash{$bitDescr2} = $componentEName;
            if ($stateNum == 1)
               { $componentLine .= ", $crate2, $slot2, $addr2, $bit2x "; }
            }

         # BIT 3 loc, if it exists
         my $blen3 = length($bit3);
         # print "BIT3  $blen3  *$bit3*\n";
         if ($blen3 != 0)
            {
            if ($bit3 < 16) { $addr3 = 0; } else { $addr3 = 1; }
            $bitDescr3 = $moduleDescr3 . ":" . $bit3;
            $bitHash{$bitDescr3} = $componentEName;
            if ($stateNum == 1)
               { $componentLine .= ", $crate3, $slot3, $addr3, $bit3x "; }
            }

         # then this state and sevr
         $componentLine .= ", \"$EState\", $SevrPls "; 

         # values of each bit for this state and sevr
         # BIT 1 value
         $componentLine .= ", $value1 "; 

         # BIT 2 value
         if ($blen2 != 0)
            { $componentLine .= ", $value2 "; }

         # BIT 3 value
         if ($blen3 != 0)
            { $componentLine .= ", $value3 "; }
         }

      # now add this bitDescr to the list of bitDescr's for the component.  There should only be one
      # (i.e. all states for a component use one set of bits - any other configuration will require development of 
      # special templates by Sonya)
      $thisBits = $bitDescr1."-".$bitDescr2."-".$bitDescr3;
      if (!(defined $allBitsHash{$thisBits}))
         { $allBitsHash{$thisBits} = 1; }

      if ($compNum > 0 && ($numBits != $currNumBits || $numStates != $currNumStates))
         { $badComponent = 1; $badMsg .= "$attribute $EState inconsistent number of states or number of bits.  "; }

      }

   # THE LAST COMPONENT NOW...
   # check the previous component for accumulated errors over all states
   if ($ldimCount > 0 && $idimCount > 0)
      {$badComponent = 1; $badMsg .= "both IDIM and LDIM in this component. "; }

   if (scalar(keys %allBitsHash) > 1)
      {$badComponent = 1; $badMsg .= "More than one set of bits used by states. "; }

   # then, output the previous component, or error message if it is BAAAD for some reason.
   if ($badComponent == 1)
      { print "BAD COMPONENT! $currMicro $currSprim $currSunit $currcomponent:  $badMsg\n"; }
   else
      {
      if ($compNum > 0)
         { print $outFile "$componentLine }\n"; }
      }

    # now we're done with the components and states
    # output the list of crates, slots, addresses, and bit assignments
    for my $key ( keys %moduleHash ) 
       {
       # print "MODULEHASH $key\n";
       my ($modMicro, $modCrate, $modSlot) = split/:/, $key;
       print CAMACFILE "        { $modMicro,  $modCrate, $modSlot,  \"LOCA\", \"IDIM\", 1, 32  }\n";

       print IDIMPORT "        { $modMicro,  $modCrate, $modSlot,  0  }\n";
       print IDIMPORT "        { $modMicro,  $modCrate, $modSlot,  1  }\n";

       for ($i=0; $i<32; ++$i)
          {
          my $bitDescr = $key . ":" . $i;
          # print "BITHASH $bitDescr IS $bitHash{$bitDescr}\n";
          # add leading 0 to channel if needed
          my $iChan = addLeadingZero($i);
          print IDIMCHAN "        { $modMicro,  $modCrate, $modSlot,  $iChan, $bitHash{$bitDescr} }\n";
          }
       }

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

#    $dbh->rollback();
#    $dbh->disconnect();


   outputEnds;

   close CAMACFILE;
   close IDIMPORT;
   close IDIMCHAN;
   close B1S2;
   close B2S2;
   close B2S3;
   close B2S4;

   print "Done\n";

