#!/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: soliday $"


proc MakeDateTimeFrame {widget args} {
    set parent .
    set label "Date of Interest"
    APSStrictParseArguments {parent label}

    APSFrame $widget -parent $parent -label $label
    set w $parent$widget.frame

    APSDateTimeAdjEntry .startDate -parent $w \
      -yearVariable searchYear \
      -monthVariable searchMonth \
      -dayVariable searchDay 
    
}

proc SearchForGlitches {args} {
    global mainDataDir dayDirName
    set year ""
    set day ""
    set month ""
    APSStrictParseArguments {day month year}
    global glitchDay
    set glitchDay [APSFormatDate -year $year -month $month -day $day -dateFormat Y-J-MD]
    set dayDirName $mainDataDir/$glitchDay
    if ![file exists $dayDirName] {
        SetRmsGlitchReviewStatus "No data for that date."
        return
    }
    if ![file isdirectory $dayDirName] {
        SetRmsGlitchReviewStatus "Error: $dayDirName is not a directory!"
        return
    }
    if [winfo exists .notebook] {
        CheckIfNewInputSaved
    }
    set oldDir [pwd]
    cd $dayDirName
    set matchList [lsort [glob -nocomplain \[0-9\]\[0-9\]\[0-9\]\[0-9\]\[0-9\]\[0-9\]]]
    cd $oldDir
    if ![llength $matchList] {
        SetRmsGlitchReviewStatus "No data for that date."
        return
    }
    set HMSList ""
    foreach elem $matchList {
        lappend HMSList [string range $elem 0 1]:[string range $elem 2 3]:[string range $elem 4 5]
    }

    if [winfo exists .userFrame.glitchList] {
        destroy .userFrame.glitchList
    }

    APSScrolledList .glitchList -parent .userFrame \
      -name "RMS Glitch Choices for $month/$day/$year" \
      -itemList $HMSList -packOption "-side bottom" \
      -callback MakeGlitchPlots \
      -packOption "-fill y -expand yes" \
      -contextHelp "List of RMS glitchs for $month/$day/$year.  Double-click to review a glitch.  The numbers give the time of the glitchs in hours, minutes, and seconds."

}

proc showAlarmStatus {args} {
    set snapshot ""
    set searchMonth ""
    set searchDay ""
    set searchYear ""
    set HMSItem ""
    APSStrictParseArguments {snapshot searchMonth searchDay searchYear HMSItem}

    set printoutFile /tmp/[APSTmpString]
    APSAddToTmpFileList -ID RMSGlitchReview -fileList "$printoutFile"
    exec sddsprintout $snapshot $printoutFile -col=ControlName,format=%30s -col=ValueString,format=%10s
    
    APSFileDisplayWindow [APSUniqueName .] \
      -fileName $printoutFile -deleteOnClose 1 -height 50 \
      -comment "RMS Glitch: $searchMonth/$searchDay/$searchYear at $HMSItem"
    return
}

proc showFBCorrector {args} {
    set snapshot ""
    set searchMonth ""
    set searchDay ""
    set searchYear ""
    set HMSItem ""
    set suffix ""
    APSStrictParseArguments {snapshot searchMonth searchDay searchYear HMSItem suffix}
    set printoutFile /tmp/[APSTmpString]
    APSAddToTmpFileList -ID RMSGlitchReview -fileList "$printoutFile"
    switch $suffix {
        Err {
            set title "FB corrector error printout:"
        }
        Drive {
            set title "FB corrector drive printout:"
        }
    }
    foreach plane {H V} {
        if [catch {exec sddssort $snapshot -pipe=out -col=Name -numericHigh \
                     | sddsprocess  -match=col,ControlName=*:${plane}*${suffix}* -pipe -scan=col,Value,ValueString,%lf \
                     | sddsprintout -pipe=in $printoutFile.$plane -col=Name,format=%20s -col=Value,format=%20.4f "-title=$plane $title" } result] {
            return -code error $result
        }
    }
    APSFileDisplayWindow [APSUniqueName .] \
      -fileName $printoutFile.H -deleteOnClose 1 -height 50 \
      -comment "RMS Glitch: $searchMonth/$searchDay/$searchYear at $HMSItem"
    APSFileDisplayWindow [APSUniqueName .] \
      -fileName $printoutFile.V -deleteOnClose 1 -height 50 \
      -comment "RMS Glitch: $searchMonth/$searchDay/$searchYear at $HMSItem"
    
}

proc MakeGlitchPlots {HMSItem doubleClick} {
    global dayDirName searchYear searchMonth searchDay mainDataDir xrefDir
    global showAlarm plotBeamSize showFBCorrError showFBCorrDrive
    global plotFBCorrErrorTime plotFBCorrErrorRange plotFBCorrErrorMovie 
    global plotFBCorrDriveTime plotFBCorrDriveRange plotFBCorrDriveMovie 
    global plotRMSvector plotSRImage fbLimitMin  fbLimitMax plotDPCorr
    if !$doubleClick {
        return
    }
    set glitchTimeStamp "$searchMonth/$searchDay/$searchYear $HMSItem"
    set glitchTime [clock scan "$searchMonth/$searchDay/$searchYear $HMSItem"]
    SetRmsGlitchReviewStatus "Working on $HMSItem"
    regsub -all : $HMSItem "" HMS

    SetRmsGlitchReviewStatus "Checking for notebook file..."
    SearchForNotebookFile $HMS $HMSItem
    
    if $showAlarm {
        if [catch {showAlarmStatus -snapshot $dayDirName/$HMS/alarmRecord.sdds  \
                     -searchMonth $searchMonth -searchDay $searchDay -searchYear $searchYear \
                     -HMSItem $HMSItem} result] {
            return -code error $result
        }
    }
    set comment "RMS Glitch: $searchMonth/$searchDay/$searchYear at $HMSItem"
    if $plotBeamSize {
        exec sddsplot -col=Index,*WF -sep "-title=$comment" $dayDirName/$HMS/BeamSizeHistory.sdds &
    }
    if $showFBCorrError {
        if [catch { showFBCorrector -snapshot $dayDirName/$HMS/FBCorrectorError.snap.sdds \
                      -suffix Err \
                      -searchMonth $searchMonth -searchDay $searchDay -searchYear $searchYear \
                     -HMSItem $HMSItem} result] {
            return -code error $result
        } 
    }
    if $showFBCorrDrive {
        if [catch { showFBCorrector -snapshot $dayDirName/$HMS/FBCorrectorError.snap.sdds \
                      -suffix Drive \
                      -searchMonth $searchMonth -searchDay $searchDay -searchYear $searchYear \
                     -HMSItem $HMSItem} result] {
            return -code error $result
        } 
    }
    set tmpfile /tmp/[APSTmpString]
    if $plotFBCorrErrorRange {
        SetRmsGlitchReviewStatus "Displaying FB corrector error range..."
        if [catch \
              {exec sddsprocess $dayDirName/$HMS/FBCorrHistory.sdds.gz -pipe=out \
                 "-filter=col,TimeRelativeToTrip,$fbLimitMin,$fbLimitMax" \
                 "-process=*CorrErr,first,%sFirst" \
                 "-redef=col,%s,%s %sFirst -,select=*CorrErr" \
                 | sddsconvert -pipe "-del=col,*" "-retain=col,*Err" \
                 | sddstranspose -pipe \
                 | sddsprocess -pip=in $tmpfile.1 \
                 "-edit=col,magnet,OldColumnNames,azG/%/GB/S/%/:CorrErr//a%/:Horz/A:H3/%/:Vert/A:V3/"\
                 "-scan=col,Sector,magnet,S%d,type=long" \
                 "-define=column,StaggeredSector,Sector i_row 256 / +,type=float" \
                 "-print=parameter,PlotLabel,TimeStamp of Feedback RMS trip: %s,MPSTripTimeStamp"} result] {
            SetRmsGlitchReviewStatus "$result"
        } else {
            exec sddsplot $tmpfile.1 -lay=1,2 \
              "-col=StaggeredSector,Column*" "-match=col,magnet=*H3" \
              -pspace=0.15,0.9,0.2,0.85 \
              "-topl=Evolution of Horizontal Corrector Errors,scale=1.2" \
              -graph=impulse,type=1 \
              -xlabel=Sector "-ylabel=Corrector Error (A)" "-title=@PlotLabel" \
              -endp \
              "-col=StaggeredSector,Column*" "-match=col,magnet=*V3" \
              -pspace=0.15,0.9,0.25,0.9 \
              "-topl=Evolution of Vertical Corrector Errors,scale=1.2" \
              -graph=impulse,type=1 \
              -xlabel=Sector "-ylabel=Corrector Error (A)" \
              "-title=@PlotLabel" \
              -endp &
        }
    }
    if $plotFBCorrDriveRange {
        SetRmsGlitchReviewStatus "Displaying FB corrector drive range..."
        if [catch \
              {exec sddsprocess $dayDirName/$HMS/FBCorrHistory.sdds.gz -pipe=out \
                 -filter=col,TimeRelativeToTrip,$fbLimitMin,$fbLimitMax \
                 -process=*CorrDrive,first,%sFirst \
                 "-redef=col,%s,%s %sFirst -,select=*CorrDrive" \
                 | sddsconvert -pipe "-del=col,*" "-retain=col,*Drive" \
                 | sddstranspose -pipe \
                 | sddsprocess -pip=in $tmpfile.1 \
                 -edit=col,magnet,OldColumnNames,azG/%/GB/S/%/:CorrDrive//a%/:Horz/A:H3/%/:Vert/A:V3/ \
                 -scan=col,Sector,magnet,S%d,type=long \
                 "-define=column,StaggeredSector,Sector i_row 256 / +,type=float" \
                 "-print=parameter,PlotLabel,TimeStamp of Feedback RMS trip: %s,MPSTripTimeStamp" \
             } result] {
            SetRmsGlitchReviewStatus "$result"
        } else {
            exec sddsplot $tmpfile.1 -lay=1,2  \
              -col=StaggeredSector,Column* -match=col,magnet=*H3 \
              "-topl=Evolution of Horizontal Corrector Drives" \
              -graph=impulse,type=1 \
              -xlabel=Sector "-ylabel=Corrector Drive (A)" "-title=@PlotLabel" \
              -endp \
              -col=StaggeredSector,Column* -match=col,magnet=*V3 \
              "-topl=Evolution of Vertical Corrector Drives" \
              -graph=impulse,type=1 \
              -xlabel=Sector "-ylabel=Corrector Drive (A)" \
              -title=@PlotLabel \
              -endp &
        }
    }
    if $plotFBCorrErrorMovie {
        SetRmsGlitchReviewStatus "Displaying FB corrector drive movie..."
        if [catch {exec sddsprocess $dayDirName/$HMS/FBCorrHistory.sdds.gz $tmpfile.2 \
                     "-filter=col,TimeRelativeToTrip,$fbLimitMin,$fbLimitMax" \
                     "-process=*CorrErr,first,%sFirst" \
                     "-print=parameter,PlotLabel,TimeStamp of Feedback RMS trip: %s,MPSTripTimeStamp" \
                     "-redef=col,%s,%s %sFirst -,select=*CorrErr" } result] {
            SetRmsGlitchReviewStatus "$result"
        } else {
            exec sddsplot \
              -pspace=0.15,0.9,0.25,0.9 \
              -groupby=subpage,req -sep=request -layout=1,2 -graph=impulse,type=1 \
              -same=y  "-title=@PlotLabel" -transpose -xlabel=Sector -offset=xChange=1 \
              "-col=TimeRelativeToTrip,*Horz*Err*" $tmpfile.2 \
              "-ylabel=Horizontal Delta Error (A)" \
              "-col=TimeRelativeToTrip,*Vert*Err*"  $tmpfile.2 \
              "-ylabel=Vertical Delta Error (A)" \
              "-title=@PlotLabel" &
        }
    }
    if $plotFBCorrDriveMovie {
        SetRmsGlitchReviewStatus "Displaying FB corrector drive movie..."
        if [catch {exec sddsprocess $dayDirName/$HMS/FBCorrHistory.sdds.gz $tmpfile.2 \
                     "-filter=col,TimeRelativeToTrip,$fbLimitMin,$fbLimitMax" \
                     "-process=*CorrDrive,first,%sFirst" \
                     "-print=parameter,PlotLabel,TimeStamp of Feedback RMS trip: %s,MPSTripTimeStamp" \
                     "-redef=col,%s,%s %sFirst -,select=*CorrDrive" } result] {
            SetRmsGlitchReviewStatus "$result"
        } else {
            exec sddsplot \
              -pspace=0.15,0.9,0.25,0.9 \
              -groupby=subpage,req -sep=request -layout=1,2 -graph=impulse,type=1 \
              -same=y  "-title=@PlotLabel" -transpose -xlabel=Sector -offset=xChange=1 \
              "-col=TimeRelativeToTrip,*Horz*Drive*" $tmpfile.2 \
              "-ylabel=Horizontal Delta Drive (A)" \
              "-col=TimeRelativeToTrip,*Vert*Drive*"  $tmpfile.2 \
              "-ylabel=Vertical Delta Drive (A)" \
              "-title=@PlotLabel" &
        }
    }
    
    if {$plotFBCorrErrorTime || $plotFBCorrDriveTime} {
        SetRmsGlitchReviewStatus "Displaying FB corrector errors and drive time movies..."
        if [catch \
              {exec sddsprocess $dayDirName/$HMS/FBCorrHistory.sdds.gz -pipe=out \
                 "-filter=col,TimeRelativeToTrip,$fbLimitMin,$fbLimitMax" \
                 | sddstranspose -pipe \
                 | sddsprocess -pipe  \
                 "-edit=col,magnet,OldColumnNames,azG/%/GB/S/a%/:Horz/A:H3/%/:Vert/A:V3/"\
                 | sddstranspose -pipe -newColumnNames=magnet \
                 | sddscombine -pipe=in -merge $tmpfile } result] {
            SetRmsGlitchReviewStatus "$result"
        } else {
            if $plotFBCorrErrorTime {
                exec sddsplot -layout=1,2 -col=TimeRelativeToTrip,S*H*:CorrErr \
                  $tmpfile -sep -grap=sym,conn \
                  -mode=y=offset -same -title=@TimeStamp \
                  "-topline=Horizontal Corrector Error relative to first point" &
                exec sddsplot -layout=1,2  \
                  -col=TimeRelativeToTrip,S*V*:CorrErr \
                  $tmpfile -sep -grap=sym,conn \
                  -mode=y=offset -same -title=@TimeStamp \
                  "-topline=Vertical Corrector Error relative to first point" &
            }
            if $plotFBCorrDriveTime {
                exec sddsplot -layout=1,2 -col=TimeRelativeToTrip,S*H*Drive \
                  $tmpfile -sep -grap=sym,conn \
                  -mode=y=offset -same -title=@TimeStamp \
                  "-topline=FB Horizontal Corrector Drive relative to first point" &
                exec sddsplot -layout=1,2 -col=TimeRelativeToTrip,S*V*Drive \
                  $tmpfile -sep -grap=sym,conn \
                  -mode=y=offset -same -title=@TimeStamp \
                  "-topline=FB Vertical Corrector Drive relative to first point" &
            }
        }
    }
    
    if $plotDPCorr {
        SetRmsGlitchReviewStatus "Displaying InUse datapool corrector time plots..."
        if [catch {exec sddsquery $dayDirName/$HMS/InUseDPCorrHistory.sdds.gz -col -sddsOutput=$tmpfile.4 } result] {
            return -code error $result
        }
        foreach index {1 2 3 4} {
            foreach plane {H V} x {HTimeStamps VTimeStamps} {
                foreach type {A B C} {
                    if [catch {exec sddsprocess $tmpfile.4 $tmpfile.5 -match=col,Name=S*${type}:${plane}$index } result] {
                        continue
                    }
                    exec sddsplot -sep -layout=1,2 -same -mode=y=offset \
                      -tick=xtime -axe=x $dayDirName/$HMS/InUseDPCorrHistory.sdds.gz \
                      "-topline=InUse DP $plane Corrector Error relative to first point" \
                      -title=@TimeStamp \
                      -col=$x,S*${type}:${plane}$index &
                }
            }
        }
    }
    
    
    if $plotRMSvector {
        exec sddsplot -sep -col=Index,*WF $dayDirName/$HMS/rmsVectors.sdds \
          "-topline=RMS vectors" \
          -title=@TimeStamp &
    }

    if $plotSRImage {
       exec sddscontour -shade -col=x,HLine* -yaxis=scalePar=VLineSpacing,offsetPar=VLineOffset $dayDirName/$HMS/SRImage.sdds \
         "-title=SR Image for RMS glitch at $glitchTimeStamp" &
    }
    SetRmsGlitchReviewStatus "Done."
}


proc SearchForNotebookFile {HMS HMSItem} {
    global mainDataDir glitchDay fileTime notebookFile noNotes
    set notebookFile $mainDataDir/notebookFiles/Note-$glitchDay.$HMS
    set blankFile $mainDataDir/notebookFiles/blankFile
    set fileTime $HMSItem

    if [winfo exists .notebook] {
        CheckIfNewInputSaved
    }

    APSEnableButton .userFrame.buttons.frame.note.button

    if ![file exists $blankFile] {
        exec touch $blankFile
        catch {file attribute $blankFile -permissions 00664}
    }

    if [file exists $notebookFile] {
        set noNotes 0
    } else {
        catch {file copy -force -- $blankFile $notebookFile}
        catch {file attribute $notebookFile -permissions 00664}
        set noNotes 1
    }
}

proc EditNotebookFile {} {
    global dayDirName  fileTime glitchDay noNotes timeStamp
    global notebookFile inputSaved text1 text2 noNotes
    set inputSaved 0

    APSDisableButton .userFrame.buttons.frame.note.button

    if !$noNotes {
        SetRmsGlitchReviewStatus "Editing $notebookFile"
    }

    set notebookCmd "CheckIfNewInputSaved; APSEnableButton .userFrame.buttons.frame.note.button"

    APSWindow .notebook -name "Notebook for RMS Glitch: $glitchDay/$fileTime" 
    .notebook.buttonRow.close.button configure -command $notebookCmd
    APSScrolledText .file1 -parent .notebook.userFrame -width 80 -height 10
    APSScrolledText .file2 -parent .notebook.userFrame -width 80 -height 10
    
    set text1 .notebook.userFrame.file1.text
    set text2 .notebook.userFrame.file2.text
    bind .notebook.userFrame.file2.text <Key> {set inputSaved 0} 

    if !$noNotes {
        set fileName $notebookFile
        
        if [file exists $fileName] {
            if [catch {open $fileName r} f] {
                SetRmsGlitchReviewStatus "EditNotebookFile: $f"
                return
            }
            while {![eof $f]} {
                $text1 insert end [read $f 1000]
            }
            if [catch {close $f} results] {
                SetRmsGlitchReviewStatus "EditNotebookFile: $results"
                return
            }
        } else {
            SetRmsGlitchReviewStatus "Notebook file $notebookFile not found."
            return
        }
    } else {
        SetRmsGlitchReviewStatus "No previous entries in the notebook for                    \
				    $glitchDay/$fileTime."
        bell
    }

    $text1 configure -state disabled
    set timeStamp [eval exec date]

    APSDialogBoxAddButton .print -parent .notebook -text Print  \
      -command {SetCombineText $text1 $text2 print} -contextHelp \
      "Print contents of window using enscript command."
    
    APSDialogBoxAddButton .saveFile -parent .notebook -text "Save"  \
      -command "SaveNotebookFile $text1 $text2"  -contextHelp "Export contents of window to a file."

    APSDialogBoxAddButton .undo -parent .notebook -text "Undo Saving"  \
      -command "UndoSaving"  -contextHelp "Export contents of window to a file."

    APSDialogBoxAddButton .tomail -parent .notebook -text "Email..."  \
      -command {SetCombineText $text1 $text2 mail} \
      -contextHelp "Send the contents of window as an email message."

    APSDisableButton .notebook.buttonRow.undo.button
}

proc SetCombineText {text_1 text_2 printMail} {
    global noNotes timeStamp
    set T3 ""
    set T1 ""
    set T2 ""

    if !$noNotes {
        set T1 [$text_1 get 1.0 insert]
    }
    set T2 [$text_2 get 1.0 insert]
    if [llength $T1] {
        append T3 $T1
    }
    if [llength $T2] {
        append T3 "$timeStamp \n"
        append T3 $T2
    }

    if ![string compare $printMail mail] {
        APSEMailDialog [APSUniqueName .] -width 80 -message $T3 -modal 1
    }
    if ![string compare $printMail print] {
        APSPrint -text $T3
    }
}

proc UndoSaving {} {
    global notebookFile inputSaved

    SetRmsGlitchReviewStatus "Undoing saving..."
    
    catch {file delete $notebookFile}
    if [file exists $notebookFile~] {
        catch {file copy -force -- $notebookFile~ $notebookFile}
        catch {file attribute $notebookFile -permissions 00664}
    }

    APSDisableButton .notebook.buttonRow.undo.button
    set inputSaved 0
    SetRmsGlitchReviewStatus "Done."
}

proc SaveNotebookFile {textWidget1 textWidget2} {
    global notebookFile inputSaved noNotes timeStamp

    if [catch {CheckUsersList} result] {
        bell
        APSAlertBox .alert1 -errorMessage "$result"
        return
    }

    SetRmsGlitchReviewStatus "Saving notes..."

    if !$noNotes {
        if [file exists $notebookFile~] {
            catch {file delete $notebookFile~}
        }
        catch {file copy -force -- $notebookFile $notebookFile~}
        catch {file attribute $notebookFile~ -permissions 00664}
    }

    # Open the notebook file for appending
    if [catch {open $notebookFile a} fid] {
        update
        # no access to the file!
        bell
        APSDialogBox .dialog1 -width 40 -height 3
        pack forget .dialog1.buttonRow.cancel.button
        set t_1 .dialog1.userFrame.t1
        text $t_1 -setgrid true -wrap word -width 40 -height 3
        pack $t_1 -side top -fill both -expand true
        $t_1 insert end "No access to: $notebookFile"
        $t_1 configure -state disabled
        update
    }	 


    # See if it has a lock on it
    if [catch {os lockf $fid F_TLOCK 0} result] {
        # file is locked by another user
        close $fid
        SetRmsGlitchReviewStatus "Can't update file now---it is locked.  Try later."
        bell
    } else {
        # file is now locked by this process
        global env
        puts $fid "$timeStamp by $env(USER)"
        puts $fid "[$textWidget2 get 1.0 insert] \n"
        close $fid
        SetRmsGlitchReviewStatus "File updated by $env(USER)."
    }

    set inputSaved 1
    set noNotes 0
    APSEnableButton .notebook.buttonRow.undo.button
    SetRmsGlitchReviewStatus "Done."
}

proc CheckUsersList {} {
    set usersList [list oag sr asdops borland lemery cyao carwar nassiri decker]

    catch {eval exec whoami} userName
    
    if {[lsearch -exact $usersList $userName] < 0} {
        return -code error "You do not have permission to write into this file. Please, send e-mail to borland to be put on the permission list."
    } else {
        return -code ok
    }
}

proc CheckIfNewInputSaved {} {
    global inputSaved text1 text2

    if !$inputSaved {
        catch {APSMultipleChoice [APSUniqueName .] \
                 -question "Last entry in the notebook is not saved. What do you want to do?" \
                 -labelList {Quit Save} \
                 -returnList  {Quit Save}} choice
        
        if ![string compare $choice Save] {
            SaveNotebookFile $text1 $text2
        }
    }
    
    destroy .notebook    
}

proc SetRmsGlitchReviewStatus {text} {
    global rmsGlitchReviewStatus 
    set rmsGlitchReviewStatus "[exec date +%H:%M:%S]: $text"
    update
}

proc SearchGlitchData {args} {
    global GlitchReason StartYear StartMonth StartDay EndYear EndMonth EndDay Answer glitchDataList
    
    set oldDir [pwd]
    cd /home/helios/oagData/rmsOrbitGlitch/
    set glitchDataList ""
    set startTime [clock scan $StartMonth/$StartDay/$StartYear]
    set endTime [expr [clock scan $EndMonth/$EndDay/$EndYear] + 24*3600 - 1]
    set step [expr 24*3600]
    for {set time $startTime} {$time<$endTime} {incr time $step} {
        set date [clock format $time -format %Y-%j-%m%d]
        if ![file exist $date] {
            continue
        }
        cd $date
        set glitchList [lsort [glob -nocomplain \[0123456\]?????]]
        cd ..
        if {[llength $glitchList] == 0} continue
        foreach glitch $glitchList {
            if [catch {exec sddsprocess $date/$glitch/glitchRecord.snap.gz -pipe=out \
                           -match=col,ControlName=S:RMS:lastTripCauseSI \
                           | sdds2stream -pipe -col=ValueString} result] {
                puts stderr $result
            }
            if {[regexp $GlitchReason $result]} {
                lappend glitchDataList $date/$glitch 
            }
        }
    }
    if ![llength $glitchDataList] {
        cd $oldDir
        return -code error "No glitch record found for $GlitchReason from $StartMonth/$StartDay/$StartYear to $EndMonth/$EndDay/$EndYear." 
    }
    set tmpfile /tmp/[APSTmpString]
    if [catch {exec sddsmakedataset -pipe=out -col=GlitchTime,type=string -data=[join $glitchDataList ,] \
                   | sddsprintout -pipe=in $tmpfile "-title=Glitch record found for \"$GlitchReason\"  from $StartMonth/$StartDay/$StartYear to $EndMonth/$EndDay/$EndYear." \
                   -col=GlitchTime } result] {
        cd $oldDir
        return -code error $result
    }
    APSFileDisplayWindow [APSUniqueName .] -fileName $tmpfile -width 50 -deleteOnClose 1
    cd $oldDir

}

APSApplication . -name rmsGlitchReview -version $CVSRevisionAuthor -overview \
  "Provides a way to review data from storage ring rms glitches.  The data consists of a snapshot file\
 giving values of RMS process variables after the glitch, along with automatically collected beam\
 history data from relevant BPMs."

set mainDataDir /home/helios/oagData/rmsOrbitGlitch
set xrefDir $OAGGlobal(SRLatticesDirectory)/scripts

set oldDir [pwd]
set rmsGlitchReviewStatus Ready.
APSScrolledStatus .status -parent .userFrame -textVariable rmsGlitchReviewStatus -width 60

MakeDateTimeFrame .datetime -parent .userFrame 

set showAlarm 0
set plotBeamSize 0
set showFBCorrError 0
set showFBCorrDrive 0
set plotFBCorrErrorTime 0
set plotFBCorrErrorRange 0
set plotFBCorrErrorMovie 0
set plotFBCorrDriveTime 0
set plotFBCorrDriveRange 0
set plotFBCorrDriveMovie 0
set plotDPCorr 0
set plotRMSvector 0
set plotSRImage 0
set fbLimitMin -76.8
set fbLimitMax -0.6

APSCheckButtonFrame .plane -parent .userFrame \
  -orientation vertical -limitPerRow 7 \
  -label "Output choices" -allNone 1 \
  -variableList {showAlarm plotBeamSize showFBCorrError showFBCorrDrive \
                   plotFBCorrErrorTime plotFBCorrErrorRange plotFBCorrErrorMovie \
                   plotFBCorrDriveTime plotFBCorrDriveRange plotFBCorrDriveMovie \
                   plotDPCorr plotRMSvector plotSRImage } \
  -buttonList {"Alarm Status" "Beam Size History Plots" "FB Corrector Error Printout" "FB Corrector DriveError Printout" \
                 "FB Corrector Error time-domain Plots" "FB Corrector Error Range Plots" "FB Corrector Error Movie Plot" \
                 "FB Corrector Drive time-domain Plots" "FB corrector Drive Range Plots" "FB Corrector Drive Movie Plot" \
                 "InUse DP Corrector Plots" "RMS vector Plots" "SR Image Plot" } \
  -contextHelp \
  "Choose what items you want to review for each glitch, prior to double-clicking on the glitch time.\n\nFast BPM plots show data from the fast beam histories; note that these may not be available for several minutes after a glitch.\n\nFB corrector error data shows what the realtime orbit feedback system predicts to be the required corrector changes to correct the orbit error it sees; this may point to where the source of motion is.\n\nOrbit correction last step plots show the last change to corrector strengths made by the slow orbit correction program.\n\nGlitch data printouts show a selection of PV values taken just after the glitch.\n\nOrbit comparison converts the BPM history data into unadjusted bpm readbacks and then compares them with the expected unadjusted bpm readbacks inferred from the SR User Beam Preferred file."

set labelWidth -60
APSLabeledEntryFrame .movielimits -parent .userFrame \
  -label [format %${labelWidth}s "Time limits (mS) for corrector error plots (start, end):"] \
  -variableList {fbLimitMin fbLimitMax} -orientation horizontal -width 5 -contextHelp \
  "Enter the minimum and maximum time limits for the corrector error movie.  If the two numbers are the same, then the plots are autoscaled."

APSFrame .buttons -parent .userFrame -relief flat -label ""
#APSButton .search1 -parent .userFrame.buttons.frame -command "SearchGlitchReason" \
#    -text "Search Glitch Reason..." -contextHelp "search rms glitch data from glitchRecord.snap.gz\
# (i.e. string value of :RMS:lastTripCauseSI) and returns a list of rms glitch directories."
APSButton .search -parent .userFrame.buttons.frame -command \
  {SearchForGlitches -year $searchYear -month $searchMonth -day $searchDay} \
  -text "Search" \
  -contextHelp "Searches for RMS glitch data from the day selected."
APSButton .note -parent .userFrame.buttons.frame -text "Edit Notebook" \
  -command EditNotebookFile
APSDisableButton .userFrame.buttons.frame.note.button
