#!/usr/local/bin/perl -w
# jrock: perl to dump various aspects of the slcdb

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

use POSIX qw(log10);
use DBI qw(:sql_types);
use Switch;

    my %chansHash;

#    my $firstMicro = 1;
#    my $lastMicro = 1;

    my $dbh;
    my $egu_dbh;
    my $asts_row;
    my $sam_row;
    my $secn;
    my $unit;
    my $astsUnit;
    my $micro;
    my $local_index;
    my $value;
    my $currHDSC;
    my $i = 0; # general counter for all rows
    my $curr_micro = "none";
    my $curr_unit = 0;
    my $currASTSunit = 0;
    my $startChan = 0;
    my $numChans = 0;
    my @names = ();
    my $name;
    my @stats = ();
    my $stat;
    my @lims = ();
    my $lim;
    my @ptrs = ();
    my $ptr;
    my @scals = ();
    my $scal;
    my @egus = ();
    my $egu;
    my @ctrls = ();
    my @ctrl_PHASs = ();
    my @ctrl_TOLs = ();
    my @ctrl_LOG10s = ();
    my @ctrl_IONs = ();
    my @ctrl_GRAY_TOLs = ();
    my @ctrl_ASTS_RMSs = ();
    my @ctrl_DISABLEs = ();
    my @ctrl_NOTOLCHKs = ();
    my $astsCrate;
    my $astsModule;
    my $astsFunction;
    my $astsAddress;
    my @chans = ();
    my $chan;
    my %namesHash;
    my %inUseHash;
    my @namesToFind;
    my $nameCount;
    my $poly0 = 0;
    my $poly1 = 0;
    my $poly2 = 0;
    my $poly3 = 0;
    my $poly4 = 0;
    my $poly5 = 0;
    my $poly6 = 0;
    my $poly7 = 0;
    my $poly8 = 0;
    my $poly9 = 0;

    my $isSPARE = 0;
    my @SAMCHArray = ();
    my %SAMChanHash = ();
    my %SAMModuleHash = ();

    my $CAMACINHB_MSK = hex "10000";
    my $NOTOLCHK_MSK = hex "8000";
    my $DLWG_MSK = hex "1000000";
    my $PHAS_MSK = hex "4000";
    my $TOL_MSK = hex "100";
    my $LOG10_MSK = hex "800";
    my $ION_MSK = hex "400";
    my $GRAY_TOL_MSK = hex "200";
    my $ASTS_RMS_MSK = hex "80";
    my $DISABLE_MSK = hex "20";

    my $THRMS_MSK = hex "01000000";
    my $isTherm = 0;
    my $isDlwg = 0;
    my $isCamacInhb = 0;

    my $WARN_TOL = .05;
    my $DISP_TOL = 0.1;
    my $HYSTERESIS = .02;


#===============================================================
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.

print "ORACLE DATABASE:  CONNECTING to SLACDEV!\n";
#SLACDEV
    my $db_host = "slac-oracle02";
    my $db_database = "SLACDEV";

#SLACPROD
#    my $db_host = "slac-oracle03";
#    my $db_database = "SLACPROD";

    my $db_user = "nlcdev";
    my $db_password = "do~boson6";

    # 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 rpad($$)
#===============================================================
{
   my $strToPad = shift;
   my $len = shift;

   my $blanks = "                              ";

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


#===============================================================
sub preloadSAMHash
{
   my $ch;
   my $chStr;

   foreach $key (keys %SAMModuleHash) 
      {
      print "CRATE/MOD: " . $key . "\n";
      
      for ($ch = 0; $ch < 32; ++$ch)
         {
         if (length($ch) < 2)
            { $chStr = "0" . $ch; }
         else 
            { $chStr = $ch; }

         $SAMChanHash{$key ."|".$chStr} = $micro."|".$key."|".$chStr."|"."\"SPARE\""."|"."\"SPARE\""."|"."\"1 second\"";
         # print $key ."|".$chStr . " : " . $SAMChanHash{$key ."|".$chStr} . "\n";
         }
      }

}

#===============================================================
sub outputSAMCHArray
{
# now done in outputTops
#   print SAMCHFILE "# samChannel info\n";
#   print SAMCHFILE "file ../../AnalogIn/samChannel.template\n";
#   print SAMCHFILE "{\n";
#   print SAMCHFILE "pattern { MICRO,  CRAT, SLOT, CHAN, ALIAS,                       SLCALIAS,               SCAN  }\n";

my $currCrate = 0;
my $currModule = 0;
my $currChan = 0;
my $currChanStr = "00";
my @AllSAMCHArray;

# first, preload the SAM channel hash with SPAREs.
preloadSAMHash;

# then put the existing channels into the SAM channel hash in the appropriate slots.
for my $SAMCH (@SAMCHArray)
   {
   # split the channel line into its component parts
   my ($outMicro, $outCrate, $outModule, $outChan, $outAlias, $outSLCAlias, $outScan) = split /\|/, $SAMCH;

   $SAMChanHash{$outCrate."|".$outModule."|".$outChan} = $SAMCH;

   # print $outCrate."|".$outModule."|".$outChan." : " . $SAMChanHash{$outCrate."|".$outModule."|".$outChan} . "\n";
   }

# finally output the SAM channel hash in key (crate, module, channel) order.
foreach $key (sort (keys(%SAMChanHash)))
   {

   #@SAMCHArray = sort(@SAMCHArray);
   #for my $SAMCH (@SAMCHArray)
   #{

   # print "$SAMChanHash{$key}\n";
   # split the channel line into its component parts
   ($outMicro, $outCrate, $outModule, $outChan, $outAlias, $outSLCAlias, $outScan) = split /\|/, $SAMChanHash{$key};

   my $outoutCrate = substr $outCrate, 1, 1;

   print SAMCHFILE "        { "; 
   print SAMCHFILE rpad($outMicro, 5) . ", ";
   # print SAMCHFILE rpad($outCrate, 4) . ", ";
   print SAMCHFILE rpad($outoutCrate, 5) . ", ";
   print SAMCHFILE rpad($outModule, 4) . ", ";
   print SAMCHFILE rpad($outChan, 4) . ", ";
   print SAMCHFILE rpad($outAlias, 27) . ", ";
   print SAMCHFILE rpad($outSLCAlias, 24) . ", " ;
   print SAMCHFILE rpad($outScan, 8) ;
   print SAMCHFILE " }\n"; 
   }

# now done in outputEnds
#print SAMCHFILE "}\n\n"; 
}

#===============================================================
sub getEguForName ($)
#===============================================================
{
    my $thisName = shift;
  
    my $unit;
    my @units = ();
    my $local_index;
    my $eguStr = "none";

    # this takes 2 selects:
    # first to get the ASDF unit and the index of the name
    # and then to select the egu (same index as the name)
#select unit, local_index from slc_data_view_tot
#where prim='ASDF' and secn = 'CNAM' and value = 'KLY_W1_1'
#
#select distinct value from slc_data_view_tot
#where prim='ASDF' and 
#    ((unit=59 and local_index=41) or
#     (unit=192 and local_index=192))
#and secn = 'UNAM'

    my $select_egu_sql =  "select unit, local_index from slc_data_view_all ";
       $select_egu_sql .= "where prim = 'ASDF' and ";
       $select_egu_sql .= "      secn = 'CNAM' and ";
       $select_egu_sql .= "     micro = 'VX00' and ";
       $select_egu_sql .= "     value = '$thisName'";
    eval {
        $select_egu_st = $egu_dbh->prepare($select_egu_sql);
        $select_egu_st->execute();
    };
    if ($@) {
        print "error in egu select for $thisName:$@\n";
        exit;
    }

    my $selCount = 0;
    while ($egu_row = $select_egu_st->fetchrow_hashref)  
       {
        $unit = $egu_row->{unit};
        $local_index = $egu_row->{local_index};
        $sel = "(unit = '$unit' and local_index=$local_index)"; 
        push @units, $sel;
        ++$selCount;
       }

    if ($selCount == 0 )
       {
       print "WARNING: NO egu specified for $thisName\n"; 
       return $eguStr; # actually, return "none"
       }

    my $unitStr = "and (";
    $selCount = 0;
    foreach $sel (@units)
       {
       if ($selCount > 0)
          { $unitStr .= " or "; }
       $unitStr .= $sel; 
       ++$selCount;
       }
    $unitStr .= ")";

    $select_egu_sql =  "select distinct rtrim(value) value from slc_data_view_all ";
       $select_egu_sql .= "where prim = 'ASDF' and ";
       $select_egu_sql .= "      secn = 'UNAM' ";
       $select_egu_sql .= "     $unitStr";
    # print "select is $select_egu_sql\n";
    eval {
        $select_egu_st = $egu_dbh->prepare($select_egu_sql);
        $select_egu_st->execute();
    };
    if ($@) {
        print "error in egu select for $thisName:$@\n";
        exit;
    }

    my $eguCount = 0;
    while ($egu_row = $select_egu_st->fetchrow_hashref)  
       {
       ++$eguCount;
       $eguStr = $egu_row->{value};
       }

    # print warning of > 1 distinct found
    # return the first one found
    if ($eguCount ==0 )
       { print "WARNING: NO egu specified for $thisName\n"; }
    if ($eguCount > 1)
       { print "WARNING: more than one egu for $thisName\n"; }
  print "found $eguStr\n";
    return $eguStr;
}

#===============================================================
sub isTHERM ($)
#===============================================================
{
   my $hdscVal = shift;

   my $hdsc = substr($hdscVal, 17, 8);
   my $hexHdsc = hex $hdsc;

   if (($hexHdsc & $THRMS_MSK) == 0)
      { return 0; }
   else
      { return 1; }
}

#===============================================================
sub isCAMACINHB ($)
#===============================================================
{
   my $hdscVal = shift;

   my $hdsc = substr($hdscVal, 17, 8);
   my $hexHdsc = hex $hdsc;

   if (($hexHdsc & $CAMACINHB_MSK) == 0)
      { return 0; }
   else
      { return 1; }
}

#===============================================================
sub isDLWG ($)
#===============================================================
{
   my $hdscVal = shift;

   my $hdsc = substr($hdscVal, 17, 8);
   my $hexHdsc = hex $hdsc;

   if (($hexHdsc & $DLWG_MSK) == 0)
      { return 0; }
   else
      { return 1; }
}

#===============================================================
sub has_MSK ($$)
#===============================================================
{
   my $ctrlVal = shift;
   my $MSK = shift;

   my $ctrl = substr($ctrlVal, 21, 4);
   my $hexCtrl = hex $ctrl;

   # print "IN has_MSK: ctrl = " . sprintf("%x",$hexCtrl) . " MSK = " . sprintf("%x",$MSK) ."\n";
   my $ANDval = $hexCtrl & $MSK;
   # print "AND says " . sprintf ("%x", $ANDval) . "\n";
   # if ($ANDval == 0) { print "AND SAYS 0\n"; } else { print "AND SAYS NON-0\n"; }
   #   if (($hexCtrl & $MSK) == 0)
   if ($ANDval == 0)
      { return 0; }
   else
      { return 1; }
}

#===============================================================
sub getEpicsName ($$$$$)
#===============================================================
{
my $name = shift;
my $devref = shift;
my $arearef = shift;
my $unitref = shift;
my $attrref = shift;

my $epicsName;
my $tempUnit = $curr_unit;


# remove leading whitespace from unit
$tempUnit =~ s/^\s+//;

my $slcName = "ASTS:" . $curr_micro . ":" . $tempUnit . ":" . $name;

# TEMPORARY TIL NEW NAMES LIST IS READY 
# FOR NOW, JUST RETURN SLC NAMES
#$$devref = "eASTS";
#$$arearef = "e" . $curr_micro;
#$$unitref = "e" . $tempUnit;
#$$attrref = "e" . $name;
#return 1;
if ($inUseHash{$slcName} =~ /^NO/)
   { return 0; }

$epicsName = $namesHash{$slcName};
if (!(defined $namesHash{$slcName}))
   { 
   $epicsName = "unknown"; 
   $$devref = "unk";
   $$arearef = "unk";
   $$unitref = "unk";
   $$attrref = $name;
   }
else 
   { 
   ($$devref, $$arearef, $$unitref, $$attrref) = split /:/,$epicsName;
   }

print "epics name for $slcName is: $epicsName\n";
print "NAME IS: asts, $slcName, $epicsName\n";
#$$devref = "DEV";
#$$arearef = "LI24";
#$$unitref = 999;
#$$attrref = "MEASUREMENT";

return 1;
}

#===============================================================
sub loadNamesHash ()
#===============================================================
{
#   my $namesFile = "li2030_to_epics_name_list_R0.csv";
#   my $namesFile = "names_17_18.csv";
#   my $namesFile = "/afs/slac/g/lcls/epics/iocTop/users/sonya/analogDigitalStaIOC/analogStatusApp/Db/anlgNames_17_18";
#   my $namesFile = "/afs/slac/g/lcls/epics/iocTop/CAMAC/Sonya/camacApp/Db/AnalogIn/anlg1718_slc_epics.csv";
   my $namesFile = "/afs/slac/g/lcls/epics/iocTop/CAMAC/working/camacApp/Db/AnalogIn/anlg2030_slc_epics.csv";

   die "Could not open names file $namesFile\n" unless (open(NFILE, $namesFile));

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

   foreach $line (@lines)
      {
      chomp $line;
#      chop $line;
      my ($slcName, $epicsName, $inUse) = split /,/, $line;
      my (@slcnameAndBlanks) = split / /, $slcName;
      $slcName = $slcnameAndBlanks[0]; 
      my (@epicsnameAndBlanks) = split / /, $epicsName;
      $epicsName = $epicsnameAndBlanks[0]; 

print $slcName . " = " . $epicsName . "\n";

      $namesHash{$slcName} = $epicsName;
      $inUseHash{$slcName} = $inUse;
print "INUSE:  slc:*$slcName* epics:*$epicsName* is *$inUse*\n";
#print "just loaded: slcName=$slcName; $namesHash{$slcName} $inUseHash{$slcName}\n";
      }

   
}

#===============================================================
sub outputTops ()
# template file will have this data:
#  dev area unit attr lims1 lims2 scal1 scal2 egu
#===============================================================
{
# for scaling, DATA = SCAL1 + SCAL2*RVAL
# This seems to be equivalent to the EPICS ai linear processing
# with the slope=SCAL2 and the offset=SCAL1
# NOTE: For special modules, there will be additional processing
# required in the EPICS templates.
    # ASTSFILE;
    # SAMFILE;
    # CAMACFILE;
    # SAMCHFILE;
    # LINFILE;
    # LINPOLYFILE;
    # LOGPOLYFILE;
    # TEMPSAMREFFILE;
    # TEMPSAMTTFILE;
    # DLWGFILE;

   print SAMCHFILE "# samChannel info\n"; 
   print SAMCHFILE "file ../../AnalogIn/samChannel.template\n";
   print SAMCHFILE "{\n"; 
   print SAMCHFILE "pattern { MICRO,  CRAT, SLOT, CHAN, ALIAS,                       SLCALIAS,               SCAN  }\n";

   print ASTSFILE "# ASTS descriptions\n"; 
   print ASTSFILE "file ../../AnalogIn/asts.template\n";
   print ASTSFILE "{\n"; 
   print ASTSFILE "pattern { PRIM,  LOCA, UNIT, ATTR,   DISPTEXT  }\n";

   print SAMFILE "# samModule info\n"; 
   print SAMFILE "file ../../AnalogIn/samModule.template\n";
   print SAMFILE "{\n"; 
   print SAMFILE "pattern { MICRO,  CRAT, SLOT  }\n";

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

   print LINFILE "# analogIn\n"; 
   print LINFILE "file ../../AnalogIn/analogIn.template\n";
   print LINFILE "{\n"; 
   print LINFILE "pattern { ";
   print LINFILE "MICRO" . ",  ";
   print LINFILE "CRAT" . ", ";
   print LINFILE "SLOT  " . ", ";
   print LINFILE "CHAN     " . ", ";
   print LINFILE "OFFS         " . ", ";
   print LINFILE "COEF        " . ", ";
   print LINFILE "PRIM" . ",  ";
   print LINFILE "LOCA" . ",  ";
   print LINFILE "UNIT" . ", ";
   print LINFILE "ATTR    " . ", ";
   print LINFILE "P, ";
   print LINFILE "EGU  " . ", ";
   print LINFILE "HI      " . ", ";
   print LINFILE "LO      " . ", ";
   print LINFILE "HH           " . ", ";
   print LINFILE "LL           " . ", ";
   print LINFILE "HY           " . ", ";
   print LINFILE "AD,    ";
   print LINFILE "MD,   ";
   print LINFILE "AUNIT " . ", ";
   print LINFILE "SLCNAME " . ", ";
   print LINFILE "H           " . ", ";
   print LINFILE "L           " . ", " ;
   print LINFILE "ASSOC       " . ", ";
   print LINFILE "SIGN       " . ", ";
   print LINFILE "TYPE       ";
   print LINFILE " }\n";

   print LINPOLYFILE "# linearPolyAnalogIn\n"; 
   print LINPOLYFILE "file ../../AnalogIn/linearPolyAnalogIn.template\n";
   print LINPOLYFILE "{\n"; 
   print LINPOLYFILE "pattern { MICRO,  CRAT, SLOT, CHAN, OFFS, COEFF, PRIM, LOCA, UNIT, ATTR,   P, EGU,  H,  L,  HH,  LL,  HI,  LO,  HY,  AD,  MD,  DISA, POLY0, POLY1, POLY2, POLY3, POLY4, POLY5, POLY6, POLY7, POLY8, POLY9, PPIM, PUNIT   }\n";

   print LOGPOLYFILE "# linearPolyAnalogIn\n"; 
   print LOGPOLYFILE "file ../../AnalogIn/linearPolyAnalogIn.template\n";
   print LOGPOLYFILE "{\n"; 
   print LOGPOLYFILE "pattern { MICRO,  CRAT, SLOT, CHAN, OFFS, COEFF, PRIM, LOCA, UNIT, ATTR,   P, EGU,  H,  L,  HH,  LL,  HI,  LO,  HY,  AD,  MD,  DISA, POLY0, POLY1, POLY2, POLY3, POLY4, POLY5, POLY6, POLY7, POLY8, POLY9, PPIM, PUNIT   }\n";

   print TEMPSAMREFFILE "# tempSamRef\n";        
   print TEMPSAMREFFILE "file ../../AnalogIn/tempSamRef.template\n";
   print TEMPSAMREFFILE "{\n";
   print TEMPSAMREFFILE "pattern { MICRO,  CRAT, SLOT,   CHAN, ADDR      }\n";

   print TEMPSAMTTFILE "# tempSamTypeT\n";        
   print TEMPSAMTTFILE "file ../../AnalogIn/tempSamTypeT.template\n";
   print TEMPSAMTTFILE "{\n";
   print TEMPSAMTTFILE "pattern { ";
   print TEMPSAMTTFILE "MICRO" . ",  ";
   print TEMPSAMTTFILE "CRAT" . ", ";
   print TEMPSAMTTFILE "SLOT  " . ", ";
   print TEMPSAMTTFILE "CHAN     " . ", ";
   print TEMPSAMTTFILE "PRIM" . ",  ";
   print TEMPSAMTTFILE "LOCA" . ",  ";
   print TEMPSAMTTFILE "UNIT" . ", ";
   print TEMPSAMTTFILE "ATTR    " . ",   ";
   print TEMPSAMTTFILE "EGU  " . ", ";
   print TEMPSAMTTFILE "HI           " . ", ";
   print TEMPSAMTTFILE "LO           " . ", ";
   print TEMPSAMTTFILE "HH           " . ", ";
   print TEMPSAMTTFILE "LL           " . ", ";
   print TEMPSAMTTFILE "HY           " . ", ";
   print TEMPSAMTTFILE "AD,   ";
   print TEMPSAMTTFILE "MD,  ";
   print TEMPSAMTTFILE "AUNIT " . ", ";
   print TEMPSAMTTFILE "SLCNAME " . ", ";
   print TEMPSAMTTFILE "TCINP " . ", ";
   print TEMPSAMTTFILE "ADDR " . ", ";
   print TEMPSAMTTFILE "H           " . ", ";
   print TEMPSAMTTFILE "L           " ;
   print TEMPSAMTTFILE " }\n";

   print DLWGFILE "# dlwgLimits\n";        
   print DLWGFILE "file ../../AnalogIn/dlwgLimits.template\n";
   print DLWGFILE "{\n";
   print DLWGFILE "pattern { MICRO, PRIM,   LOCA,  UNIT,   ATTR,      PPIM,   PUNIT   }\n";
}

#===============================================================
sub outputEnds ()
# template file will have this data:
#  dev area unit attr lims1 lims2 scal1 scal2 egu
#===============================================================
{
   print ASTSFILE "}\n\n"; 

   print SAMFILE "}\n\n"; 

   print SAMCHFILE "}\n\n"; 

   print CAMACFILE "}\n\n"; 

   print LINFILE "}\n\n"; 

   print LINPOLYFILE "}\n\n"; 

   print LOGPOLYFILE "}\n\n"; 

   print TEMPSAMREFFILE "}\n\n";

   print TEMPSAMTTFILE "}\n\n";

   print DLWGFILE "}\n\n";
}

#===============================================================
sub inList ($)
#===============================================================
{
my $name = shift;

# DO ALL NAMES NOW 
return 1;

foreach my $listName (@namesToFind)
   {
   if ($listName =~ /$name/)
      { return 1; }
   }

return 0;
}

#===============================================================
sub outputSAMInfo ($)
# template file will have this data:
#  dev area unit attr lims1 lims2 scal1 scal2 egu
# how to compute lims and such is here, in FORTRAN:
#      anlgchck.f86 
#===============================================================
{
print "now outputting SAM Info...\n";
# Select distinct SAM modules for the micros in question
    my $thisMicro = shift;

    my $i;

    my $select_sql  = "select distinct micro, crate, module ";
       $select_sql .= "from slc_data_view_all ";
       $select_sql .= "where micro = '" . $thisMicro . "' and ";
       $select_sql .= "secn = 'CTLW' and prim = 'ASTS' and ";
       $select_sql .= "crate != 0 ";
       $select_sql .= "order by micro, crate, module";

    eval {
print "SAM select: $select_sql\n";
        $select_st = $dbh->prepare($select_sql);
        $select_st->execute();
    };
    if ($@) {
        print "error in SAM select from secndx:$@\n";
        exit;
    }

    while ($sam_row = $select_st->fetchrow_hashref) {
        ++$i;
        my $micro = $sam_row->{micro};
        my $crate = $sam_row->{crate};
        my $slot = $sam_row->{module};

        my $outSlot;
        if ($slot < 10)
           { $outSlot = "0" . $slot; }
        else 
           { $outSlot = $slot; }
        print SAMFILE    "        { " . $micro. ",   " . $crate . ",     " . $outSlot. " }\n";
    }
print "done with SAM Info!\n";
}


#===============================================================
sub outputCAMACInfo ($)
# template file will have this data:
#===============================================================
{
print "now outputting CAMAC Info...\n";
# Select distinct CAMAC modules for the micros in question for analogs, sam select as SAM
    my $thisMicro = shift;

    my $i;

    my $select_sql  = "select distinct micro, crate, module ";
       $select_sql .= "from slc_data_view_all ";
       $select_sql .= "where micro = '" . $thisMicro . "' and ";
       $select_sql .= "secn = 'CTLW' and prim = 'ASTS' and ";
       $select_sql .= "crate != 0 ";
       $select_sql .= "order by micro, crate, module";

    eval {
print "CAMAC select: $select_sql\n";
        $select_st = $dbh->prepare($select_sql);
        $select_st->execute();
    };
    if ($@) {
        print "error in CAMAC select from secndx:$@\n";
        exit;
    }

    while ($sam_row = $select_st->fetchrow_hashref) {
        ++$i;
        my $micro = $sam_row->{micro};
        my $crate = $sam_row->{crate};
        my $slot = $sam_row->{module};
        my $outSlot;
        if ($slot < 10)
           { $outSlot = "0" . $slot; }
        else 
           { $outSlot = $slot; }

        print CAMACFILE    "        { " . $micro. ",   " . $crate . ",     " . $outSlot. ",     LOC, \"SAM 123-603\", 1, 32 }\n";
    }
print "done with CAMAC Info!\n";
}


#===============================================================
sub outputChans ()
# template file will have this data:
#  dev area unit attr lims1 lims2 scal1 scal2 egu
# how to compute lims and such is here, in FORTRAN:
#      anlgchck.f86 
#===============================================================
{
my $dev;
my $area;
my $unit;
my $attr;
my $astsName;
my $ptr1 = 0;
my $ptr2 = 0;
my $lim1;
my $lim2;
my $scal1;
my $scal2;
my $egu;
my $disa;
my $chan;
my $ctrl;
my $isLOG = 0;
#3 phase mixer things:
my $type;
my $assoc;
my $sign;

    # ASTSFILE;
    # SAMFILE;
    # SAMCHFILE;
    # CAMACFILE;
    # LINFILE;
    # LINPOLYFILE;
    # LOGPOLYFILE;
    # TEMPSAMREFFILE;
    # TEMPSAMTTFILE;
    # DLWGFILE;

   my $i;
print "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n";
print "DOING OUTPUT CHANS\n";
print "NUMCHANS IS $numChans\n";   
print "NAMES has $#names\n";
print "NAMES is @names\n";   
print "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n";
   for ($i = 0; $i < $numChans; ++$i)
      { 
      $isSPARE = 0;
      $type = 1;
      $sign = "\"\"";
      $assoc = "\"\"";

      $astsName = $names[$i];
print "I: $i $astsName\n";

      #skip if this isn't the name we're looking for!
      if (!(inList($astsName)))
         { next; }

      #using numChans, so don't need this check anymore
      # NEW: DO SPARES TOO
      if ($astsName =~ /^SPARE/)
      #  { next; }
        { $isSPARE = 1; }

      # look up device name based on name
      my $inUse = getEpicsName($astsName, \$dev, \$area, \$unit, \$attr);
print "INUSE FOUND: $astsName  $inUse\n";
      if ($inUse == 0)
         { next; }
      # print "$name: $dev:$area:$unit:$attr\n";

      # do limits based on mask values
      my $lolo;
      my $log_lolo;
      my $hihi;
      my $log_hihi;
      my $low;
      my $high;
      my $warnBand;
      my $dispBand;
      my $hysteresis = 0;
      my $hopr;
      my $lopr;

      my $isPoly = 0;
      my $polyUnit = 0;
      $ptr1 = 0;
      $ptr2 = 0;
      $poly0 = 0;
      $poly1 = 0;
      $poly2 = 0;
      $poly3 = 0;
      $poly4 = 0;
      $poly5 = 0;
      $poly6 = 0;
      $poly7 = 0;
      $poly8 = 0;
      $poly9 = 0;
      
      if (defined $ptrs[($i*2)])
         { $ptr1 = $ptrs[($i*2)] + 0; }
      if (defined $ptrs[($i*2)+1])
         { $ptr2 = $ptrs[($i*2)+1] + 0; }

      if ($ptr1 == 165)
         { 
         $isPoly = 1; 
         $polyUnit = $ptr2;
         getPolyCoeffs($polyUnit);
         }
     
      $lim1 = $lims[($i*2)];
      $lim2 = $lims[($i*2)+1];
      if ($ctrl_TOLs[$i*2])
         {
         $lolo = $lim1 - $lim2;
         $hihi = $lim1 + $lim2;
         }
      else
         {
         $lolo = $lim1;
         $hihi = $lim2;
         }

      if ($ctrl_PHASs[$i*2])
         {
         # print "PHAS MIXER FOUND $micro\n";
         my $phPrim;
         my $phSecn;
         my $phUnit = $ptr2;
         $type = 3;

         $phPrim = "NONE";
         $phSecn = "NONE";
         $sign = 0;

         switch($ptr1) 
            {
            case 33
               {
               $phPrim = "AMPL";      
               $phSecn = "VDES";      
               $sign = -1;
               }
            case 34
               {
               $phPrim = "AMPL";      
               $phSecn = "VACT";      
               $sign = -1;
               }
            case 35
               {
               $phPrim = "PHAS";      
               $phSecn = "VDES";      
               $sign = 1;
               }
            case 36
               {
               $phPrim = "PHAS";      
               $phSecn = "VACT";      
               $sign = 1;
               }
            }

         $assoc = $phPrim.":".$micro.":".$phUnit.":".$phSecn;
         }

      # JROCK 8/9/2011 only set hysteresis if NOT log.  (Sonya)
      if ($ctrl_LOG10s[$i*2])
         {
#print "doing log...\n";
         $isLOG = 1;
         $type = 2;
         $log_lolo = log10($lolo);
         $log_hihi = log10($hihi);
         $warnBand = $WARN_TOL * ($log_hihi - $log_lolo);
         $low = 10**($log_lolo + $warnBand);
         $high = 10**($log_hihi - $warnBand);

         $dispBand = $DISP_TOL * ($log_hihi - $log_lolo);
         $hopr = 10**($log_hihi + $dispBand);
         $lopr = 10**($log_lolo - $dispBand);

         # JROCK 8/9/2011 SET HYST TO 0 FOR LOG
         $hysteresis = 0;
         }
      else
         {
         $isLOG = 0;
         $warnBand = $WARN_TOL * ($hihi - $lolo);
         $low = $lolo + $warnBand;
         $high = $hihi - $warnBand;
         # set hopr and lopr to 10% outside hihi and lolo range
         # ?? make sure!
         $hopr = $hihi + (0.1 * ($hihi - $lolo));
         $lopr = $lolo - (0.1 * ($hihi - $lolo));

         # JROCK 8/9/2011 MOVED THIS INTO THE NOLOG SECTION
         # hysteresis, if specified
         # ALWAYS set this, altho its not always set in the slcdb
         # ?? make sure!
         #if ($ctrl_GRAY_TOLs[$i*2])
         #   {
             $hysteresis = $HYSTERESIS * ($hihi - $lolo);
         #   }
         }

      $ctrl = substr($ctrls[($i*2)], 21); 

# these will no doubt change!!
      $scal1 = $scals[($i*2)];
      $scal2 = $scals[($i*2)+1];

print "**ATTR: $attr  SCAL1: v:@scals[($i*2)] p:$scal1   SCAL2: v:@scals[($i*2)+1] p:$scal2\n";

      # note: chan starts at 0, and goes through 31 (i.e. 0-based)
      $chan = $chans[$i] + $startChan;

      $egu = $egus[$i];
     
      $disa = $ctrl_DISABLEs[($i)]; 

print "msks: $ctrl ";
my $idx = $i*2;
print "PHASs: $ctrl_PHASs[($idx)] ETC: $ctrl_TOLs[($idx)] $ctrl_LOG10s[($idx)] $ctrl_IONs[($idx)] $ctrl_GRAY_TOLs[($idx)] $ctrl_ASTS_RMSs[($idx)] $ctrl_DISABLEs[($idx)]\n";
print "LIMS: $lim1, $lim2\n";
print "  $lolo, $low, $high, $hihi\n";
print "==========================\n";

#print "lim2 = $lim2\n";
#print "scal1 = $scal1\n";
#print "scal2 = $scal2\n";
print "chan= $chan    astsName=$astsName\n";
#print "egu = *$egu*\n";
#print "crate = $astsCrate\n";
#print "module = $astsModule\n";
#print "channel = $chan\n";

# FOR TESTING, MAKE THE SLC NAME:
my $TESTSLCPV = "ASTS:". $curr_micro . ":" . $curr_unit . ":" . $astsName;
# now we have enough information to check the chansHash.
# if crate:module:chan is there, then output.  Else skip!
my $hashKey = $astsCrate . ":" . $astsModule . ":" . $chan;
print "HASHKEY is *$hashKey*\n";
print "ASTSNAME is *$astsName*\n";
if (!(defined $chansHash{$hashKey}))
   {  
   print "$hashKey channel not in chansHash, so skipping\n";  
   print "============================================================\n";
   next; 
   }
elsif (!($chansHash{$hashKey} eq $astsName))
   {  
   print "$hashKey name $astsName not in chansHash, so skipping\n";  
   print "============================================================\n";
   next; 
   }

# OUTPUT samChannel
my $thisAlias;
my $thisSLCAlias;
my $thisScan;
my $thisASTSUnit = $currASTSunit;
$thisASTSUnit =~ s/^\s+//;

if ($isSPARE == 1)
   {
   $thisAlias = "\"SPARE\"";
   $thisSLCAlias = "\"SPARE\"";
   $thisScan = "\"1 second\"";
   }
else
   {
   $thisAlias = "\"" . $dev. ":" . $area . ":" . $unit . ":" . $attr . "\"";
   $thisSLCAlias = "\"ASTS " . $micro . " " .  $thisASTSUnit . " " .  $astsName . "\"";
   $thisScan = "\"Passive\"";
   }

if (length($chan)<2)
   { $chan = "0".$chan; }
my $thisCrate = $astsCrate;
if (length($thisCrate)<2)
   { $thisCrate = "0".$thisCrate; }
my $thisModule = $astsModule;
if (length($thisModule)<2)
   { $thisModule = "0".$thisModule; }
push @SAMCHArray, $micro."|".$thisCrate."|".$thisModule."|".$chan."|".$thisAlias."|".$thisSLCAlias."|".$thisScan;
$SAMModuleHash{$thisCrate . "|" . $thisModule} = 1;

#print SAMCHFILE "        { "; 
#print SAMCHFILE rpad($micro, 5) . ", ";
#print SAMCHFILE rpad($astsCrate, 4) . ", ";
#print SAMCHFILE rpad($astsModule, 4) . ", ";
#print SAMCHFILE rpad($chan, 4) . ", ";
#print SAMCHFILE rpad($thisAlias, 27) . ", ";
#print SAMCHFILE rpad($thisSLCAlias, 24) ;
#print SAMCHFILE rpad($thisScan, 8) ;
#print SAMCHFILE " }\n"; 

# no more output for SPARES
if ($isSPARE == 1)
   {
   print "SPARE: no more output\n";
   next;
   }

# OUTPUT DLWG
if ($isDlwg && $ptr1 == 9)
   {
   # populate dlwgLimits.template here
   print DLWGFILE "        { "; 
   print DLWGFILE rpad($micro, 5) . ", ";
   print DLWGFILE rpad($dev, 6) . ", ";
   print DLWGFILE rpad($area, 5) . ", ";
   print DLWGFILE rpad($unit, 6) . ", ";
   print DLWGFILE rpad($attr, 9) . ", ";
   print DLWGFILE "KLYS  , ";
   print DLWGFILE rpad($ptr2, 6) ;
   print DLWGFILE " }\n"; 
   }

# OUTPUT POLYs
if ($isPoly)
   {
   # populate poly.template here, depending on log or lin - could this also be therm?
   # if so, put inside the "else" below
   }

# OUTPUT THERMS
if ($isTherm)
   {
   my $tcinp;
   if ($chan != 15 && $chan != 31)
      {
      # set EGU and TCINP; populate tempSamTypeT.template
      if ($egu eq "degC" or $egu eq "DegC")
         {
         $egu = "DegC";
         $tcinp = "TEMP_C";
         }
      else
         {
         if ($egu eq "none")
            { print "NO EGU DEFINED\n"; }
         $egu = "DegF";
         $tcinp = "TEMP";
         }

      print TEMPSAMTTFILE "        { "; 
      print TEMPSAMTTFILE rpad($micro, 6) . ", ";
      print TEMPSAMTTFILE rpad($astsCrate, 5) . ", ";
      print TEMPSAMTTFILE rpad($astsModule, 6) . ",";
      print TEMPSAMTTFILE rpad($chan, 9) . ", ";
      print TEMPSAMTTFILE rpad($dev, 4) . ",  ";
      print TEMPSAMTTFILE rpad($area,4) . ",  ";
      print TEMPSAMTTFILE rpad($unit, 4) . ", ";
      print TEMPSAMTTFILE rpad($attr, 8) . ", ";
      print TEMPSAMTTFILE rpad($egu, 5) . ", ";
      print TEMPSAMTTFILE rpad(sprintf("%.3e",$high), 13) . ", ";
      print TEMPSAMTTFILE rpad(sprintf("%.3e",$low), 13) . ", ";
      print TEMPSAMTTFILE rpad(sprintf("%.7e",$hihi), 13) . ", ";
      print TEMPSAMTTFILE rpad(sprintf("%.7e", $lolo), 13) . ", ";
      print TEMPSAMTTFILE rpad(sprintf("%.7e", $hysteresis), 13) . ", ";
      print TEMPSAMTTFILE ".001, ";
      print TEMPSAMTTFILE ".001, ";
      print TEMPSAMTTFILE "$curr_unit,   ";
      print TEMPSAMTTFILE "$astsName,  ";
      print TEMPSAMTTFILE "$tcinp,   ";
      if ($chan < 16)
         { print TEMPSAMTTFILE "0, "; }
      else
         { print TEMPSAMTTFILE "1, "; }
      print TEMPSAMTTFILE rpad(sprintf("%.2e",$hopr), 13) . ",";
      print TEMPSAMTTFILE rpad(sprintf("%.2e",$lopr), 13) . " ";
      print TEMPSAMTTFILE " }\n"; 
      }
   else
      {
      # populate tempSamTypeRef.template
      print TEMPSAMREFFILE "        { "; 
      print TEMPSAMREFFILE rpad($micro, 6) . ", ";
      print TEMPSAMREFFILE rpad($astsCrate, 5) . ", ";
      print TEMPSAMREFFILE rpad($astsModule, 6) . ", ";
      print TEMPSAMREFFILE rpad($chan, 3) . ", ";
      if ($chan < 16)
         { print TEMPSAMREFFILE "0"; }
      else
         { print TEMPSAMREFFILE "1"; }
#      print TEMPSAMREFFILE " }   $TESTSLCPV\n"; 
      print TEMPSAMREFFILE " } \n"; 
      }
   }
else
   {
   # OUTPUT LOGS AND LINEARS
   my $outastsModule;
   if ($astsModule < 10)
      { $outastsModule = "0" . $astsModule; }
   else 
      { $outastsModule = $astsModule; }
print "JTEST ASTSMODULE: $astsModule;  OUTASTSMODULE: $outastsModule\n";

   if ($isLOG)
      {
      # print out LOG analog data items
      print LINFILE "        { "; 
      print LINFILE rpad($micro, 6) . ", ";
      print LINFILE rpad($astsCrate, 5) . ",";
      print LINFILE rpad($outastsModule, 6) . ", ";
      print LINFILE rpad($chan, 9) . ", ";
      print LINFILE rpad(sprintf("%.7e",$scal1), 13) . ", ";
      print LINFILE rpad(sprintf("%.7e",$scal2), 13) . ",";
      print LINFILE rpad($dev, 4) . ",  ";
      print LINFILE rpad($area,4) . ",  ";
      print LINFILE rpad($unit, 4) . ", ";
      print LINFILE rpad($attr, 8) . ", ";
      print LINFILE "11, ";
      print LINFILE rpad($egu, 5) . ", ";
      print LINFILE rpad(sprintf("%.3e",$high), 8) . ", ";
      print LINFILE rpad(sprintf("%.3e",$low), 8) . ", ";
      print LINFILE rpad(sprintf("%.7e",$hihi), 13) . ", ";
      print LINFILE rpad(sprintf("%.7e", $lolo), 13) . ", ";
      print LINFILE rpad(sprintf("%.7e", $hysteresis), 13) . ", ";
      print LINFILE "    \"\", ";
      print LINFILE "    \"\", ";
      print LINFILE "$curr_unit,   ";
      print LINFILE "$astsName,  ";
      print LINFILE rpad(sprintf("%.2e",$hopr), 13) . ",";
      print LINFILE rpad(sprintf("%.2e",$lopr), 13) . ",";
      print LINFILE "\"\"                  , ";
      print LINFILE "\"\"   , ";
      print LINFILE rpad($type, 5);
     # print LINFILE " }  $TESTSLCPV\n"; 
      print LINFILE " } \n"; 
      }
   else
      {
      print LINFILE "        { "; 
      print LINFILE rpad($micro, 6) . ", ";
      print LINFILE rpad($astsCrate, 5) . ",";
      print LINFILE rpad($outastsModule, 6) . ", ";
      print LINFILE rpad($chan, 9) . ", ";
      print LINFILE rpad(sprintf("%.7e",$scal1), 13) . ", ";
      print LINFILE rpad(sprintf("%.7e",$scal2), 13) . ",";
      print LINFILE rpad($dev, 4) . ",  ";
      print LINFILE rpad($area,4) . ",  ";
      print LINFILE rpad($unit, 4) . ", ";
      print LINFILE rpad($attr, 8) . ", ";
      print LINFILE "3,  ";
      print LINFILE rpad($egu, 5) . ", ";
      print LINFILE rpad(sprintf("%.3e",$high), 8) . ", ";
      print LINFILE rpad(sprintf("%.3e",$low), 8) . ", ";
      print LINFILE rpad(sprintf("%.7e",$hihi), 13) . ", ";
      print LINFILE rpad(sprintf("%.7e", $lolo), 13) . ", ";
      print LINFILE rpad(sprintf("%.7e", $hysteresis), 13) . ", ";
      print LINFILE ".001, ";
      print LINFILE ".001, ";
      print LINFILE "$curr_unit,   ";
      print LINFILE "$astsName,  ";
      print LINFILE rpad(sprintf("%.2e",$hopr), 13) . ",";
      print LINFILE rpad(sprintf("%.2e",$lopr), 13) . ",";
      print LINFILE rpad($assoc, 20) . ", ";
      print LINFILE rpad($sign, 5) . ", ";
      print LINFILE rpad($type, 5);
     # print LINFILE " }  $TESTSLCPV\n"; 
      print LINFILE " } \n"; 
      }
   }
   }
return 0;
}

#===============================================================
sub munchName($)
#===============================================================
{
   my $name = shift;
 
   # remove leading/trailing blanks
   chomp $name;
   $name =~ s/^\s+//;
   if ($name =~ /(.*) / ) 
      { $name = $1; }
   return $name;
}

#===============================================================
sub getPolyCoeffs($)
#===============================================================
{
   my $pUnit = shift;
 
   # query for polynomial coefficients here
}


#===============================================================
sub loadNamesList($)
#===============================================================
{
   my $nameFile = shift;

   if (!(open(NFILE, $nameFile)))
      {
      print "couldn't open names list file $nameFile\n";
      return 0;
      }

   @namesToFind = <NFILE>;
   close NFILE;
   return 1; 
}

#===============================================================
sub preloadChansHash($)
#===============================================================
{
    my $micro = shift;
    %chansHash = ();

    my $asts_row;
    my $astsCrate;
    my $astsModule;
    my $astsChan;
    my $crate;
    my $module;
    my $secn;
    my $value;
    my $local_index;
    my $startChan;

print "preloading Chans Hash: MICRO $micro\n";
    my $select_sql =  "select rtrim(micro) micro, ";
       $select_sql .= "       rtrim(prim) prim, "; 
       $select_sql .= "       rtrim(unit) unit, "; 
       $select_sql .= "       rtrim(secn) secn, "; 
       $select_sql .= "       rtrim(value) value, "; 
       $select_sql .= "       local_index, "; 
       $select_sql .= "       crate, "; 
       $select_sql .= "       module "; 
       $select_sql .= " from slc_data_view_all ";
       $select_sql .= "where prim = 'ASTS' and ";
       # $select_sql .= "      unit = 11 and ";
       $select_sql .= "      micro = '$micro'";
       $select_sql .= "order by micro, prim, unit, secn, local_index"; 

    eval {
        $select_st = $dbh->prepare($select_sql);
        $select_st->execute();
    };
    if ($@) {
        print "error in select from secndx:$@\n";
        exit;
    }

    while ($asts_row = $select_st->fetchrow_hashref) {
        ++$i;

        $crate = $asts_row->{crate};
        $module = $asts_row->{module};
        $secn = $asts_row->{secn};
        $local_index = $asts_row->{local_index};
        $value = $asts_row->{value};

        if (($secn eq "CHAN") && ($local_index == 1))
           { $startChan = $value; next; }

        if ($secn eq "CTLW")
           { 
           if ($local_index == 1)
              {
              $astsCrate = $crate; 
              $astsModule = $module; 
              next; 
              }
           }

        if ($secn eq "NAME")
           { 
           $astsChan = $local_index - 1 + $startChan;

           if ($astsCrate != 0 && $astsModule != 0) 
              {
              my $hashKey = $astsCrate . ":" . $astsModule . ":" . $astsChan;

              if (!(defined $chansHash{$hashKey}))
                 {
                 # if this is a new crate/module/channel, add it
                 # print "ADDING $value to chansHash\n";
                 $chansHash{$hashKey} = $value;
                 print "$hashKey: adding value $value\n";
                 }
              else
                 {
                 if ($chansHash{$hashKey} =~ /^SPARE/ || $chansHash{$hashKey} =~ /^USED/)
                    { 
                    # if the existing value is SPARE, replace it
                    # jrock 09/23/2010 also replace USED (per Sonya)
                    $chansHash{$hashKey} = $value; 
                    print "$hashKey: replacing SPARE OR USED with value $value\n";
                    } 
                 else 
                    {
                    # if the existing value is not SPARE and the new value is not SPARE then flag a conflict
                    # jrock 09/23/2010 also don't overwrite with USED (per Sonya)
                    if (!($value =~ /^SPARE/) && !($value =~ /^USED/))
                       { print "$hashKey: COLLISION! CRATE: $astsCrate MODULE: $astsModule CHANNEL: $astsChan NAME: $chansHash{$hashKey}  NAME: $value\n"; }
                    else { print "$hashKey: not replacing $chansHash{$hashKey} with SPARE or USED\n"; }
                    }
                 }
              }
           }
    }

print "end of preloading Chans Hash\n";
}

#===============================================================
# main code starts here
#===============================================================

if ($#ARGV < 1) { die "Please specify micro, name list file, isFirstMicro, isLastMicro...Exiting!)\n"; }

   my $MICRO = $ARGV[0];
#   my $nameListFile = "ALL";
#   if ($#ARGV > 1)
 $nameListFile = $ARGV[1]; 
# $firstMicro = $ARGV[2]; 
# $lastMicro = $ARGV[3]; 

 if (!(loadNamesList($nameListFile)))
    { print "exiting\n"; exit; }
 $nameCount = @namesToFind;

print "querying for ASTS $MICRO, names in $nameListFile\n";

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

   preloadChansHash($MICRO);

   my $TFname = $MICRO . "asts" . ".substitutions";
   die "Could not open $TFname\n" unless (open(ASTSFILE, '>>'.$TFname));
   $TFname = $MICRO . "samModule" . ".substitutions";
   die "Could not open $TFname\n" unless (open(SAMFILE, '>>'.$TFname));
   $TFname = $MICRO . "samChannel" . ".substitutions";
   die "Could not open $TFname\n" unless (open(SAMCHFILE, '>>'.$TFname));
   $TFname = $MICRO . "camacModule" . ".substitutions";
   die "Could not open $TFname\n" unless (open(CAMACFILE, '>>'.$TFname));

   $TFname = $MICRO . "analogInChans" . ".substitutions";
   die "Could not open $TFname\n" unless (open(LINFILE, '>>'.$TFname));

   $TFname = $MICRO . "linearPolyAnalogIn" . ".substitutions";
   die "Could not open $TFname\n" unless (open(LINPOLYFILE, '>>'.$TFname));
   $TFname = $MICRO . "logPolyAnalogIn" . ".substitutions";
   die "Could not open $TFname\n" unless (open(LOGPOLYFILE, '>>'.$TFname));

   $TFname = $MICRO . "tempSamRef" . ".substitutions";
   die "Could not open $TFname\n" unless (open(TEMPSAMREFFILE, '>>'.$TFname));
   $TFname = $MICRO . "tempSamTypeT" . ".substitutions";
   die "Could not open $TFname\n" unless (open(TEMPSAMTTFILE, '>>'.$TFname));
   $TFname = $MICRO . "dlwgLimits" . ".substitutions";
   die "Could not open $TFname\n" unless (open(DLWGFILE, '>>'.$TFname));

    # load up names list hash
    loadNamesHash();

    #my $select_ioc_sql = 'select distinct prim from secndx order by prim';
    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 .= "       crate, "; 
       $select_ioc_sql .= "       module, "; 
       $select_ioc_sql .= "       function, "; 
       $select_ioc_sql .= "       address "; 
       $select_ioc_sql .= " from slc_data_view_all ";
       $select_ioc_sql .= "where prim = 'ASTS' and ";
#       $select_ioc_sql .= "      (micro = 'LI17' or micro = 'LI18') ";
       $select_ioc_sql .= "      micro = '$MICRO'";
#       $select_ioc_sql .= "      unit in "; 
#       $select_ioc_sql .= "        (select distinct unit from slc_data_view_all ";
#       $select_ioc_sql .= "         where prim='ASTS' and micro='$MICRO' and secn='NAME' and ";
#       $select_ioc_sql .= "         (";
#for (my $i=0; $i<$nameCount; ++$i)
#   {
#   $name = munchName($namesToFind[$i]);
#print "$name is *$name*\n";
#   if (length($name) == 0)
#      { next; }
#   if ($i > 0)
#      { $select_ioc_sql .= " or "; }
#   $select_ioc_sql .= "value like '$name%' "; 
#   }
#       $select_ioc_sql .= "         )";
#       $select_ioc_sql .= "        ) ";
       $select_ioc_sql .= "order by micro, prim, unit, secn, local_index"; 

#if ($firstMicro == 1)
    outputTops(); 
    eval {
print "select: $select_ioc_sql\n";
        $select_ioc_st = $dbh->prepare($select_ioc_sql);
        $select_ioc_st->execute();
    };
    if ($@) {
        print "error in select from secndx:$@\n";
        exit;
    }

    while ($asts_row = $select_ioc_st->fetchrow_hashref) {
        ++$i;

        $micro = $asts_row->{micro};
        $secn = $asts_row->{secn};
        $unit = $asts_row->{unit};
        $astsUnit = $asts_row->{unit};
        $local_index = $asts_row->{local_index};
        $value = $asts_row->{value};
        $crate = $asts_row->{crate};
        $module = $asts_row->{module};
        $function = $asts_row->{function};
        $address = $asts_row->{address};
        if ((!($curr_micro eq $micro)) || ($curr_unit != $unit))
           {
           if (!($curr_micro eq "none"))
              {
              # output to file!
              outputChans;          
              }

           # print "new micro $micro, new unit $unit\n";
           $curr_unit = $unit;
           $currASTSunit = $astsUnit;
           $curr_micro = $micro;
           $startChan = 0;
           $numChans = 0;
           $isTherm = 0;
           $isDlwg = 0;
           $isCamacInhb = 0;
           @names = ();
           @stats = ();
           @lims = ();
           @ptrs = ();
           @scals = ();
           @egus = ();
           @chans = ();
           @ctrls = ();
           @ctrl_PHASs = ();
           @ctrl_TOLs = ();
           @ctrl_LOG10s = ();
           @ctrl_IONs = ();
           @ctrl_GRAY_TOLs = ();
           @ctrl_ASTS_RMSs = ();
           @ctrl_DISABLEs = ();
           @ctrl_NOTOLCHKs = ();

           $astsModule = -1;
           $astsCrate = -1;
           }

        if (($secn eq "CHAN") && ($local_index == 1))
           { $startChan = $value; next; }
        if (($secn eq "CHAN") && ($local_index == 2))
           { $numChans = $value; next; }
        if ($secn eq "SCAL")
           { push @scals, $value; print "**SCAL: $value\n"; next; }
        if ($secn eq "STAT")
           { push @stats, $value; next; }
        if ($secn eq "LIMS")
           { push @lims, $value; next; }
        if ($secn eq "PTR")
           { 
           #IF THE VALUE IS 165, then this is a poly - don't forget to handle this later
           push @ptrs, $value; next;
           }
        if ($secn eq "HDSC")
           { 
           $currHDSC = $value; 
           $isTherm = isTHERM($currHDSC);
           $isDlwg = isDLWG($currHDSC);
           $isCamacInhb = isCAMACINHB($currHDSC);
           print "HDSC: $currHDSC\n"; 
           next; 
           }

        if ($secn eq "CTRL")
           { 
           push @ctrls, $value; 
           push @ctrl_PHASs, has_MSK($value, $PHAS_MSK);
           push @ctrl_TOLs, has_MSK($value, $TOL_MSK);
           push @ctrl_LOG10s, has_MSK($value, $LOG10_MSK);
           push @ctrl_IONs, has_MSK($value, $ION_MSK);
           push @ctrl_GRAY_TOLs, has_MSK($value, $GRAY_TOL_MSK);
           push @ctrl_ASTS_RMSs, has_MSK($value, $ASTS_RMS_MSK);
           push @ctrl_DISABLEs, has_MSK($value, $DISABLE_MSK);
           push @ctrl_NOTOLCHKs, has_MSK($value, $NOTOLCHK_MSK);
           next; 
           }
        if ($secn eq "NAME")
           { 
           push @names, $value; 
           $egu = getEguForName($value);
           push @egus, $egu;
# local_index starts at 1; make this 0-based
           push @chans, $local_index-1; 
#           push @chans, $local_index; 
print "PUSHED NAME: *$value* EGU: $egu  CHAN $local_index\n";
           next; 
           }
        if ($secn eq "CTLW")
           { 
print "crate: $crate, module: $module, function: $function, address: $address\n";
           if ($local_index == 1)
              {
              $astsCrate = $crate; 
              $astsModule = $module; 
              $astsFunction = $function; 
              $astsAddress = $address; 
              next; 
              }
           }
    }
    outputChans;          

    # check - may not need this extra sam info thing!
    outputSAMCHArray;
    outputSAMInfo($MICRO);
    outputCAMACInfo($MICRO);

    $dbh->rollback();
    $dbh->disconnect();
#    if ($lastMicro == 1)
       outputEnds();

    close ASTSFILE;
    close SAMFILE;
    close SAMCHFILE;
    close CAMACFILE;
    close LINFILE;
    close TEMPSAMREFFILE;
    close TEMPSAMTTFILE;
    close DLWGFILE;
    
    # could delete files with no records during this pass...for now, don't
    # use the unlink command
    print "Done\n";

