#!/bin/sh
# \
  exec oagwish "$0" "$@"


set auto_path [linsert $auto_path 0 /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]

APSStandardSetup
set args $argv
set lab 0
APSStrictParseArguments {lab}
set CVSRevisionAuthor "Version 1.0, H. Shang"

set BPLDarming(lab) $lab

proc SetStatus {text} {
    global status
    set status "$text"
    update
}

proc ClearFaults {args} {
    global sectorList BPLDarming
    set SimBeam $BPLDarming(SimBeam)
    SetStatus "Clear faults..."
    if [catch {APScavput -list=S -list=[join $sectorList ,] \
		   -list=-LMPS:BPLD:ID -list=1,2 -list=:AIOR- \
		   -list=H,V -list=1,2 -list=-SP=0 -pend=60} result] {
	return -code error "Error set ID bpm offsts to zero: $result"
    }
    if $SimBeam {
	if [catch {APScavput -list=S -list=[join $sectorList ,] \
		       -list=-LMPS:BM_ -list=X,Y -range=begin=1,end=28 -list=_Offset-SP=0 -pend=60} result] {
	    return -code error "Error set BM bpm offsets to zero: $result"
	}
    }
    #clear External inputs faults
    if [catch {APScavput -list=S -list=[join $sectorList ,] -list=-LMPS:CtrlReg0-Cmd=0 -pend=30 } result] {
	return -code error "Error clear ext inputs: $result"
    }
    after 5000
    if [catch {APScavput -list=S -list=[join $sectorList ,]  -list=-LMPS:UsrReset-SP=1 -pend=30 } result] {
	return -code error "Error reset to clear faults: $result"
    }
    SetStatus "done."
}

proc WriteLogFileHeader {args} {
    global  BPLDarming
    set logDir $BPLDarming(archiveDir)
    if ![file exist $logDir] {
	exec mkdir $logDir
	exec chmod 777 $logDir
    }
    set logFile $logDir/$BPLDarming(rootname).sdds
    set BPLDarming(logFile) $logFile
    if ![file exist $logFile] {
	set BPLDarming(logID) [open $BPLDarming(logFile) a+]
	puts $BPLDarming(logID) "SDDS1"
	puts $BPLDarming(logID) "&column name=StartTime, type=string, &end"
	puts $BPLDarming(logID) "&column name=EndTime, type=string, &end"
	puts $BPLDarming(logID) "&column name=Sector, type=string, &end"
	puts $BPLDarming(logID) "&column name=Result, type=string, &end"
	puts $BPLDarming(logID) "&column name=FaultDesc, type=string, &end"
	puts $BPLDarming(logID) "&data mode=ascii, no_row_counts=1, &end"
	exec chmod 777 $BPLDarming(logFile)
	flush $BPLDarming(logID)
    }
}

proc WriteLogFile {args} {
    global BPLDarming
    set sectorList $BPLDarming(sectorList)
    foreach sector $sectorList {
	set valList ""
	lappend valList $BPLDarming(startTime)
	lappend valList $BPLDarming(endTime)
	lappend valList S$sector
	lappend valList $BPLDarming(S$sector.result)
	lappend valList \"$BPLDarming(S$sector.desc)\"
	puts $BPLDarming(logID) "[join $valList]"
    }
    flush $BPLDarming(logID)
}

proc SetupValidation {args} {
    set type BM
    APSParseArguments {type}
    global BPLDarming
    set SimBeam $BPLDarming(SimBeam)
    set sectorList $BPLDarming(sectorList)
    SetStatus "enabling trip inhibitor..."
    APSInfoWindow .info -width 20 -infoMessage "Please enable the trip inhibitor for arming test." -modal 1
    if {0} {
	if [catch {exec cavput -list=APSU:MMPS2:CtrlReg0-Cmd.BC=1 -pend=10 } result] {
	    return -code error "Error enabling trip inhibitor: $result"
	}
    }
    if [catch {ClearFaults} result] {
	return -code error "Error clearing faults: $result"
    }
    SetStatus "To enable BM/ID validation, it needs following conditions"
    SetStatus "1)the simulated hardware limit should be equal or greater than BM engaged current."
    #SetStatus "2) software limit should be less than the hardware limit but greater than BM/ID engaged current."
    SetStatus "2) MPS arming current should be greater than 0 (normally set to 0.5mA)"
    SetStatus "3) beam simulation current has to be equal or greater than BM/ID engaged current."
    SetStatus "checking hardware limit..."
    if [catch {exec cavget -list=APSU:MMPS2:Sim:BeamCurrent-SP,APSU:MMPS2:ID:Thold-SP,APSU:MMPS2:BM:Thold-SP,APSU:MMPS2:Sim:HWmaxBeam-SP,APSU:MMPS2:MaxSoftBeam-SP -pend=10} valList] {
	return -code error "Error reading sim current and current limit: $valList"
    }
    set simCurrent [lindex $valList 0]
    set IDcurrent [lindex $valList 1]
    set BMcurrent [lindex $valList 2]
    set hwLimit [lindex $valList 3]
    set swLimit [lindex $valList 4]
    set armingCurrent [set ${type}current]
    if {$hwLimit<[expr $armingCurrent+5]} {
	set limit [expr $armingCurrent  + 20]
	SetStatus "Hardware limit is lower than $type engage current, increase it to $limit."
	if [catch {exec cavput -list=APSU:MMPS2:Sim:HWmaxBeam-SP=$limit -pend=10} result] {
	    return -code error "Error increase hardward limit: $result"
	}
	set hwLimit $limit
    }
    set limit 0
    if {$swLimit>$hwLimit} {
	SetStatus "software limit is higher than hardward limit, reduce it..."
	set limit [expr $hwLimit -2]
    }
    if {$swLimit<$armingCurrent} {
	set limit [expr $armingCurrent + 1 ]
	puts "software limit is lower than $type engage current, increase it."
    }
    if {$limit>0} {
	if [catch {exec cavput -list=APSU:MMPS2:MaxSoftBeam-SP=$limit -pend=10} result] {
	    return -code error "Error change software current limit to $limit: $result"
	}
    }
    SetStatus "check beam current: it should be equal or greater than BM engaged current"
    if $SimBeam {
	if [catch {exec cavget -list=APSU:MMPS2:Sim:BeamCurrent-SP -pend=10} current] {
	    return -code error "Error reading simulated current: $current"
	}
	if {$current<$armingCurrent} {
	    set limit [expr $armingCurrent+1]
	    SetStatus "Increase simulated current to $limit.."
	    if [catch {exec cavput -list=APSU:MMPS2:Sim:BeamCurrent-SP=$limit -pend=10} result] {
		return -code error "Error setting simulated current: $result"
	    }
	}
    } else {
	if [catch {exec cavget -list=PSU:MMPS2:BeamCurrent-I -pend=10} current] {
	    return -code error "Error reading beam current: $current"
	}
	set limit [expr $armingCurrent+1]
	if {$current<$armingCurrent} {
	    APSInfoWindow .info -width 20 -infoMessage "The beam current is less than $type engage current, please increase the beam current to $limit mA." -modal 1
	}
    }
    #SetStatus "Disable ID BPLD ..."
    global sectorlist
    #if [catch {exec cavput -list=S -list=[join $sectorList ,] -list=-LMPS:BPLD: -list=ID1,ID2 \
#		   -list=_Enable-SP=0 -pend=10 } result] {
#	return -code error "Error disable ID BPLD: $result"
  #  }
    
  
    if [catch {exec cavput -list=S -list=[join $sectorList ,] -list=-LMPS:BPLD:BM_Enable-SP=0 } result] {
	return -code error "Error enabling BM BPLDs: $result"
    }
    
    SetStatus "Reset BPLD..."
    if [catch {APScavput -list=S -list=[join $sectorList ,]  -list=-LMPS:UsrReset-SP=1 -pend=30 } result] {
	return -code error "Error reset to clear faults: $result"
    }
    
    SetStatus "BPLD validation setup done."
}

proc GetBPMs {args} {
    set all 1
    APSParseArguments {all}
    #all use all eligible BPMs
    global BPLDarming
    set statusFile /home/helios/oagData/sr/BPMStatus/config.sdds
    set configFile /home/helios/oagData/sr/BPLD/BPLD_Config/config.sdds
    set tmpRoot /tmp/[APSTmpString]
    set sectorList $BPLDarming(sectorList)
    if $all {
	if [catch {exec sddsprocess $statusFile $tmpRoot.0 \
		       "-filter=col,NonexistentH,0,0,NonexistentV,0,0,|" \
		       "-filter=col,OkForBMBPLDH,1,1,OkForBMBPLDV,1,1,|" } result] {
	    return -code error "Error obtaining BM BPLD bpms: $result"
	}
	if [catch {exec sddsxref $configFile $tmpRoot.0 $tmpRoot.1 -match=DeviceName -nowarn} result] {
	    return -code error "Error getting BM bpms0: $result"
	}
    } else {
	#use BM-BPLD BPMs in default cnfig
	if [catch {exec sddsprocess $configFile $tmpRoot.1 \
		       -filter=col,BMBPM,1,1 } result] {
	    return -code error "Error getting BM bpms1: $result"
	}
    }
    APSAddToTmpFileList -ID bm -fileList "$tmpRoot.0 $tmpRoot.1"
    foreach sector $sectorList {
	set sector0 [scan $sector %ld]
	if [catch {exec sddsprocess $tmpRoot.1 -pipe=out -filter=col,BPLDSector,$sector0,$sector0 \
		       | sdds2stream -pipe=in -col=BPLDIndex } bpmList] {
	    return -code error "Error obtaining S$sector BM BPLD bpms: $bpmList"
	}
	set BPLDarming(S$sector.bpmIndexList) [join $bpmList]
	set BPLDarming(S$sector.bpmList) [exec sdds2stream -col=DeviceName $tmpRoot.1]
	set maskValue 0
	foreach bpm $bpmList {
	    set num [expr $bpm+3]
	    set Bit [format %X $num]
	    set maskValue [expr $maskValue + pow(2, $bpm-1)]
	}
	set BPLDarming(S$sector.mask) $maskValue
    }
}
proc SetBMMask {args} {
    global BPLDarming
    SetStatus "Get BPMs..."
    set sectorList $BPLDarming(sectorList)
    if [catch {GetBPMs} result] {
	return -code error "Error getting BM BPLD BPMs: $result"
    }
    set putList ""
    foreach sector $sectorList {
	lappend putList  S${sector}-LMPS:BPLD:BpmMask-SP=$BPLDarming(S$sector.mask)
    }
    SetStatus "Set BM masks for [join $BPLDarming(sectorList)]..."
    if [catch {exec cavput -list=[join $putList ,] -pend=10} result] {
	return -code error "Error setting mask: $result"
    }
    SetStatus "done."
}

proc ArmingBM {args} {
    global BPLDarming
    set sectorList $BPLDarming(sectorList)
    if [catch {APScavget -list=APSU:MMPS2:BM:Thold-SP -pend=10} BMarming] {
	   return -code error "Error reading BM arming current: $BMarming"
    }
    if !$BPLDarming(lab) {
	APSInfoWindow .info -width 20 -infoMessage "Please inject beam to greater than $BMarming mA." -modal 1
	if [catch {exec cavget -list=S-DCCT:currentM \
		   } current] {
	    return -code error "Error reading SR current: $current"
	}
	if {$current<$BMarming} {
	    return -code error "The SR current is $current, less than the BM arming current. can not arm BM-BPLD."
	}
    } else {
	if [catch {APScavput -list=APSU:MMPS2:Sim:BeamCurrent-SP=[expr $BMarming+1] -pend=10} result] {
	    return -code error "Error setting simulating current: $result"
	}
	after 1000
    }
    if [catch {APScavget -num -list=APSU:MMPS2:Beam_BM_Th-Sts -pend=10} armed] {
	return -code error "Error reading BM arming state: $armed"
    }
    if !$armed {
	return -code error "BM arming test failed: the BM current is not armed!"
    }
    if [catch {SetBMMask} result] {
	return -code error "$result"
    }
    if [catch {APScavput -list=S -list=[join $sectorList ,] -list=-LMPS:BPLD:BM_Enable-SP=1 -pend=10} result] {
	return -code error "Error enabling BM BPLD: $result"
    }
    after 3000
}

proc ArmingID {args} {
    global BPLDarming lab
    set sectorList $BPLDarming(sectorList)
    foreach sector $sectorList {
	set BPLDarming(S$sector.ID1.result) closed
	set BPLDarming(S$sector.ID2.result) closed
	set BPLDarming(S$sector.ID1exist) 0
	set BPLDarming(S$sector.ID2exist) 0
	set BPLDarming(S$sector.msg) ""
    }
    #29 is IEX
    set BBPLDarming(S29.ID2exist) 1
    if [catch {APScavget -list=APSU:MMPS2:ID:Thold-SP -pend=10} IDarming] {
	   return -code error "Error reading ID arming current: $BMarming"
    }
    if $BPLDarming(lab) {
	if [catch {exec cavget -list=APSU:MMPS2:BeamCurrent-I \
		   } current] {
	    return -code error "Error reading SR current: $current"
	}
	if {$current<$IDarming} {
	    return -code error "The current is $current, less than the ID arming current. can not arm ID-BPLD."
	}
    } else {
	APSInfoWindow .info -width 20 -infoMessage "Please inject the beam to above $IDarming mA" -modal 1
	if [catch {exec cavget -list=S-DCCT:currentM \
		   } current] {
	    return -code error "Error reading SR current: $current"
	}
	if {$current<$IDarming} {
	    return -code error "The SR current is $current, less than the ID arming current. can not arm ID-BPLD."
	}
    }
    after 1000
    if [catch {APScavget -num -list=APSU:MMPS2:Beam_ID_Th-Sts -pend=10} armed] {
	return -code error "Error reading ID arming state: $armed"
    }
    if !$armed {
	return -code error "ID arming test failed: the ID current is not armed!"
    }
    SetStatus "enabling ID1/ID2..."
    if [catch {APScavput -list=S -list=[join $sectorList ,] -list=-LMPS:BPLD: -list=ID1,ID2 -list=_Enable-SP=1 -pend=10 } result] {
	return -code error "Error enabling ID1/ID2: $resutl"
    }
    
    if $BPLDarming(lab) {
	SetStatus "closing simulated gaps..."
	if [catch {APScavput -list=S -list=[join $sectorList ,] -list=-LMPS:ID:GapSim-SP=1,-LMPS:ID:GapSimClose-SP=1 -pend=10 } result] {
	    return -code error "Error closing simulated gaps: $result"
	}
    } else {
	SetStatus "move ID gaps to 48mm.."
	if [catch {MoveGapToBPLDTripLimits -moveTo 48 } deviceList] {
	    return -code error "$deviceList"
	}
	set moveSectors ""
	foreach device $deviceList {
	    set sector [scan $device S%ld]
	    #check if gap closed
	    if [regexp "US" $device] {
		set st US
	    } else {
		set st DS
	    }
	    if [catch {exec cavget -num -list=S[format %02d $sector]-LMPS:${st}ID-GapStatus -printErrors -pend=10} gapOpen] {
		return -code error "Error reading gap status: $gapOpen"
	    }
	    if [expr $sector % 2] {
		set sectorf [format %02d $sector]
		set BPLDarming(S$sectorf.ID2exist) 1
		#odd sector, ID2
		if $gapOpen {
		    set BPLDarming(S$sectorf.ID2.result) open
		    SetStatus "Error ID$sectorf is not closed, S$sectorf arming test failed."
		    set BPLDarming(S$sectorf.msg) "ID$sectorf is not closed."
		    set BPLDarming(S$sectorf.result) failed
		}
	    } else {
		#even sector ID1
		set sector1 [expr $sector+1]
		set sectorf [format %02d $sector1]
		set BPLDarming(S$sectorf.ID1exist) 1
		if $gapOpen {
		    set BPLDarming(S$sectorf.ID1.result) open
		    SetStatus "Error ID[format %02d $sector] is not closed, S$sectorf arming test failed."
		    set BPLDarming(S$sectorf.msg) "ID[format %02d $sector] is not closed."
		    set BPLDarming(S$sectorf.result) failed
		}
	    }
	}
	if [lsearch -exact 29 $sectorList]>=0 {
	    #check if IEX is on
	    if [catc {exec cavget -num  -list=S29ID:Main_on_offC.VAL -pend=10} onoff] {
		return -code error "Error checking IEX state: $onoff"
	    }
	    if !$onoff {
		SetStatus "Error IEX is off, arming test for S29 failed."
		set BPLDarming(S29.result) failed
		set BPLDarming(S29.msg) "IEX is off."
	    }
	}
    }
}

proc CheckBMArming {args} {
    global BPLDarming
    set sectorList $BPLDarming(sectorList)
    SetStatus "check BM amring..."
    
    if [catch {APScavget -num -list=APSU:MMPS2:Beam_BM_Th-Sts -pend=10} armed] {
	return -code error "Error reading BM arming state: $armed"
    }
    if !$armed {
	SetStatus "BM current is not armed."
	return -code error "BM current is not armed."
    }
    
    foreach sector $sectorList {
	set msg ""
	if [catch {APScavget -list=S${sector}-LMPS:BPLD:BM_Enable-I -pend=10} val] {
	    return -code error "Error reading BM arming of S$sector: $val"
	}
	if {$val!=$BPLDarming(S$sector.mask)} {
	    SetStatus "S$sector BM is not armed correctly..."
	    set bitstring [format %b $val]
	    set len [string length $bitstring]
	    if {$len<[lindex $BPLDarming(S$sector.bpmIndexList) end]} {
		append msg "S$sector BM arming failed."
		continue
	    }
	    set badBPMList ""
	    foreach index $BPLDarming(S$sector.bpmIndexList) bpm $BPLDarming(S$sector.bpmList) {
		set i [expr $len-$index]
		puts "$i $index"
		set i0 [string index $bitstring $i]
		if !$i0 {
		    lappend badBPMList $bpm
		}
	    }
	    set msg "S$sector [join $badBPMList ,] arming test failed."
	}
	if [string length $msg] {
	    SetStatus "S$sector BM arming test failed: $msg."
	    set BPLDarming(S$sector.result) failed
	    set BPLDarming(S$sector.desc) $msg
	} else {
	    set BPLDarming(S$sector.result) passed
	    set BPLDarming(S$sector.desc) ""
	    SetStatus "S$sector BM arming test passed."
	}
    }
    
}

proc CheckIDArming {args} {
    global BPLDarming
    set sectorList $BPLDarming(sectorList)
    SetStatus "Check ID arming states..."
    if [catch {APScavget -list=S -list=[join $sectorList ,]  -num -list=-LMPS:SysStatus-I.B0 -pend=10} valList] {
	return -code error "Error reading ID current arming state: $valList"
    }
   
    set msg ""
    foreach sector $sectorList val $valList {
	set sectorf [format %02d $sector]
	set BPLDarming(S$sectorf.result) passed
	set BPLDarming(S$sectorf.desc) ""
	if !$val {
	    set BPLDarming(S$sectorf.result) failed
	    set BPLDarming(S$sectorf.desc) "S$sector current not armed."
	}
    }
    if [catch {APScavget -list=S -list=[join $sectorList ,] -list=-LMPS:SysStatus-I.B2 -pend=10} ID1List] {
	return -code error "Error reading ID1 status: $ID1List"
    }
   
    if [catch {APScavget -list=S -list=[join $sectorList ,] -list=-LMPS:SysStatus-I.B3 -pend=10} ID2List] {
	return -code error "Error reading ID1 status: $ID2List"
    }
    
    foreach sector $sectorList ID1 $ID1List ID2 $ID2List {
	if [string compare "$BPLDarming(S$sector.result)" "failed"]==0 {
	    continue
	}
	set sectorf [format %02d $sector]
	set msg ""
	#check if gap is closed first
	#ID2
	set sector0 [scan $sector %d]
	if {$sector0==1} {
	    #ID1
	    set sector1 40
	} else {
	    set sector1 [expr $sector0 -1]
	}
	set msg $BPLDarming(S$sector.msg)
	if {$BPLDarming(S$sectorf.ID1exist) && $BPLDarming(S$sectorf.ID1.result)=="closed"  && !$ID1} {
	    append msg "S$sectorf ID1 gap is closed but BPLD is not armed."
	    set BPLDarming(S$sector.result) failed
	}
	if {$BPLDarming(S$sector.ID2exist) && $BPLDarming(S$sectorf.ID2.result)=="closed"  && !$ID2} {
	    append msg "S$sector ID2 gap is closed but BPLD is not armed."
	    set BPLDarming(S$sector.result) failed
	}
	set BPLDarming(S$sector.desc) $msg
    }
    
    SetStatus "done."
}

proc MoveGapToBPLDTripLimits {args} {
    set moveTo ""
    APSParseArguments {moveTo}
    global BPLDarming
    set sectorList $BPLDarming(sectorList)
    
    set tmpRoot /tmp/[APSTmpString]
    if [catch {exec sddsmakedataset $tmpRoot.sector -col=LMPSSector,type=long -data=[join $sectorList ,] } result] {
        return -code error "Error moving gaps1: $result"
    }
    APSAddToTmpFileList -ID idbpld -fileList "$tmpRoot.sector $tmpRoot.move"
    
    if [catch {exec sddsselect /home/helios/oagData/sr/IDs/SetGapToBPLDTripLimits $tmpRoot.sector -reuse -equate=LMPSSector $tmpRoot.move } result] {
        return -code error "Error moving gaps2: $result"
    }
    set rows [exec sdds2stream -rows=bar $tmpRoot.move]
    if !$rows {
        #no ID gap to move
        return
    }
    if [string length $moveTo] {
        if [catch {exec sddsprocess $tmpRoot.move -nowarnings -reprint=col,ValueString,$moveTo } result] {
            return -code error "Error moving gaps3: $result"
        }
    }
    SetStatus "Restore device values"
    set deviceList [exec sdds2stream -col=DeviceName $tmpRoot.move]
    
    if [catch {exec sddscasr -restore $tmpRoot.move } result] {
        APSMpReturn error "APSMpIDRestoreGapsFromSCR: $result"
    }
    
    after 1000
    if [catch {exec sddsprocess $tmpRoot.move -pipe=out -reedit=col,ControlName,%/:GapSetC/:StartC/ \
                 -reprint=col,ValueString,1 \
                 | sddscasr -pipe=in -restore -pend=30 } result] {
        return -code error "Error1: $result"
    }
    after 1000
    SetStatus "Waiting for ID gaps stop moving. (it may take several minutes, please be patient.)"
    if [catch {APSMpCheckAndWaitForIDs -deviceList $deviceList -timeout 500} results] {
        if {[APSPEMTKDialog .warningDialog -text "Problem1 occurred while waiting restoring ID gaps\n$results"] == 1} {
            return -code error "Error in checking ID gaps: $results"
        }
    }
}


proc StartArmingTest {args} {
    set type BM
    APSParseArguments {type}
    global BPLDarming
    
    set timestr  [clock format [clock seconds] -format %Y-%m%d:%H%M%S]
    set BPLDarming(rootname) ${type}Arming-$timestr
    set BPLDarming(startTime) $timestr
   
    if [catch {SetupValidation -type $type} result] {
	return -code error "Error setup BPLD: $result"
    }
    switch $type {
	BM {
	    if [catch {ArmingBM} result] {
		SetStatus "Error arming BM BPLD:$result"
		return
	    }
	    after 3000
	    if [catch {CheckBMArming} result] {
		SetStatus "Error checking BM BPLD arming result: $result"
		return
	    }
	}
	ID {
	    if [catch {ArmingID} result] {
		SetStatus "Error arming ID BPLD:$result"
		return
	    }
	    after 3000
	    if [catch {CheckIDArming} result] {
		SetStatus "Error checking ID BPLD arming result: $result"
		return
	    }
	}

    }
    WriteLogFileHeader
    set timestr  [clock format [clock seconds] -format %Y-%m%d:%H%M%S]
    set BPLDarming(endTime) $timestr
    WriteLogFile
    APSInfoWindow .info -width 20 -infoMessage "Please disable the trip inhibitor after arming test." -modal 1
    
    SetStatus "$type arming test done."
    WriteLogFile
    set tmpRoot  /tmp/[APSTmpString]
    if [catch {exec sddsprintout $BPLDarming(logFile) $tmpRoot.print -col=StartTime,format=%20s -col=EndTime,format=%20s \
		   -col=Sector,format=%6s -col=Result,format=%10s -col=FaultDesc,format=%30s } result] {
	return -code error "Error printing result: $result"
    }
    APSFileDisplayWindow [APSUniqueName .] -fileName $tmpRoot.print -height 30 -width 150 -deleteOnClose 1
    
    if [catch {APScavput -list=S -list=[join $BPLDarming(sectorList) ,] \
		   -list=-LMPS:ID:GapSim-SP=0,-LMPS:ID:GapSimClose-SP=0 } result] {
	return -code error "Error clear ID gap simulator: $result"
    }
}

proc PrintResult {args} {
    global BPLDarming SelectFile
    cd $BPLDarming(archiveDir)
    set files [glob -nocomplain ????-???-????/*Arming*.sdds]
    if ![llength $files] {
	SetStatus "No arming test files found."
	return
    }
    set SelectFile ""
    APSScrolledListWindow .process -name "Select a file" \
      -label "Select a file" \
      -itemList $files -selectionVar SelectFile
    tkwait variable SelectFile
    set tmpRoot /tmp/[APSTmpString]
    if [catch {exec sddsprintout $SelectFile $tmpRoot.print \
		   "-title=[string range [file root [file tail $SelectFile]] 0 7]  result" \
		   -col=StartTime,format=%20s \
		   -col=EndTime,format=%20s \
		   -col=Sector,format=%6s -col=Result,format=%10s -col=FaultDesc,format=%30s  } result] {
	return -code error "Error print result: $result"
    }
    APSFileDisplayWindow [APSUniqueName .] -height 30  \
	-fileName $tmpRoot.print  -width 140  -deleteOnClose 1
}

if $lab  {
    set sectorList {01 03 05}
    set archiveDir /home/oxygen/DIAG/oagData/sr/BPLD/Validation/Arming
    set BPLD(configDir) /home/oxygen/DIAG/apsu/BPLD/BPLD_Config
} else {
    for {set sector 1} {$sector<=35} {incr sector 2} {
	lappend sectorList [format %02d $sector]
    }
    set archiveDir /home/helios/oagData/sr/BPLD/Validation/Arming/
    set BPLD(configDir)  /home/helios/oagData/sr/BPLD/BPLD_Config
}

set BPLDarming(lab) $lab
set BPLDarming(sectorList) $sectorList
set BPLDarming(archiveDir) $archiveDir
set BPLDarming(mainDir) $archiveDir

APSApplication . -name "SRBPLDArmingTest" -version $CVSRevisionAuthor \
  -overview "SR BM/ID BPLD arming test" \
  -contextHelp "SR BM/ID BPLD arming test."
set status ""
set BPLDarming(SimBeam) 0

APSScrolledStatus .ss -parent .userFrame -textVariable status \
  -packOption "-side top -fill x" -height 10 -width 60 \
  -contextHelp "Provides execution status and operation hints."
SetStatus "Working..."
set dataDir [APSGoToDailyDirectory -subdirectory BMSteer]
APSLabeledEntry .dir -parent .userFrame -width 70 -textVariable BPLDarming(archiveDir) -label "Data dir:"
#APSRadioButtonFrame .beam -parent .userFrame -label "Use Simulated Beam?" -buttonList {Yes No} \
#	 -valueList {1 0} -variable BPLDarming(SimBeam) -orientation horiontal


APSButton .bm -parent .userFrame -text "BM Arming Test" -command "StartArmingTest -type BM"
APSButton .id -parent .userFrame -text "ID Arming Test" -command "StartArmingTest -type ID"
APSButton .display -parent .userFrame -text "Display Result" -command "PrintResult"
