#!/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)]
set CVSRevisionAuthor "\$Revision: 1.6 $ \$Author: sereno $"
APSDebugPath

APSApplication . -name processIntenScanDataApp -version $CVSRevisionAuthor \
  -overview "This application will help to analyze two SR bpm intensity measurements.  \
   The script interpolates the raw data for each bpm between two specified limits.  \
   It then takes differences and computes the rms difference for each bpm.  \
   The rms differences are then histogrammed and plotted.  Outliers are flagged \
   which are more than two standard deviations away from the mean rms deviation." 

set status Ready.
APSScrolledStatus .status -parent .userFrame -width 83 \
        -textVariable status 

set histogramFile ""
set outliersFile ""
set returnFlag 0

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

proc PickFilename {args} { 
    set prefix ""
    APSStrictParseArguments {prefix}
    global firstfile secondfile
    set pickFileDir /home/helios/oagData/sr/offsetAdjustmentData/dataFiles

    set ${prefix}file [APSFileSelectDialog .[APSTmpString] -listDir $pickFileDir \
                        -contextHelp "File select box for quickSDDSplot data file."]
}


proc DoProcessing {} {
     global firstfile secondfile plane minSum maxSum sort stDev
     global histogramFile outliersFile
     set histogramFile ""
     set outliersFile ""
     set sumName S5B:P5.*sum.*
     set output /tmp/[APSTmpString]

     if {![string length $firstfile] || ![string length $secondfile]} {
           SetStatus "Input file missing."
	   return
     }
     if ![file exists $firstfile] {
	  SetStatus "File $firstfile does not exists."
	  return
     }

     if ![file exists $secondfile] {
	  SetStatus "File $secondfile does not exists."
	  return
     }

     setOpenCloseButtons1 0
     setOpenCloseButtons2 0

     SetStatus "Processing data to compute rms differences between each measurement for each bpm..."
    
     catch {exec sddsquery ${firstfile} -column | grep $sumName} sumName
     eval exec sddscombine -pipe=out ${firstfile} ${secondfile} \
	    | sddsprocess -pipe "-noWarnings" "-filter=col,${sumName},${minSum},${maxSum}" \
	    | sddssort -pipe "-col=${sumName},increasing" \
	    | sddsinterp -pipe "-col=${sumName},S*:${plane}" \
	      "-sequence=500" \
	    | sddschanges -pipe "-copy=${sumName}" "-changesIn=S*:${plane}" \
	    | sddscollect -pipe "-collect=suffix=:${plane}" \
	    | sddsenvelope -pipe=in $output "-rms=:${plane}" \
	      "-copy=Rootname" 

      set histogramFile /tmp/[APSTmpString]

      eval exec sddshist ${output} $histogramFile \
		"-dataColumn=:${plane}Rms" \
		"-sizeOfBins=0.0001 -statistics"

      set outliersFile /tmp/[APSTmpString]

      if !$stDev {
          set stDevSet ""
      } else {
          set stDevSet {-stDevLimit=$stDev}
      }
      if ![string compare $sort value] {
           eval exec sddsoutlier $output -pipe=out $stDevSet \
		    "-columns=:${plane}Rms" -invert \
	           | sddssort -pipe=in $outliersFile -column=:${plane}Rms,decreasing
      } else {
           eval exec sddsoutlier $output $outliersFile $stDevSet \
		    "-columns=:${plane}Rms" -invert 
      }
       
      SetStatus "Done."
      setOpenCloseButtons1 1
      setOpenCloseButtons2 1
}

proc DoPlotting {} {
    global histogramFile plane firstfile secondfile
    set pickFileDir [pwd]

    InputFilesPresent 0

    if {![string length $firstfile] || ![string length $secondfile]} {
         set histogramFile [APSFileSelectDialog .[APSTmpString] -listDir $pickFileDir \
                        -contextHelp "File select box for quickSDDSplot data file."]
    }
    if ![string length $histogramFile] {
         SetStatus "No histogrammed file present to plot."
	 return
    }
    
    set planeColumnList [APSGetSDDSNames -fileName $histogramFile]
    if {[lsearch $planeColumnList :${plane}Rms] < 0} {
         switch -exact $plane {
		x {set plane y; SetStatus "Changing plane setup to \"y\"."}
		y {set plane x; SetStatus "Changing plane setup to \"x\"."}
	 }
         update
    }

    SetStatus "Plotting Intensity scan difference data..."

    if [catch {eval exec sddsplot -title= {"-topline=BPM RMS Differences for the ${plane} Plane"} \
	       {"-labelsize=0.03"} {"-xlabel=Rms:${plane}:Difference"} \
	       {"-col=:${plane}Rms,frequency"} $histogramFile &} result] {
	SetStatus "Error: $result"
	return
    }        
}

proc MakequickSDDSplot {} {
     global histogramFile returnFlag

     InputFilesPresent 1
     if $returnFlag {
	 return
     }

     if ![string length $histogramFile] {
          SetStatus "No histogrammed file present to plot."
	 return
     } else {
         eval exec quickSDDSplot -dataFileList $histogramFile &
     }
}

proc DosddsExportData {} {
     global histogramFile returnFlag

     InputFilesPresent 1
     if $returnFlag {
	 return
     }

     if ![string length $histogramFile] {
          SetStatus "No histogrammed data present to export."
	 return
     } else {
         exec sddsExportData -dataFileList $histogramFile &
     }
}

proc MakeDisplay {} {
     global outputRoot plane histogramFile outliersFile
     global firstfile secondfile
     set printFile /tmp/[APSTmpString]
     set pickFileDir [pwd]

     InputFilesPresent 0

     if {![string length $firstfile] || ![string length $secondfile]} {
         set outliersFile [APSFileSelectDialog .[APSTmpString] -listDir $pickFileDir \
                        -contextHelp "File select box for quickSDDSplot data file."]
     }
     if ![string length $outliersFile] {
         SetStatus "No outlier file present to display."
	 return
     }

     if {[string length $firstfile] && [string length $secondfile]} {
	  set title "Printout of BPM RMS differences for $plane between files $firstfile & $secondfile."
     } else {
          set title "Printout for SDDS file $outliersFile"
     }

     if [catch {eval exec sddsprintout $outliersFile $printFile \
	        {"-col=(Rootname,:${plane}Rms)"} {"-title=$title"}} result] {
	 SetStatus "Error: $result"
	 return
     } else {
         APSFileDisplayWindow .[APSUniqueName review] \
            -fileName $printFile -sddsExportableFile $outliersFile 
     }
}

proc InputFilesPresent {statusFlag} {
     global firstfile secondfile returnFlag
     set returnFlag 0
     if {![string length $firstfile] || ![string length $secondfile]} {
           setOpenCloseButtons1 0
           if $statusFlag {
               SetStatus "No input files present."
	       set returnFlag 1
	   }
     }
}

proc setOpenCloseButtons1 {state} {
     global f
     if $state {
         APSEnableButton $f.export.button
         APSEnableButton $f.quickPlot.button
     } else {
         APSDisableButton $f.export.button
         APSDisableButton $f.quickPlot.button
     }  
}

proc setOpenCloseButtons2 {state} {
     global f
     if $state {
         APSEnableButton $f.print.button
         APSEnableButton $f.plot.button
         APSEnableButton $f.process.button
     } else {
         APSDisableButton $f.print.button
         APSDisableButton $f.plot.button
         APSDisableButton $f.process.button
     }  
}

APSFrame .file_1 -parent .userFrame -packOption "-fill x -side top"

APSLabeledEntry .firstfile -parent .userFrame.file_1.frame -textVariable firstfile -width 70 -label "First File: " \
      -contextHelp "Holds the name of the file from which data will be taken.  You may enter the filename by typing or using the PICK FILE... button below.  If you have entered filename by typing, press RETURN-key on your keyboard."
bind .userFrame.file_1.frame.firstfile.entry <Return> {set firstfile [list $firstfile]}

APSButton .pick1 -parent .userFrame.file_1.frame -text "PICK FILE..." -command "PickFilename -prefix first" \
      -contextHelp "Brings up a file selection dialog to pick first file to compare." -size small

APSFrame .file_2 -parent .userFrame -packOption "-fill x -side top"

APSLabeledEntry .secondfile -parent .userFrame.file_2.frame -textVariable secondfile -width 70 -label "Second File: " \
      -contextHelp "Holds the name of the file from which data will be taken.  You may enter the filename by typing or using the PICK FILE... button below.  If you have entered filename by typing, press RETURN-key on your keyboard."
bind .userFrame.file_2.frame.secondfile.entry <Return> {set  secondfile [list $secondfile]}

APSButton .pick2 -parent .userFrame.file_2.frame -text "PICK FILE..." -command "PickFilename -prefix second" \
      -contextHelp "Brings up a file selection dialog to pick second file to compare." -size small

APSFrame .frame1 -parent .userFrame -label "Process Options"
APSFrameGrid .options -parent .userFrame.frame1.frame -yList {y1 y2} -width 40m -xList {x1 x2 x3}
 
set w .userFrame.frame1.frame.options

set stDev 2
APSLabeledEntry .stDev -parent $w.x1.y1 -textVariable stDev -width 20 -label "Sigma: " \
   -contextHelp "Set the number of standart deviations by which a data point from a column \
    may deviate from the average for the column before being considered an outlier."
$w.x1.y1 configure -relief groove

set minSum 1000
APSLabeledEntry .minSum -parent $w.x2.y1 -textVariable minSum -width 20 -label "minSum: " \
   -contextHelp "Minimum limit for the bpm data."
$w.x2.y1 configure -relief groove

set maxSum 1175
APSLabeledEntry .maxSum -parent $w.x3.y1 -textVariable maxSum -width 20 -label "maxSum: " \
   -contextHelp "Maximum limit for the bpm data."
$w.x3.y1 configure -relief groove

set plane x
APSRadioButtonFrame .plane -parent $w.x1.y2 -label "Plane:       " -buttonList [list x y] \
   -variable plane -valueList [list x y] -orientation horizontal \
   -contextHelp "This setup helps to pick a plane which is a subject of interest."
$w.x1.y2 configure -relief groove

set sort value
APSRadioButtonFrame .sort -parent $w.x2.y2 -label "Sort by:   " -buttonList [list sector value] \
   -variable sort -valueList [list sector value] -orientation horizontal \
   -contextHelp "This setup helps to pick a sort column for a display."
$w.x2.y2 configure -relief groove


APSFrame .buttRow -parent .userFrame -packOption "-side bottom -fill x" -width 100
set f .userFrame.buttRow.frame

APSButton .process -parent $f -text "Process Histogram" -command "DoProcessing" \
   -contextHelp "Invokes processing for a creation of histogram and outlier files as temporary files. \
    User is able to save processed data into fixed files by using \"sddsExportData\" function in: \
    - main application to save histogrammed file; - \"Display Differences\" to save outlier file."
APSButton .print -parent $f -text "Display Differences" -command MakeDisplay \
   -contextHelp "Displays differences between input files for bpm's plane of interest. \
    If input files are not specified user can display a saved alredy outlier file."
APSButton .export -parent $f -text "sddsExportData" -command DosddsExportData \
   -contextHelp "Calls \"sddsExportData\" program to save a histogrammed file."
APSButton .plot -parent $f -text "Plot" -command "DoPlotting" \
   -contextHelp "Invokes ploting of histogrammed data from the input files. If input files \
    are not specified user can plot a saved alredy histogrammed file."  
APSButton .quickPlot -parent $f -text "quickSDDSplot" -command MakequickSDDSplot \
   -contextHelp "Calls \"quickSDDSplot\" program to do custom plotting."

setOpenCloseButtons1 0

