#!/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)]
APSDebugPath

APSStandardSetup
set lab 0
set args $argv
APSParseArguments {lab}

#source /home/oxygen/SHANG/oag/apps/src/tcltkapp/oagapp/LiberaSyntheticDataSetup.tcl
set sectorList ""
set varList ""
if $lab {
    for {set i 1} {$i<2} {incr i 2} {
	set sector [format %02d $i]
	lappend sectorList [format %02d $i]
	set BPLD(S$sector) 0
	lappend varList BPLD(S$sector)
    }
    set BPLD(sectorList) $sectorList
    set BPLD(sectorVarList) $varList
} else {
    set sectList [exec sdds2stream -col=Sector /home/helios/oagData/sr/BPLD/doubleSectors.sdds]
    foreach i $sectList {
	set sector [format %02d $i]
	lappend sectorList [format %02d $i]
	set BPLD(S$sector) 0
	lappend varList BPLD(S$sector)
    }
    set BPLD(sectorList) $sectorList
    set BPLD(sectorVarList) $varList
}

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

set BPLD(mainDir) [APSGoToDailyDirectory -subdirectory APSUBPLDValidation]
set BPLD(rootname) BMValidation

set bmBPMConfigStatus ""
APSApplication . -name LiberaSyntheticDataSetup  \
  -overview "LiberaBPMGainWaveform provides convenience controls for generating gain waveform for libera BPMs."
APSScrolledStatus .status -parent .userFrame -width 100 \
        -textVariable bmBPMConfigStatus

set itemLabelList ""
set indexList ""
for {set i 1} {$i<=28} {incr i} {
    lappend indexList $i
}
set itemLabelList {n-1AP5 n-1AP6 n-1BP6 n-1BP5 n-1BP4 n-1BP3 n-1BP2 n-1BP1 n-1BP0 \
		       nAP0 nAP1 nAP2 nAP3 nAP4 nAP5 nAP6 nBP6 nBP5 nBP4 nBP3 nBP2 nBP1 nBP0 \
		       n+1AP0 n+1AP1 n+1AP2 n+1AP3 n+1AP4}

set itemList $itemLabelList

set wList [APSTabFrame .tab -parent .userFrame -labelList {"Gain_Waveform" "Setup"} -height 800 -width 950]
set f1 [lindex $wList 0]
set f2 [lindex $wList 1]

APSSRSectorButtons .bpm -parent $f1 -rootname bmBPM -allButtons 1 \
    -label "BPLD BM BPM Selection"  -sectorList $sectorList -orientation horizontal \
    -itemList $itemList -itemLabelList $itemLabelList -description "BPLD BM BPM Config" \
    -sectorControl 1 -packOption "-side top" -globalButtons 1 -colorDesc 0

APSSetSRSectorButtons -mode all-off -rootname bmBPM  -itemList $itemList -sectorList $sectorList



set BPLD(filename) test.sdds
APSLabeledEntry .dir -parent $f1 -textVariable BPLD(mainDir) -width 80 \
    -label "Data Dir:" 
APSLabeledEntry .file -parent $f1 -label "Filename:" -width 40 -textVariable BPLD(filename)
#APSFrameGrid .grid -parent .userFrame -xList {x1 x2}

set BPLD(gainType) step
#APSRadioButtonFrame .plane -parent $f1 -label "Gain Type: " -buttonList {step sine} -valueList {step sine} \
#    -orientation horizontal -variable BPLD(gainType)
set BPLD(loadGain) 0
set BPLD(sineCycles) 1
set BPLD(sineAmp) 2.0
set BPLD(sineDecay) 0.0
set BPLD(stepStart0) 100
set BPLD(stepEnd0) 200
set BPLD(stepStart1) 300
set BPLD(stepEnd1) 400
set BPLD(stepStart2) 500
set BPLD(stepEnd2) 600
set width 20
set BPLD(plot) 1
set BPLD(sineOffset) 1.0
set BPLD(stepAmp0) 1.2
set BPLD(stepAmp1) 1.2
set BPLD(stepAmp2) 1.2

set width 15
#APSRadioButtonFrame .plot -parent $w2 -label "Plot Waveform?" -buttonList {Yes No} \
#    -valueList {1 0} -orientation horizontal -variable BPLD(plot)
APSLabeledEntryFrame .sine -parent $f1 -label "Sine Function Amplitude/Offset/Cycles/Decay:" \
    -width $width -variableList {BPLD(sineAmp) BPLD(sineOffset) BPLD(sineCycles) BPLD(sineDecay)} -orientation horizontal
set BPLD(step0) 1
set BPLD(step1) 0
set BPLD(step2) 0
APSLabeledEntryFrame .step0 -parent $f1 -label "Step Function1 Amp/Start/End:" -width $width \
    -orientation horizontal -variableList {BPLD(stepAmp0) BPLD(stepStart0) BPLD(stepEnd0)}
APSLabeledEntryFrame .step1 -parent $f1 -label "Step Function2 Amp/Start/End:" -width $width \
    -orientation horizontal -variableList {BPLD(stepAmp1) BPLD(stepStart1) BPLD(stepEnd1)}
APSLabeledEntryFrame .step2 -parent $f1 -label "Step Function3 Amp/Start/End:" -width $width \
    -orientation horizontal -variableList {BPLD(stepAmp2) BPLD(stepStart2) BPLD(stepEnd2)}
APSFrameGrid .grid -parent $f1 -xList {x1 x2 x3}
set w1 $f1.grid.x1
set w2 $f1.grid.x2
set w3 $f1.grid.x3
APSRadioButtonFrame .plane -parent $w1 -label "Gain Type: " -buttonList {step sine} -valueList {step sine} \
    -orientation horizontal -variable BPLD(gainType)
APSRadioButtonFrame .plot -parent $w2 -label "  Plot Waveform?" -buttonList {Yes No} \
    -valueList {1 0} -orientation horizontal -variable BPLD(plot)
APSCheckButtonFrame .step -parent $w3 -label "  Step function to use:" -buttonList {step1 step2 step3} \
    -variableList {BPLD(step0) BPLD(step1) BPLD(step2)} -orientation horizontal


APSButton .gen -parent $f1 -text "Generate" -command "Generate"
APSButton .load -parent $f1 -text "Load" -command "LoadGainWaveform"
APSButton .plot -parent $f1 -text "Plot" -command "Plot"

#setup tab
set BPLD(plane) X
set BPLD(Xmask) 64
set BPLD(Ymask) 128
#X plane mask is 64, Y plane is 128
set BPLD(XStatic) 1000
set BPLD(YStatic) 2000
set BPLD(repetition) 4095
set BPLD(samples) 4095

set BPLD(doubleSector) ""
set liberaList {ioc2sn1bpm1 ioc2sn1bpm2 ioc2sn1bpm3 ioc2sn1bpm4 ioc2snbpm5 ioc2snbpm6 ioc2snbpm7}
#set liberaList {Sn1LB1 Sn1LB2 Sn1LB3 Sn1LB4 SnLB5 SnLB6 SnLB7}
set BPLD(liberaList) $liberaList
set iocLabelList {LBP1 LBP2 LBP3 LBP4 LBP5 LBP6 LBP7}
set varList ""
set checkList ""
foreach ioc $liberaList {
    #set BPLD(${ioc}Event) 119
    set BPLD(${ioc}Event) 62
    lappend varList BPLD(${ioc}Event)
    set BPLD(${ioc}.checked) 1
    lappend checkList BPLD(${ioc}.checked)
}
APSCheckButtonEntryFrame .check -parent $f2 -buttonList $iocLabelList -variableList $checkList \
    -allNone 1 -entryWidth 10 -entryVariableList $varList -label "Libera trigger event number to be used:" -orientation horizontal \
    -limitPerRow 3

APSRadioButtonFrame .sector -parent $f2 -label "Double Sector:" -buttonList $sectorList -valueList $sectorList -variable BPLD(doubleSector) \
    -orientation horizontal -limitPerRow 10
set width 25
APSRadioButtonFrame .plane -parent $f2 -label "Gain waveform data plane:" -buttonList {X Y} -valueList {X Y} -orientation horizontal \
    -variable BPLD(plane)
APSLabeledEntryFrame .static -parent $f2 -label "X/Y plane static value:" -width $width -orientation horizontal \
    -variableList {BPLD(XStatic) BPLD(YStatic)}
APSLabeledEntry .rep -parent $f2 -label "The repetition number of gain waveform to be applied(0-4095):" -width $width -textVariable BPLD(repetition)
APSLabeledEntry .samples -parent $f2 -label "The number of gain waveform samples to be used(0-4095):" -width $width -textVariable BPLD(samples)
set BPLD(triggerEvent) event
APSRadioButtonFrame .trig -parent $f2 -label "Synthetic waveform trigger:" -buttonList {trigger_on_next_event trigger_immediatly} \
    -valueList {event immediate} -orientation horizontal -variable BPLD(triggerEvent)

APSFrame .ff -parent $f2 
$f2.ff.frame configure -bd 0
APSButton .setup -parent $f2.ff.frame -text "Setup" -command SetupSynData

#set configFile /home/oxygen/SHANG/APSU_test/BPLD_Config/config.sdds
if $lab {
    set configFile /home/oxygen/DIAG/apsu/BPLD/BPLD_Config/config.sdds
}  else {
    set configFile /home/helios/oagData/sr/BPLD/BPLD_Config/config.sdds
}

proc Generate {args} {
    global BPLD itemList execList lab
  #  puts "$BPLD(step0) $BPLD(step1) $BPLD(step2)"
    set bpmList [GetSelectedBPMs]
    if ![llength $bpmList] {
	SetStatus "No BPMs chosen!"
	return
    }
    if [catch {GenerateGainWaveform -mainDir $BPLD(mainDir) -filename $BPLD(filename) \
		   -bpmList $bpmList -lab $lab \
		   -gainType $BPLD(gainType) -sineAmp $BPLD(sineAmp) -sineOffset $BPLD(sineOffset) \
		   -sineCycles $BPLD(sineCycles) -sineDecay $BPLD(sineDecay) -step0 $BPLD(step0) -step1 $BPLD(step1) -step2 $BPLD(step2) \
		   -stepStart0 $BPLD(stepStart0) -stepEnd0 $BPLD(stepEnd0) -stepAmp0 $BPLD(stepAmp0) \
		   -stepStart1 $BPLD(stepStart1) -stepEnd1 $BPLD(stepEnd1) -stepAmp1 $BPLD(stepAmp1) \
		   -stepStart2 $BPLD(stepStart2) -stepEnd2 $BPLD(stepEnd2) -stepAmp2 $BPLD(stepAmp2) \
		   -statusCallback SetStatus } result] {
	return -code error "Error generate gain wf: $result"
    }

    if $BPLD(plot) {
	exec sddsplot -topline=@BPMName "-title=Gain Waveform" -col=Index,Waveform -split=page \
	    -sep=page $BPLD(mainDir)/$BPLD(filename) &
    }
    SetStatus "done."
}


proc GetSelectedBPMs {args} {
    global BPLD itemList execList configFile
    
   # set configFile /home/oxygen/SHANG/APSU_test/BPLD_Config/config.sdds
    set selectBPMList ""
    set tmpFile /tmp/[APSTmpString]
    APSAddToTmpFileList -ID libera -fileList $tmpFile
    foreach sector $BPLD(sectorList) {
	set indexList ""
	for {set i 1} {$i<=28} {incr i} {
	    set item [lindex $itemList [expr $i-1]]
	    set name bmBPM$sector$item
	    global $name
	    if [set $name] {
		lappend indexList $i
	    }
	    
	}
	if ![llength $indexList] {
	    #SetStatus "No bpms chosen for S$sector, skip."
	    continue
	}
	set opt ""
	foreach index $indexList {
	    if ![string length $opt] {
		set opt -filter=col,BPLDIndex,$index,$index
	    } else {
		append opt ,BPLDIndex,$index,$index,|
	    }
	}
	if [catch {exec sddsprocess $configFile -filter=col,BPLDSector,$sector,$sector \
		       $opt $tmpFile} result] {
	    return -code error "Error reading data from config file: $result"
	}
	set bpmList [exec sdds2stream -col=DeviceName $tmpFile]
	set selectBPMList [concat $selectBPMList $bpmList]
    }
    return $selectBPMList
}

proc LoadGainWaveform {args} {
    global BPLD lab
    set outFile $BPLD(mainDir)/$BPLD(filename)
    
    if [catch {Generate} result] {
	return -code error "Error generating gain waveform file: $result"
    }
    
    SetStatus "Loding $outFile ..."
    
    if [catch {exec sddswput $outFile  -pend=30} result] {
	return -code error "Error loading gain waveform: $result"
    }
    SetStatus "Gain WF loaded."
}

proc Plot {args} {
    global BPLD
    set filename $BPLD(mainDir)/$BPLD(filename)
    if ![file exist $filename] {
	SetStatus "$filename does not exit, click Generate first"
	return
    }
    exec sddsplot -topline=@BPMName "-title=Gain Waveform" -col=Index,Waveform -split=page \
	-sep=page $filename &

}

proc SetupSynData {args} {
    global BPLD configFile lab
    if ![string length $BPLD(doubleSector)] {
	SetStatus "Please select a sector to start setup"
	return
   }
    set sector [scan $BPLD(doubleSector) %d]
    if !$lab {
	if {$sector==1} {
	    set liberaList [regsub -all "n1" $BPLD(liberaList) 40]
	} else {
	    set liberaList [regsub  -all "n1" $BPLD(liberaList) [format %02d [expr $sector-1]]]
	}
	set liberaList [regsub -all  "n2" $liberaList [format %02d [expr $sector+1]]]
	
	set liberaList [regsub -all "n" $liberaList [format %02d $sector]]
    } else {
	set liberaList {S44LBP1 S44LBP2 S44LBP3 S44LBP4 S45LBP5 S45LBP6 S45LBP7}
	#only S44 libera available in the lab,
    }
    set hostList ""
    set eventList ""
    foreach libera $BPLD(liberaList) LB $liberaList {
	if $BPLD(${libera}.checked) {
	    lappend hostList $LB
	    lappend eventList $BPLD(${libera}Event)
	}
    }
   # puts $hostList
    if [catch {exec sddsprocess $configFile -pipe=out -filter=col,BPLDSector,$sector,$sector \
		   | sdds2stream -pipe=in -col=DeviceName } bpmList] {
	return -code error "Error obtaining bpms from config file: $bpmList"
    }
   # puts $BPLD(XStatic)
    if [catch {SetupSyntheticData -statusCallback SetStatus -doubleSector [scan $BPLD(doubleSector) %d] \
		   -lab $lab -bpmList [join $bpmList]  \
		   -hostList $hostList -eventList $eventList \
		   -xstatic $BPLD(XStatic) -ystatic $BPLD(YStatic) \
		   -repetition $BPLD(repetition) -samples $BPLD(samples) \
		   -loadGain 0 -plane $BPLD(plane) \
		   -trigger $BPLD(triggerEvent) } result] {
	return -code error "Error setup synthetic data for sector $BPLD(doubleSector): $result"
    }
    return
}
