#!/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

set CVSRevisionAuthor "\$Revision: 1.2 $ \$Author: emery $"

APSApplication . -name RFConditioningScheduler -version $CVSRevisionAuthor \
  -overview {Creates schedule of beam injection for RF conditioning with beam given user-entered parameters. Assumes that the beam will be injected in a uniform pattern. The schedule is created to increase the HOM heating in the cavities linearly with time.}

set status Working...
APSScrolledStatus .status -parent .userFrame -textVariable status \
        -width 60 -height 6
update

proc MakeInputWidget {widget args} {
    set parent ""
    APSStrictParseArguments {parent}

    set w $parent$widget.frame
    APSFrame $widget -parent $parent \
      -label "Input parameters" -contextHelp \
      "Input parameters which define the speed of the conditioning."
    APSLabeledEntry .startTime -parent $w -label "Start Hour (h): " \
      -textVariable startHour -width 60
    APSLabeledEntry .endTime -parent $w -label "End Hour (h): " \
      -textVariable endHour -width 60 \
      -contextHelp "Enter the target end time. To include the case for the next day use a number greater than 24."

    APSLabeledEntry .startCurrent -parent $w -label "Start Current (mA): " \
      -textVariable startCurrent -width 60
    APSLabeledEntry .endCurrent -parent $w -label "End Current (mA): " \
      -textVariable endCurrent -width 60 \
      -contextHelp "Enter the target current."

    APSLabeledEntry .bunches -parent $w -label "Number of Bunches: " \
      -textVariable bunches -width 60 \
      -contextHelp "Enter the number of bunches in the symmetric pattern including the initial bunch injected."
    APSLabeledEntry .firstBunchCurrent -parent $w -label "Current of first bunch (mA): " \
      -textVariable firstBunchCurrent -width 60 \
      -contextHelp "Enter the current in the first bunch, which is injected before all others."

}

proc MakePlotInputFrame {widget args} {
    APSStrictParseArguments {parent}
    
    set w $parent$widget.frame
    APSFrame $widget -parent $parent -label "Plot options"

    APSLabeledEntry .printer -parent $w \
      -label "Printer (color postscript):" -textVariable printer \
      -width 10 \
      -contextHelp "Enter the color printer name for the print command."

    APSRadioButtonFrame .device  -parent  $w \
      -label Device -orientation horizontal -limitPerRow 4 \
      -variable fileDevice \
      -buttonList {None "Color eps" "png" "Large png"} \
      -valueList {"" ceps png,onwhite lpng,onwhite} \
      -contextHelp "Choose the plotting device for the plot to a file command.\n\nColor eps is for figures imported into latex. png is for importing into a web page or sending through email."

    APSLabeledEntry .directory -parent $w \
      -label "Output directory for plot file:" -textVariable outputDirectory \
      -contextHelp "Directory of output file." -width 55
    APSLabeledEntry .file -parent $w \
      -label "Output file root:" -textVariable outputFileRoot \
      -contextHelp "Output file root in above directory. Used to create file names of plot output and printout." -width 55
    return
}

proc MakePlotCommandFrame {widget args} {
    set parent ""
    APSStrictParseArguments {parent}
    
    set w $parent$widget.frame
    APSFrame $widget -parent $parent -label "Plot commands"
    
    APSButton .plot -parent $w \
      -text "Plot"  \
      -packOption "-side left" \
      -command {PlotSchedule \
                  -fileRoot [file join $outputDirectory $outputFileRoot]} \
      -contextHelp "Plots the schedule of injection between the two time limits."

    # The only valid choice for printer device is cpost.
    APSButton .print -parent $w \
      -text "Plot+Print"  \
      -packOption "-side left" \
      -command {PlotSchedule \
                  -fileRoot [file join $outputDirectory $outputFileRoot] \
                  -printDevice cpost -printer $printer} \
      -contextHelp "Plots and prints the schedule of injection between the two time limits."

    # Creates a file of the plot
    APSButton .file -parent $w \
      -text "Plot+File"  \
      -packOption "-side left" \
      -command {PlotSchedule  \
                  -fileDevice $fileDevice \
                  -fileRoot [file join $outputDirectory $outputFileRoot]} \
      -contextHelp "Plots the schedule to a file."

    APSButton .table -parent $w \
      -text "Table Printout"  \
      -packOption "-side left" \
      -command {PrintoutSchedule \
                  -fileRoot [file join $outputDirectory $outputFileRoot]} \
      -contextHelp "Printouts the data of the schedule to a window which you can send to a printer."

}

proc PlotSchedule {args} {
    global startHour endHour firstBunchCurrent startCurrent endCurrent bunches

    set parent ""
    set printDevice cpost
    set printer ""
    set fileDevice ""
    set fileRoot ""
    APSStrictParseArguments {parent printDevice printer fileDevice fileRoot}
    
    if {$fileRoot==""} {
        return -code error "PlotSchedule: No fileRoot given."
    }

    exec sddssequence -pipe -def=Time,units=h,type=double \
      -sequence=begin=$startHour,delta=0.5,end=$endHour \
      | sddsprocess -pipe=in $fileRoot \
      "-def=para,Increment,$endCurrent $firstBunchCurrent -" \
      "-def=para,Bunches,$bunches" \
      "-def=para,BunchesM1,$bunches 1 -" \
      "-def=para,Duration,$endHour $startHour -,units=h" \
      "-def=col,ElapsedTime,Time $startHour -,units=h" \
      "-def=para,HOMPowerEnd,$firstBunchCurrent sqr Increment sqr BunchesM1 / +" \
      "-def=para,HOMPowerStart,$firstBunchCurrent sqr $startCurrent $firstBunchCurrent - sqr BunchesM1 / +" \
      "-def=para,HOMPowerSlope,HOMPowerEnd HOMPowerStart - $endHour $startHour - /" \
      "-def=col,BunchCurrent,ElapsedTime HOMPowerSlope * HOMPowerStart + $firstBunchCurrent sqr - BunchesM1 / sqrt" \
      "-def=col,Current,$firstBunchCurrent BunchCurrent BunchesM1 * + int,type=long" \
      "-def=col,HOMPower,$firstBunchCurrent sqr Current $firstBunchCurrent - sqr BunchesM1 / +,units=arb."

    exec sddsplot $fileRoot -grap=line,vary,thick=2  -leg \
      "-topline=Conditioning with ramping HOM power" \
      -alignZero=yfactor \
      -tick=xgrid,xspacing=4,linetype=2 \
      -subtick=xdiv=4,xgrid,line=3 \
      -col=Time,Current -tick=ygrid -sep \
      -col=Time,HOMPower  -yscale=id=power \
      &
    
    if [string length $printer] {
        exec sddsplot $fileRoot -grap=line,vary,thick=2  -leg \
          "-topline=Conditioning with ramping HOM power" \
          -alignZero=yfactor \
          -tick=xgrid,xspacing=4,linetype=2 \
          -subtick=xdiv=4,xgrid,line=3 \
          -col=Time,Current -tick=ygrid -sep \
          -col=Time,HOMPower  -yscale=id=power \
          -dev=$printDevice | lpr -P$printer
    }
    if [string length $fileDevice] {
        switch -regexp $fileDevice {
            eps {
                set file $fileRoot.ceps
            }
            png {
                set file $fileRoot.png
            }
        }
        exec sddsplot $fileRoot -grap=line,vary,thick=2  -leg \
          "-topline=Conditioning with ramping HOM power" \
          -alignZero=yfactor \
          -tick=xgrid,xspacing=4,linetype=2 \
          -subtick=xdiv=4,xgrid,line=3 \
          -col=Time,Current -tick=ygrid -sep \
          -col=Time,HOMPower  -yscale=id=power \
          -dev=$fileDevice -out=$file 
        switch -regexp $fileDevice {
            eps {
                exec ghostview $file &
            }
            png {
                exec xv $file &
            }
        }
    }
 }


proc PrintoutSchedule {args} {
    set fileRoot ""
    APSStrictParseArguments {fileRoot}

    if ![file exists $fileRoot] {
        APSSetVarAndUpdate status "File $fileRoot not generated yet. Press one of the Plot buttons first."
        return
    }
    exec sddsprintout -col=(Time,Current) -format=double=%4.1f \
      $fileRoot $fileRoot.print

    APSFileDisplayWindow [APSUniqueName .] -fileName $fileRoot.print \
      -deleteOnClose 0 -width 100 -height 45 -printCommand "enscript -r"

}

set outputDirectory [pwd]
set outputFileRoot conditioning
set printer color
set printDevice cpost
set fileDevice ceps

MakeInputWidget .input -parent .userFrame
MakePlotInputFrame .plotInput -parent .userFrame
MakePlotCommandFrame .plotCommand -parent .userFrame

set startHour  8
set endHour  24
set firstBunchCurrent  5 
set startCurrent  5
set endCurrent  102
set bunches  24

