#!/usr/bin/env python
#==============================================================
#
#  Abs:  A tool to convert a SCP config file to a list of caputs
#  to migrate the settings to stdout
#
#  Name: scpPull
#
#  Facility:  SLAC/LCLS
#
#  Auth: 10-Jan-2011, Dayle Kotturi       (dayle)
#  Rev:  dd-mmm-yyyy, Reviewer's Name     (USERNAME)
#
#  steps for python to parse tim21-30$3.cnf 
#  Note: that despite its name, this file has info for LI20 as well 
#
#  while not EOF:
#  read a line
#  ignore lines starting with !
#  extract beam code (for entire file) from line startin with !  BEAM NO.=           1
#  if the line ends in '-', then strip off '-' and 
#    read the next line, strip off the leading '>' and 
#    append it to this one repeat this until 
#    the line doesn't end with '-'
#  throw line away if 1st field is PAU or TNOM
#  throw line away if 2nd field is not LI20, LI21, LI22, ... , LI30
#
#  for PVs that don't have TRIG as the first field, convert them to 
#    generic name via LUT. Eg SBBP:LI25:208 -> TRIG:LI25:208
#  the 3 field device name is first 3 fields
#  read the 4th field. If it's TOFF or TOH0, then set $DEV:ACTIVATE=0
#                      If it's TACT or TAH0, then set $DEV:ACTIVATE=1
#                      If it's any of the above, read the 5th field.
#                         This is TDES in nsec. set to .............
#                      If it's RACT, then DON'T EXPECT A NUMBER IN 5TH FIELD
#                         Look for COND = string; TIMV = string; pairs until '}'
#                         For each COND,TIMV pair store the values
#                         Match up COND value with a global rule name
#                         Handle TIMV as follows:
#                           If it's "deact" or "DEACT", set this rule's TDES to TDES for this device's
#                             Type 2 data 
#                           If it's any of these *+PSK2_L2, *+PSK2_L3, *+PSK2,
#                             set this rule's TDES to TDES for this device's Type 2 data 
#
# 2011/01/13: values of PSK2, PSK2_L2, PSK2_L3 are all zero
# Date: Fri, 14 Jan 2011 17:16:05 -0800               
# From: "Stanek, Michael W." <stanek@slac.stanford.edu> 
# Subject: RE: Numeric values of PSK2, PSK2_L2, PSK2_L3                         
# All the PSK's should be 0.0                          
#
# Example input for device KLYS:LI24:81. There are two lines in the SCP conf. One
# is Type 2 data:
#
#   KLYS,LI24,    81,TOFF, -0.74957983E+04,TACT,TACT,TACT,  1R4,  
#
# and the second is a multiple-line occurence with Type 3 data:
#
#  KLYS,LI24,    81,RACT,                 RACT,RACT,RACT,  6B0                  -
# >{COND = bcsfault;                                                            -
# >   TIMV = deact;                                                             -
# >   COND = ~tcav3;                                                            -
# >   TIMV = deact;                                                             -
# >   COND = *;                                                                 -
# >   TIMV = *+PSK2;}  
# 
# Example output for device KLYS:LI24:81:
# From just the Type 2 data:
# caput TRIG:LI24:402:BEAMCODE1_TCTL 0 (Notes: 1=TACT,0=TOFF; BEAMCODE1 PV because SCP conf
#                                      is for BEAM NO. 1)
# 
# From Type 3 data (for the rules) and from the Type 2 data (for the delays):
# caput TRIG:LI24:402:RULE0.DESC "BC1 BCSFAULT"
# caput TRIG:LI24:402:RULE0_TDES "" (CHECK nsec ok, how to OR in deact)

# caput TRIG:LI24:402:RULE1.DESC "NO TCAV3"
# caput TRIG:LI24:402:RULE1_TDES "" (CHECK nsec ok, how to OR in deact)

# caput TRIG:LI24:402:RULE7.DESC "DEFAULT" (CHECK this exists with all-zero masks)
# caput TRIG:LI24:402:RULE7_TDES "-0.74957983E+04" (CHECK nsec ok)

# The rest needs to be done on lcls-builder with aidaPull.
#--------------------------------------------------------------
#  Mod:
#  26-Jan-2011, Dayle Kotturi
#    brought in aidaPull contents so that mode could be known and used for the
#    decision making re: setting TDES to BEAMCODE1_TDES vs RULE0_TDES
#
#  27-Jan-2011, Dayle Kotturi
#     changes:
# 1. set TDES, not TDLY (that's the summed readback)
# 2. candidates for once-only migration: TREF, TDEF, MODE
# 3. BEAMCODE1_TCTL values are 0 and 2, not 0 and 1 ---- UNDO 2011/04/14
# 4. Set RULEx_TMVAB15 to 1 when rulex is 'deact'
# 5. For PP mode trigs, set BEAMCODE1_TDES, instead of RULE7_TDES
# 6. If *+PSK2 in rulex delay, set RULEx_TMVAB0 to '1'
# 7. If *+PSK2_L2 in rulex delay, set RULEx_TMVAB1 to '1'
# 8. If *+PSK2_L3 in rulex delay, set RULEx_TMVAB2 to '1'
# 9. Don't write PDUT to TRIG:LIxx:{2,3,4,5}[00-15]:TDEF; write to
#     PDU:LIxx:{2,3,4,5}23:TDEF
# 10.Get TDEF for mode 7 (Reuse) channels a different way:
#     aidaget PDU:LIxx:{2,3,4,5}//REUT
# 11.Waiting on name of PV to put rate into
# 
# #9 is the only one that looks wrong to me now. The reason is that there
# is not just one value of TDEF per module. There is one value per channel.
# 
# [cdlx08] ~/work/scp>grep TDEF READY/scpPull17-30.out | grep LI20:2
# TRIG:LI20:208:TDEF -1000
# TRIG:LI20:206:TDEF -1213
# TRIG:LI20:211:TDEF 0
# TRIG:LI20:215:TDEF 0
# TRIG:LI20:201:TDEF -892
# TRIG:LI20:202:TDEF -892
# TRIG:LI20:207:TDEF 3000
# TRIG:LI20:203:TDEF -892
#
# 28-Feb-2011, Dayle Kotturi
# Add a second pass through infile. The order dictates this.
# The first pass is done to create the list of triggers that have
# default rules. The second pass is done to create the TDES caputs
# for those triggers that have default rules
#
# 02-Mar-2011, Dayle Kotturi
# PDU:<loca>:<module>23:CH0x_TDEF -> PDU:<loca>:<module>23:CHx_TDEF, x=0-9
#
# caput the BEAMCODEx_TDES regardless of whether or not it has a cond exp "*"
# This means that the two passes through infile could be taken out
#
# 16-Mar-2011 Dayle Kotturi
# For the PP0/1 trigs that are KLYS or SBST devices, the BEAMCODE<>_TDES and
# BEAMCODE<>_TCTL should be put to the KLYS/SBST PV, not the TRIG PV. 
#
# So for example, currently:
# caput TRIG:LI20:401:BEAMCODE1_TCTL 2
# caput TRIG:LI20:401:BEAMCODE1_TDES "-0.74957983E+04"
# caput TRIG:LI20:402:BEAMCODE1_TCTL 2
# caput TRIG:LI20:402:BEAMCODE1_TDES "-0.74957983E+04"
#
# would ideally be:
# caput KLYS:LI20:71:BEAMCODE1_TCTL 2
# caput KLYS:LI20:71:BEAMCODE1_TDES "-0.74957983E+04"
# caput KLYS:LI20:81:BEAMCODE1_TCTL 2
# caput KLYS:LI20:81:BEAMCODE1_TDES "-0.74957983E+04"
#
# 17-Mar-2011 Dayle Kotturi
# The request from yesterday should have been only for > TCTL, not for TDES.
#==============================================================
import os
import sys
import subprocess
import optparse

__all__ = ['create_caput_comands','exec_caget_TMSK','exec_aidaget_TREF','exec_aidaget_CHMO','exec_aidaget_PDUT','exec_aidaget_REUT','import_LUT_from_file','find_first', 'import_trig_LUT_from_file','process_options']

# Specify all valid primaries and sectors that you want extracted
primaries = ('TRIG','TRBR','KLYS','SBST','SBBP')

# 2011/02/25: Since normal usage is to deal with only one sector at a time, this array specifies
# the possible ones. Script now takes a passed in arg specifying which sector to work with
sectors = ('LI17','LI20','LI21','LI22','LI23','LI24','LI25','LI26','LI27','LI28','LI29','LI30')

modules = ('2','3','4','5')

# MODE:   0     1     2     3     4      5      6          7
modes = ('ZERO','PP0','TWO','PP1','FOUR','FIVE','Modulo36','Reuse')

# STATUSES:
statuses = ('Disable','Enable','2','3','4','5','6','7','8','9','10')

# 2011/01/26 NEW. Needed to figure out which PV gets SCP conf TDES value
# I.e. whether it goes to generic_name:RULE0_TDLY or generic_name:RULE7_TDLY
# depends on the mode. This dict gets filled in by exec_aidaget_CHMO and used
# by the soon-to-be-imported scpPull 
MODE_dict = {}

# Key is the name found in SCP conf. Look it up in dict and then assign
# the trigger's DESC field to the associated attribute in order to trigger
# the copying of the waveform
global_rules = { 'bcsfault':'BCSFAULT BC1', 'no_gun_perm':'NO GUN PERM BC1', 'NO_GUN_PERM':'NO GUN PERM BC1', '~pockcel_perm':'NO PC PERM BC1', '~one_hertz':'NO 1 HZ BC1', '~shutter_perm':'NO SHTR PERM BC1', '~TS4':'NO TS 4 BC1', '~tcav3':'NO TCAV3 BC1', '*':'Default BC1' }

# The index of this list is used to map to the _ID
# Eg. a trigger device, TRIG:LI21:205, is being migrated over from SCP
# It has mode "PP0". Its RULE0 is BC1 BCSFAULT
# Via this list, TRIG:LI21:205:RULE0_ID would get caput to 1
# Note: This order needs to be kept in sync with what is actually in the global rules.
# Alternatively, this script could go and connect to the global rule PVs and put the DESC
# fields into this array. I.e. global_rule_nums[0] = `caget -t TRIG:SYS0:1:RULEx.DESC`, x=0-10
global_rule_nums = ( 'UNASSIGNED', 'BCSFAULT BC1', 'NO GUN PERM BC1', 'NO PC PERM BC1', 'NO 1 HZ BC1', 'NO SHTR PERM BC1', 'NO TS 4 BC1', 'NO TCAV3 BC1', 'Default BC1' )

default_rules = []

# Ignore lines starting with '!' or blank lines
# Read CSVs are field1 (hex), field2 (hex), tmsk[0], tmsk[1], ..., tmsk[35], comment
# Eg. caget -0x KLYS:LI26:11:TMSK -> KLYS:LI26:11:TMSK 2 0x49249249 0xC000002
# Now you have the mapping between SCP values and mask settings
# 2011/01/30 NEW: put first value into TMSK.A and second into TMSK.B and done
# 2011/02/22 CHANGE: from Kristi, there are 2-32 bit words, can you please
#                    restore 3 16-bit words.  <device>:TMSK0, <device>:TMSK1, <device>:TMSK2
#                    Currently you are restoring <device>:TMSK.A <device>:TMSK.B
#==============================================================


# Given an index into the arrays, write out the caput commands to set
# the binary output records to On or Off based on the value in bxx array
def create_caput_commands(pv, tmsk1, tmsk2):
    #print 'caput %s:TMSK.A %s' % (pv,tmsk1)
    #print 'caput %s:TMSK.B %s' % (pv,tmsk2)

    # tmsk1 and tmsk2 are 32 bit values
    # tmsk1 are the 32 least significant bits, i.e. they map to 'A'
    # tmsk2 are the 32 most  significant bits, i.e. they map to 'B'

    # desired is that the least significant 16 bits of tmsk1 -> TMSK0
    #        and that the most  significant 16 bits of tmsk1 -> TMSK1
    #        and that the least significant 16 bits of tmsk2 -> TMSK2

    if (tmsk1.startswith('0x') or tmsk1.startswith('0X')):
        first_sixteen_bits = int(tmsk1,16) & 0xFF
        print 'caput %s:TMSK0 %s' % (pv,first_sixteen_bits)
        second_sixteen_bits  = int(tmsk1,16) >> 16
        print 'caput %s:TMSK1 %s' % (pv,second_sixteen_bits)
    else: 
        sys.stderr.write('Found non-hex value in tmsk waveform for %s: |%s|. Attempting to parse as decimal' % (pv,tmsk1))
        tmsk1_as_float = float(tmsk1)
        first_sixteen_bits = int(tmsk1_as_float) & 0xFF
        print 'caput %s:TMSK0 %s' % (pv,first_sixteen_bits)
        second_sixteen_bits = int(tmsk1_as_float) >> 16
        print 'caput %s:TMSK1 %s' % (pv,second_sixteen_bits)
        sys.stderr.write('Decimal parse okay: lower 16 bits: %d, upper 16 bits: %d\n' % (first_sixteen_bits,second_sixteen_bits))
    
    if (tmsk2.startswith('0x') or tmsk2.startswith('0X')):
        third_sixteen_bits  = int(tmsk2,16) & 0xFF 
        print 'caput %s:TMSK2 %s' % (pv,third_sixteen_bits)
    else:
        sys.stderr.write('Found non-hex value in tmsk waveform for %s: |%s|. Attempting to parse as decimal' % (pv,tmsk2))
        tmsk2_as_float = float(tmsk2)
        third_sixteen_bits = int(tmsk2_as_float) & 0xFF
        print 'caput %s:TMSK1 %s' % (pv,third_sixteen_bits)
        sys.stderr.write('Decimal parse okay: lower 16 bits: %d, upper 16 bits: ignored\n' % third_sixteen_bits)
    

# Use the look up table to try to get TMSK for the device name
# If it exists, then set up a caput to ?? of the generic trigger name
def exec_caget_TMSK(LUT_dict, s):
    for device, generic_name in LUT_dict.items():

        # added complexity: TRBR PVs are avail only via SLCCAS, i.e. with
        # first two fields swapped
        try:
            (prim,loca,unit) = device.split(':')
        except ValueError, e:
            sys.stderr.write('Could not split: |%s| into 3 colon delimited fields\n' % device)
            return

        if s == loca:
            if prim == 'TRBR':
                #print 'device was: %s' % device
                device = loca + ':' + prim + ':' + unit 
                #print 'device is: %s' % device

            #print device, generic_name
            cagetArg = device + ':TMSK'
            cagetArg = cagetArg.strip()
            #print 'cagetArg is |%s|' % cagetArg
            process = subprocess.Popen(['caget','-t','-0x', cagetArg], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
            (stdoutStr, stderrStr) =  process.communicate()
            #print 'stdoutStr: |%s|' % stdoutStr
            #print 'stderrStr: |%s|' % stderrStr
            if not stderrStr.startswith('Channel connect timed out'):
                # the strip MUST be done to get rid of line feed
                stdoutStr = stdoutStr.strip()
                #try:
                (nelm,field1,field2) = stdoutStr.split()
                #except ValueError, e:
                #sys.stderr.write('No TMSK for %s (Could not split: |%s| into 3 space delimited fields)\n' % (device,stdoutStr))
                #print 'field1: |%s| field2: |%s|' % (field1,field2) 
                create_caput_commands(generic_name,field1,field2)



# THIS ROUTINE IS BREAKING WHEN IT FINDS VALUE OF 8 RETURNED FOR PDU:LI28:{2,3,4}//STAT
# SINCE THESE PVS (ENB_{BPLN,DEQR}) DO NOT NEED SETTING, NO LONGER CALL THIS   
def exec_aidaget_STAT(s):
    print '\n# Pulling PDU:LIxx:<module>//STAT values into caput PDU:LIxx:<module>23:ENB_{BPLN,SEQR}'
    print '#######################################################################################'   
    for m in modules:
        # Only sectors 20 and 30 have a PDU module 5
        if int(m) < 5 or (int(m)==5 and (s == 'LI20' or s == 'LI30')):
            aidaArg = 'PDU:'+s+':'+m+'//STAT'
            aidaArg = aidaArg.strip()
            #print 'aidaget |'+ aidaArg +'|'
            process = subprocess.Popen(['aidaget', aidaArg], shell=False,stdout=subprocess.PIPE)
            (stdoutStr, stderrStr) =  process.communicate()
            if not stdoutStr.startswith('Exception'):
                #print '|' + stdoutStr + '|'
                stat = stdoutStr.strip()
                print '# NOT USED caput PDU:%s:%s23:ENB_BPLN %s' % (s, m, statuses[int(stat)])
                print '# NOT USED caput PDU:%s:%s23:ENB_SEQR %s' % (s, m, statuses[int(stat)])


def exec_aidaget_TREF(s):
    print '\n# Pulling PDU:LIxx:<module>//TREF values into caput PDU:LIxx:<module>23:TREF'
    print '############################################################################'   
    for m in modules:
        # Only sectors 20 and 30 have a PDU module 5
        if int(m) < 5 or (int(m)==5 and (s == 'LI20' or s == 'LI30')):
            aidaArg = 'PDU:'+s+':'+m+'//TREF'
            aidaArg = aidaArg.strip()
            #print 'aidaget |'+ aidaArg +'|'
            process = subprocess.Popen(['aidaget', aidaArg], shell=False,stdout=subprocess.PIPE)
            (stdoutStr, stderrStr) =  process.communicate()
            if not stdoutStr.startswith('Exception'):
                #print '|' + stdoutStr + '|'
                tref = stdoutStr.strip()
                print 'caput PDU:%s:%s23:TREF %s' % (s, m, tref)


def exec_aidaget_CHMO(s):
    print '\n# Pulling PDU:LIxx:<module>//CHMO values into caput TRIG:LIxx:<module><channel>:MODE'
    print '####################################################################################'   
    for m in modules:
        # Only sectors 20 and 30 have a PDU module 5
        if int(m) < 5 or (int(m)==5 and (s == 'LI20' or s == 'LI30')):
            scpPv = 'PDU:'+s+':'+m+'//CHMO'
            #aidaArg = '-format=rows ' + scpPv this doesn't work in the pipe
            aidaArg = scpPv
            aidaArg = aidaArg.strip()
            #print 'aidaget |'+ aidaArg +'|'
            process = subprocess.Popen(['aidaget', aidaArg], shell=False,stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
            (stdoutStr, stderrStr) =  process.communicate()
            if not stdoutStr.startswith('Exception'):
                #print '|' + stdoutStr + '|'
                # There are 16 line feeds in what aidaget returns
                # There is nothing in the variable 'sixteen', but
                # it needs to be there for split to work
                (zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen) = stdoutStr.split('\n') 

                # aidaget returns the MODE for each channel: zero-fifteen as a 
                # string: '0','1',...'7'. Convert these to integers and look
                # up the name in modes at the index MODE to speak caput 
               
                # Ignore any mode == '0'
                mode = int(zero)
                if mode != 0:
                    trig = 'TRIG:%s:%s00' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH00_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(one)
                if mode != 0:
                    trig = 'TRIG:%s:%s01' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH01_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(two)
                if mode != 0:
                    trig = 'TRIG:%s:%s02' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH02_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(three)
                if mode != 0:
                    trig = 'TRIG:%s:%s03' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH03_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(four)
                if mode != 0:
                    trig = 'TRIG:%s:%s04' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH04_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(five)
                if mode != 0:
                    trig = 'TRIG:%s:%s05' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH05_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(six)
                if mode != 0:
                    trig = 'TRIG:%s:%s06' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH06_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(seven)
                if mode != 0:
                    trig = 'TRIG:%s:%s07' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH07_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(eight)
                if mode != 0:
                    trig = 'TRIG:%s:%s08' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH08_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(nine)
                if mode != 0:
                    trig = 'TRIG:%s:%s09' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH09_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(ten)
                if mode != 0:
                    trig = 'TRIG:%s:%s10' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH10_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(eleven)
                if mode != 0:
                    trig = 'TRIG:%s:%s11' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH11_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(twelve)
                if mode != 0:
                    trig = 'TRIG:%s:%s12' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH12_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(thirteen)
                if mode != 0:
                    trig = 'TRIG:%s:%s13' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH13_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(fourteen)
                if mode != 0:
                    trig = 'TRIG:%s:%s14' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH14_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
                mode = int(fifteen)
                if mode != 0:
                    trig = 'TRIG:%s:%s15' % (s,m)
                    MODE_dict [trig] = modes[mode]
                    pdu = 'PDU:%s:%s:CH15_MODE_SET' % (s,m)
                    print '#caput %s %s' % (pdu, modes[mode]) 
            else:
                # TODO: make this write to stderr
                print '# No CHMO for %s' % scpPv 
 

# Use the look up table to try to get PDUT for the device name
# If it exists, then set up a caput to TDEF of the generic trigger name
def exec_aidaget_PDUT(LUT_dict,s):
    print '\n# Pulling TRIG:LIxx:<module>//PDUT values into caput PDU:LIxx:<module>23:CH<channel>_TDEF'
    print '#########################################################################################'   
    for device, generic_name in LUT_dict.items():
        #print device, generic_name
        try:
            (prim,loca,unit) = generic_name.split(':')
        except ValueError, e:
            sys.stderr.write('Could not split: |%s| into 3 colon delimited fields\n' % generic_name)
            return

        if (s == loca): 
            aidaArg = device + '//PDUT'
            aidaArg = aidaArg.strip()
            #print 'aidaArg is |%s|' % aidaArg
            process = subprocess.Popen(['aidaget', aidaArg], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
            (stdoutStr, stderrStr) =  process.communicate()
            #print stdoutStr
            if not stdoutStr.startswith('Exception'):
                stdoutStr = stdoutStr.strip()
                # 2011/01/28 New complexity: don't write to TRIG:LIxx:<mod><chan>:TDEF,
                # write to PDU:LIxx:<mod>23:CH<chan>_TDEF
                unit_number = int(unit)
                #print 'UNIT number is %d' % unit_number
                channel = unit_number % 100 # needs leading 0 if < 10
                module = (unit_number - channel)/100 
                #print 'MODULE number is %d' % module
                # No leading zero needed for channels < 10 2011/03/02
                #if channel < 10:
                #    channel = '0' + str(channel)
                print 'caput PDU:%s:%d23:CH%s_TDEF %s' % (loca,module,channel,stdoutStr) 
            #else:
                # This is ok. Triggers that are mode Reuse do not have a PDUT. Instead they have a default delay in REUT.
                # The scpPull of REUT is done in exec_aida_get_REUT
                #sys.stderr.write('No PDUT for %s\n' % device)

# SPECIAL CASE for the Reuse mode triggers:
# Use the look up table to try to get REUT for the device name
# If it exists, then set up a caput to TDEF of the generic trigger name
def exec_aidaget_REUT(s):
    print '\n# Pulling PDU:LIxx:<module>//REUT values into caput PDU:LIxx:<module>23:CH<channel>_TDEF'
    print '#########################################################################################'   
    for m in modules:
        # Only sectors 20 and 30 have a PDU module 5
        if int(m) < 5 or (int(m)==5 and (s == 'LI20' or s == 'LI30')):
            aidaArg = 'PDU:'+s+':'+m+'//REUT'
            aidaArg = aidaArg.strip()
            #print 'aidaget |'+ aidaArg +'|'
            process = subprocess.Popen(['aidaget', aidaArg], shell=False,stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
            (stdoutStr, stderrStr) =  process.communicate()
            if not stdoutStr.startswith('Exception'):
                #print '|' + stdoutStr + '|'
                # There are 16 line feeds in what aidaget returns
                # There is nothing in the variable 'sixteen', but
                # it needs to be there for split to work
                (zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen) = stdoutStr.split('\n') 

                # aidaget returns the REUT for each channel: zero-fifteen as a 
                # string (which is really an int). 
               
                # Ignore any reut == '0'
                # COULD BE A TODO: use only the CHANNEL 0 REUT values (because all channels > 0 of mode Reuse are not actually used)
                # No leading zero needed for channel<10 2011/03/02
                tdef = int(zero)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH0_TDEF %s' % (s,m,tdef) 
                tdef = int(one)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH1_TDEF %s' % (s,m,tdef) 
                tdef = int(two)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH2_TDEF %s' % (s,m,tdef) 
                tdef = int(three)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH3_TDEF %s' % (s,m,tdef) 
                tdef = int(four)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH4_TDEF %s' % (s,m,tdef) 
                tdef = int(five)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH5_TDEF %s' % (s,m,tdef) 
                tdef = int(six)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH6_TDEF %s' % (s,m,tdef) 
                tdef = int(seven)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH7_TDEF %s' % (s,m,tdef) 
                tdef = int(eight)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH8_TDEF %s' % (s,m,tdef) 
                tdef = int(nine)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH9_TDEF %s' % (s,m,tdef) 
                tdef = int(ten)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH10_TDEF %s' % (s,m,tdef) 
                tdef = int(eleven)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH11_TDEF %s' % (s,m,tdef) 
                tdef = int(twelve)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH12_TDEF %s' % (s,m,tdef) 
                tdef = int(thirteen)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH13_TDEF %s' % (s,m,tdef) 
                tdef = int(fourteen)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH14_TDEF %s' % (s,m,tdef) 
                tdef = int(fifteen)
                if tdef != 0:
                    print 'caput PDU:%s:%s23:CH15_TDEF %s' % (s,m,tdef) 
            else:
                # TODO: make this write to stderr
                print '# No REUT for %s' % scpPv 
 

# Based on http://mail.python.org/pipermail/python-list/2009-July/1212493.html
#def find_first(s, subs, start=None, end=None):
#    results = [s.find(sub, start, end) for sub in subs]
#    results = [r for r in results if r != -1]
#    if results:
#        return min(results)
#
#    return -1

def find_first(s, subs, start=None, end=None):
    results = [s.find(subs, start, end)]
    results = [r for r in results if r != -1]
    if results:
        return min(results)

    return -1


def import_trig_LUT_from_file(trig_LUT_file_path = None):
    trig_LUT_dict = {}

    if (trig_LUT_file_path != None):
        try:
            lut_file = open(trig_LUT_file_path, 'r')
            # print 'Opened ' + trig_LUT_file_path + ' for read of generic trigger name, device name pairs'
        except IOError, e:
            sys.stderr.write('Could not open "%s": %s\n' % (trig_LUT_file_path, e.strerror))
            return None

        for line in lut_file:
            line = line.strip()
            try:
                (generic_name,device)=line.split(',')
                device = device.strip()
                trig_LUT_dict[device] = generic_name
                # print 'pair: %s, %s' % (device,generic_name)
            except ValueError, e:
                sys.stderr.write('Ignoring line |%s|. No pair here.\n' % line)
    return trig_LUT_dict


def process_options(argv):
    if argv is None:
        argv = sys.argv[1:]

    usage = 'Usage: %prog [SCP config file] [trigger lookup table] [optional: LI<sector> default is all]'    
    version = '%prog 0.1'
    parser = optparse.OptionParser(usage=usage, version=version)

    parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='print verbose output')

    parser.set_defaults(verbose=False,
        db_file=None)

    (options, args) = parser.parse_args(argv)

    if len(args) >= 2:
        options.scp_config_file_path = os.path.normcase(args[0])
        options.trig_LUT_file_path = os.path.normcase(args[1])
        # print 'process_options: Using generic names'
        if len(args) == 3:
            options.sector = os.path.normcase(args[2])
            if not ((options.sector).startswith('LI')):
                sys.stderr.write('Unrecognized input in arg3 "%s". Expecting LIxx\n' % options.sector)
                return None
            print 'process_options: Creating caput commands for sector %s' % options.sector
        else:
            options.sector = "all"
            print 'process_options: Creating caput commands for all sectors'
    else:
        options.scp_config_file_path = None
        options.trig_LUT_file_path = None
        options.sector = "all"
        # print 'process_options: Using device names, since no generic name map given'

    return options 

def main(argv=None):
    num_comments = 0
    parsing_multi_line = False     
    last_line = ''
    num_pass = 1

    options = process_options(argv)

    # Set up dictionary to map devices to their generic trigger name
    # I.e. KLYS:LI26:11 maps to TRIG:LI26:201
    # This is used to set up PVs in EPICS that are now named the generic
    # way but which were named by device in the SCP. This is true for
    # the PVs that indicate whether the device is active or not.
    # print 'trig_LUT_file_path is: %s' % options.trig_LUT_file_path
    trig_LUT = import_trig_LUT_from_file(options.trig_LUT_file_path) 


    if options.sector == 'all':
        for s in sectors:
            #print 'Getting all PDUTs that exist via device name and writing out caputs with generic trigger name TDEFs'
            exec_aidaget_PDUT(trig_LUT, s)
            exec_aidaget_REUT(s)
            exec_aidaget_CHMO(s) # DO NOT COMMENT THIS OUT TO SAVE TIME. MAIN PROGRAM USES MODE_dict
            exec_aidaget_TREF(s)
            #exec_aidaget_STAT(s) NOT NEEDED. VALUE OF '8' FOR PDU:LI28:{2,3,4}//STAT IS BREAKING THIS 
            print '\n# Pulling <device>:TMSK values into caput <generic_name>:TMSK.A and <generic_name>:TMSK.B'
            print '#########################################################################################'   
            exec_caget_TMSK(trig_LUT, s)
    else:
        #print 'Getting all PDUTs that exist via device name and writing out caputs with generic trigger name TDEFs'
        exec_aidaget_PDUT(trig_LUT, options.sector)
        exec_aidaget_REUT(options.sector)
        exec_aidaget_CHMO(options.sector) # DO NOT COMMENT THIS OUT TO SAVE TIME. MAIN PROGRAM USES MODE_dict
        exec_aidaget_TREF(options.sector)
        #exec_aidaget_STAT(options.sector) NOT NEEDED. VALUE OF '8' FOR PDU:LI28:{2,3,4}//STAT IS BREAKING THIS 

        print '\n# Pulling <device>:TMSK values into caput <generic_name>:TMSK.A and <generic_name>:TMSK.B'
        print '#########################################################################################'   
        exec_caget_TMSK(trig_LUT, options.sector)

    # 2011/02/28 new loop for num_pass
    # Read in_file twice. The first time through, deal with the type 1 data (to parse beam code)
    # and the type 3 data (to make the list of triggers with default rules
    # The second time through, deal with type 2 data, making use of the list of default rules
    # now that it's been created

    for num_pass in 1,2:
        num_comments = 0
        if num_pass == 1:
            print 'Pass #1 work with the rules part of .cnf file'
        else:
            print 'Pass #2 work with the tdes part of .cnf file'

        if (options.scp_config_file_path):
            try:
                in_file = open(options.scp_config_file_path, 'r')
                # print 'Opened ' + options.scp_config_file_path + ' for read'
            except IOError, e:
                sys.stderr.write('Could not open "%s": %s\n' % (options.scp_config_file_path, e.strerror))
                return None
    
            if num_pass == 1:
                print '# Using this mapping between SCP conditional expression names and EPICS global rules:'
                print '#    SCP name = EPICS name'
                for k,v in global_rules.iteritems():
                    print '#    "%s" = "%s"' % (k,v)
                print '\n# Using this numbering for EPICS global rules:'
                for k in global_rule_nums:
                    print '# %d. %s' % (global_rule_nums.index(k),k) 
                print
        
                print '\n# Pulling tim<sector range>.cnf into caput TRIG:LIxx:<module><channel>:BEAMCODE1_TCTL,RULEx_TDES,BEAMCODE1_TDES.RULEx.DESC'
                print '##########################################################################################################################'   

            # Example input line types:
            # 1. the comment:
            #  !TIM21-30$3.CNF
            # !13-DEC-10 11:16:37
            # !DIRECTORY=SCRATCH 
            # !  BEAM NO.=           1 <----------IMPORTANT: this means
            #                           the file is ONLY for Beam Code 1
            # !TITLE=Beam 1 LCLS 13.6 GeV                                        
            # !
            # 2. the active (="TACT" or "TAH0" or "TALO", for MOD36) 
            #   vs. inactive (="TOFF" or "TOHO" or "TOL0") trigger:
            #   TRIG,LI21,   214,TACT, -0.10000000E+05,TACT,TACT,TACT,  1R4,
            #   TRIG,LI21,   209,TOFF, -0.66386554E+03,TACT,TACT,TACT,  1R4,   
            #   TRBR,LI24,   410,TOH0,  0.99999990E+07,TACT,TACT,TACT,  1R4,
            #   TRBR,LI29,   207,TAH0,  0.42403359E+05,TACT,TACT,TACT,  1R4
            #   TRBR,LI29,   410,TAL0,  0.17000000E+07,TACT,TACT,TACT, 1R4,
            # 3. the trigger rule conditions 
            #   KLYS,LI21,    11,RACT,                 RACT,RACT,RACT,  4B0                  -
            # >{COND = bcsfault;                                                            -
            # >   TIMV = deact;                                                             -
            # >   COND = no_gun_perm;                                                       -
            # >   TIMV = deact;}                                
            for line in in_file:
                bad = False
                # Handle input line type 1
                if line.startswith( ' !' ):
                    if line.startswith( ' !  BEAM NO.='):
                        (label,beam_code) = line.split('=')
                        beam_code = beam_code.strip()
                        # print 'Found beam code = |%s|' % beam_code
                        # This will be used to determine PV names where
                        # beam code is in the name (i.e. $DEVICE:BEAMCODEx_TCTL)
                    else: 
                        num_comments = num_comments + 1 
                        # print 'Type 1: ignoring comment [' + num_comments + ']: ' + line 
                else: 
                    # Now, remove line feed
                    line = line.strip()
                    # Check what you got
                    # print '|' + line + '|'
    
                    # Look for type 3 data 
                    if num_pass == 1 and line.endswith( '-' ): 
                        #print 'Type 3 data continues past this line: |' + line + '|'
    
                        # Handle input line type 3
                        if line.startswith( '>' ): # leading blank was removed by strip() above
                            # print 'Type 3 data continuation: |' + line + '|'
                            # multi line has already been detected
                            # strip off the ' >' chars at the front of a continued line
                            # not working: line.lstrip( ' >' )
                            multi_line = last_line + line  
                            #print 'Type 3 line becomes: |' + multi_line + '|'
                        
                            # Maybe needed to build on, depending what's next
                            last_line = multi_line
                        else: 
                            # it is the first line of a multi-line rule
                            last_line = line
                    else: 
                        # Look for the end of type 3 data
                        if num_pass == 1 and line.startswith( '>' ): # leading blank was removed by strip() above
                            # print 'Type 3 data ending: |' + line + '|'
                            multi_line = last_line + line  
                            # print 'Type 3: |' + multi_line + '|'
                            # Do processing on multi_line. 
                            # What's important? Take out the first 3 fields as device,
                            # take out the 4th field as activate/deactive, 
                            # take out the 5th field as TDES,
                            # inside {}, parse the COND, TIMV pairs
                            list = multi_line.split( ',' )
                            # We only care KLYS, SBBP, SBST, TRIG primaries
                            if list[0] in primaries:
                                # We only care about the sectors specified in the array "sectors"
                                if (options.sector == 'all' and list[1] in sectors) or (options.sector != 'all' and options.sector == list[1]):
                                    
                                    list[0] = list[0].strip()
                                    list[1] = list[1].strip()
                                    list[2] = list[2].strip()
    
                                    device = "%s:%s:%s" % (list[0],list[1],list[2])
                                    activate = list[3].strip()
                                    tdes = list[4].strip()
    
                                    #print 'device is: ' + device + ', activate is: ' + activate + ', tdes is: ' + tdes
                                    # Look up device in LUT for its generic trigger name 
                                    # and use that in place of 'device' 
                                    if (options.trig_LUT_file_path != None):
                                        # print 'Looking up |%s|' % device
                                        try:
                                            generic_name = trig_LUT[device]
                                            # print 'Replacing device name, |%s|, with generic trigger name, |%s|' % (device,generic_name)
                                        except KeyError, e:
                                            bad = True
                                            sys.stderr.write('Could not find this device in dict:|%s|\n' % device)
                                    else:
                                        # Use this for testing if you don't have the mapping
                                        # print 'Using device names'
                                        generic_name = device
    
                                    i = 5
                                    #print 'There are %d CSVs in the list' % len(list)
                                    while i < len(list): 
                                        #print 'list[%d] = %s' % (i,list[i])
                                        # Extract the substring inside the {}
                                        start = find_first(list[i],'{') 
                                        if (start == -1 ):
                                            i = i + 1
                                        else:
                                            #print 'Found { at index %d' % start
                                            end = find_first(list[i],'}')
                                            if (end != -1 ):
                                                #print 'Found } at index %d' % end
                                                trig_rule_num = 0
                                                # Make new string from what's inside {}
                                                subs = list[i][start+1:end]
                                                #print 'Parse COND/TIMV pairs out of this: |%s|' % subs
                                                # Repeat this until you get them all (i.e. until start = -1)
                                                start_cond = find_first(subs,'COND = ')
                                                while (start_cond != -1):
                                                    #print 'Found COND = at index: %d' % start_cond
                                                    # First, get the rule
                                                    end_cond = find_first(subs,';')
                                                    rule = subs[start_cond+7:end_cond]
                                                    #rule = rule.strip()
    
                                                    # Now, get the time delay. Advance past end of 'COND = <str>;' to begin
                                                    subs = subs[end_cond+1:]
                                                    #print 'For TIMV, subs is now: %s' % subs
                                                    start_timv = find_first(subs,'TIMV = ') 
                                                    #print 'Found TIMV = at index: %d' % start_timv
                                                    start_timv += 7
                                                    if (start_timv == -1 ):
                                                        sys.stderr.write('Device %s, generic name %s: %d Error: no delay for Rule\n' % (device,generic_name,trig_rule_num,rule))
                                                    else:
                                                        end_timv = find_first(subs,';')
                                                        time_delay = subs[start_timv:end_timv]
                                                        time_delay = time_delay.strip()
                                                        # print 'Device %s, generic name %s: %d. Rule: %s; Delay: |%s|' % (device,generic_name,trig_rule_num,rule,time_delay)
    
                                                        # Translate rule from its SCP name to EPICS name 
                                                        # If epics_rule.contains('Default') make it rule 7?
                                                        for scp_rule in global_rules.keys():
                                                            #print 'comparing %s to %s' % (rule,scp_rule)
                                                            if scp_rule == rule:
                                                                epics_rule = global_rules[scp_rule]
                                                                # print 'Found scpRule: %s. Matching it to epicsRule: %s' % (scp_rule,epics_rule) 
                                                                if scp_rule == '*':
                                                                    print '# Default rule set for %s:RULE7.DESC' % generic_name
                                                                    print 'caput %s:RULE7.DESC "%s"' % (generic_name,epics_rule)
                                                                    default_rules.append(generic_name)
                                                                    #print 'Appending |%s| to default_rules' % generic_name
                                                                else:
                                                                    print 'caput %s:RULE%s.DESC "%s"' % (generic_name,trig_rule_num,epics_rule)
    
                                                                # Get the number of epicsRule next
                                                                for rule in global_rule_nums:
                                                                    if epics_rule == rule:
                                                                        epics_rule_num = global_rule_nums.index(rule)
                                                                        #print 'Found %s at index %d' % (epics_rule,epics_rule_num) 
                                                                        if scp_rule == '*': 
                                                                            print 'caput %s:RULE7_ID %s' % (generic_name,epics_rule_num)
                                                                        else:
                                                                            print 'caput %s:RULE%s_ID %s' % (generic_name,trig_rule_num,epics_rule_num)
                                                                        # Handle the time_delay here:
                                                                        if time_delay == '*+PSK2' or time_delay == '*+psk2':
                                                                            print 'caput %s:RULE%s_TMVAB0 On' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB1 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB2 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB3 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB4 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB5 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB6 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB7 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB8 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB9 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB10 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB11 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB12 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB13 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB14 Off' % (generic_name,trig_rule_num)
                                                                            print 'caput %s:RULE%s_TMVAB15 Off' % (generic_name,trig_rule_num)
                                                                        else:
                                                                            if time_delay == '*+PSK2_L2' or time_delay == '*+psk2_l2':
                                                                                print 'caput %s:RULE%s_TMVAB0 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB1 On' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB2 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB3 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB4 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB5 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB6 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB7 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB8 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB9 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB10 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB11 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB12 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB13 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB14 Off' % (generic_name,trig_rule_num)
                                                                                print 'caput %s:RULE%s_TMVAB15 Off' % (generic_name,trig_rule_num)
                                                                            else:
                                                                                if time_delay == '*+PSK2_L3' or time_delay == '*+psk2_l3':
                                                                                    print 'caput %s:RULE%s_TMVAB0 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB1 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB2 On' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB3 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB4 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB5 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB6 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB7 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB8 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB9 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB10 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB11 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB12 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB13 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB14 Off' % (generic_name,trig_rule_num)
                                                                                    print 'caput %s:RULE%s_TMVAB15 Off' % (generic_name,trig_rule_num)
                                                                                else:
                                                                                    if time_delay == '*+PSK2TS' or time_delay == '*+psk2ts':
                                                                                        print 'caput %s:RULE%s_TMVAB0 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB1 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB2 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB3 On' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB4 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB5 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB6 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB7 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB8 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB9 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB10 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB11 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB12 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB13 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB14 Off' % (generic_name,trig_rule_num)
                                                                                        print 'caput %s:RULE%s_TMVAB15 On' % (generic_name,trig_rule_num)
                                                                                    else:
                                                                                        if time_delay == 'deact' or time_delay == 'DEACT':
                                                                                            # CHANGE 2011/02/22: Kristi wants to set the activate/deactivate 
                                                                                            # for a conditional rule to be 
                                                                                            # <device>:RULE<rl>_TCTL  "Deactivate"  = 0
                                                                                            #                         "Reactivate"  = 1
                                                                                            # Instead of <device>:TMSKB15
    
                                                                                            # SO, REPLACE ALL THIS:
                                                                                            # Clear bits 0-14, set bit 15
                                                                                            #print 'caput %s:RULE%s_TMVAB0 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB1 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB2 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB3 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB4 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB5 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB6 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB7 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB8 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB9 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB10 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB11 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB12 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB13 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB14 Off' % (generic_name,trig_rule_num)
                                                                                            #print 'caput %s:RULE%s_TMVAB15 On' % (generic_name,trig_rule_num)
    
                                                                                            # WITH:
                                                                                            print 'caput %s:RULE%s_TCTL Deactivate' % (generic_name,trig_rule_num)
                                                                                        else:
                                                                                            sys.stderr.write('Unrecognized TIMV string: |%s| for device: %s\n' % (time_delay,device))
    
                                                        # Move to next pair
                                                        #print 'For next pair, subs is now: %s' % subs
                                                        trig_rule_num = trig_rule_num + 1
                                                        subs = subs[end_timv+1:]
                                                        start_cond = find_first(subs,'COND = ') 
                                            i = i + 1
    
                            # Reset multi-line to NULL
                            multi_line = ''
                        else: 
                            if num_pass == 2 and not line.endswith( '-' ):
                                # Handle input line type 2
                                #print 'Type 2: |' + line + '|' 
                                list = line.split( ',' )
                                # We only care KLYS, SBBP, SBST, TRIG primaries
                                if list[0] in primaries:
                                    # We only care about the sectors specified in the array "sectors"
                                    if (options.sector == 'all' and list[1] in sectors) or (options.sector != 'all' and options.sector == list[1]):
                                        list[0] = list[0].strip()
                                        list[1] = list[1].strip()
                                        list[2] = list[2].strip()
                                        activate = list[3].strip()
                                        tdes = list[4].strip()
                                        device = '%s:%s:%s' % (list[0],list[1],list[2])
        
                                        # Look up device in LUT for its generic trigger name 
                                        # and use that in place of 'device' 
                                        if (options.trig_LUT_file_path != None):
                                            # print 'Looking up |%s|' % device
                                            try:
                                                generic_name = trig_LUT[device]
                                                # print 'Replacing device name, |%s|, with generic trigger name, |%s|' % (device,generic_name)
                                            except KeyError, e:
                                                bad = True
                                                sys.stderr.write('Could not find this device in dict:|%s|\n' % device)
                                        else:
                                            # Use this for testing if you don't have the mapping
                                            # print 'Using device names'
                                            generic_name = device
        
                                        if not bad:
                                            # print 'Device %s: Activated? (Y=TACT N=TOFF): %s; TDES (nsec): %s' % (device,activate,tdes)
                                            attribute = 'BEAMCODE'+beam_code+'_TCTL'
                                            if activate == 'TACT' or activate == 'TAH0' or activate == 'TAL0':
# 2011/04/14 undo
                                                value = 1 
                                            else:
                                                if activate == 'TOFF' or activate == 'TOH0' or activate == 'TOL0':
                                                    value = 0
                                                else:
                                                    # weird value
                                                    sys.stderr.write('Unrecognized value for activate/deactivated: "%s"\n' % activate)

                                            # 2011/03/16 Use device name instead of generic_name for KLYS and SBST
                                            if device.startswith('KLYS') or device.startswith('SBST'):
                                                print 'caput %s:%s %s' % (device,attribute,value)
                                            else:
                                                print 'caput %s:%s %s' % (generic_name,attribute,value)

                                            try:
                                                # Use beamcode1_tdes if it's PP0 or PP1; use rule0_tdes otherwise
                                                if MODE_dict[generic_name]=='PP0' or MODE_dict[generic_name]=='PP1':
                                                    # 2011/01/28 NEW: only set this if a default rule exists for this trigger. 
                                                    # Use a list "default_rules" to keep track
                                                    # 2011/03/02 NEWER: want to caput BEAMCODE1_TDES regardless of whether cond exp "*" is 
                                                    # there or not
                                                    #if generic_name in default_rules:
                                                    #    print '# FOUND DEFAULT RULE for %s' % generic_name

                                                    # 2011/03/16 Use device name instead of generic_name for KLYS and SBST
                                                    # 2011/03/17 The change is not needed
                                                    #if device.startswith('KLYS') or device.startswith('SBST'):
                                                    #    print 'caput %s:BEAMCODE1_TDES "%s"' % (device,tdes)
                                                    #else:
                                                    print 'caput %s:BEAMCODE1_TDES "%s"' % (generic_name,tdes)
                                                    #else:
                                                    #    print '# NO DEFAULT RULE so no caput %s:BEAMCODE1_TDES "%s"' % (generic_name,tdes)
                                                else:
                                                    print 'caput %s:RULE0_TDES "%s"' % (generic_name,tdes)
                                            except KeyError, e:
                                                sys.stderr.write('Key %s" not in MODE_dict\n' % (generic_name))
                                    #else:
                                    #    print 'Ignoring device: %s' % generic_name
                                #else:
                                #    print 'Ignoring device: %s' % generic_name
        
                                #assemble_cvs_inputs_from_file(key,value)
                                #export_release_site_file(inputs)
                   
                                #print 'done with ' + line
                                # repeat above for all lines in file
    
            in_file.close()
            num_pass = 2
    

    return 0
    

if __name__ == '__main__':
    status = main()
    sys.exit(status)
