#!/usr/local/bin/wish -f

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 PrintLogical {v name fid} {
  if {$v} {puts $fid "$name=yes"} else {puts $fid "name=no"}
}

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

proc MakeParFile {} {
 if { [CheckEvtFile] } {
   upvar parfile par_file; set PAR [open $par_file w]
   upvar evtfile v; puts $PAR "evtfile=$v"
   upvar external_gti v; PrintString $v "gtifile" $PAR
   upvar do_cti  v; PrintLogical $v "do_cti" $PAR
   upvar do_tgain v; PrintLogical $v "do_tgain" $PAR
   upvar vf_clean v; PrintLogical $v "vf_clean" $PAR
   upvar clean_afterglow v; PrintLogical $v "clean_afterglow" $PAR
   upvar grade_set v; PrintString $v "grade_set" $PAR
   upvar flt_grade_set v; PrintString $v "flt_grade_set" $PAR
   upvar ccdset v; PrintString $v "ccd_set" $PAR
   close $PAR;
   exec "cat" $par_file > /dev/tty 2> /dev/tty
   exit
 }
}


# 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 -text "Events file:    "
  pack $f.0 -side left
  entry $f.1 -width 40 -textvariable evtfile
  pack  $f.1 -side left
  pack $f  -side top -anchor sw
  CheckEvtFile
}

proc ParFile { parent } {
  set f [frame .parfile]
  label $f.0 -text "tool parameter file: "
  pack $f.0 -side left -fill none -anchor nw
  entry $f.1 -width 20 -textvariable parfile
  pack  $f.1 -side left -fill none -anchor nw
  $f.1 config -bg lightgreen
  label $f.2 -text "(created)"
  pack  $f.2 -side top -fill none -anchor sw
  pack $f  -side top -anchor sw -pady 0
  set f [frame .incparfile]
  label $f.0 -text "include parameter file: "
  pack $f.0 -side left -fill none -anchor nw
  entry $f.1 -width 20 -textvariable incparfile
  pack  $f.1 -side left -fill none -anchor nw
  $f.1 config -bg lightcyan
  label $f.2 -text "(optional)"
  pack  $f.2 -side top -fill none -anchor sw
  pack $f  -side top -anchor sw -pady 2
}

proc ShowChapter { parent item } {
  label $parent.chapter -text $item -justify right 
  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 } {
 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 -text "$name$nameaff" -justify left
         pack $g.0 -side left
	 upvar $item val
	 if { $val == 1 || $val == 0 } {
    	   checkbutton $g.1 -variable $item -selectcolor green
           pack $g.1
         } else {
           entry $g.1 -textvariable $item -width [string length $val]
           pack $g.1 -fill x
         }
	 pack $g -side top -anchor sw -pady 0
	 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 evtfile_lc $evtfile
set parfile  "process.par"

set do_cti 1 ; set do_cti_name "CTI correction";
set do_tgain 1; set do_tgain_name "tgain correction";
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";
set external_gti "         "; set external_gti_name "external GTI";

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


# Options
ShowOptions {.corrections} {Correctins:} do_cti  do_tgain
pack .corrections -side top -anchor nw -fill none

ShowOptions {.cleanings}   {Cleaning:} \
    grade_set flt_grade_set vf_clean clean_afterglow
pack .cleanings -side top -anchor nw

frame .filters
ShowOptions {.filters.opt} {Filters:} ccdset external_gti 
pack .filters.opt -side left -anchor sw
button .filters.cleanlc -text "clean_lc ..." -command [list RunCleanLc evtfile external_gti]
pack .filters.cleanlc -side left -anchor sw
pack .filters  -side top -anchor nw



button .doit -text Process -command [list MakeParFile]
pack .doit -padx 20 -pady 10 -side left

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


set clean_lc_filter "ccd_id<4&&energy>300&&energy<10000"
set clean_lc_gradefilter "grade!=1&&grade!=5&&grade!=7"
set clean_lc_binsize 259.28
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_clipmode "clip"
set clean_lc_cutmode "factor"

#############################################################
proc RunCleanLc {evt gti} {
 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


 frame .cleanlc.evtfile
 label .cleanlc.evtfile.0 -text "Events file:            "
 pack .cleanlc.evtfile.0 -side left
 entry .cleanlc.evtfile.1 -width 40 -textvariable evtfile_lc
 pack  .cleanlc.evtfile.1 -side left
 pack .cleanlc.evtfile  -side top -anchor sw

 frame .cleanlc.gtifile
 label .cleanlc.gtifile.0 -text "0-th order GTI file:    "
 pack .cleanlc.gtifile.0 -side left
 entry .cleanlc.gtifile.1 -width 40 -textvariable gtifile_tel
 pack  .cleanlc.gtifile.1 -side left
 pack .cleanlc.gtifile  -side top -anchor sw

 frame .cleanlc.outgti
 label .cleanlc.outgti.0  -text "output GTI file:        "
 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 -text "event filter: "
 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 -text "grade filter: "
 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.options
 label .cleanlc.options.binsize0 -text "binsize "
 entry .cleanlc.options.binsize1 -textvariable clean_lc_binsize
 label .cleanlc.options.binsize2 -text "259.28=3.241*80 (3.241s is std. frame time)"
 
 radiobutton .cleanlc.options.clipA -variable clean_lc_clipmode -value "clip" -selectcolor green
 label .cleanlc.options.clip0 -text "clip " -justify left
 entry .cleanlc.options.clip1 -textvariable clean_lc_clip
 label .cleanlc.options.clip2 -text "sigma clip to calc.mean"
 
 radiobutton .cleanlc.options.meanA -variable clean_lc_clipmode -value "mean" -selectcolor green
 label .cleanlc.options.mean0 -text "mean " -justify left
 entry .cleanlc.options.mean1 -textvariable clean_lc_mean
 label .cleanlc.options.mean2 -text "force this value (cts/s) as mean rate"
 
 radiobutton .cleanlc.options.max_factorA -variable clean_lc_cutmode -value "factor" -selectcolor blue
 label .cleanlc.options.max_factor0 -text "factor " -justify left
 entry .cleanlc.options.max_factor1 -textvariable clean_lc_max_factor
 label .cleanlc.options.max_factor2 -text "max increase/decrease factor from mean"
 
 radiobutton .cleanlc.options.max_sigmaA -variable clean_lc_cutmode -value "sigma" -selectcolor blue
 label .cleanlc.options.max_sigma0 -text "sigma " -justify left
 entry .cleanlc.options.max_sigma1 -textvariable clean_lc_max_sigma
 label .cleanlc.options.max_sigma2 -text "max deviation from mean rate, sigmas"
 
 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

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


 button .cleanlc.run -text "run clean_lc" -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 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;

   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_gtifile" $PAR
   }

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

   puts $PAR "lc_dirty=?.lc    - (optional) files for lightcurves"
   puts $PAR "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"
   }

   close $PAR;
   exec "cat" "lc_clean.par" > /dev/tty 2> /dev/tty
   exec "/home/maxim/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 \"acis.lc\"
      lines 1 1000000
      read {x1 1 y1 2}
      set x1=x1/1000

      data \"acis.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 SM
      set SM [open "|sm" 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}
}

}
