def sbitReadOut(args):
    """
    Launches a call of sbitReadOut.py

    args - object returned by argparse.ArgumentParser.parse_args()
    """

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    # Determine number of OH's
    cardName = getCardName(args.shelf,args.slot)
    amcBoard = HwAMC(cardName, args.debug)
    print('opened connection')

    for ohN in range(0,amcBoard.nOHs):
        # Skip masked OH's
        if( not ((args.ohMask >> ohN) & 0x1)):
            continue

        ohKey = (args.shelf,args.slot,ohN)
        print("Reading out SBITs from shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

        # Get & make the output directory
        dirPath = makeScanDir(args.slot, ohN, "sbitMonRO", startTime, args.shelf)

        # Build Command
        cmd = [
                "sbitReadOut.py",
                "--gemType={}".format(args.gemType),
                "--detType={}".format(args.detType),
                "--vfatmask=0x{:x}".format(args.vfatmask if (args.vfatmask is not None) else amcBoard.getLinkVFATMask(ohN) ),
                str(args.shelf),
                str(args.slot),
                str(ohN),
                str(args.time),
                dirPath
                ]

        # debug flag raised?
        if args.debug:
            cmd.insert(1,"--debug")

        # Additional options
        if args.amc13local:
            cmd.insert(1,"--amc13local")
        if args.fakeTTC:
            cmd.insert(1,"--fakeTTC")
        if args.t3trig:
            cmd.insert(1,"--t3trig")

        # Execute
        executeCmd(cmd,dirPath)
        print("Finished reading out SBITs from shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

    print("Finished reading out SBITs from all optohybrids on shelf{0} slot{1} in ohMask: 0x{2:x}".format(args.shelf,args.slot,args.ohMask))

    return
def ultraThreshold(args):
    """
    Launches a call of ultraThreshold.py

    args - object returned by argparse.ArgumentParser.parse_args()
    """

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    # Determine number of OH's
    cardName = getCardName(args.shelf,args.slot)
    amcBoard = HwAMC(cardName, args.debug)
    print('opened connection')

    for ohN in range(0,amcBoard.nOHs):
        # Skip masked OH's
        if( not ((args.ohMask >> ohN) & 0x1)):
            continue

        ohKey = (args.shelf,args.slot,ohN)
        print("Launching CFG_THR_ARM_DAC scan for shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

        # Get & make the output directory
        dirPath = makeScanDir(args.slot, ohN, "thresholdch", startTime, args.shelf)

        # Build Command
        cmd = [
                "ultraThreshold.py",
                "--gemType={}".format(args.gemType),
                "--detType={}".format(args.detType),
                "--chMax={}".format(args.chMax),
                "--chMin={}".format(args.chMin),
                "-f {0}/ThresholdScanData.root".format(dirPath),
                "-g {}".format(ohN),
                "--nevts={}".format(args.nevts),
                "--perchannel",
                "--shelf={}".format(args.shelf),
                "--slot={}".format(args.slot),
                "--vfatmask=0x{:x}".format(args.vfatmask if (args.vfatmask is not None) else amcBoard.getLinkVFATMask(ohN) ),
                ]

        # debug flag raised?
        if args.debug:
            cmd.append("-d")

        # Execute
        executeCmd(cmd,dirPath)
        print("Finished CFG_THR_ARM_DAC scan for shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

    print("Finished all CFG_THR_ARM_DAC scans for all optohybrids on shelf{0} slot{1} in ohMask: 0x{2:x}".format(args.shelf,args.slot,args.ohMask))

    return
def ultraScurve(args):
    """
    Launches a call of ultraScurve.py

    args - object returned by argparse.ArgumentParser.parse_args()
    """

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    # Determine number of OH's
    cardName = getCardName(args.shelf,args.slot)
    amcBoard = HwAMC(cardName, args.debug)
    print('opened connection')

    from gempython.vfatqc.utils.scanUtils import launchSCurve
    for ohN in range(0,amcBoard.nOHs):
        # Skip masked OH's
        if( not ((args.ohMask >> ohN) & 0x1)):
            continue

        ohKey = (args.shelf,args.slot,ohN)
        print("Launching scurve for shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

        # Get & make the output directory
        dirPath = makeScanDir(args.slot, ohN, "scurve", startTime, args.shelf)
        logFile = "%s/scanLog.log"%(dirPath)

        # Launch the scurve
        launchSCurve(
                cardName = cardName,
                chMax = args.chMax,
                chMin = args.chMin,
                filename = "{}/SCurveData.root".format(dirPath),
                latency = args.latency,
                link = ohN,
                logFile = logFile,
                makeLogFile = True,
                mspl = args.mspl,
                nevts = args.nevts,
                setChanRegs = False,
                vfatmask = (args.vfatmask if (args.vfatmask is not None) else amcBoard.getLinkVFATMask(ohN)),
                voltageStepPulse = True,
                gemType = args.gemType,
                detType = args.detType)

        # Execute
        runCommand( ["chmod","-R","g+r",dirPath] )
        print("Finished scurve for shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

    print("Finished all scurves for all optohybrids on shelf{0} slot{1} in ohMask: 0x{2:x}".format(args.shelf,args.slot,args.ohMask))

    return
def checkSbitMappingAndRate(args):
    """
    Launches a call of checkSbitMappingAndRate.py

    args - object returned by argparse.ArgumentParser.parse_args()
    """

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    # Determine number of OH's
    cardName = getCardName(args.shelf,args.slot)
    amcBoard = HwAMC(cardName, args.debug)
    print('opened connection')

    for ohN in range(0,amcBoard.nOHs):
        # Skip masked OH's
        if( not ((args.ohMask >> ohN) & 0x1)):
            continue

        ohKey = (args.shelf,args.slot,ohN)
        print("Checking SBIT Mapping for shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

        # Get & make the output directory
        dirPath = makeScanDir(args.slot, ohN, "sbitMonInt", startTime, args.shelf)

        # Build Command
        cmd = [
                "checkSbitMappingAndRate.py",
                "--gemType={}".format(args.gemType),
                "--detType={}".format(args.detType),
                "--shelf={}".format(args.shelf),
                "--slot={}".format(args.slot),
                "-f {}/SBitMappingAndRateData.root".format(dirPath),
                "-g {}".format(ohN),
                "--nevts={}".format(args.nevts),
                "--rates={}".format(args.rates),
                "--time={}".format(args.time),
                "--vfatmask=0x{:x}".format(args.vfatmask if (args.vfatmask is not None) else amcBoard.getLinkVFATMask(ohN) ),
                "--voltageStepPulse"
                ]

        # debug flag raised?
        if args.debug:
            cmd.append("-d")

        # Execute
        executeCmd(cmd,dirPath)
        print("Finished Checking SBIT Mapping for shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

    print("Finished Checking SBIT Mapping for all optohybrids on shelf{0} slot{1} in ohMask: 0x{2:x}".format(args.shelf,args.slot,args.ohMask))

    return
def monitorT(args):
    """
    Launches a call of monitorTemperatures.py

    args - object returned by argparse.ArgumentParser.parse_args()
    """

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    dirPath = makeScanDir(args.slot, -1, "temperature", startTime, args.shelf)

    # Build Command
    cmd = [
            "monitorTemperatures.py",
            "--gemType={}".format(args.gemType),
            "--detType={}".format(args.detType),
            "-f {}/temperatureData.root".format(dirPath),
            "--noOHs",
            "--noVFATs",
            "-t {}".format(args.time),
            str(args.shelf),
            str(args.slot),
            "0x{:x}".format(args.ohMask)
            ]

    # debug flag raised?
    if args.debug:
        cmd.insert(1,"--debug")
    if args.extTempVFAT:
        cmd.insert(1,"--extTempVFAT")

    # Execute
    try:
        executeCmd(cmd,dirPath)
    except KeyboardInterrupt:
        print("Finished monitoring temperatures for optohybrids on shelf{0} slot{1} in ohMask: 0x{2:x}".format(args.shelf,args.slot,args.ohMask))

    return
def dacScanV3(args):
    """
    Launches a call of dacScanV3.py

    args - object returned by argparse.ArgumentParser.parse_args()
    """

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    # Make output directory
    dirPath = makeScanDir(args.slot, -1, "dacScanV3", startTime, args.shelf)

    # Build Command
    cmd = [
            "dacScanV3.py",
            "--gemType={}".format(args.gemType),
            "--detType={}".format(args.detType),
            "-f {}/dacScanV3.root".format(dirPath),
            str(args.shelf),
            str(args.slot),
            "0x{:x}".format(args.ohMask)
            ]

    # debug flag raised?
    if args.debug:
        cmd.insert(1,"--debug")

    # Additional Options
    if args.dacSelect is not None:
        cmd.insert(1,"--dacSelect={}".format(args.dacSelect))
    if args.extRefADC:
        cmd.insert(1,"--extRefADC")

    # Execute
    executeCmd(cmd,dirPath)
    print("Finished DAC scans for optohybrids on shelf{0} slot{1} in ohMask: 0x{2:x}".format(args.shelf,args.slot,args.ohMask))

    return
def sbitThreshScan(args):
    """
    Launches a call of sbitThreshScan.py

    args - object returned by argparse.ArgumentParser.parse_args()
    """

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    # Make output directory
    dirPath = makeScanDir(args.slot, -1, "sbitRateor", startTime, args.shelf)

    # Build Command
    cmd = [
            "sbitThreshScan.py",
            "--gemType {}".format(args.gemType),
            "--detType {}".format(args.detType),
            "-f {}/SBitRateData.root".format(dirPath),
            "--scanmax={}".format(args.scanmax),
            "--scanmin={}".format(args.scanmin),
            "--stepSize={}".format(args.stepSize),
            "--waitTime={}".format(args.waitTime),
            str(args.shelf),
            str(args.slot),
            "0x{:x}".format(args.ohMask)
            ]

    # debug flag raised?
    if args.debug:
        cmd.insert(1,"--debug")

    # Execute
    executeCmd(cmd,dirPath)
    print("Finished all SBIT Rate vs. CFG_THR_ARM_DAC scans for all optohybrids on shelf{0} slot{1} in ohMask: 0x{2:x}".format(args.shelf,args.slot,args.ohMask))

    return
    amcBoard = HwAMC(cardName, args.debug)
    print("Opened connection")

    # Get DATA_PATH
    dataPath = os.getenv("DATA_PATH")

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    for ohN in range(0, amcBoard.nOHs):
        # Skip masked OH's
        if (not ((args.ohMask >> ohN) & 0x1)):
            continue

        dict_dirPaths[ohN] = makeScanDir(args.slot,
                                         ohN,
                                         "iterTrim",
                                         startTime,
                                         shelf=args.shelf)

        # Check to make sure dirPath exists
        if not os.path.exists(dict_dirPaths[ohN]):
            print("Directory {:s} does not exist, exiting".format(
                dict_dirPaths[ohN]))
            sys.exit(os.EX_CANTCREAT)

    # Declare the hardware board
    cardName = getCardName(args.shelf, args.slot)

    for ohN in range(0, amcBoard.nOHs):
        # Skip masked OH's
        if (not ((args.ohMask >> ohN) & 0x1)):
def ultraLatency(args):
    """
    Launches a call of ultraLatency.py

    args - object returned by argparse.ArgumentParser.parse_args()
    """

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    # Determine number of OH's
    cardName = getCardName(args.shelf,args.slot)
    amcBoard = HwAMC(cardName, args.debug)
    print('opened connection')

    for ohN in range(0,amcBoard.nOHs):
        # Skip masked OH's
        if( not ((args.ohMask >> ohN) & 0x1)):
            continue

        ohKey = (args.shelf,args.slot,ohN)
        print("Launching CFG_LATENCY scan for shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

        # Get & make the output directory
        dirPath = makeScanDir(args.slot, ohN, "latency", startTime, args.shelf)

        # Get base command
        cmd = [
                "ultraLatency.py",
                "--gemType={}".format(args.gemType),
                "--detType={}".format(args.detType),
                "--filename={}/LatencyScanData.root".format(dirPath),
                "-g {}".format(ohN),
                "--mspl={}".format(args.mspl),
                "--nevts={}".format(args.nevts),
                "--scanmax={}".format(args.scanmax),
                "--scanmin={}".format(args.scanmin),
                "--shelf={}".format(args.shelf),
                "--slot={}".format(args.slot),
                "--stepSize={}".format(args.stepSize),
                "--vfatmask=0x{:x}".format(args.vfatmask if (args.vfatmask is not None) else amcBoard.getLinkVFATMask(ohN) ),
                ]

        # debug flag raised?
        if args.debug:
            cmd.append("-d")

        # Additional options
        if args.throttle is not None:
            cmd.append( "--throttle=%i"%(args.throttle) )
        if args.amc13local:
            cmd.append( "--amc13local")
        if args.t3trig:
            cmd.append( "--t3trig")
        if args.randoms is not None:
            cmd.append( "--randoms=%i"%(args.randoms))
        if args.internal:
            cmd.append( "--internal")
            cmd.append( "--voltageStepPulse")
            if args.chan is not None:
                cmd.append("--chan={}".format(args.chan))
            if args.vcal is not None:
                cmd.append("--vcal={}".format(args.vcal))

        # Execute
        executeCmd(cmd,dirPath)
        print("Finished CFG_LATENCY scan for shelf{0} slot{1} OH{2} detector {3}".format(args.slot,args.shelf,ohN,chamber_config[ohKey]))

    print("Finished all CFG_LATENCY scans for all optohybrids on shelf{0} slot{1} in ohMask: 0x{2:x}".format(args.shelf,args.slot,args.ohMask))

    return
def iterTrim(args):
    """
    Launches a call of iterativeTrim.py

    args - object returned by argparse.ArgumentParser.parse_args()
    """

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    # Determine number of OH's
    cardName = getCardName(args.shelf,args.slot)
    amcBoard = HwAMC(cardName, args.debug)
    print("opened connection")

    # Get DATA_PATH
    dataPath = os.getenv("DATA_PATH")

    for ohN in range(0,amcBoard.nOHs):
        # Skip masked OH's
        if( not ((args.ohMask >> ohN) & 0x1)):
            continue

        ohKey = (args.shelf,args.slot,ohN)

        # Get & make the output directory
        dirPath = makeScanDir(args.slot, ohN, "iterTrim", startTime, args.shelf)

        calDacCalFile = "{0}/{1}/calFile_calDac_{1}.txt".format(dataPath,chamber_config[ohKey])
        calDacCalFileExists = os.path.isfile(calDacCalFile)
        if not calDacCalFileExists:
            print("Skipping shelf{0} slot{1} OH{2}, detector {3}, missing CFG_CAL_DAC Calibration file:\n\t{2}".format(
                args.shelf,
                args.slot,
                ohN,
                chamber_config[ohKey],
                calDacCalFile))
            continue

    print("iterativeTrimming shelf{0} slot{1} 0x{2:x}".format(args.shelf,args.slot,args.ohMask,chamber_config[ohKey]))

    # Get base command
    cmd = [
        "iterativeTrim.py",
        "{}".format(args.shelf),
        "{}".format(args.slot),
        "0x{:x}".format(args.ohMask),
        "--chMax={}".format(args.chMax),
        "--chMin={}".format(args.chMin),
        "--latency={}".format(args.latency),
        "--maxIter={}".format(args.maxIter),
        "--nevts={}".format(args.nevts),
        "--vfatmask=0x{:x}".format(args.vfatmask if (args.vfatmask is not None) else amcBoard.getLinkVFATMask(ohN) ),
        "--sigmaOffset={}".format(args.sigmaOffset),
        "--highTrimCutoff={}".format(args.highTrimCutoff),
        "--highTrimWeight={}".format(args.highTrimWeight),
        "--highNoiseCut={}".format(args.highNoiseCut)
    ]

    # debug flag raised?
    if args.debug:
        cmd.append("-d")

    # add calFile flag
    if args.calFileCAL:
        cmd.append("--calFileCAL")

    # Additional optional arguments
    if args.armDAC is not None:
        cmd.append("--armDAC={}".format(args.armDAC))

    # add CPU usage flag
    if args.light:
        cmd.append("--light")
    if args.medium:
        cmd.append("--medium")
    if args.heavy:
        cmd.append("--heavy")

    # Execute
    executeCmd(cmd,dirPath)
    print("Finished iterativeTrimming on shelf{0} slot{1} in ohMask: 0x{2:x}".format(args.shelf,args.slot,args.ohMask))

    return
def trimChamberV3(args):
    """
    Launches a call of trimChamberV3.py

    args - object returned by argparse.ArgumentParser.parse_args()
    """

    startTime = datetime.datetime.now().strftime("%Y.%m.%d.%H.%M")

    # Determine number of OH's
    cardName = getCardName(args.shelf,args.slot)
    amcBoard = HwAMC(cardName, args.debug)
    print('opened connection')

    # Get DATA_PATH
    dataPath = os.getenv("DATA_PATH")

    for ohN in range(0,amcBoard.nOHs):
        # Skip masked OH's
        if( not ((args.ohMask >> ohN) & 0x1)):
            continue

        ohKey = (args.shelf,args.slot,ohN)
        print("Trimming shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

        # Get & make the output directory
        dirPath = makeScanDir(args.slot, ohN, "trimV3", startTime, args.shelf)

        calDacCalFile = "{0}/{1}/calFile_calDac_{1}.txt".format(dataPath,chamber_config[ohKey])
        calDacCalFileExists = os.path.isfile(calDacCalFile)
        if not calDacCalFileExists:
            print("Skipping shelf{0} slot{1} OH{2}, detector {3}, missing CFG_CAL_DAC Calibration file:\n\t{2}".format(
                args.shelf,
                args.slot,
                ohN,
                chamber_config[ohKey],
                calDacCalFile))
            continue

        # Get base command
        cmd = [
                "trimChamberV3.py",
                "--gemType {}".format(args.gemType),
                "--detType {}".format(args.detType),
                "--calFileCAL={}".format(calDacCalFile),
                "--chMax={}".format(args.chMax),
                "--chMin={}".format(args.chMin),
                "--dirPath={}".format(dirPath),
                "-g {}".format(ohN),
                "--latency={}".format(args.latency),
                "--mspl={}".format(args.mspl),
                "--nevts={}".format(args.nevts),
                "--shelf={}".format(args.shelf),
                "--slot={}".format(args.slot),
                "--trimPoints={}".format(args.trimPoints),
                "--vfatmask=0x{:x}".format(args.vfatmask if (args.vfatmask is not None) else amcBoard.getLinkVFATMask(ohN) ),
                "--voltageStepPulse"
                ]

        # debug flag raised?
        if args.debug:
            cmd.append("-d")

        # Additional optional arguments
        if args.armDAC is not None:
            cmd.append("--armDAC={}".format(args.armDAC))
        else:
            # Check to see if a vfatConfig exists
            vfatConfigFile = "{0}/configs/vfatConfig_{1}.txt".format(dataPath,chamber_config[ohKey])
            if os.path.isfile(vfatConfigFile):
                cmd.append("--vfatConfig={}".format(vfatConfigFile))
                pass
            pass

        # Execute
        executeCmd(cmd,dirPath)
        print("Finished trimming shelf{0} slot{1} OH{2} detector {3}".format(args.shelf,args.slot,ohN,chamber_config[ohKey]))

    print("Finished trimming all optohybrids on shelf{0} slot{1} in ohMask: 0x{2:x}".format(args.shelf,args.slot,args.ohMask))

    return