#!/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.41 $ \$Author: emery $"

APSApplication . -name XrayBPMReview -version $CVSRevisionAuthor \
  -overview "Shows Xray bpm data averaged over some time interval. Allows the comparison of Xray positions for two time periods."

proc SetStatus {text} {
    global status
    set status $text
    update
    bell
}

proc XrayBPMAverage {args} {
    global gapFile filterFile
    global minVoltage plane type label posDiffTolerance

    set type IDs
    set plane y
    set year 1997
    set date ""
    set start 0
    set end 24
    set label ""
    set usage "xrayBPMsAverage -type \{IDs|BMs\} -plane \[x|y\] \
        -month <MM> -day <DD> -start <hours> -end <hours>"

    APSStrictParseArguments {type plane year month day start end}
    
    if { ![string length $type] ||  ![string length $plane] \
           || ![string length $year] \
           || ![string length $month]  || ![string length $day] \
           || ![string length $start] \
           || ![string length $end] } {
        return -code error "xrayBPMsAverage: $usage"
    }
    set excludeIDSectorList ""
    if [expr -1 != [lsearch $type {IDs BMs}]] {
        return -code error "xrayBPMsAverage: invalid type: $type"
    }
    if [expr -1 != [lsearch $plane {x y}]] {
        return -code error "xrayBPMsAverage: invalid plane: $plane"
    }
    if {$end < $start} {
        return -code error "xrayBPMsAverage: Error: End hour less than $start hour"
    }
    set label "$month/$day/$year from $start to $end (minimal acceptable \
               voltage $minVoltage V)"
    
    set dir  /home/helios/oagData/monitoring/$type
    set fileList [glob $dir/$type-$year-*-[format %02ld ${month}][format %02ld ${day}].*]
    if [expr [llength $fileList] > 1 ] {
        SetStatus "Combining multiple files $fileList."
        set file $type-$year-[format %02ld ${month}][format %02ld ${day}].comb
        if [catch {eval exec sddscombine $fileList $file -merge -overWrite \
                 } result ] {
            return -code error "xrayBPMsAverage: $result"
        }
    } else {
        set file $fileList
        if {1} {
        if [exec sdds2stream $fileList -npages=bare]>1 {
            set tmpfile /tmp/[APSTmpString]Split
            if [catch {exec sddssplit $file -rootname=$tmpfile} result] {
                return -code error $result
            }
            set files [glob $tmpfile*] 
            APSAddToTempFileList $files
            if [catch {eval exec sddscombine $files $tmpfile -merge -overwrite} result] {
                return -code error $result
            }
            APSAddToTempFileList $tmpfile
            set file $tmpfile
        }
        }
    }
    set root [file root [file tail $file]]
    set resultsFile /tmp/${root}-[APSTmpString].proc
    APSAddToTempFileList $resultsFile
    SetStatus "Using data in $file"
    
 
    switch $type {
        IDs {
            CreateFilterFile
            switch $plane {
                x {
                    set direction Horizontal
                }
                y {
                    set direction Vertical
                }
            }
            set IDList [APSIDSectorList]
            # List of data required for analysis. Most of these are supposed
            # to be included as columns of the data logger file as 
            # suffixes to each ID sector.
            #  set dataList {HorizontalPosition1 HorizontalPosition2 \
              #                 VerticalPosition1 VerticalPosition2 \
              #                AverageGap Blade1MaxVoltage Blade2MaxVoltage}
            set dataList {HorizontalPosition1 HorizontalPosition2 \
                            VerticalPosition1 VerticalPosition2 \
                            Blade1MaxVoltage Blade2MaxVoltage}
            
            set rowstatsOptions ""
            foreach sector $IDList {
                set sectorLabel [format %02ld $sector]
                # create new columns called ID<n>Blade<i>MaxVoltage for each bpm i.
                lappend rowstatsOptions -maximum=ID${sectorLabel}Blade1MaxVoltage,ID${sectorLabel}?1
                lappend rowstatsOptions -maximum=ID${sectorLabel}Blade2MaxVoltage,ID${sectorLabel}?2
            }
            set averageValues /tmp/${root}-[APSTmpString].ave
            APSAddToTempFileList $averageValues
             # process all gap PVs, even when there are 2 gaps in each straight section.
            if [catch {eval exec sddsrowstats $file \
                         -pipe=out $rowstatsOptions -nowarning \
                         | sddsprocess -pipe -nowarning \
                         -filter=col,TimeOfDay,$start,$end \
                         \"-test=param,n_rows 3 >\" \
                         -process=ID*Position1,ave,%sAVE \
                         -process=ID*Position2,ave,%sAVE \
                         -process=ID*AverageGap,ave,%sAVE \
                         -process=ID*Blade?MaxVoltage,ave,%sAVE \
                         | sddscollapse -pipe \
                         | sddsconvert -pipe=in $averageValues \
                         -retain=col,*AVE -edit=col,*AVE,%/AVE// \
                     } result ] {
                return -code error "xrayBPMsAverage: $result"
            }
           # puts $averageValues
            if [catch {APSGetSDDSNames -class column \
                         -fileName $averageValues} columns] {
                return -code error "xrayBPMsAverage: $columns"
            }
            # check that all columns are present for each sector
            set totalCount 0
            set renameColumns ""
            set defineColumns ""
            foreach sector $IDList {
              #  if {-1 < [lsearch -exact $excludeIDSectorList $sector]} continue
                set sectorLabel [format %02ld $sector]
                set completeData 1
                set renamed 0
                foreach data $dataList {
                    if {-1 == [lsearch -exact $columns ID${sectorLabel}${data}]} {
                        set completeData 0
                        break
                    }
                }
                if !$completeData {
                    SetStatus "Eliminating ID${sectorLabel} data because of incompleteness."
                } else {
                    if {[lsearch -exact $columns ID${sectorLabel}DSAverageGap]>=0} {
                        set dsGap [exec sdds2stream $averageValues -col=ID${sectorLabel}DSAverageGap]
                        if {[lsearch -exact $columns ID${sectorLabel}AverageGap]==-1 && !$renamed} {
                            set renamed 1
                            lappend renameColumns "ID${sectorLabel}DSAverageGap=ID${sectorLabel}AverageGap"
                            lappend defineColumns "-redefine=col,ID${sectorLabel}AverageGap,$dsGap"
                        }
                    } else {
                        if {[lsearch -exact $columns ID${sectorLabel}AverageGap]==-1 && !$renamed} {
                            lappend defineColumns "-redefine=col,ID${sectorLabel}AverageGap,0,units=mm"
                        }
                    }
                    if [lsearch -exact $columns ID${sectorLabel}USAverageGap]>=0 {
                        set usGap [exec sdds2stream $averageValues -col=ID${sectorLabel}USAverageGap]
                        lappend defineColumns "-redefine=col,ID${sectorLabel}AverageGapUS,$usGap,units=mm"
                    } else {
                        lappend defineColumns "-redefine=col,ID${sectorLabel}AverageGapUS,0,units=mm"
                    }
                    
                    lappend retainColumns ID${sectorLabel}AverageGap
                    foreach data $dataList {
                        lappend retainColumns ID${sectorLabel}${data}
                    }
                }
            }
            if [llength $renameColumns] {
                set rename "-rename=col,[join $renameColumns ,]"
            } else {
                set rename ""
            }
            #puts "[llength $defineColumns], $defineColumns"
            # puts stderr $averageValues
            if [catch {eval exec sddsconvert $averageValues -pipe=out \
                         $rename \
                         | sddsconvert -pipe -retain=col,[join $retainColumns ,] \
                         | sddsprocess -pipe $defineColumns \
                         | sddscollect -pipe=in $resultsFile.all \
                         -collect=suffix=AverageGap,column=gap \
                         -collect=suffix=AverageGapUS,column=USgap \
                         -collect=suffix=VerticalPosition1,column=ybpm1 \
                         -collect=suffix=HorizontalPosition1,column=xbpm1 \
                         -collect=suffix=VerticalPosition2,column=ybpm2 \
                         -collect=suffix=HorizontalPosition2,column=xbpm2 \
                         -collect=suffix=Blade1MaxVoltage,col=maxV1 \
                         -collect=suffix=Blade2MaxVoltage,col=maxV2 \
                     } result] {
                return -code error "xrayBPMsAverage: $result"
            }
            # Filter out bpms that either OkForDCOrbitCorrectionH or 
            # OkForDCOrbitCorrectionV is not OK
            APSAddToTmpFileList -ID XrayBPMsAverage -fileList $resultsFile.all
            #puts $resultsFile.all
            if [catch {exec sddsselect $resultsFile.all $filterFile -match=Rootname \
                         $resultsFile} result] {
                return -code error "XrayBPMsAverage: $result"
            }
            if [catch {eval printTable -resultsFile $resultsFile} status] {
                return -code error "xrayBPMsAverage: $status"
            }                           
        }
        BMs {
            set plane y
            set direction Vertical
            set dataList {VerticalPosition1 VerticalPosition2 \
                            Blade1MaxVoltage Blade2MaxVoltage}
            set BMList [APSBMSectorList]
            set rowstatsOptions ""
            foreach sector $BMList {
                set sectorLabel [format %02ld $sector]
                lappend rowstatsOptions \
                  -maximum=BM${sectorLabel}Blade1MaxVoltage,BM${sectorLabel}?1
                lappend rowstatsOptions \
                  -maximum=BM${sectorLabel}Blade2MaxVoltage,BM${sectorLabel}?2
            }
            set averageValues /tmp/${root}-[APSTmpString].ave
            APSAddToTempFileList $averageValues
            if [catch {eval exec sddsrowstats $file -pipe=out \
                         $rowstatsOptions -nowarning \
                         | sddsprocess -pipe -nowarning \
                         -filter=col,TimeOfDay,$start,$end \
                         {"-test=param,n_rows 3 >"} \
                         -process=BM??${direction}Position1,ave,%sAVE \
                         -process=BM??${direction}Position2,ave,%sAVE \
                         -process=BM??Blade?MaxVoltage,ave,%sAVE \
                         | sddscollapse -pipe \
                         | sddsconvert -pipe=in $averageValues \
                         -retain=col,*AVE -edit=col,*AVE,%/AVE// \
                     } result ] {
                return -code error "xrayBPMsAverage: $result"
            }
            SetStatus "Result of averaging in file $averageValues"
            if [catch {exec sddsquery -col $averageValues} columns] {
                return -code error "xrayBPMsAverage: $columns"
            }
            # check that all columns are present for each sector
            set deleteColumns ""
            for {set sector 1} {$sector < 40 } {incr sector} {
                set sectorLabel [format %02ld $sector]
                set completeData 1
                foreach data $dataList {
                    if {-1 == [lsearch -exact $columns BM${sectorLabel}${data}]} {
                        set completeData 0
                        continue
                    }
                }
                if !$completeData {
                    lappend deleteColumns "*$sectorLabel*"
                }
            }
            if [catch {exec sddsconvert $averageValues -pipe=out \
                         -delete=col,[join $deleteColumns ,] \
                         | sddscollect -pipe=in $resultsFile \
                         -collect=suffix=${direction}Position1,column=${plane}bpm1 \
                         -collect=suffix=${direction}Position2,column=${plane}bpm2 \
                         -collect=suffix=Blade1MaxVoltage,col=maxV1 \
                         -collect=suffix=Blade2MaxVoltage,col=maxV2 \
                     } result ] {
                return -code error "XrayBPMsAverage: $result"
            }
            if [catch {eval printTable -resultsFile $resultsFile} status] {
                return -code error "xrayBPMsAverage: $status"
            }                           
        }
    }
    return $resultsFile
}

proc printTable {args} {

    global minVoltage plane type label

    APSParseArguments {resultsFile}

    set mergedFiles ""
    set tmpfile /tmp/[APSTmpString]
    set totalFile $tmpfile.total
    set printoutFile  $tmpfile.print
    set printoutFile1 $tmpfile.print1
    set printoutFile2 $tmpfile.print2
    set printoutFile3 $tmpfile.print3
    set printoutFile4 $tmpfile.print4
    APSAddToTempFileList $totalFile $printoutFile $printoutFile1 $printoutFile2 $printoutFile3 $printoutFile4
    set good   "      "
    set wrong1 " bad1 "
    set wrong2 " bad2 "
    set wrong  " bad  "

    if ![catch {exec sddsprocess $resultsFile $printoutFile1 \
                  -filter=column,maxV1,0,$minVoltage,! \
                  -filter=column,maxV2,0,$minVoltage,! \
                  -print=parameter,Title,$label \
                  -print=column,State,$good -noWarning} result]==0 {
                      SetStatus "Problems due to $result"
                  }                          
    if ![catch {exec sdds2stream $printoutFile1 \
                  -rows | token -n=1} rows1]==0 {
                      SetStatus "Problems due to $rows1"
                  }
    #    SetStatus "rows1 = $rows1"

    if ![catch {exec sddsprocess $resultsFile  $printoutFile2 \
                  -filter=column,maxV1,0,$minVoltage \
                  -filter=column,maxV2,0,$minVoltage,! \
                  -print=parameter,Title,$label \
                  -print=column,State,$wrong1 -noWarning} result]==0 {
                      SetStatus "Problems due to $result"
                  }                          
    if ![catch {exec sdds2stream $printoutFile2 \
                  -rows | token -n=1} rows2]==0 {
                      SetStatus "Problems due to $rows2"
                  }
    #    SetStatus "rows2 = $rows2"

    if ![catch {exec sddsprocess $resultsFile  $printoutFile3 \
                  -filter=column,maxV1,0,$minVoltage,! \
                  -filter=column,maxV2,0,$minVoltage \
                  -print=parameter,Title,$label \
                  -print=column,State,$wrong2 -noWarning} result]==0 {
                      SetStatus "Problems due to $result" 
                  }                          
    if ![catch {exec sdds2stream $printoutFile3 \
                  -rows | token -n=1} rows3]==0 {
                      SetStatus "Problems due to $rows3"
                  }
    #    SetStatus "rows3 = $rows3"

    if ![catch {exec sddsprocess $resultsFile  $printoutFile4 \
                  -filter=column,maxV1,0,$minVoltage \
                  -filter=column,maxV2,0,$minVoltage \
                  -print=parameter,Title,$label \
                  -print=column,State,$wrong -noWarning} result]==0 {
                      SetStatus "Problems due to $result"
                  }                           
    if ![catch {exec sdds2stream $printoutFile4 \
                  -rows | token -n=1} rows4]==0 {
                      SetStatus "Problems due to $rows4"
                  }
    #    SetStatus "rows4 = $rows4"

    if {$rows1 > 0} {lappend mergedFiles $printoutFile1}        
    if {$rows2 > 0} {lappend mergedFiles $printoutFile2}
    if {$rows3 > 0} {lappend mergedFiles $printoutFile3}
    if {$rows4 > 0} {lappend mergedFiles $printoutFile4}
    
    catch {eval exec sddscombine $mergedFiles $totalFile -merge -overWrite}

    switch $type {
        IDs { 
            set dlina 85
            exec sddsprintout $totalFile $printoutFile -param=Title \
              -col=Rootname,label=ID,format=%7s \
              -col=(gap,USgap),format=%6.2f \
              -col=(?bpm1,?bpm2),format=%7.3f \
              -col=maxV?,format=%6.1f \
              -col=State,format=%5s
        } 
        BMs {    
            set dlina 70
            exec sddsprintout $totalFile $printoutFile -param=Title \
              -col=Rootname,label=BM,format=%7s \
              -col=${plane}bpm*,format=%7.3f \
              -col=maxV?,format=%6.2f \
              -col=State,format=%5s
        }                    
    }  

    APSFileDisplayWindow [APSUniqueName .] -fileName $printoutFile \
      -deleteOnClose 1 -width 100 -height 45 -printCommand "enscript -r"
}

proc MoveGaps {args} {
    set file ""
    APSParseArguments {file}
    
    if ![string length $file] {
        return -code error "MoveGaps: No file specified."
    }
    set tmpFile /tmp/[APSTmpString]
    APSAddToTempFileList $tmpFile
    
    # Don't move gaps if shutters are permitted to be open
    if [ShutterPermit] {
        return
    }
    # best way to generate a valid burt snapshot file
    # don't do anything since the burt request file will return ca errors
    # because not all IDs are installed in the ring.
    exec sddsprocess /home/helios/oagData/SCR/requestFiles/IDBM.req \
      $tmpFile.IDgaps.req -match=col,ControlName=ID*:Gap \
      -reedit=col,ControlName,ei/Set/
    catch {exec burtrb -f $tmpFile.IDgaps.req -o $tmpFile}

    # if the gaps in the first data set were set to higher than 150 mm
    # then there is no use in moving the present gaps.
    set gapThreshold 185
    if [catch {exec sddsprocess $tmpFile -match=column,ControlName=ID* -pipe=out \
                 -scan=col,IDNumber,ControlName,ID%ld,type=long \
                 -print=col,IDLabel,ID%02ld,IDNumber \
                 | sddsconvert -pipe -dele=column,ValueString  \
                 | sddsxref -pipe $file -nowarning \
                 -match=IDLabel=Rootname -take=gap \
                 | sddsprocess -pipe=in $tmpFile.1 -noWarning \
                 -filter=col,gap,0,$gapThreshold \
                 -print=col,ValueString,%lf,gap \
             } result ] {
        return -code error "MoveGaps: $result"
    }
    set numGaps [exec sdds2stream -rows=bare $tmpFile.1]
    if {$numGaps == 0} {
        SetStatus "All gaps in first data set are above threshold of $gapThreshold. No gaps move commands sent."
        return
    }

    SetStatus "BURT file prepared."
    
    set answer [tk_dialog .dialog "Warning" "Warning: Check if all gap access mode \
              is switched to Machine Physics mode before moving gaps. \
              Precess following buttons to continue or abort:" \
                  warning -1 OK Cancel]
    if $answer {
        SetStatus "Moving Gaps command is cancelled!"
        return
    }
    if [APSYesNoPopUp "Confirm: Move gaps now?"] {
        catch {exec carestore -sddsin $tmpFile.1 >& $tmpFile.1.log}
        SetStatus "Gap configuration file sent."
        
        catch {exec cavput -list=ID -range=beg=1,end=40,format=%02ld \
                 -list=:Start=1 -pend=20 -blunderAhead=silently &}
        SetStatus "Move gaps command sent."
        return
    }
    
    return -code error "Moving gaps was canceled."
}

proc CompareData {args} {
    global bpmType gapDiffTolerance posDiffTolerance minVoltage
    global label1 label2

    set file1 ""
    set file2 ""
    set label1 ""
    set label2 ""

    APSParseArguments {file1 file2 label1 label2}
    # puts "file1: $file1"
    # puts "file2: $file2"
    set newFile /tmp/[APSTmpString].new
    set resultsFile [file root $file1].results
    APSAddToTempFileList $newFile
    APSAddToTempFileList $resultsFile
    APSAddToTempFileList $resultsFile.help

    if [catch {exec sddsconvert $file2 $newFile \
                 -edit=col,*bpm*,ei/New/ \
                 -edit=col,gap,ei/New/ \
                 -edit=col,max*,ei/New/ \
             } result ] {
        return -code error "CompareData: $result"
    }
    if [catch {exec sddsxref $file1 $newFile -pipe=out -nowarning \
                 -match=Rootname -take=* \
                 | sddsprocess -pipe  \
                 "-def=col,%sDiff,%sNew %s -,select=*New,edit=%/New//,units=mm" \
                 | sddsprocess -pipe=in  $resultsFile \
                 "-def=col,%sAbs,%s abs,select=*Diff,units=mm" \
             } result ] {
        return -code error "CompareData: $result"
    }
    set printoutFile /tmp/[APSTmpString]
    APSAddToTempFileList $printoutFile
    # puts "new file, $newFile"
    # puts "results file, $resultsFile"
    if ![string compare $bpmType IDs] {
        if [catch {exec sddsprocess $resultsFile $resultsFile.help -nowarning \
                     -filter=col,gapDiffAbs,0,$gapDiffTolerance \
                     "-def=col,minmaxV1,maxV1New maxV1 min2,units=V" \
                     "-def=col,minmaxV2,maxV2New maxV2 min2,units=V"} result] {
            return -code error "CompareData: $result"
        }
        set rows [exec sdds2stream $resultsFile.help -rows=bare]
        #	puts $rows
        if !$rows {
            return -code error "CompareData: all gap differences are bigger than $gapDiffTolerance (tolerance)"
        }
        foreach plane {x y} {
            if [catch {APSSCRPrintXrayBPMCompTable -resultsFile $resultsFile.help \
                         -snap1Label $label1 -snap2Label $label2 -DifferenceLabel Diff(2-1) \
                         -Value1Label dataset1 -Value2Label dataset2 \
                         -posDiffTolerance $posDiffTolerance -minVoltage $minVoltage \
                         -bpmType ID -plane $plane} result] {
                return -code error $result
            }

        }                  
    } else {
      
        if [catch {exec sddsprocess $resultsFile $resultsFile.help -nowarning \
                     "-def=col,minmaxV1,maxV1New maxV1 min2,units=V" \
                     "-def=col,minmaxV2,maxV2New maxV2 min2,units=V" \
                 } result ] {
            return -code error "CompareData: $result"
        }
       
        if [catch {APSSCRPrintXrayBPMCompTable -resultsFile $resultsFile.help \
                     -snap1Label $label1 -snap2Label $label2 -DifferenceLabel Diff(2-1) \
                     -Value1Label dataset1 -Value2Label dataset2 \
                     -posDiffTolerance $posDiffTolerance -minVoltage $minVoltage \
                     -bpmType BM -plane y} result] {
            return -code error $result
        }
    }
    return $resultsFile
}

proc MakeDateTimeFrame {widget args} {
    set parent .
    set rootname ""
    APSStrictParseArguments {parent rootname}
    set label "Date/Time Range of Interest for $rootname data set."

    APSFrame $widget -parent $parent -label $label
    set w $parent$widget.frame
    global ${rootname}StartMonth ${rootname}StartYear 
    global ${rootname}StartDay ${rootname}StartHour ${rootname}EndHour

    APSDateTimeAdjEntry .startDate -parent $w \
      -yearVariable ${rootname}StartYear \
      -monthVariable ${rootname}StartMonth \
      -dayVariable ${rootname}StartDay \
      -hourVariable ${rootname}StartHour \
      -label "Start (year, month, day, hour): " -defaultHour 0 \
      -command ResetDataFileList -buttonSize small
    APSLabeledEntry .endHour -parent $w \
      -label "End hour:" \
      -textVariable ${rootname}EndHour -contextHelp \
      "Select hour of the end of the averaging."

    SetDateTimeToToday -rootname ${rootname}Start -hour 0
    SetDateTimeToToday -rootname ${rootname}End  -hour 24
}

proc SetDateTimeToToday {args} {
    set rootname ""
    set hour 0
    ResetDataFileList
    APSStrictParseArguments {rootname hour}

    global ${rootname}Month ${rootname}Year ${rootname}Day ${rootname}Hour
    
    APSDateBreakDown -dayVariable ${rootname}Day -yearVariable ${rootname}Year \
      -monthVariable ${rootname}Month -twoDigitYear 0 -leadingZeros 0
    set ${rootname}Hour $hour
}

set dataFileList ""
set dataFileListIsOld 1

proc ResetDataFileList {} {
    global dataFileList  dataFileListIsOld
    set dataFileList ""
    set dataFileListIsOld 1
}

proc MakeOptionFrame {widget args} {

    global bpmType bpmPlane minVoltage

    set parent .

    APSParseArguments {parent}

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

    APSRadioButtonFrame .type -parent $w \
      -label "BPM types" \
      -buttonList {BM ID} \
      -valueList {BMs IDs} \
      -variable bpmType \
      -commandList {ClearFiles  ClearFiles} \
      -orientation horizontal \
      -contextHelp \
      "Choose between BM Xray bpms and ID \
                               xray bpms."

    $w.type.frame configure -relief flat

    APSLabeledEntry .gapTolerance -parent $w \
      -label "Gap difference tolerance:" \
      -textVariable gapDiffTolerance \
      -contextHelp \
      "Enter tolerance for difference in gap between data sets. \
      Data with gap differences that are greaters will not be \
      shown in comparison."
    APSLabeledEntry .posTolerance -parent $w \
      -label "Position difference tolerance:" \
      -textVariable posDiffTolerance \
      -contextHelp \
      "Enter tolerance for difference in position between data sets. "
    
    APSLabeledEntry .filterVoltage -parent $w \
      -label "Minimal acceptable voltage:" \
      -textVariable minVoltage \
      -contextHelp \
      "Enter minimal acceptable voltage. \
      Data with smaller voltage  will not be shown."
}

proc ClearFiles {} {

    global data1Results data2Results
    global widgetCompare

    set data1Results ""
    set data2Results ""

    APSDisableButton $widgetCompare.button
}

proc ShutterPermit {} {
    global errorCode
    if [catch {exec cavget -list=ACIS:ShutterPermit -pend=5} result] {
        APSAlertBox [APSUniqueName .] \
          -errorMessage "Couldn't read shutter permit PV: $errorCode"
        return 1
    }
    if [string compare $result "PERMIT"]==0 {
        APSAlertBox [APSUniqueName .] \
          -errorMessage "Shutter permit is on--can't direct beam to ring."
        return 1
    }
    return 0
}


proc AnalyzeData {flag} {

    global bpmType bpmPlane 
    global data1Results data2Results
    global FirstStartYear 
    global FirstStartMonth FirstStartDay FirstStartHour FirstEndHour
    global SecondStartYear 
    global SecondStartMonth SecondStartDay SecondStartHour SecondEndHour
    global widgetCompare

    if {$flag == 1} {
        if [catch {XrayBPMAverage -type $bpmType \
                     -plane $bpmPlane \
                     -year $FirstStartYear \
                     -month $FirstStartMonth \
                     -day $FirstStartDay \
                     -start [APSConvertTimeToHours $FirstStartHour] \
                     -end [APSConvertTimeToHours $FirstEndHour]} status] {
            SetStatus "status = $status"
        }      
        set data1Results $status
    } else {
        if [catch {XrayBPMAverage -type $bpmType \
                     -plane $bpmPlane \
                     -year $SecondStartYear \
                     -month $SecondStartMonth \
                     -day $SecondStartDay \
                     -start [APSConvertTimeToHours $SecondStartHour] \
                     -end [APSConvertTimeToHours $SecondEndHour]} status] {
            SetStatus "status = $status"
        }      
        set data2Results $status
    }
    # puts $status
    if ![string length $data1Results] {
        APSDisableButton $widgetCompare.button
        return
    }
    if ![string length $data2Results] {
        APSDisableButton $widgetCompare.button
        return
    }
    APSEnableButton $widgetCompare.button
}

proc MakeActionFrame {widget args} {

    global bpmType bpmPlane
    global data1Results data2Results
    global widgetCompare

    set parent .
    set one 1
    set two 2

    APSParseArguments {parent}

    APSFrame $widget -parent $parent -label Actions
    set w $parent$widget.frame
    global FirstStartMonth FirstStartDay FirstStartHour FirstEndHour

    APSButton .first -parent $w -text "Analyze Data Set 1" \
      -command  "AnalyzeData $one" \
      -contextHelp \
      "Generate a printout of the Xray bpm readout for the type selected."

    APSButton .second -parent $w -text "Analyze Data Set 2" \
      -command "AnalyzeData $two" \
      -contextHelp \
      "Generate a printout of the Xray bpm readout for the type selected."

    APSButton .moveGap -parent $w -text "Move Gaps to Data Set 1 Values" \
      -command \
      { \
          catch {eval MoveGaps \
                   -file $data1Results \
               } status
      } \
      -contextHelp \
      "Moves gaps to values found in data set 1. Some gaps will not be \
    moved if the gaps in data set 1 had large values (>150 mm). \
    IDs with large gaps wouldn't produce radation anyway."

    APSButton .compare -parent $w -text "Compare Data" \
      -command \
      { \
          catch {CompareData -file1 $data1Results \
                   -label1 "$FirstStartMonth/$FirstStartDay/$FirstStartYear \
                          from $FirstStartHour to $FirstEndHour" \
                   -file2 $data2Results \
                   -label2 "$SecondStartMonth/$SecondStartDay/$SecondStartYear \
                          from $SecondStartHour to $SecondEndHour"} status
          set CompareFile $status
      } \
      -contextHelp \
      "Compares the corresponding data from the two data sets."

    set widgetCompare $w.compare
    APSDisableButton $widgetCompare.button
}

proc CreateFilterFile {args} {
    #create the filter file from config.sdds where both OKForDCOrbitCorrectionH 
    # and OKForDCOrbitCorrectionV are OK (=1)
    global filterFile
    set configfile /home/helios/oagData/sr/BPMStatus/config.sdds
    if {[file exist $filterFile] && \
          [file mtime $filterFile] > [file mtime $configfile] } {
        return
    }
    APSAddToTmpFileList -ID XrayBPMReview -fileList $filterFile
    if [catch {exec sddsprocess $configfile -pipe=out \
                 -filter=col,OkForDCOrbitCorrectionH,1,1,OkForDCOrbitCorrectionV,1,1,& \
                 -match=col,DeviceName=*ID* -scan=col,Sector,DeviceName,S%ld,type=long \
                 -print=col,Rootname,ID%02ld,Sector \
                 | sddssort -pipe -col=Rootname -unique \
                 | sddsconvert -pipe=in \
                 -retain=col,Rootname,OkForDCOrbitCorrection* $filterFile } result] {
        return -code error $result
    }
}

set status ""
APSScrolledStatus .status -parent .userFrame -textVariable status -width 80
MakeDateTimeFrame .date1   -parent .userFrame -rootname First
MakeDateTimeFrame .date2   -parent .userFrame -rootname Second
MakeOptionFrame .option   -parent .userFrame
MakeActionFrame .commands -parent .userFrame
set bpmType IDs
set bpmPlane y
set data1Results ""
set data2Results ""
set gapDiffTolerance 0.1
set posDiffTolerance 0.1
set minVoltage 0.01
set filterFile /tmp/[APSTmpString].IDfilter
