#!/bin/sh
# the next line restarts using wish \
exec chavwish "$0" "$@"

# global parfile evtfile outfile \
# 	outputbgfile external_gti badpixfilter do_cti do_au_gain do_tgain do_gain \
# 	do_aspect aspfile vf_clean clean_afterglow grade_set flt_grade_set \
# 	ccdset tmpdir GAINFILE GRADEFILE CTIFILE inputbgfile

global PROCPID
global PIPE
set PROCPID -1

global PADOPT
set PADOPT "12"

######################################################################

proc SelectBadPix { } {
 global env
 global badpixfilter
 set gov [tk_getOpenFile -initialfile $badpixfilter -initialdir "$env(CH)/BG"]
 if { [string length $gov] > 0 } { set badpixfilter $gov }
}

proc SelectGTI { } {
 global external_gti
 set gov [tk_getOpenFile -initialfile $external_gti -initialdir "./"]
 if { [string length $gov] > 0 } { set external_gti $gov }
}


######################################################################

proc SelFile {inifile inidir} {
 if { [string length $inidir] > 0 } {
    set dir $inidir 
 } else {
    set dir "./"
 }
 set gov  [tk_getOpenFile -initialfile $inifile -initialdir $dir]
 if { [string length $gov] > 0 } { return $gov } else { return $inifile }
}

##############################################################3
proc RunProg { prog file } {
  exec $prog $file "&"
}

#################################################################
proc SaveStateDefault { } {
   SaveState ".process_acis_data" [list parfile evtfile outfile \
	    outputbgfile external_gti badpixfilter do_cti do_au_gain do_tgain do_gain \
	    do_aspect aspfile vf_clean clean_afterglow grade_set flt_grade_set \
	    ccdset tmpdir GAINFILE GRADEFILE CTIFILE inputbgfile \
	    evtfile_lc gtifile_tel lc_clean_psrcreg lc_clean_vfbg \
            lc_clean_afterglow clean_lc_ccdfilter clean_lc_range clean_lc_range_ref\
	    clean_lc_filter clean_lc_gradefilter clean_lc_binsize clean_lc_clip \
	    clean_lc_mean clean_lc_max_factor clean_lc_max_sigma \
	    clean_lc_keep_neg clean_lc_clipmode clean_lc_cutmode \
	    destreak destreak_max destreak_filter destreak_mask destreak_ccd_id\
	    bg_only outputreadoutbgfile readoutbg_only do_cti_t do_subpix mtlfile
	    ]
}

proc SaveState {stateFile list} {
  set output [open $stateFile "w"]

  foreach variable $list {
    eval "global $variable" 
    puts $output "[list $variable [subst $$variable]]"
  } 
  close $output
}

proc RestoreState {stateFile} {
    if { [file exists $stateFile] } {
	set input [open $stateFile "r"]
	while {![eof $input]} {
	    set len [gets $input list]
	    if {$len > 0} {
# 		puts -nonewline [lindex $list 0]
# 		puts -nonewline "=|"
# 		puts -nonewline [lindex $list 1]
# 		puts "|"
		eval "global [lindex $list 0]"
		eval "[list set [lindex $list 0] [lindex $list 1]]"
	    }
	}
	close $input
   }
} 

#############################################################
proc RunCleanLcRatio {evt gti} {
 global PADOPT
 toplevel .cleanlc
 set gx [winfo x .]; set gy [winfo y .]; set gh [winfo height .]
 set gw [winfo width .]
 set gy [expr $gy+$gh]; set gx [expr $gx+$gw/4];
 wm geometry .cleanlc +$gx+$gy

 set WD 17

 frame .cleanlc.evtfile
 label .cleanlc.evtfile.0 -width $WD -text "Events file:" -anchor w
 entry .cleanlc.evtfile.1 -width 40 -textvariable evtfile_lc
 button .cleanlc.evtfile.2 -text "ds9" -command {RunProg "ds9" $evtfile_lc}
 button .cleanlc.evtfile.3 -text "fv" -command {RunProg "fv" $evtfile_lc}
 pack  .cleanlc.evtfile.0 .cleanlc.evtfile.1 .cleanlc.evtfile.2 .cleanlc.evtfile.3 -side left
 pack .cleanlc.evtfile  -side top -anchor sw

 frame .cleanlc.gtifile
 label .cleanlc.gtifile.0 -width $WD -text "0-th order GTI file:" -anchor w
 pack .cleanlc.gtifile.0 -side left
 entry .cleanlc.gtifile.1 -width 40 -textvariable gtifile_tel
 pack  .cleanlc.gtifile.1 -side left
 button .cleanlc.gtifile.2 -text "sel" -command {set gtifile_tel [SelFile $gtifile_tel ""]} -padx $PADOPT -pady 0
 pack  .cleanlc.gtifile.2 -side left
 pack .cleanlc.gtifile  -side top -anchor sw

 frame .cleanlc.outgti
 label .cleanlc.outgti.0  -width $WD -text "output GTI file:" -anchor w
 pack .cleanlc.outgti.0 -side left
 entry .cleanlc.outgti.1 -width 20 -textvariable external_gti
 pack  .cleanlc.outgti.1 -side left
 pack .cleanlc.outgti  -side top -anchor sw

 frame .cleanlc.filters
 label .cleanlc.filters.0  -width $WD -text "Exclude region file:" -anchor w
 pack .cleanlc.filters.0 -side left
 entry .cleanlc.filters.1 -width 20 -textvariable lc_clean_psrcreg
 pack  .cleanlc.filters.1 -side left
 button .cleanlc.filters.2 -text "sel" -command {set lc_clean_psrcreg [SelFile $lc_clean_psrcreg ""]} -padx $PADOPT -pady 0
 pack  .cleanlc.filters.2 -side left -padx 0

 label .cleanlc.filters.3 -text " Clean VF" -justify left
 checkbutton .cleanlc.filters.4 -variable lc_clean_vfbg -selectcolor green
 pack  .cleanlc.filters.3 -side left -padx 0
 pack  .cleanlc.filters.4  -side left -padx 0

 label .cleanlc.filters.5 -text "afterglows" -justify left
 checkbutton .cleanlc.filters.6 -variable lc_clean_afterglow -selectcolor green
 pack  .cleanlc.filters.5 -side left -padx 0
 pack  .cleanlc.filters.6  -side left -padx 0
 pack .cleanlc.filters  -side top -anchor sw


 set WD2 11

 frame .cleanlc.badpixfilter
 label .cleanlc.badpixfilter.0 -width $WD2 -text "badpix filter:" -anchor w
 pack .cleanlc.badpixfilter.0 -side left
 entry .cleanlc.badpixfilter.1 -width 40 -textvariable badpixfilter
 pack  .cleanlc.badpixfilter.1 -side left -padx 0
 button .cleanlc.badpixfilter.2 -text "sel" -command {SelectBadPix} -padx $PADOPT -pady 0
 pack  .cleanlc.badpixfilter.2 -side left -padx 0
 pack .cleanlc.badpixfilter  -side top -anchor sw

 frame .cleanlc.ccdfilter
 label .cleanlc.ccdfilter.0 -width $WD2 -text "CCD filter:" -anchor w
 pack .cleanlc.ccdfilter.0 -side left
 entry .cleanlc.ccdfilter.1 -width 40 -textvariable clean_lc_ccdfilter
 pack  .cleanlc.ccdfilter.1 -side left
 .cleanlc.ccdfilter.1 config -fg darkslateblue
 pack .cleanlc.ccdfilter  -side top -anchor sw

 frame .cleanlc.gradefilter
 label .cleanlc.gradefilter.0 -width $WD2 -text "grade filter:" -anchor w
 pack .cleanlc.gradefilter.0 -side left
 entry .cleanlc.gradefilter.1 -width 40 -textvariable clean_lc_gradefilter
 pack  .cleanlc.gradefilter.1 -side left
 pack .cleanlc.gradefilter  -side top -anchor sw


 frame .cleanlc.range
 label .cleanlc.range.0 -width $WD2 -text "E-range:" -anchor w
 pack .cleanlc.range.0 -side left
 entry .cleanlc.range.1 -width 40 -textvariable clean_lc_range
 pack  .cleanlc.range.1 -side left
 pack .cleanlc.range  -side top -anchor sw
 .cleanlc.range.1 config -fg darkslateblue

 frame .cleanlc.rangeref
 label .cleanlc.rangeref.0 -width $WD2 -text "Ref E-range:" -anchor w
 pack .cleanlc.rangeref.0 -side left
 entry .cleanlc.rangeref.1 -width 40 -textvariable clean_lc_range_ref
 pack  .cleanlc.rangeref.1 -side left
 pack .cleanlc.rangeref  -side top -anchor sw
 .cleanlc.rangeref.1 config -fg darkslateblue


 set WDG 10
 set WDC 40
 frame .cleanlc.options
 label .cleanlc.options.binsize0 -width $WDG -text "binsize:" -anchor w
 entry .cleanlc.options.binsize1 -textvariable clean_lc_binsize
 label .cleanlc.options.binsize2 -width $WDC -text " 259.28=3.241*80 (3.241s is std. frame time)" -anchor w
 
 radiobutton .cleanlc.options.meanA -variable clean_lc_clipmode -value "mean" -selectcolor green
 label .cleanlc.options.mean0 -width $WDG -text "mean:" -anchor w
 entry .cleanlc.options.mean1 -textvariable clean_lc_mean
 .cleanlc.options.mean1 config -fg red2
 label .cleanlc.options.mean2 -width $WDC -text " mean ratio" -anchor w

 radiobutton .cleanlc.options.clipA -variable clean_lc_clipmode -value "clip" -selectcolor green
 label .cleanlc.options.clip0 -width $WDG -text "clip" -anchor w
 entry .cleanlc.options.clip1 -textvariable clean_lc_clip
 label .cleanlc.options.clip2 -width $WDC -text " sigma clip to calc.mean" -anchor w
 
 
 radiobutton .cleanlc.options.max_factorA -variable clean_lc_cutmode -value "factor" -selectcolor blue
 label .cleanlc.options.max_factor0 -width $WDG -text "factor" -justify left -anchor w
 entry .cleanlc.options.max_factor1 -textvariable clean_lc_max_factor
 label .cleanlc.options.max_factor2 -width $WDC -text " max increase/decrease factor from mean" -anchor w
 
 radiobutton .cleanlc.options.max_sigmaA -variable clean_lc_cutmode -value "sigma" -selectcolor blue
 label .cleanlc.options.max_sigma0 -width $WDG -text "sigma" -anchor w
 entry .cleanlc.options.max_sigma1 -textvariable clean_lc_max_sigma
 label .cleanlc.options.max_sigma2 -width $WDC -text " max deviation from mean rate, sigmas" -anchor w

 checkbutton .cleanlc.options.keep_negA -variable clean_lc_keep_neg -selectcolor green
 label .cleanlc.options.keep_neg0 -width $WDG -text "keep neg" -anchor w
 label .cleanlc.options.keep_neg2 -width $WDC -text "ignore negative deviations" -anchor w
 
 grid .cleanlc.options.binsize0 -row 0 -column 1
 grid .cleanlc.options.binsize1 -row 0 -column 2
 grid .cleanlc.options.binsize2 -row 0 -column 3
 grid .cleanlc.options.clipA -row 2 -column 0
 grid .cleanlc.options.clip0 -row 2 -column 1
 grid .cleanlc.options.clip1 -row 2 -column 2
 grid .cleanlc.options.clip2 -row 2 -column 3
 grid .cleanlc.options.meanA -row 1 -column 0
 grid .cleanlc.options.mean0 -row 1 -column 1
 grid .cleanlc.options.mean1 -row 1 -column 2
 grid .cleanlc.options.mean2 -row 1 -column 3
 grid .cleanlc.options.max_factorA -row 3 -column 0
 grid .cleanlc.options.max_factor0 -row 3 -column 1
 grid .cleanlc.options.max_factor1 -row 3 -column 2
 grid .cleanlc.options.max_factor2 -row 3 -column 3
 grid .cleanlc.options.max_sigmaA -row 4 -column 0
 grid .cleanlc.options.max_sigma0 -row 4 -column 1
 grid .cleanlc.options.max_sigma1 -row 4 -column 2
 grid .cleanlc.options.max_sigma2 -row 4 -column 3
 grid .cleanlc.options.keep_negA -row 5 -column 0
 grid .cleanlc.options.keep_neg0 -row 5 -column 1
 grid .cleanlc.options.keep_neg2 -row 5 -column 3

 pack .cleanlc.options -side top -anchor sw -pady 10


 button .cleanlc.run -text "run lc_clean" -command {RunCleanLcRatio_EXE}
 pack .cleanlc.run -side left  -anchor sw -padx 10

 button .cleanlc.inspect -text "Inspect" -command {RunCleanLc_SHOW}
 pack .cleanlc.inspect -side left  -anchor sw -padx 10

 button .cleanlc.cancel -text "Done" -command {destroy .cleanlc}
 pack .cleanlc.cancel -side left  -anchor sw -padx 10
}


#############################################################
proc RunCleanLc {evt gti} {
 global PADOPT
 toplevel .cleanlc
 set gx [winfo x .]; set gy [winfo y .]; set gh [winfo height .]
 set gw [winfo width .]
 set gy [expr $gy+$gh]; set gx [expr $gx+$gw/4];
 wm geometry .cleanlc +$gx+$gy

 set WD 17

 frame .cleanlc.evtfile
 label .cleanlc.evtfile.0 -width $WD -text "Events file:" -anchor w
 entry .cleanlc.evtfile.1 -width 40 -textvariable evtfile_lc
 button .cleanlc.evtfile.2 -text "ds9" -command {RunProg "ds9" $evtfile_lc} -padx $PADOPT -pady 0
 button .cleanlc.evtfile.3 -text "fv" -command {RunProg "fv" $evtfile_lc} -padx $PADOPT -pady 0
 pack  .cleanlc.evtfile.0 .cleanlc.evtfile.1 .cleanlc.evtfile.2 .cleanlc.evtfile.3 -side left
 pack .cleanlc.evtfile  -side top -anchor sw

 frame .cleanlc.gtifile
 label .cleanlc.gtifile.0 -width $WD -text "0-th order GTI file:" -anchor w
 pack .cleanlc.gtifile.0 -side left
 entry .cleanlc.gtifile.1 -width 40 -textvariable gtifile_tel
 pack  .cleanlc.gtifile.1 -side left
 button .cleanlc.gtifile.2 -text "sel" -command {set gtifile_tel [SelFile $gtifile_tel ""]} -padx $PADOPT -pady 0
 pack  .cleanlc.gtifile.2 -side left
 pack .cleanlc.gtifile  -side top -anchor sw

 frame .cleanlc.outgti
 label .cleanlc.outgti.0  -width $WD  -text "output GTI file:" -anchor w
 pack .cleanlc.outgti.0 -side left
 entry .cleanlc.outgti.1 -width 20 -textvariable external_gti
 pack  .cleanlc.outgti.1 -side left
 pack .cleanlc.outgti  -side top -anchor sw

 frame .cleanlc.filter
 label .cleanlc.filter.0 -width $WD -text "event filter:" -anchor w
 pack .cleanlc.filter.0 -side left
 entry .cleanlc.filter.1 -width 40 -textvariable clean_lc_filter
 pack  .cleanlc.filter.1 -side left
 pack .cleanlc.filter  -side top -anchor sw
 frame .cleanlc.gradefilter
 label .cleanlc.gradefilter.0 -width $WD  -text "grade filter:" -anchor w
 pack .cleanlc.gradefilter.0 -side left
 entry .cleanlc.gradefilter.1 -width 40 -textvariable clean_lc_gradefilter
 pack  .cleanlc.gradefilter.1 -side left
 pack .cleanlc.gradefilter  -side top -anchor sw

 set WDG 10
 set WDC 40

 frame .cleanlc.options
 label .cleanlc.options.binsize0 -width $WDG -text "binsize" -anchor w
 entry .cleanlc.options.binsize1 -textvariable clean_lc_binsize
 label .cleanlc.options.binsize2 -width $WDC -text "259.28=3.241*80 (3.241s is std. frame time)" -anchor w
 
 radiobutton .cleanlc.options.clipA -variable clean_lc_clipmode -value "clip" -selectcolor green
 label .cleanlc.options.clip0 -width $WDG -text "clip" -anchor w
 entry .cleanlc.options.clip1 -textvariable clean_lc_clip
 label .cleanlc.options.clip2 -width $WDC -text "sigma clip to calc.mean" -anchor w
 
 radiobutton .cleanlc.options.meanA -variable clean_lc_clipmode -value "mean" -selectcolor green
 label .cleanlc.options.mean0 -width $WDG -text "mean" -justify left -anchor w
 entry .cleanlc.options.mean1 -textvariable clean_lc_mean
 label .cleanlc.options.mean2 -width $WDC -text "force this value (cts/s) as mean rate" -anchor w
 
 radiobutton .cleanlc.options.max_factorA -variable clean_lc_cutmode -value "factor" -selectcolor blue
 label .cleanlc.options.max_factor0 -width $WDG -text "factor" -anchor w
 entry .cleanlc.options.max_factor1 -textvariable clean_lc_max_factor
 label .cleanlc.options.max_factor2 -width $WDC -text "max increase/decrease factor from mean" -anchor w
 
 radiobutton .cleanlc.options.max_sigmaA -variable clean_lc_cutmode -value "sigma" -selectcolor blue
 label .cleanlc.options.max_sigma0 -width $WDG -text "sigma" -anchor w
 entry .cleanlc.options.max_sigma1 -textvariable clean_lc_max_sigma
 label .cleanlc.options.max_sigma2 -width $WDC -text "max deviation from mean rate, sigmas" -anchor w

 checkbutton .cleanlc.options.keep_negA -variable clean_lc_keep_neg -selectcolor green
 label .cleanlc.options.keep_neg0 -width $WDG -text "keep neg" -anchor w
 label .cleanlc.options.keep_neg2 -width $WDC -text "ignore negative deviations" -anchor w
 
 grid .cleanlc.options.binsize0 -row 0 -column 1
 grid .cleanlc.options.binsize1 -row 0 -column 2
 grid .cleanlc.options.binsize2 -row 0 -column 3
 grid .cleanlc.options.clipA -row 1 -column 0
 grid .cleanlc.options.clip0 -row 1 -column 1
 grid .cleanlc.options.clip1 -row 1 -column 2
 grid .cleanlc.options.clip2 -row 1 -column 3
 grid .cleanlc.options.meanA -row 2 -column 0
 grid .cleanlc.options.mean0 -row 2 -column 1
 grid .cleanlc.options.mean1 -row 2 -column 2
 grid .cleanlc.options.mean2 -row 2 -column 3
 grid .cleanlc.options.max_factorA -row 3 -column 0
 grid .cleanlc.options.max_factor0 -row 3 -column 1
 grid .cleanlc.options.max_factor1 -row 3 -column 2
 grid .cleanlc.options.max_factor2 -row 3 -column 3
 grid .cleanlc.options.max_sigmaA -row 4 -column 0
 grid .cleanlc.options.max_sigma0 -row 4 -column 1
 grid .cleanlc.options.max_sigma1 -row 4 -column 2
 grid .cleanlc.options.max_sigma2 -row 4 -column 3
 grid .cleanlc.options.keep_negA -row 5 -column 0
 grid .cleanlc.options.keep_neg0 -row 5 -column 1
 grid .cleanlc.options.keep_neg2 -row 5 -column 3

 pack .cleanlc.options -side top -anchor sw -pady 10


 button .cleanlc.run -text "run lc_clean" -command {RunCleanLc_EXE}
 pack .cleanlc.run -side left  -anchor sw -padx 10

 button .cleanlc.inspect -text "Inspect" -command {RunCleanLc_SHOW}
 pack .cleanlc.inspect -side left  -anchor sw -padx 10

 button .cleanlc.cancel -text "Done" -command {destroy .cleanlc}
 pack .cleanlc.cancel -side left  -anchor sw -padx 10
}

proc RunCleanLcRatio_EXE {} {
   set PAR [open "lc_clean.par" w]
   puts $PAR "num_datafiles=1"
   upvar evtfile_lc evt;
   upvar clean_lc_range range;
   upvar clean_lc_range_ref rangeref;
   upvar clean_lc_ccdfilter ccdfilt;
   upvar clean_lc_gradefilter gradefilt;
   upvar lc_clean_psrcreg  psrcreg;
   upvar lc_clean_vfbg  vfbg;
   upvar lc_clean_afterglow  afterglow;
   upvar badpixfilter  badpix;
   global env;

   
   SaveStateDefault;


   set TMPFILE "lc_clean_tmp.fits";

   set FILTER "";
   if { [string length $ccdfilt] > 0 } {
     set FILTER "($ccdfilt)";
   }
   if { [string length $gradefilt] > 0 } {
      if { [string length $FILTER] > 0 } {
         set FILTER "$FILTER&&($gradefilt)";
      } else {
         set FILTER "$gradefilt";
    }
   }
   if { [string length $psrcreg] > 0 } {
      if { [string length $FILTER] > 0 } {
         set FILTER "$FILTER&& ! regfilter( \"$psrcreg\" )";
      } else {
         set FILTER "! regfilter( \"$psrcreg\" )";
    }
   }
   if { $afterglow } {
      if { [string length $FILTER] > 0 } {
         set FILTER "$FILTER&& status==bxxxxxxxxxxxx0000xxxxxxxxxxxxxxxx";
      } else {
         set FILTER "status==bxxxxxxxxxxxx0000xxxxxxxxxxxxxxxx";
    }
   }

   puts "fitscopy $evt\[events\]\[$FILTER\] !$TMPFILE";
   exec "fitscopy" "$evt\[events\]\[$FILTER\]" "!$TMPFILE";

   if { $vfbg } {
      exec "clean55" "-g" "$TMPFILE";
      exec "fitscopy" "$TMPFILE\[events\]\[grade!=255\]" "!$TMPFILE.gov";
      exec "mv" "$TMPFILE.gov" "$TMPFILE";
    }

   if { [string length $badpix] > 0 } {
      exec "badpixfilter" "evtfile=$TMPFILE" "o=!$TMPFILE.gov" "badpixfilter=$badpix";
      exec "mv" "$TMPFILE.gov" "$TMPFILE";
    }

   puts -nonewline $PAR "file1=$TMPFILE\[events\]\["
   if { [string length $range] > 0 } {
      puts -nonewline $PAR "$range";
   }
   puts  -nonewline $PAR "\]";
   puts $PAR ""

   puts -nonewline $PAR "fileref1=$TMPFILE\[events\]\[";
   if { [string length $rangeref] > 0 } {
      puts -nonewline $PAR "$rangeref";
   }
   puts  -nonewline $PAR "\]";
   puts $PAR ""

   upvar gtifile_tel v;   set v [string trim $v]
   if { [string length $v] == 0 } {
     puts "Error: no 0-th order gti file"
     .cleanlc.gtifile.1 config -bg Hotpink
     return
   } else {
      .cleanlc.gtifile.1 config -bg [.cleanlc cget -bg]
      PrintString $v "gti_file" $PAR
   }

   upvar external_gti v;   set v [string trim $v]
   if { [string length $v] == 0 } {
     puts "Error: no output gti file"
     .cleanlc.outgti.1 config -bg Hotpink
     return
   } else {
      .cleanlc.outgti.1 config -bg [.cleanlc cget -bg]
      PrintString $v "clean_gti_file" $PAR
   }

   upvar clean_lc_binsize v; PrintString $v "binsize" $PAR

   puts $PAR "lc_dirty=lc_clean.lc    - (optional) files for lightcurves"
   puts $PAR "lc_clean=lc_clean.clean.lc"

   upvar clean_lc_clipmode v;
   if { $v == "clip" } {
     upvar clean_lc_clip v
     puts $PAR "clip=$v"
   } else {
     upvar clean_lc_mean v
     puts $PAR "mean=$v"
   }

   upvar clean_lc_cutmode v;
   if { $v == "factor" } {
     upvar clean_lc_max_factor v
     puts $PAR "max_factor=$v"
   } else {
     upvar clean_lc_max_sigma v
     puts $PAR "max_sigma=$v"
   }
   upvar clean_lc_keep_neg v;
   if { $v } {
     puts $PAR "ignore_neg_dev=yes"
   }

   close $PAR;
   exec "cat" "lc_clean.par" > /dev/tty 2> /dev/tty
   exec "$env(CH)/bin/lc_clean" > /dev/tty 2> /dev/tty
   exec "rm" "$TMPFILE"
}

proc RunCleanLc_EXE {} {
   set PAR [open "lc_clean.par" w]
   puts $PAR "num_datafiles=1"
   upvar evtfile_lc evt;
   upvar clean_lc_filter filt;
   upvar clean_lc_gradefilter gradefilt;
   global env;

   puts -nonewline $PAR "file1=$evt\[events\]"
   if { [string length $filt] > 0 || [string length $gradefilt] > 0 } {
    puts -nonewline $PAR "\["
    if { [string length $filt] > 0 && [string length $gradefilt] > 0 } {
      puts -nonewline $PAR "$filt&&$gradefilt"
    } elseif { [string length $filt] > 0 } {
      puts -nonewline $PAR "$filt"
    } else {
      puts -nonewline $PAR "$gradefilt"
    }
    puts  -nonewline $PAR "\]"
   }
   puts $PAR ""

   upvar gtifile_tel v;   set v [string trim $v]
   if { [string length $v] == 0 } {
     puts "Error: no 0-th order gti file"
     .cleanlc.gtifile.1 config -bg Hotpink
     return
   } else {
      .cleanlc.gtifile.1 config -bg [.cleanlc cget -bg]
      PrintString $v "gti_file" $PAR
   }

   upvar external_gti v;   set v [string trim $v]
   if { [string length $v] == 0 } {
     puts "Error: no output gti file"
     .cleanlc.outgti.1 config -bg Hotpink
     return
   } else {
      .cleanlc.outgti.1 config -bg [.cleanlc cget -bg]
      PrintString $v "clean_gti_file" $PAR
   }

   upvar clean_lc_binsize v; PrintString $v "binsize" $PAR

   puts $PAR "lc_dirty=lc_clean.lc    - (optional) files for lightcurves"
   puts $PAR "lc_clean=lc_clean.clean.lc"

   upvar clean_lc_clipmode v;
   if { $v == "clip" } {
     upvar clean_lc_clip v
     puts $PAR "clip=$v"
   } else {
     upvar clean_lc_mean v
     puts $PAR "mean=$v"
   }

   upvar clean_lc_cutmode v;
   if { $v == "factor" } {
     upvar clean_lc_max_factor v
     puts $PAR "max_factor=$v"
   } else {
     upvar clean_lc_max_sigma v
     puts $PAR "max_sigma=$v"
   }
   upvar clean_lc_keep_neg v;
   if { $v } {
     puts $PAR "ignore_neg_dev=yes"
   }

   close $PAR;
   exec "cat" "lc_clean.par" > /dev/tty 2> /dev/tty
   exec "$env(CH)/bin/lc_clean" > /dev/tty 2> /dev/tty
}

proc RunCleanLc_SHOW {} {
  set PAR [open "lc_clean_sm" w]
  puts $PAR "lc_clean_sm       
      define dc black ctype \$dc
      lw 0  ltype 0  angle 0
      notation -4 4 -4 4    format \"i\" \"i\"
      ticksize 0 0 0 0

      data \"lc_clean.lc\"
      lines 1 1000000
      read {x1 1 y1 2}
      set x1=x1/1000

      data \"lc_clean.clean.lc\"
      lines 1 1000000
      read {x2 1 y2 2}
      set x2=x2/1000

      define mean (sum(y2)/dimen(y2))
      define up (\$mean*1.5)
      define down (\$mean/1.5)

      define t0 (x1\[0\])
      define t1 (x1\[dimen(x1)-1\])

      location 3500 31500 25500 31500

      define t01 (\$t0+(\$t1-\$t0)/4)
      limits \$t0 \$t01  \$down \$up

      box 1 2 0 0
      ltype 1 grid 1 ltype 0
      ylabel {cts/s}

      ctype red
      connect  x1 y1
      ctype \$dc
      connect  x2 y2


      
      location 3500 31500 18000 24000

      define t00 (\$t0+1*(\$t1-\$t0)/4)
      define t01 (\$t0+2*(\$t1-\$t0)/4) 
      limits  \$t00  \$t01  \$down \$up

      box 1 2 0 0
      ltype 1 grid 1 ltype 0
      ylabel {cts/s}

      ctype red
      connect  x1 y1
      ctype \$dc
      connect  x2 y2


      
      location 3500 31500 10500 16500

      define t00 (\$t0+2*(\$t1-\$t0)/4)
      define t01 (\$t0+3*(\$t1-\$t0)/4)
      limits  \$t00 \$t01  \$down \$up

      box 1 2 0 0
      ltype 1 grid 1 ltype 0
      ylabel {cts/s}

      ctype red
      connect  x1 y1
      ctype \$dc
      connect  x2 y2


      
      location 3500 31500 3000 9000

      define t00 (\$t0+3*(\$t1-\$t0)/4)
      limits  \$t00 \$t1  \$down \$up

      box 1 2 0 0
      ltype 1 grid 1 ltype 0
      ylabel {cts/s}
      xlabel {Chandra time, ks}

      ctype red
      connect  x1 y1
      ctype \$dc
      connect  x2 y2
"
      close $PAR

	  global env;
	  if [info exists env(SUPERMONGOBINARY)] {
        # okay, it's there, use it
        set smbinary $env(SUPERMONGOBINARY)
      } else {
        # the environment var isn't set, use a default
        set smbinary "sm"
      }
      global SM
      set SM [open "|$smbinary" w]
      puts $SM "macro read lc_clean_sm lc_clean_sm"
      puts $SM "page"
      flush $SM
      
     .cleanlc.inspect config -text "Quit SM" -bg lightgreen -command {QuitSM}

proc QuitSM {} {
   global SM
   puts $SM "quit";
   close $SM;
   .cleanlc.inspect config -text "Inspect" -bg [.cleanlc cget -bg] -command {RunCleanLc_SHOW}
}

}

#################################################################
proc PrintByName { varname parname} {
 upvar 2 $varname var
 puts stdout "$parname=$var"
}

proc CheckEvtFile {} {
  upvar #0 evtfile events_file
  set OK 1
  if { [string length $events_file] == 0 } {
    puts "NO EVENT FILE!"
    set OK 0
  }
  if { $OK && ! [file exists $events_file] } {
    puts "$events_file: no such file or directory"
    set OK 0
  }
  if { $OK }  {
    .evtfile.1 config -bg [. cget -bg]
  } else {
    .evtfile.1 config -bg HotPink
 }
 return $OK
}
proc CheckOutFile {} {
  upvar #0 outfile events_file
  set OK 1
  if { [string length $events_file] == 0 } {
    puts "NO OUTPUT FILE!"
    set OK 0
  }
  if { $OK }  {
    .outfile.1 config -bg [. cget -bg]
  } else {
    .outfile.1 config -bg HotPink
 }
 return $OK
}

proc CheckGTIFile {} {
  upvar #0 inputbgfile bgfile
  upvar #0 external_gti extgti
  set bgfile [string trim $bgfile]
  set extgti [string trim $extgti]
  set OK 1
  if { [string length $bgfile] > 0 } {
    if { [string length $extgti] == 0 } {
      puts "ACIS_PROCESS_EVENTS NEEDS A GTI FILE!"
      set OK 0
    }
    if { $OK && ! [file exists $extgti] } {
      puts "$extgti: no such file or directory"
      set OK 0
    }
  }
  if { $OK }  {
    .filters.opt.booleans1.1 config -bg [. cget -bg]
  } else {
    .filters.opt.booleans1.1 config -bg HotPink
  }
 return $OK
}

proc CheckASPFile {} {
  upvar #0 aspfile asp_file
  upvar #0 do_aspect doaspect
  upvar #0 outputbgfile doingbg
  upvar #0 outputreadoutbgfile doingreadoutbg
  set OK 1
  set asp_file [string trim $asp_file]
  set doingbg  [string trim $doingbg]
  set doingreadoutbg  [string trim $doingreadoutbg]
  if { ($doaspect || [string length $doingbg] > 0 || [string length $doingreadoutbg] > 0) && [string length $asp_file] == 0 } {
    puts "NO ASPECT FILE!"
    set OK 0
  }
  if { $doaspect && [string length $asp_file] > 0 } {
    if {! [file exists $asp_file] } {
       puts "$asp_file: no such file"
       set OK 0
    }
  }
  if { $OK }  {
    .calmenu.options.aspfile config -bg [. cget -bg]
  } else {
    .calmenu.options.aspfile config -bg HotPink
 }
 return $OK
}   

proc CheckMTLFile {} {
  upvar #0 mtlfile mtl_file
  upvar #0 do_cti_t doctit
  set OK 1
  set mtl_file [string trim $mtl_file]
  if { $doctit && [string length $mtl_file] == 0 } {
    puts "NO MTL FILE!"
    set OK 0
  }
  if { $doctit && [string length $mtl_file] > 0 } {
    if {! [file exists $mtl_file] } {
       puts "$mtl_file: no such file"
       set OK 0
    }
  }
  if { $OK }  {
    .calmenu.options.mtlfile config -bg [. cget -bg]
  } else {
    .calmenu.options.mtlfile config -bg HotPink
 }
 return $OK
}



    
proc PrintLogical {v name fid} {
  if {$v} {puts $fid "$name=yes"} else {puts $fid "$name=no"}
}

proc PrintString {v name fid} {
  set vv1 [string trim $v];
  regsub -all {[ \t,]+} $vv1 , vv
  if {[string length $vv]>0} {
        puts $fid "$name=$vv"
    }
}

# proc PrintString {v name fid} {
#   set vv [string trim $v];
#   if {[string length $vv]>0} {
#         puts $fid "$name=$vv"
#     }
# }

proc RunProc {} {
    global PROCPID
    global PIPE
    if { [CheckEvtFile] && [CheckASPFile] && [CheckGTIFile] } {
	MakeParFile
	upvar parfile par_file
	
	set PROCPID [exec -keepnewline "process_lev1_data_exe" "@$par_file" "&"]
	button .stop -text "Stop Proc" -command {KillProc}
	pack .stop -side left -padx 2
	.stop config -bg red
	
	set flag 0
	while { ! $flag } {
	    after 3000 {set flag 1}
	    vwait flag
	    if { [catch {exec ps -p $PROCPID} results]} {
	      # ps returned status=1
 	      set PROCPID -1
 	      destroy .stop
 	      set flag 1
 	      return 0
	     }
        }
    }
}

proc KillProc {} {
    global PROCPID
    if {$PROCPID>0} {
	exec "kill" $PROCPID
	set PROCPID -1
	destroy .stop
    }
}




proc CheckPar {} {
   puts " "
   puts " "
   if { [CheckEvtFile] && [CheckASPFile] && [CheckGTIFile]  && [CheckMTLFile] } {
    MakeParFile
   }
}

proc MakeParFile {} {
   upvar 2 parfile par_file; set PAR [open $par_file w]
   upvar 2 evtfile v; puts $PAR "inputevtfile=$v"
   upvar 2 outfile v; puts $PAR "evtfile=$v"
   upvar 2 outputbgfile v; PrintString $v "bg_file" $PAR
   upvar 2 outputreadoutbgfile v; PrintString $v "readout_bg_file" $PAR
   upvar 2 external_gti v; PrintString $v "gtifile" $PAR
   upvar 2 badpixfilter v; PrintString $v "badpixfilter" $PAR
   upvar 2 do_cti  v; PrintLogical $v "do_cti" $PAR
   upvar 2 do_cti_t v; PrintLogical $v "do_cti_t" $PAR
   upvar 2 do_au_gain v; PrintLogical $v "do_au_gain" $PAR
   upvar 2 do_tgain v; PrintLogical $v "do_tgain" $PAR
   upvar 2 do_gain v; PrintLogical $v "do_gain" $PAR
   upvar 2 do_aspect v; PrintLogical $v "do_aspect" $PAR
   upvar 2 do_subpix v; PrintLogical $v "do_subpix" $PAR
   upvar 2 aspfile v; PrintString $v "aspfile" $PAR
   upvar 2 mtlfile v; PrintString $v "mtlfile" $PAR
   upvar 2 vf_clean v; PrintLogical $v "vf_clean" $PAR
   upvar 2 clean_afterglow v; PrintLogical $v "clean_afterglow" $PAR
   upvar 2 grade_set v; PrintString $v "grade_set" $PAR
   upvar 2 flt_grade_set v; PrintString $v "flt_grade_set" $PAR
   upvar 2 ccdset v; PrintString $v "ccd_set" $PAR
   upvar 2 tmpdir v; PrintString $v "tmpdir" $PAR
   upvar 2 GAINFILE  v; PrintString $v "GAINFILE" $PAR
   upvar 2 GRADEFILE v; PrintString $v "GRADEFILE" $PAR
   upvar 2 CTIFILE   v; PrintString $v "CTIFILE" $PAR
   upvar 2 inputbgfile v; PrintString $v "input_bg_file" $PAR
   upvar 2 bg_only v; PrintLogical $v "bg_only" $PAR
   upvar 2 readoutbg_only v; PrintLogical $v "readout_bg_only" $PAR
   upvar 2 destreak v; PrintLogical $v "destreak" $PAR
   upvar 2 destreak_max v; PrintString $v "destreak_max" $PAR
   upvar 2 destreak_filter v; PrintLogical $v "destreak_filter" $PAR
   upvar 2 destreak_mask v; PrintString $v "destreak_mask" $PAR
   upvar 2 destreak_ccd_id v; PrintString $v "destreak_ccd_id" $PAR
   close $PAR;

   exec "cat" $par_file > /dev/tty 2> /dev/tty

   SaveStateDefault;
}


proc DestreakPars { } {
 toplevel .destreak
 set gx [winfo x .cleanings]; set gy [winfo y .cleanings]; 
 set gh [winfo height .cleanings]; set gw [winfo width .cleanings]
 set gy [expr $gy+$gh/10]; set gx [expr $gx+$gw/2];
 wm geometry .destreak +$gx+$gy

#    upvar 2 destreak_max v; PrintString $v "destreak_max" $PAR
#    upvar 2 destreak_filter v; PrintLogical $v "destreak_filter" $PAR
#    upvar 2 destreak_mask v; PrintString $v "destreak_mask" $PAR
#    upvar 2 destreak_ccd_id v; PrintString $v "destreak_ccd_id" $PAR

 label .destreak.maxtext -text    " max   "
 entry .destreak.maxval  -textvariable destreak_max

 label .destreak.filtertext -text " filter"
 checkbutton .destreak.filterval  -variable destreak_filter -selectcolor green -text "                 "

 label .destreak.masktext -text    " mask "
 entry .destreak.maskval  -textvariable destreak_mask
 
 label .destreak.ccd_id_text -text " CCDs "
 entry .destreak.ccd_id_val  -textvariable destreak_ccd_id
 
 grid .destreak.maxtext -row 0 -column 0
 grid .destreak.maxval  -row 0 -column 1

 grid .destreak.filtertext -row 1 -column 0
 grid .destreak.filterval  -row 1 -column 1

 grid .destreak.masktext -row 2 -column 0
 grid .destreak.maskval  -row 2 -column 1
 
 grid .destreak.ccd_id_text -row 3 -column 0
 grid .destreak.ccd_id_val  -row 3 -column 1
 

 button .destreak.ok -text "OK" -command {destroy .destreak}
 grid .destreak.ok  -column 1 -row 4

}

######################################################################
proc SetCalFiles { } {
 toplevel .caldb
 set gx [winfo x .]; set gy [winfo y .]; set gh [winfo height .]
 set gw [winfo width .]
 set gy [expr $gy+$gh/10]; set gx [expr $gx+$gw/2];
 wm geometry .caldb +$gx+$gy

 button .caldb.gaintext -text "GAIN:  " -command {set GAINFILE [SelFile $GAINFILE "$env(CALDB)/data/chandra/acis/bcf/gain"]}
 entry .caldb.gainfile -textvariable GAINFILE -width 70

 button .caldb.gradetext -text "GRADE: " -command {set GRADEFILE [SelFile $GRADEFILE "$env(CALDB)/data/chandra/acis/bcf/grade"]}
 entry .caldb.gradefile -textvariable GRADEFILE -width 70

 button .caldb.ctitext -text "CTI:   " -command {set CTIFILE [SelFile $CTIFILE "$env(CALDB)/data/chandra/acis/bcf/cti"]}
 entry .caldb.ctifile -textvariable CTIFILE -width 70

 grid .caldb.gaintext -column 0 -row 0
 grid .caldb.gainfile -column 1 -row 0

 grid .caldb.gradetext -column 0 -row 1
 grid .caldb.gradefile -column 1 -row 1

 grid .caldb.ctitext -column 0 -row 2
 grid .caldb.ctifile -column 1 -row 2

 button .caldb.ok -text "OK" -command {destroy .caldb}
 grid .caldb.ok  -column 1 -row 3

}

# proc ShowChoices { parent varname args } {
#  set f [frame $parent.choices -borderwidth 5]
#  set b 0
#  foreach item $args {
# 	 radiobutton $f.$b -variable $varname -text $item -value $item
#          pack $f.$b -side top
#          incr b
#  }
#  pack $f -side top
# }

proc EvtFile { parent } {
  set f [frame .evtfile]
  label $f.0 -width 17 -text "Events file:" -anchor w
  entry $f.1 -width 30 -textvariable evtfile
  button $f.2 -text "ds9" -command {RunProg "ds9" $evtfile}
  button $f.3 -text "fv" -command {RunProg "fv" $evtfile}
  pack $f.0 $f.1 $f.2 $f.3 -side left
  pack $f  -side top -anchor sw -padx 3
  set f [frame .outfile]
  label $f.0 -width 17 -text "output file:" -anchor w
  entry $f.1 -width 30 -textvariable outfile
  button $f.2 -text "ds9" -command {RunProg "ds9" $outfile}
  button $f.3 -text "fv" -command {RunProg "fv" $outfile}
  pack $f.0 $f.1 $f.2 $f.3 -side left
  pack $f  -side top -anchor sw -padx 3
  CheckEvtFile
  CheckOutFile
}

proc ParFile { parent } {
  set f [frame .parfile]
  label $f.0 -width 17 -text "out par file:" -anchor w
  pack $f.0 -side left
  entry $f.1 -width 12 -textvariable parfile
  pack  $f.1 -side left
  label $f.3 -text " \[include par file:"
  pack $f.3 -side left
  entry $f.4 -width 10 -textvariable incparfile
  pack  $f.4 -side left
  $f.4 config -bg lightcyan
  label $f.5 -text "\]"
  pack $f.5 -side left
  pack $f  -side top -anchor sw -pady 2 -padx 3
}

proc CalMenu { } {
  global PADOPT
  frame .calmenu -relief sunken -borderwidth 2
  label .calmenu.titletext -text "PHOTON CORRECTIONS:"
  frame .calmenu.titledelim -relief ridge -borderwidth 2 -width 10 -height 2
  pack .calmenu.titletext -side top
  pack .calmenu.titledelim -side top -fill x

  frame .calmenu.options

  set WD 17
  set WD2 14

  label .calmenu.options.ctitext -width $WD -text "CTI correction" -anchor w
  checkbutton .calmenu.options.do_cti -variable do_cti -selectcolor green

  label .calmenu.options.tctitext -width $WD -text "T-dependent CTI" -anchor w
  checkbutton .calmenu.options.do_cti_t -variable do_cti_t -selectcolor green

  entry .calmenu.options.mtlfile -textvariable mtlfile
  label .calmenu.options.mtlfiletext -width $WD2 -text "MTL file:" -anchor e
  button .calmenu.options.mtlfileset -text "sel" -command {set mtlfile [SelFile $mtlfile ""]} -padx $PADOPT -pady 0

  label .calmenu.options.tgaintext -width $WD  -text "tgain correction" -anchor w
  checkbutton .calmenu.options.do_tgain -variable do_tgain -selectcolor green

  label .calmenu.options.augaintext -width $WD  -text "Au gain adjustment" -anchor w
  checkbutton .calmenu.options.do_au_gain -variable do_au_gain -selectcolor green

  # label .calmenu.options.gaintext -width $WD -text "gain only" -anchor w
  # checkbutton .calmenu.options.do_gain -variable do_gain -selectcolor green
  checkbutton .calmenu.options.do_gain_w -variable do_gain -width $WD2  -selectcolor green -text "gain only" -anchor w

  checkbutton .calmenu.options.do_aspect -variable do_aspect -width $WD2 -text "apply aspect:" -selectcolor green -anchor w
  entry .calmenu.options.aspfile -textvariable aspfile
  button .calmenu.options.aspfileset -text "sel" -command {set aspfile [SelFile $aspfile ""]} -padx $PADOPT -pady 0

  label .calmenu.options.subpixtext -width $WD -text "subpix positions" -anchor w
  checkbutton .calmenu.options.do_subpix -variable do_subpix -selectcolor green


  button .calmenu.options.setup -text "Calibration setup ..." -command {SetCalFiles} -anchor e

  grid .calmenu.options.ctitext -row 0 -column 0
  grid .calmenu.options.do_cti  -row 0 -column 1
  grid .calmenu.options.tctitext -row 1 -column 0
  grid .calmenu.options.do_cti_t  -row 1 -column 1
  grid .calmenu.options.mtlfiletext  -row 1 -column 2
  grid .calmenu.options.mtlfile   -row 1 -column 3
  grid .calmenu.options.mtlfileset   -row 1 -column 4
  grid .calmenu.options.tgaintext -row 2 -column 0
  grid .calmenu.options.do_tgain  -row 2 -column 1
  grid .calmenu.options.do_gain_w  -row 2 -column 2
  # grid .calmenu.options.gaintext -row 3 -column 0
  # grid .calmenu.options.do_gain  -row 3 -column 1
  grid .calmenu.options.do_aspect  -row 0 -column 2
  grid .calmenu.options.aspfile     -row 0 -column 3
  grid .calmenu.options.aspfileset     -row 0 -column 4

  grid .calmenu.options.augaintext -row 3 -column 0
  grid .calmenu.options.do_au_gain  -row 3 -column 1
  grid .calmenu.options.do_subpix   -row 4 -column 1
  grid .calmenu.options.subpixtext  -row 4 -column 2

  grid .calmenu.options.setup  -row 3 -column 3 -columnspan 2

  pack .calmenu.options -side top

  pack .calmenu -side top -pady 2 -padx 5
}

#####################################################################

proc ReadoutBGMenu { } {
  global PADOPT

  global outputreadoutbgfile
  global readoutbg_only

  frame .routbgmenu -relief sunken -borderwidth 2
  label .routbgmenu.titletext -text "READOUT ARTIFACT:"
  frame .routbgmenu.titledelim -relief ridge -borderwidth 2 -width 10 -height 2
  pack .routbgmenu.titletext -side top
  pack .routbgmenu.titledelim -side top -fill x

  frame .routbgmenu.options
  checkbutton .routbgmenu.options.routbg_only -variable readoutbg_only -selectcolor green -text "process readout bg ONLY"
  label .routbgmenu.options.outfiletext -text "Output Readout BG file: "
  entry .routbgmenu.options.outfile -textvariable outputreadoutbgfile -width 30
  button .routbgmenu.options.outfileset -text "sel" -command {set outputreadoutbgfile [SelFile $outputreadoutbgfile ""]} -padx $PADOPT -pady 0
  button .routbgmenu.options.outfileds9 -text "ds9" -command {RunProg "ds9" $outputreadoutbgfile} -padx $PADOPT -pady 0

  grid .routbgmenu.options.outfiletext -row 1 -column 0
  grid .routbgmenu.options.outfile     -row 1 -column 1
  grid .routbgmenu.options.outfileset  -row 1 -column 2
  grid .routbgmenu.options.outfileds9  -row 1 -column 3

  grid .routbgmenu.options.routbg_only      -row 2 -column 0

  pack .routbgmenu.options -side top 

  pack .routbgmenu -side top -pady 3 -padx 5 -fill x

}
  

#####################################################################
  
proc BgMenu { } {
  global PADOPT

  global outputbgfile
  global inputbgfile
  global bg_only

  frame .bgmenu -relief sunken -borderwidth 2
  label .bgmenu.titletext -text "BACKGROUND:"
  frame .bgmenu.titledelim -relief ridge -borderwidth 2 -width 10 -height 2
  pack .bgmenu.titletext -side top
  pack .bgmenu.titledelim -side top -fill x

  frame .bgmenu.options

  label .bgmenu.options.infiletext -text   "Input BG file:  "
  entry .bgmenu.options.infile -textvariable inputbgfile -width 30
  button .bgmenu.options.infileset -text "sel" -command {set inputbgfile [SelFile $inputbgfile "$env(CH)/BG"]; set outputbgfile [file tail $inputbgfile] } -padx $PADOPT -pady 0
  button .bgmenu.options.infileds9 -text "ds9" -command {RunProg "ds9" $inputbgfile} -padx $PADOPT -pady 0

  checkbutton .bgmenu.options.bg_only -variable bg_only -selectcolor green -text "process BG ONLY"

  label .bgmenu.options.outfiletext -text "Output BG file: "
  entry .bgmenu.options.outfile -textvariable outputbgfile -width 30
  button .bgmenu.options.outfileset -text "sel" -command {set outpufbgfile [SelFile $outputbgfile ""]} -padx $PADOPT -pady 0
  button .bgmenu.options.outfileds9 -text "ds9" -command {RunProg "ds9" $outputbgfile} -padx $PADOPT -pady 0


  grid .bgmenu.options.infiletext -row 0 -column 0
  grid .bgmenu.options.infile     -row 0 -column 1
  grid .bgmenu.options.infileset  -row 0 -column 2
  grid .bgmenu.options.infileds9  -row 0 -column 3

  grid .bgmenu.options.outfiletext -row 1 -column 0
  grid .bgmenu.options.outfile     -row 1 -column 1
  grid .bgmenu.options.outfileset  -row 1 -column 2
  grid .bgmenu.options.outfileds9  -row 1 -column 3

  grid .bgmenu.options.bg_only      -row 2 -column 0

  pack .bgmenu.options -side top 

  pack .bgmenu -side top -pady 5 -padx 5 -fill x

}

#####################################################################

proc ShowChapter { parent item } {
  label $parent.chapter -text $item -justify left
  pack $parent.chapter -side top
  frame $parent.delim -relief ridge -borderwidth 2 -width 10 -height 2
  pack $parent.delim -side top -fill x
}

proc ShowOptions { parent name args } {
 global PADOPT

 frame $parent -relief sunken -borderwidth 2
# set f [frame $parent.booleans -borderwidth 0]
 ShowChapter $parent $name
 set i 0
 foreach item $args {
         set g [frame $parent.booleans$i -borderwidth 0]
	 set v ${item}_name; upvar $v prompt_name
	 set name [string trim $prompt_name]
#	 set nameaff [string repeat " " [expr 20 - [string length $name]]]
#         label $g.0 -width 10 -text "$name$nameaff" -justify left
         label $g.0 -width 19 -text "$name:" -anchor w
         pack $g.0 -side left
	 upvar $item val
	 if { $val == 1 || $val == 0 } {
    	   checkbutton $g.1 -variable $item -selectcolor green
           pack $g.1 -side left
         } else {
#           entry $g.1 -textvariable $item -width 9 -justify left
           entry $g.1 -textvariable $item -width [string length $val] -justify left
           pack $g.1 -side left
         }
	if { $item == "external_gti" } {
	   if { [string length $val] == 0 } {
	    $g.1 config -width 11
           }
        }
        if { $item == "badpixfilter" } {
           button $g.2 -text "sel" -command {SelectBadPix} -padx $PADOPT -pady 0
           pack $g.2 -side left
	}

        if { $item == "destreak" } {
           button $g.2 -text "parameters..." -command {DestreakPars} -padx $PADOPT -pady 0
           pack $g.2 -side left
	}

	 pack $g -side top -anchor sw -pady 0 -fill x
	 incr i
 }
#pack $parent -side top -anchor nw -fill none -pady 2
}

# set choice kiwi
# ShowChoices {} choice apple orange peach kiwi strawberry

set evtfile  [lindex $argv 0]
set outfile  [lindex $argv 1]
set aspfile  [lindex $argv 2]
set mtlfile  [lindex $argv 3]
set external_gti [lindex $argv 4]
set evtfile_lc $evtfile
set parfile  "process.par"

set tmpdir  "./    "; set tmpdir_name "Temp. directory"

set do_cti 1; set do_tgain 1 ;  set do_au_gain 0; 
set do_gain 0; set do_aspect 0; set do_cti_t 1; set do_subpix 1;
set vf_clean 1; set vf_clean_name "clean VF bg";
set clean_afterglow 1; set clean_afterglow_name "clean afterglow";
set grade_set     "0,2,3,4,6"; set grade_set_name "ASCA grade set";
set flt_grade_set "         "; set flt_grade_set_name "fltgrade set";
set ccdset "         "; set ccdset_name "CCD set (e.g. 7,5)";
set external_gti_name "external GTI";
set badpixfilter "$env(CH)/BG/badpix_E"; set badpixfilter_name "bad pixels";
set destreak 0; set destreak_name "destreak";
set destreak_max "DEFAULT"
set destreak_filter 1
set destreak_mask "DEFAULT"
set destreak_ccd_id 8

global env;
if { [info exists env(P_A_D_GAINFILE)] } {
    set GAINFILE "$env(P_A_D_GAINFILE)";
} else {
    set GAINFILE "\$CALDB/data/chandra/acis/bcf/gain/acisD2000-01-29gain_ctiN0005.fits"
}
#set GRADEFILE "\$CALDB/data/chandra/acis/bcf/grade/acisD1996-11-01gradeN0002.fits"
set GRADEFILE "CALDB"
set CTIFILE "CALDB"

set clean_lc_range     "energy>2500&&energy<7000"
set clean_lc_range_ref "energy>9500&&energy<12000"
set clean_lc_filter "ccd_id<4&&energy>300&&energy<12000"
set clean_lc_ccdfilter "ccd_id<4"
set clean_lc_gradefilter "grade!=1&&grade!=5&&grade!=7"
set clean_lc_binsize 1037.12
set clean_lc_clip 3
set clean_lc_mean 1.0
set clean_lc_max_factor 1.2
set clean_lc_max_sigma  4
set clean_lc_keep_neg  0

set clean_lc_clipmode "clip"
set clean_lc_cutmode "factor"
set lc_clean_afterglow 1
set gtifile_tel ""
set lc_clean_psrcreg ""
set lc_clean_vfbg 0
set lc_clean_afterglow 1

RestoreState ".process_acis_data"


# EVT File:
EvtFile {}
ParFile {}
bind .evtfile.1 <Return> {CheckEvtFile}
bind .outfile.1 <Return> {CheckOutFile}


# Options
frame .titledelim -width 10 -height 0
pack .titledelim -side top -fill x -pady 5 

CalMenu

ShowOptions {.cleanings}   {CLEANING:} \
    grade_set flt_grade_set vf_clean clean_afterglow badpixfilter destreak
pack .cleanings -side top -anchor nw -fill x -pady 2 -padx 5

frame .filters
ShowOptions {.filters.opt} {FILTERS:} ccdset external_gti 
pack .filters.opt -side left -anchor sw
button .filters.cleanlc -text "LC_CLEAN" -command [list RunCleanLc evtfile external_gti]
button .filters.cleanlc2 -text "LC_CLEAN-ratio" -command [list RunCleanLcRatio evtfile external_gti]
button .filters.cleanlcsel -text "sel" -command {SelectGTI} -padx $PADOPT -pady 0
pack .filters.cleanlcsel -side left -anchor sw
pack .filters.cleanlc  -side left -anchor sw -padx 20
pack .filters.cleanlc2  -side left -anchor sw
pack .filters  -side top -anchor sw -fill x -padx 5 -pady 2

BgMenu
ReadoutBGMenu

ShowOptions {.misc} {Misc} tmpdir
pack .misc -side top -anchor nw -fill none -pady 10 -padx 5


button .checkpar -text "Check parameters" -command {CheckPar}
pack .checkpar -padx 20 -pady 10 -side left

button .doit -text Process -command {RunProc}
pack .doit -padx 20 -pady 10 -side left

button .quit -text Quit -command {exit}
pack .quit -side left



vwait forever

