proc APSMpITS_SwitchToTestStandInfo {} {
    return "This is a Linac Waveguide Switch procedure only for (Mode 3) or  K3-->ITS operation. This procedure will first attenuate L3 rf power followed by taking its modulator to ready-to-pulse. Then it will position S-band switches 4, 5, and 6 to position 1, 2 and 2 respectively. See 'Position chart and rack indication' MEDM display (ACIS_LP_WG.adl) for details"
}

proc APSMpITS_SwitchToTestStandDialog {} {
    pack [message $frame.msg -aspect 300 -justify left -text "Click OK to execute."]
    return
}

proc APSMpITS_SwitchToTestStand {args} {
    
    if {[catch {APScavget -list=LP-ACIS:ItsMode:BpM -num -pend=20} gunRoomStatus]} {
        APSMpReturn error "APSMpITS_SwitchToTestStand: $gunRoomStatus"
    }
    if {$gunRoomStatus != 1} {
        APSMpReturn error "APSMpITS_SwitchToTestStand: The Gun Room status is not in Beam Permit mode."
    }

    if {[catch {APScavget -list=LP-ACIS:ItsMode:AaDlM -num -pend=20} ITSStatus]} {
        APSMpReturn error "APSMpITS_SwitchToTestStand: $ITSStatus"
    }
    if {$ITSStatus != 0} {
        APSMpReturn error "APSMpITS_SwitchToTestStand: The ITS status is in Authorized Access mode."
    }
    if {[catch {APScavget -list=LP-ACIS:ItsMode:PpM -num -pend=20} ITSStatus]} {
        APSMpReturn error "APSMpITS_SwitchToTestStand: $ITSStatus"
    }
    if {$ITSStatus != 0} {
        APSMpReturn error "APSMpITS_SwitchToTestStand: The ITS status is in Permit Pending mode."
    }
    if {[catch {APScavget -list=LP-ACIS:ItsMode:SvM -num -pend=20} ITSStatus]} {
        APSMpReturn error "APSMpITS_SwitchToTestStand: $ITSStatus"
    }
    if {$ITSStatus != 0} {
        APSMpReturn error "APSMpITS_SwitchToTestStand: The ITS status is in Search in Progress mode."
    }

    APSMpStep init -promptDialog APSMpPromptInitDialog
    
    if {[catch {APScavget -list=LP-ACIS:ItsMode:BpM -num -pend=20} gunRoomStatus]} {
        APSMpReturn error "APSMpITS_SwitchToTestStand: $gunRoomStatus"
    }
    if {$gunRoomStatus != 1} {
        if {[APSPEMTKDialog .warningDialog \
               -text "The Gun Room status is not in Beam Permit mode."] == 1} {
            APSMpReturn error "APSMpITS_SwitchToTestStand: The Gun Room status is not in Beam Permit mode."
        }
    }

    APSMpStep "Shutdown till ready to pulse is off in L3" -desc "Shutdown till ready to pulse is off" -proc LMOCS_ShutdownTillReadyToPulseOff
    if {[catch {LMOCS_ShutdownTillReadyToPulseOff -sector L3} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while shutting down to ready to pulse is off in L3 \n$result"] == 1} {
            APSMpReturn error "LMOCS_TurnOff: $result"
        }
    }

    APSMpStep "Requesting remote switch control"
    if {[catch {APScavput -list=LRFSCS:MCR:RemoteRequest=1 -pend=20} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem requesting remote switching control: $result"] == 1} {
            APSMpReturn error "Problem requesting remote switching control: $result"
        }
    }
    APSWaitWithUpdate -waitSeconds 5
    APSMpStep "Verifying remote switch control"
    if {[catch {APScavget -list=LRFSCS:MCR:RemoteEnabled -num -pend=20} result]} {
        APSMpReturn error "Problem verifying remote switch control"
    }
    if {$result != 1} {
        if {[APSPEMTKDialog .warningDialog -text "Problem requesting remote switching control"] == 1} {
            APSMpReturn error "Problem requesting remote switching control"
        }
    }
    


    APSMpStep "Switch To Normal mode"
    if {[catch {APScavput -list=LRFSCS:MCR:SelectNormalWater=1 -pend=20} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem changing to Normal mode: $result"] == 1} {
            APSMpReturn error "Problem changing to Normal mode: $result"
        }
    }
    APSMpStep "Verifying we are now in Normal mode"
    set tries 0
    while {$tries <= 25} {
        APSWaitWithUpdate -waitSeconds 1
        if {[catch {APScavget -list=LRFSCS:PLC:ModeState -num -pend=20} modestate]} {
            APSMpReturn error "Problem getting the mode state: $modestate"
        }
        if {($modestate != 5)} {
            if {$tries == 25} {
                if {[APSPEMTKDialog .warningDialog -text "Unable to switch to Normal mode"] == 1} {
                    APSMpReturn error "Unable to switch to Normal mode"
                }
            } else {
                incr tries
            }
        } else {
            break
        }
        if {($modestate == 3)} {
            #If there was a problem switching and the operator switched back to Normal manually 
            #it is possible they switched here from K1 or K2 down mode.
            break
        }
        if {($modestate == 4)} {
            #If there was a problem switching and the operator switched back to Normal manually 
            #it is possible they switched here from the test stand mode.
            break
        }
    }
    if {[catch {APScavget -list=LRFSCS:PLC:SwitchFault -num -pend=20} switchfault]} {
        APSMpReturn error "Problem getting the mode state: $switchfault"
    }
    if {($switchfault != 12)} {
        if {[APSPEMTKDialog .warningDialog -text "Switch faults seen while switching to Normal mode"] == 1} {
            APSMpReturn error "Switch faults seen while switching to Normal mode"
        }
    }


    APSMpStep "Switch To TestRoom mode"
    if {[catch {APScavput -list=LRFSCS:MCR:SelectTestroom=1 -pend=20} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem changing to TestRoom mode: $result"] == 1} {
            APSMpReturn error "Problem changing to TestRoom mode: $result"
        }
    }
    APSMpStep "Verifying we are now in TestRoom mode"
    set tries 0
    while {$tries <= 25} {
        APSWaitWithUpdate -waitSeconds 1
        if {[catch {APScavget -list=LRFSCS:PLC:ModeState -num -pend=20} modestate]} {
            APSMpReturn error "Problem getting the mode state: $modestate"
        }
        if {($modestate != 6)} {
            if {$tries == 25} {
                if {[APSPEMTKDialog .warningDialog -text "Unable to switch to TestRoom mode"] == 1} {
                    APSMpReturn error "Unable to switch to TestRoom mode"
                }
            } else {
                incr tries
            }
        } else {
            break
        }
    }
    
    APSMpStep "Run mode switch"
    if {[catch {APScavput -list=LRFSCS:MCR:SelectRun=1 -pend=20} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem running mode switch: $result"] == 1} {
            APSMpReturn error "Problem running mode switch: $result"
        }
    }
    
    APSMpStep "Set L3 Timing source to LI Beam (RFG)"
    if {[catch {APScavput -list=LI:TM:L3TimingSourceC=1 -pend=20} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem running mode switch: $result"] == 1} {
            APSMpReturn error "Problem running mode switch: $result"
        }
    }
    
    APSMpReturn ok

}


proc APSMpITS_SwitchToL3DownInfo {} {
    return "This is a Linac Waveguide Switch procedure only for (Mode 0) or  K3-->WL operation. This procedure will first attenuate L3 rf power followed by taking its modulator to ready-to-pulse. Then it will position S-band switches 4, 5, and 6 to position 2, 1 and 1 respectively. See 'Position chart and rack indication' MEDM display (ACIS_LP_WG.adl) for details."
}

proc APSMpITS_SwitchToL3DownDialog {} {
    pack [message $frame.msg -aspect 300 -justify left -text "Click OK to execute."]
    return
}

proc APSMpITS_SwitchToL3Down {args} {
    
    APSMpStep init -promptDialog APSMpPromptInitDialog
    
    if {[catch {APScavget -list=LP-ACIS:ItsMode:BpM -num -pend=20} gunRoomStatus]} {
        APSMpReturn error "APSMpITS_SwitchToL3Down: $gunRoomStatus"
    }
    if {$gunRoomStatus != 1} {
        if {[APSPEMTKDialog .warningDialog \
               -text "The Gun Room status is not in Beam Permit mode."] == 1} {
            APSMpReturn error "APSMpITS_SwitchToL3Down: The Gun Room status is not in Beam Permit mode."
        }
    }

    #    APSMpStep "Decreasing PFN to 0 in L3"
    #    if {[catch {APSLRampPFNVoltage -klystronList 3 -rampTo 0 -steps 1} result]} {
    #        if {[APSPEMTKDialog .warningDialog -text "Error while decreasing PFN to 0 in L3 \n$result"] == 1} {
    #            APSMpReturn error "APSMpITS_SwitchToL3Down: $result"
    #        }
    #    }

    APSMpStep "Shutdown till ready to pulse is off in L3" -desc "Shutdown till ready to pulse is off" -proc LMOCS_ShutdownTillReadyToPulseOff
    if {[catch {LMOCS_ShutdownTillReadyToPulseOff -sector L3} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Error while shutting down to ready to pulse is off in L3 \n$result"] == 1} {
            APSMpReturn error "LMOCS_TurnOff: $result"
        }
    }

    APSMpStep "Requesting remote switch control"
    if {[catch {APScavput -list=LRFSCS:MCR:RemoteRequest=1 -pend=20} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem requesting remote switching control: $result"] == 1} {
            APSMpReturn error "Problem requesting remote switching control: $result"
        }
    }
    APSWaitWithUpdate -waitSeconds 5
    APSMpStep "Verifying remote switch control"
    if {[catch {APScavget -list=LRFSCS:MCR:RemoteEnabled -num -pend=20} result]} {
        APSMpReturn error "Problem verifying remote switch control"
    }
    if {$result != 1} {
        if {[APSPEMTKDialog .warningDialog -text "Problem requesting remote switching control"] == 1} {
            APSMpReturn error "Problem requesting remote switching control"
        }
    }
    
    if {[catch {APScavget -list=LRFSCS:PLC:ModeState -num -pend=20} modestate]} {
        APSMpReturn error "Problem getting the mode state: $modestate"
    }
    if {($modestate != 5)} {
        APSMpStep "Switch To Normal mode"
        if {[catch {APScavput -list=LRFSCS:MCR:SelectNormalTest=1 -pend=20} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem changing to Normal mode: $result"] == 1} {
                APSMpReturn error "Problem changing to Normal mode: $result"
            }
        }
        APSMpStep "Verifying we are now in Normal mode"
        set tries 0
        while {$tries <= 25} {
            APSWaitWithUpdate -waitSeconds 1
            if {[catch {APScavget -list=LRFSCS:PLC:ModeState -num -pend=20} modestate]} {
                APSMpReturn error "Problem getting the mode state: $modestate"
            }
            if {($modestate != 4)} {
                if {$tries == 25} {
                    if {[APSPEMTKDialog .warningDialog -text "Unable to switch to Normal mode"] == 1} {
                        APSMpReturn error "Unable to switch to Normal mode"
                    }
                } else {
                    incr tries
                }
            } else {
                break
            }
            if {($modestate == 3)} {
                #If there was a problem switching and the operator switched back to Normal manually 
                #it is possible they switched here from K1 or K2 down mode.
                break
            }
            if {($modestate == 5)} {
                #If there was a problem switching and the operator switched back to Normal manually 
                #it is possible they switched here from some other mode.
                break
            }
        }
        if {[catch {APScavget -list=LRFSCS:PLC:SwitchFault -num -pend=20} switchfault]} {
            APSMpReturn error "Problem getting the mode state: $switchfault"
        }
        if {($switchfault != 12)} {
            if {[APSPEMTKDialog .warningDialog -text "Switch faults seen while switching to Normal mode"] == 1} {
                APSMpReturn error "Switch faults seen while switching to Normal mode"
            }
        }
    }

    if {[catch {APScavget -list=LRFSCS:PLC:GunState -num -pend=20} gunstate]} {
        APSMpReturn error "Problem getting the mode state: $gunstate"
    }
    if {($gunstate == 2)} { #PG1

        APSMpStep "Shutdown till ready to pulse is off in L1" -desc "Shutdown till ready to pulse is off" -proc LMOCS_ShutdownTillReadyToPulseOff
        if {[catch {LMOCS_ShutdownTillReadyToPulseOff -sector L1} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error while shutting down to ready to pulse is off in L1 \n$result"] == 1} {
                APSMpReturn error "LMOCS_TurnOff: $result"
            }
        }

        APSMpStep "Shutdown till ready to pulse is off in L2" -desc "Shutdown till ready to pulse is off" -proc LMOCS_ShutdownTillReadyToPulseOff
        if {[catch {LMOCS_ShutdownTillReadyToPulseOff -sector L2} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Error while shutting down to ready to pulse is off in L2 \n$result"] == 1} {
                APSMpReturn error "LMOCS_TurnOff: $result"
            }
        }


        APSMpStep "Switch To RG2 mode"
        if {[catch {APScavput -list=LRFSCS:MCR:SelectRG2=1 -pend=20} result]} {
            if {[APSPEMTKDialog .warningDialog -text "Problem changing to RG2 mode: $result"] == 1} {
                APSMpReturn error "Problem changing to RG2 mode: $result"
            }
        }
        APSMpStep "Verifying we are now in RG2 mode"
        set tries 0
        while {$tries <= 25} {
            APSWaitWithUpdate -waitSeconds 1
            if {[catch {APScavget -list=LRFSCS:PLC:GunState -num -pend=20} gunstate]} {
                APSMpReturn error "Problem getting the mode state: $gunstate"
            }
            if {($gunstate != 1)} {
                if {$tries == 25} {
                    if {[APSPEMTKDialog .warningDialog -text "Unable to switch to RG2 mode"] == 1} {
                        APSMpReturn error "Unable to switch to RG2 mode"
                    }
                } else {
                    incr tries
                }
            } else {
                break
            }
        }
    }


    APSMpStep "Switch To K3 Down (Condition) mode"
    if {[catch {APScavput -list=LRFSCS:MCR:SelectK3Down=1 -pend=20} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem changing to K3 Down (Condition) mode: $result"] == 1} {
            APSMpReturn error "Problem changing to K3 Down mode: $result"
        }
    }
    APSMpStep "Verifying we are now in K3 Down (Condition) mode"
    set tries 0
    while {$tries <= 25} {
        APSWaitWithUpdate -waitSeconds 1
        if {[catch {APScavget -list=LRFSCS:PLC:ModeState -num -pend=20} modestate]} {
            APSMpReturn error "Problem getting the mode state: $modestate"
        }
        if {($modestate != 7)} {
            if {$tries == 25} {
                if {[APSPEMTKDialog .warningDialog -text "Unable to switch to K3 Down (Condition) mode"] == 1} {
                    APSMpReturn error "Unable to switch to K3 Down (Condition) mode"
                }
            } else {
                incr tries
            }
        } else {
            break
        }
    }
    if {[catch {APScavget -list=LRFSCS:PLC:SwitchFault -num -pend=20} switchfault]} {
        APSMpReturn error "Problem getting the mode state: $switchfault"
    }
    if {($switchfault != 12)} {
        if {[APSPEMTKDialog .warningDialog -text "Switch faults seen while switching to K3 Down mode"] == 1} {
            APSMpReturn error "Switch faults seen while switching to K3 Down mode"
        }
    }
    
    APSMpStep "Run mode switch"
    if {[catch {APScavput -list=LRFSCS:MCR:SelectRun=1 -pend=20} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem running mode switch: $result"] == 1} {
            APSMpReturn error "Problem running mode switch: $result"
        }
    }
    
    APSMpStep "Set L3 Timing source to LI Beam (RFG)"
    if {[catch {APScavput -list=LI:TM:L3TimingSourceC=0 -pend=20} result]} {
        if {[APSPEMTKDialog .warningDialog -text "Problem running mode switch: $result"] == 1} {
            APSMpReturn error "Problem running mode switch: $result"
        }
    }

    APSMpStep "Waiting until LTS:Radmon:GRateAi is less than 7mR/hr"
    set tries 0
    while {$tries <= 180} {
        APSWaitWithUpdate -waitSeconds 1
        if {[catch {APScavget -list=LTS:Radmon:GRateAi -num -pend=20} rad]} {
            APSMpReturn error "Problem getting LTS:Radmon:GRateAi value: $rad"
        }
        if {($rad >= 7)} {
            APSMpStep "LTS:Radmon:GRateAi = $rad"
            APSMpStep "Waiting until LTS:Radmon:GRateAi is less than 7mR/hr"
            if {$tries == 180} {
                if {[APSPEMTKDialog .warningDialog -text "LTS:Radmon:GRateAi is still over 7mR/hr"] == 1} {
                    APSMpReturn error "LTS:Radmon:GRateAi is still over 7mR/hr"
                }
            } else {
                incr tries
            }
        } else {
            break
        }
    }

    set maxtries [expr 180 - $tries]
    if {$maxtries < 10} {
        set maxtries 10
    }
    set tries 0
    APSMpStep "Waiting until LTS:Radmon:NRateAi is less than 2mR/hr"
    set tries 0
    while {$tries <= $maxtries} {
        APSWaitWithUpdate -waitSeconds 1
        if {[catch {APScavget -list=LTS:Radmon:NRateAi -num -pend=20} rad]} {
            APSMpReturn error "Problem getting LTS:Radmon:NRateAi value: $rad"
        }
        if {($rad >= 2)} {
            APSMpStep "LTS:Radmon:NRateAi = $rad"
            APSMpStep "Waiting until LTS:Radmon:NRateAi is less than 2mR/hr"
            if {$tries == $maxtries} {
                if {[APSPEMTKDialog .warningDialog -text "LTS:Radmon:NRateAi is still over 2mR/hr"] == 1} {
                    APSMpReturn error "LTS:Radmon:NRateAi is still over 2mR/hr"
                }
            } else {
                incr tries
            }
        } else {
            break
        }
    }


    APSMpReturn ok

}

proc APSMpITS_K3RecoverDialog {frame} {
    pack [frame $frame.top]
    APSLabeledEntry .time -parent $frame.top -textVariable APSMpITS_K3Recover(maxStepSize) \
      -label "Maximum Step size (kV)" -width 40

}

proc APSMpITS_K3Recover {args} {
    global execMode APSMpLControlPS
    set SCRFile ""
    set maxStepSize 0.5
    APSStrictParseArguments {SCRFile}
    set arrayName APSMpLControlPS
    APSLGenericPSArraySetup -arrayName $arrayName -SCRFile $SCRFile
    if {(![file exists $SCRFile]) && ($execMode == "Automatic")} {
        set execMode "Semi-Automatic"
    }
    if {![file exists $SCRFile]} {
        APSMpStep init -promptDialog "APSLGenericPSDialog -packProc APSMpITS_K3RecoverDialog -chooseSCR 1 -arrayName $arrayName -frame " -vars {maxStepSize}

        set SCRFile $APSMpLControlPS(Filename)

    }
    
    APSMpStep "Calling LMOCS_Recover"
    if {[catch {LMOCS_Recover -SCRFile $SCRFile -L3 1 -maxStepSize $maxStepSize -ITSMode 1} results]} {
        APSMpReturn error "APSMpITS_K3Recover: $results"
    }

    APSMpReturn ok
}

