#!/bin/sh
# \
exec oagtclsh "$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 CVSRevisionAuthor "\$Revision: 1.56 $ \$Author: soliday $"

package require sdds
set timeStamp [exec date]
set starttime [clock seconds]
set time [clock format $starttime -format "%Y-%m%d.%H:%M"]
set date [exec date]
set startyear [clock format $starttime -format %Y]
set startmonth [clock format $starttime -format %m]
set startday [clock format $starttime -format %d]
set starthour [clock format $starttime -format %H]
set startminute [clock format $starttime -format %M]

#update the brightness every 15 minutes and plot in the web
set input $OAGGlobal(SRLatticesDirectory)/default/sector1.twi
set outputDir /home/helios/oagData/sr/IDs/brightnessLog/data
set outputDir /tmp
#get the current, coupling, and emittance
if [catch {exec cavget -list=S-DCCT:CurrentM -pend=30 -printErrors} current] {
    puts "Error: $current"
    exit
}
#set current 100
if {$current<1} {
    puts "No data will be taken since there is no beam."
    exit
}
set current [expr $current / 1000.0]

if {$current<0} {
    set current 1.0e-9
}
if [catch {exec cavget -list=S:VID1:couplingEff -pend=30 -printErrors} coupling] {
    puts "Error: $coupling"
    exit
}
if [catch {exec cavget -list=S:VID1:XemittanceEff -pend=30 -printErrors} emittance] {
    puts "Error: $emittance"
    exit
}
#set coupling 0.1
#set emittance 2
set coupling [expr $coupling / 100.0]
set emittance [expr $emittance * 1.0e-9]
#parameters of undulators
set deviceFile /home/helios/oagData/sr/IDs/deviceTypes.sdds
if [catch {sdds load $deviceFile deviceData} result] {
    puts "Error: $result"
    exit
}

set deviceNameList [lindex $deviceData(Column.DeviceType) 0]
set deviceTypeList [lindex $deviceData(Column.Type) 0]
set periodsList [lindex $deviceData(Column.EffectivePeriods) 0]
set periodLengthList [lindex $deviceData(Column.PeriodLength) 0]
set KstartList [lindex $deviceData(Column.Kstart) 0]
set KendList [lindex $deviceData(Column.Kend) 0]
set XminList [lindex $deviceData(Column.Xmin) 0]
set XmaxList [lindex $deviceData(Column.Xmax) 0]
set gapList [lindex $deviceData(Column.MinimumGap) 0]
set fileList ""
set plotFileList ""

foreach name $deviceNameList type $deviceTypeList  N $periodsList period $periodLengthList start $KstartList end $KendList {
    set period [expr $period / 1.0e3]
    set length [expr $N * $period]
    set harmonics 3
    if {$name=="CPU"} {
        set harmonics 1
    }
    if [catch {exec sddsbrightness $input $outputDir/$name-$time -coupling=$coupling \
                 -current=$current -harmonics=$harmonics -Krange=start=$start,end=$end,points=50 \
                 -totalLength=$length -periodLength=$period -method=dejus,device=$type \
             } result] {
        puts stderr "Computing $name brightness: $result"
        exit
    }
    lappend fileList $outputDir/$name-$time
    lappend plotFileList $name.bright.plot
}

set emittance [format %.2f [expr $emittance * 1.0e9]]
set coupling [format %.2f [expr $coupling * 100]]
set current [format %.1f [expr $current *1000.0]]
set string3 "-string=emitt: $emittance nm-rad,p=0.63,q=0.83"
set string4 "-string=coupl: ${coupling}%,p=0.63,q=0.77"
set string5 "-string=current: $current mA,p=0.63,q=0.72"


foreach device $deviceNameList file $fileList xmin $XminList xmax $XmaxList gap $gapList {
    #set output /home/oxygen/OAG/oagWWW-$env(EPICS_HOST_ARCH)/AutoSavedPlots/$device.png
    set output /net/epics-ops/web_roots/ops/AutoSavedPlots/$device.png

    set range2 17.98
    if {$device=="U18"} {
        set range2 16.98
    }
    if {$device=="CPU"} {
        set range2 17.9
    }
    set tmpfile /tmp/[APSTmpString]
    if [catch {exec sddsprocess $file $tmpfile -process=Brightness1,maximum,Brightness1Peak \
                 -process=K,min,KMin -process=K,max,KMax \
                 -redefine=par,StartTime,$starttime \
                 "-reprint=par,date,$startmonth/$startday/$startyear" \
                 -redefine=par,emittance,$emittance,units=nm-rad \
                 -redefine=par,coupling,$coupling,units=% \
                 -redefine=par,StartHour,$starthour -redefine=par,StartMinute,$startminute} result ] {
        puts "Error: $result"
        exit
    }
    
    if [catch {exec sddssort $file -col=Brightness1,decreasing -pipe=out | \
                 sdds2stream -pipe -col=photonEnergy1 } energies] {
        puts "Error: $energies"
        exit
    }
    set energy_peak [format %.3f [lindex $energies 0]]
    set peak [exec sdds2stream $tmpfile -par=Brightness1Peak]
    set kmax [format %.2f [exec sdds2stream $tmpfile -par=KMax]]
    if {$device=="CPU"} {
        set kx [format %.3f [expr $kmax /sqrt(2)]]
        set string1 "-string=kx=ky: max_kx is $kx,p=0.4,q=0.93"
    } else {
        set string1 "-string=Kmax $kmax @ min. gap $gap mm,p=0.4,q=0.93"
    }
    set peak1 [format %.3e $peak]
    set string2 "-string=peak: $peak1 at $energy_peak keV,p=0.4,q=0.88"
    set range1 [expr log($peak)/log(10) +0.02]
    exec mv $tmpfile $file
    if {$range1<$range2} {
        set range2 [expr $range1 - 1]
    }
    switch $device {
        CPU {
            exec sddsplot $file -device=png,onwhite -output=$output \
              -mode=y=log -tick=ylog "-topLine=${device}(circular mode)" \
              -grap=line,vary \
              "-string=Kx\=Ky: max_Kx\=$kx,p=0.25,q=.65" \
              "-string=peak: $peak1 at $energy_peak keV,p=0.25,q=0.60" \
              "-string=emitt: $emittance nm-rad,p=0.25,q=.55" \
              "-string=coupl: ${coupling}%,p=0.25,q=0.50" \
              "-string=current: $current mA,p=0.25,q=0.45" \
              "-title=$date" \
              "-ylabel=On-Axis Brilliance (ph/s/mrad^2/mm^2/0.1%bw)" \
              "-xlabel=Photon Energy (keV)" \
              -col=photonEnergy1,Brightness1 "-leg=spec=Harmonic 1" \
              -scale=$xmin,$xmax,$range2,$range1 &
        }
        U18 {
            exec sddsplot $file -device=png,onwhite -output=$output \
              -mode=y=log -tick=ylog "-topLine=${device}" \
              -grap=line,vary $string1 $string2 $string3 $string4 $string5 \
              "-title=$date" \
              "-ylabel=On-axis Brilliance (ph/s/mrad^2/mm^2/0.1%bw)" \
              "-xlabel=Photon Energy (keV)" \
              -col=photonEnergy1,Brightness1 "-leg=spec=Harmonic 1" \
              -col=photonEnergy3,Brightness3 "-leg=spec=Harmonic 3" \
              -scale=$xmin,$xmax,$range2,$range1 &
        } 
        default {
            exec sddsplot $file -device=png,onwhite -output=$output \
              -mode=y=log -tick=ylog -topLine=$device \
              -grap=line,vary  $string1 $string2 $string3 $string4 $string5 \
              "-title=$date" \
              "-ylabel=On-axis Brilliance (ph/s/mrad^2/mm^2/0.1%bw)" \
              "-xlabel=Photon Energy (keV)" \
              -col=photonEnergy1,Brightness1 "-leg=spec=Harmonic 1" \
              -col=photonEnergy3,Brightness3 "-leg=spec=Harmonic 3" \
              -col=photonEnergy5,Brightness5 "-leg=spec=Harmonic 5" \
              -scale=$xmin,$xmax,$range2,$range1 &
        }
    }
}

set endtime [clock seconds]
set endyear [clock format $endtime -format %Y]
set endmonth [clock format $endtime -format %m]
set endday [clock format $endtime -format %d]
set endhour [clock format $endtime -format %H]
set endminute [string trimleft [clock format $endtime -format %M] 0]
if {$endminute == ""} {
    set endminute 0
}
set endminute [expr [format %.0f $endminute] + 1]
set name U55
set current [format %.1f [exec sdds2stream $outputDir/$name-$time -par=current]]
set sigmax [format %.4f [exec sdds2stream $outputDir/$name-$time -par=sigmax]]
set sigmaxprime [format %.5f [exec sdds2stream $outputDir/$name-$time -par=sigmaxprime]]
set sigmay [format %.4f [exec sdds2stream $outputDir/$name-$time -par=sigmay]]
set sigmayprime [format %.5f [exec sdds2stream $outputDir/$name-$time -par=sigmayprime]]
set energyspread [format %.6f [exec sdds2stream $outputDir/$name-$time -par=EnergySpread]]
set emittancey [expr $emittance * $coupling]
set betax [format %.2f [lindex [exec sdds2stream $input -column=betax] 0]]
set betay [format %.2f [lindex [exec sdds2stream $input -column=betay] 0]]
set dispersion [format %.3f [lindex [exec sdds2stream $input -column=etax] 0]]
#set coupling [format %.4f $coupling]

#set dir /home/oxygen/OAG/oagWWW-$env(EPICS_HOST_ARCH)/AutoSavedPlots
set dir /net/epics-ops/web_roots/ops/AutoSavedPlots

if {![file exists $dir]} {
    exit
}

exec replaceText $dir/brightness.temp $dir/brightness.html \
  "-orig=<Current>,<EnergySpread>,<Sigmax>,<SigmaxPrime>,<Sigmay>,<SigmayPrime>,<date>,<betax>,<betay>,<etax>,<emittanceX>,<emittanceY>,<coupling>" \
  "-repl=$current,$energyspread,$sigmax,$sigmaxprime,$sigmay,$sigmayprime,$date,$betax,$betay,$dispersion,$emittance,$emittancey,$coupling"

foreach plot $deviceNameList {
    exec replaceText $dir/brightness.tmp $dir/${plot}.html \
      "-orig=<plot>,<Current>,<EnergySpread>,<Sigmax>,<SigmaxPrime>,<Sigmay>,<SigmayPrime>,<date>,<startyear>,<startmonth>,<startday>,<starthour>,<startminute>,<endyear>,<endmonth>,<endday>,<endhour>,<endminute>,<undulator>" \
      "-repl=${plot}.png,$current,$energyspread,$sigmax,$sigmaxprime,$sigmay,$sigmayprime,$date,$startyear,$startmonth,$startday,$starthour,$startminute,$endyear,$endmonth,$endday,$endhour,$endminute,$plot"
}

foreach title $deviceNameList {
    if [file exist $dir/${title}.brightness] {
        exec rm $dir/${title}.brightness
    }
 #   exec cp $outputDir/${title}-$time $dir/${title}.brightness
    if [catch {exec sddsconvert $outputDir/${title}-$time -pipe=out \
                 -rename=col,K=Keff -edit=col,photon*,%/photon// \
                 -edit=col,Brightness*,%/Brightness/Brilliance/ \
                 | sddsprocess -pipe=in $dir/${title}.brightness \
                 "-redefine=col,%s,%s 1.0 *,units=,select=Brilliance*" } result] {
        puts stderr $result
        exit
    }
    if {$title=="CPU"} {
        if [catch {exec sddsprintout $dir/${title}.brightness $dir/${title}.brightness.printout \
                     "-title=$title brilliance (ph/s/mrad^2/mm^2/0.1%bw) at $timeStamp\nbetax=$betax m    betay=$betay m     etax=$dispersion m\nemittance=${emittance} nm-rad    coupling=${coupling}%\nsigmax=$sigmax mm         sigmax'=$sigmaxprime mrad \nsigmay=$sigmay mm         sigmay'=$sigmayprime mrad\nEnergySpread=$energyspread    current=$current mA\n" \
                     -col=Keff,format=%.3f \
                     -col=Energy1,format=%.3f -col=Brilliance1,format=%.3e } result] {
            puts stderr "PlotBrightness Error1 (CPU): $result"
            exit
        }
    } elseif {$title=="U18"} {
        if [catch {exec sddsprintout $dir/${title}.brightness $dir/${title}.brightness.printout \
                     "-title=$title brilliance (ph/s/mrad^2/mm^2/0.1%bw) at $timeStamp\nbetax=$betax m    betay=$betay m     etax=$dispersion m\nemittance=${emittance} nm-rad    coupling=${coupling}%\nsigmax=$sigmax mm         sigmax'=$sigmaxprime mrad \nsigmay=$sigmay mm         sigmay'=$sigmayprime mrad\nEnergySpread=$energyspread    current=$current mA\n" \
                     -col=Keff,format=%.3f \
                     -col=Energy1,format=%.3f -col=Brilliance1,format=%.3e \
                     -col=Energy3,format=%.3f -col=Brilliance3,format=%.3e } result] {
            puts stderr "PlotBrightness Error2 (U18): $result"
            exit
        }
    } else {
        if [catch {exec sddsprintout $dir/${title}.brightness $dir/${title}.brightness.printout \
                     "-title=$title brilliance (ph/s/mrad^2/mm^2/0.1%bw) at $timeStamp\nbetax=$betax m    betay=$betay m     etax=$dispersion m\nemittance=${emittance} nm-rad    coupling=${coupling}%\nsigmax=$sigmax mm         sigmax'=$sigmaxprime mrad \nsigmay=$sigmay mm         sigmay'=$sigmayprime mrad\nEnergySpread=$energyspread    current=$current mA\n" \
                     -col=Keff,format=%.3f \
                     -col=Energy1,format=%.3f -col=Brilliance1,format=%.3e \
                     -col=Energy3,format=%.3f -col=Brilliance3,format=%.3e \
                     -col=Energy5,format=%.3f -col=Brilliance5,format=%.3e} result] {
            puts stderr "PlotBrightness Error3 (${title}): $result"
            exit
        }
    }
}
after 2000
eval file delete $fileList
exit
