;+
;NAME:
; thm_ui_dproc
;PURPOSE:
; A widget interface for calling tplot from the themis_w widget,
; currently of limited usefulness, but expandable
;CALLING SEQUENCE:
; thm_ui_dproc, master_widget_id
;INPUT:
; master_widget_id = the id number of the widget that calls this
;OUTPUT:
; none, there are buttons to push for plotting, setting limits, not
; sure what else yet...
;HISTORY:
; 14-dec-2006, jmm, jimm@ssl.berkeley.edu
; 13-feb-2007, jmm, fixed problem with !p.background resetting in
; set_plot commands
; 12-mar-2007, jmm, Added wavelet button
; 2-apr-2007, jmm, Added pwrspc options, NEEDS TESTING.
; 5-jun-2007, jmm, rewritten
; 12-jul-2007, jmm, added a message widget, for invalid user input
;                   errors, grays out all buttons while processing
;$LastChangedBy: kenb-mac $
;$LastChangedDate: 2007-01-26 15:52:34 -0800 (Fri, 26 Jan 2007) $
;$LastChangedRevision: 241 $
;$URL: svn+ssh://thmsvn@ambrosia.ssl.berkeley.edu/repos/thmsoc/trunk/idl/themis/common/thm_ui_dproc.pro $
;
;-
Pro thm_ui_dproc_event, event

  @tplot_com
  Common tlimits_saved, t0_sav, t1_sav, t0_init, t1_init

  err_xxx = 0
  catch, err_xxx
  If(err_xxx Ne 0) Then Begin
    catch, /cancel
    help, /last_message, output = err_msg
    For j = 0, n_elements(err_msg)-1 Do print, err_msg[j]
    If(is_struct(state)) Then Begin
      widget_control, state.messw, set_val = 'Error--See history'
      cw = state.cw
      For j = 0, n_elements(state.button_arr)-1 Do widget_control, state.button_arr[j], sensitive = 1
      widget_control, event.top, set_uval = state, /no_copy
    Endif Else Begin
      widget_control, event.top, get_uval = state, /no_copy
      If(is_struct(state)) Then Begin
        widget_control, state.messw, set_val = 'Error--See history'
        cw = state.cw
        For j = 0, n_elements(state.button_arr)-1 Do widget_control, state.button_arr[j], sensitive = 1
        widget_control, event.top, set_uval = state, /no_copy
      Endif Else cw = -1
    Endelse
    If(widget_valid(cw)) Then Begin
      If(is_struct(wstate)) Then widget_control, cw, set_uval = wstate
      thm_ui_update_history, cw, [';*** FYI', ';'+err_msg]
      thm_ui_update_progress, cw, 'Error--See history'
    Endif
    thm_ui_error
    Return
  Endif

;start here
  widget_control, event.id, get_uval = uval
  If(uval Eq 'EXIT') Then Begin
    widget_control, event.top, /destroy
  Endif Else If(uval Eq 'TLIMIT') Then Begin
    widget_control, event.top, get_uval = state, /no_copy
    cw = state.cw & messw = state.messw & button_arr = state.button_arr
    widget_control, event.top, set_uval = state, /no_copy
    widget_control, cw, get_uval = wstate, /no_copy
    If(ptr_valid(wstate.active_vnames)) Then yes_vn = 1b Else yes_vn = 0b
    widget_control, cw, set_uval = wstate, /no_copy
    If(yes_vn) Then Begin
      For j = 0, n_elements(button_arr)-1 Do widget_control, button_arr[j], sensitive = 0
      widget_control, messw, set_val = ''
      thm_ui_update_progress, cw, 'Choosing Time Limits for Processing'
      thm_ui_set_tlimits, event.top
      widget_control, event.top, get_uval = state, /no_copy
      state.st_time = t0_sav & state.en_time = t1_sav
      widget_control, event.top, set_uval = state, /no_copy
      For j = 0, n_elements(button_arr)-1 Do widget_control, button_arr[j], sensitive = 1
    Endif Else Begin
      thm_ui_update_progress, cw, 'No Active Dataset, Nothing happened'
      widget_control, messw, set_val = 'No Active Dataset, Nothing happened'
    Endelse
  Endif Else If(uval Eq 'RESTORE') Then Begin
    widget_control, event.top, get_uval = state, /no_copy
    cw = state.cw & messw = state.messw & button_arr = state.button_arr
    widget_control, event.top, set_uval = state, /no_copy
    For j = 0, n_elements(button_arr)-1 Do widget_control, button_arr[j], sensitive = 0
    widget_control, messw, set_val = ''
    fff = dialog_pickfile(title = 'Choose Filename To Restore Data:', $
                          filter = '*.tplot')
    If(is_string(fff)) Then Begin
      history_ext = 'tplot_restore, filenames = '+$
        ''''+fff+''''+', /get_tvars'
      thm_ui_update_progress, cw, 'Restoring Files: '+fff
      tplot_restore, filenames = fff, /get_tvars, restored_varnames = vn_new
      history_ext = [history_ext, $
                     thm_ui_multichoice_history('varnames = ', vn_new)]
      thm_ui_update_history, cw, history_ext
      thm_ui_update_progress, cw, 'Restored Files: '+fff
      thm_ui_update_data_all, cw, vn_new
    Endif Else Begin
      widget_control, messw, set_val = 'Invalid Filename:'+fff
      thm_ui_update_progress, cw, 'Invalid Filename: '+fff
    Endelse
    For j = 0, n_elements(button_arr)-1 Do widget_control, button_arr[j], sensitive = 1
  Endif Else Begin
;Get parameters needed then put states back into widgets
    widget_control, event.top, get_uval = state, /no_copy
    cw = state.cw & messw = state.messw & button_arr = state.button_arr
    st_time = state.st_time & en_time = state.en_time
    widget_control, state.cw, get_uval = wstate, /no_copy
    If(ptr_valid(wstate.active_vnames)) Then Begin
      tvn = *wstate.active_vnames
    Endif Else tvn = ''
    widget_control, state.cw, set_uval = wstate, /no_copy
    widget_control, event.top, set_uval = state, /no_copy
    If(is_string(tvn)) Then Begin
;Grey out all but the exit button
      For j = 0, n_elements(button_arr)-1 Do widget_control, button_arr[j], sensitive = 0
      widget_control, messw, set_val = ''
;initialize new variable array
      vn_new = tvn 
      Case uval Of
;subtracts the mean and creates new variables for plotting
        'SUBAVG':Begin
;history of this is not easy...
          history_ext = ['new_vars = strarr(n_elements(varnames))', $
                         'For j = 0, n_elements(varnames) -1 Do $', $
                         '  tsub_average, varnames[j], new_name = new_varname', $
                         '  new_vars[j] = new_varname', $
                         'varnames = new_vars']
          thm_ui_update_history, cw, history_ext
          thm_ui_update_progress, cw, 'Subtracting Average Values:'
          vn_new = strarr(n_elements(tvn))
          For j = 0, n_elements(tvn)-1 Do Begin
            tsub_average, tvn[j], nvn
            If(is_string(nvn)) Then vn_new[j] = nvn Else Begin
              help, /last_message, output = err_msg
              widget_control, messw, set_val = err_msg[0]
              thm_ui_update_progress, cw, err_msg[0]
              thm_ui_update_history, cw, ';'+err_msg[0]
            Endelse
          Endfor
          thm_ui_update_progress, cw, 'Done Subtracting Average Values:'
        End
;subtracts the mean and creates new variables for plotting
        'SUBMED':Begin
          history_ext = ['new_vars = strarr(n_elements(varnames))', $
                         'For j = 0, n_elements(varnames) -1 Do $', $
                         '  tsub_average, varnames[j], new_name = new_varname, /median', $
                         '  new_vars[j] = new_varname', $
                         'varnames = new_vars']
          thm_ui_update_history, cw, history_ext
          thm_ui_update_progress, cw, 'Subtracting Median Values:'
          vn_new = strarr(n_elements(tvn))
          For j = 0, n_elements(tvn)-1 Do Begin
            tsub_average, tvn[j], nvn, /median
            If(is_string(nvn)) Then vn_new[j] = nvn Else Begin
              help, /last_message, output = err_msg
              widget_control, messw, set_val = err_msg[0]
              thm_ui_update_progress, cw, err_msg[0]
              thm_ui_update_history, cw, ';'+err_msg[0]
            Endelse
          Endfor
          thm_ui_update_progress, cw, 'Done Subtracting Median Values:'
        End
        'SMOOTH':Begin
;Get the smoothing parameter
          smooth_res = thm_ui_par('Smoothing Resolution', '11')
          smooth_res = smooth_res[0]
          smr = strcompress(smooth_res, /remove_all)
          smooth_res = long(smooth_res)
          If(smooth_res Gt 0) Then Begin
            vn_new = tvn+'_sm_'+smr
            history_ext = ['width = '+smr, $
                           'new_vars = varnames+''_sm_'+smr+'''', $
                           'For j = 0, n_elements(new_vars)-1 Do', $
                           '  tsmooth2, varnames[j], width, newname = new_vars[j]', $
                           'varnames = new_vars']
            thm_ui_update_history, cw, history_ext
            thm_ui_update_progress, cw, 'Smoothing Data:'
            For j = 0, n_elements(vn_new)-1 Do $
              tsmooth2, tvn[j], smooth_res, newname = vn_new[j]
            thm_ui_update_progress, cw, 'Done Smoothing Data:'
          Endif Else Begin
            widget_control, messw, set_val = 'Invalid Smoothing Parameter'
            thm_ui_update_progress, cw, 'Invalid Smoothing Parameter'
          Endelse
        End
        'AVG':Begin
;Get the time_resolution
          time_res = thm_ui_par('Time Resolution (sec)', '60')
          time_res = time_res[0]
          smr = strcompress(time_res, /remove_all)
          time_res = float(time_res)
          If(time_res Gt 0) Then Begin
            vn_new = tvn+'_av_'+smr
            history_ext = ['time_res = '+smr, $
                           'new_vars = varnames+''_av_'+smr+'''', $
                           'For j = 0, n_elements(new_vars)-1 Do $', $
                           ' avg_data, varnames[j], time_res, newname = new_vars[j]', $
                           'varnames = new_vars']
            thm_ui_update_history, cw, history_ext
            thm_ui_update_progress, cw, 'Averaging Data:'
            For j = 0, n_elements(vn_new)-1 Do $
              avg_data, tvn[j], time_res, newname = vn_new[j]
            thm_ui_update_progress, cw, 'Done Averaging Data:'
         Endif Else Begin
           widget_control, messw, set_val = 'Invalid Time Resolution'
           thm_ui_update_progress, cw, 'Invalid Time Resolution'
         Endelse
         End
        'DERIV':Begin
          vn_new = 'd_'+tvn
          history_ext = ['new_vars = ''d_''+varnames', $
                         'For j = 0, n_elements(new_vars)-1 Do $', $
                         ' deriv_data, varnames[j], newname = new_vars[j]', $
                         'varnames = new_vars']
          thm_ui_update_history, cw, history_ext
          thm_ui_update_progress, cw, 'Taking Time Derivative:'
          For j = 0, n_elements(vn_new)-1 Do $
            deriv_data, tvn[j], newname = vn_new[j]
          thm_ui_update_progress, cw, 'Done Taking Time Derivative:'
        End
        'SPIKE':Begin
          vn_new = tvn+'_dspk'
          history_ext = ['new_vars = varnames+''_dspk''', $
                         'For j = 0, n_elements(new_vars)-1 Do $', $
                         ' clean_spikes, varnames[j], newname = new_vars[j]', $
                         'varnames = new_vars']
          thm_ui_update_history, cw, history_ext
          thm_ui_update_progress, cw, 'Despiking Data:'
          For j = 0, n_elements(vn_new)-1 Do $
            clean_spikes, tvn[j], new_name = vn_new[j]
          thm_ui_update_progress, cw, 'Done Despiking Data:'
        End
        'CLIP':Begin
          xxx = thm_ui_par('Min and Max for clipping', ['-20.0', '20.0'])
          amin = min(float(xxx)) & amax = max(float(xxx))
          vn_new = tvn+'_clip'
          thm_ui_update_progress, cw, 'Clipping Data:'
          history_ext = ['new_vars = varnames+''_clip''', $
                         'tclip, varnames, '+xxx[0]+', '+xxx[1]+$
                         ', newname = new_vars', 'varnames = new_vars']
          thm_ui_update_history, cw, history_ext
          tclip, tvn, amin, amax, newname = vn_new
          thm_ui_update_progress, cw, 'Done Clipping Data:'
        End
        'DEFLAG':Begin
          xxx = thm_ui_par('deflag method: LINEAR (Interpolate) or REPEAT (Last Value', 'repeat')
          method = strtrim(strlowcase(xxx[0]), 2)
          If(method Eq 'linear' Or method Eq 'repeat') Then Begin
            vn_new = tvn+'_deflag'
            history_ext = ['new_vars = varnames+''_deflag''', $
                           'tdeflag, varnames, '+method+', newname = new_vars', $
                           'varnames = new_vars']
            thm_ui_update_history, cw, history_ext
            thm_ui_update_progress, cw, 'Deflagging Data:'
            tdeflag, tvn, method, newname = vn_new
            thm_ui_update_progress, cw, 'Done Deflagging Data:'
          Endif Else Begin
            widget_control, messw, set_val = 'Invalid Method Input'
            thm_ui_update_progress, cw, 'Invalid Method Input'
          Endelse
        End
;degap button
        'DEGAP':Begin
          xxx = thm_ui_par('Time Interval, Margin, max gapsize for degapping', $
                           ['1.0', '0.25', '10000'])
          dtx = double(xxx[0])
          mrx = double(xxx[1])
          maxgapx = long(xxx[2])
          If(dtx Gt 0 And mrx Ge 0 And maxgapx Gt 0) Then Begin
            xxx = strcompress(xxx, /remove_all)
            vn_new = tvn+'_degap'
            history_ext = ['new_vars = varnames+''_degap''', $
                           'tdegap, varnames, newname = new_vars, dt = '+$
                           xxx[0]+', margin = '+xxx[1]+', maxgap = '+xxx[2], $
                           'varnames = new_vars']
            thm_ui_update_history, cw, history_ext
            thm_ui_update_progress, cw, 'Degapping Data:'
            tdegap, tvn, dt = dtx, margin = mrx, maxgap = maxgapx, $
              newname = vn_new
            thm_ui_update_progress, cw, 'Done Degapping Data:'
          Endif Else Begin
            widget_control, messw, set_val = 'Invalid Parameters input:'
            thm_ui_update_progress, cw, 'Invalid Parameters input:'
          Endelse
        End
;wavelet transform?
        'WV':Begin
          history_ext = ['thm_ui_wavelet, varnames, new_vars, [start_time, end_time]',  'varnames = new_vars']
          thm_ui_update_history, cw, history_ext
          thm_ui_update_progress, cw, 'Wavelet Transform:'
          thm_ui_wavelet, tvn, vn_new, [st_time, en_time]
          thm_ui_update_progress, cw, 'Finished Wavelet Transform:'
        End
;Dynamic Power Spectrum?
        'DPWRSPC':Begin
          history_ext = ['thm_ui_pwrspec, varnames, new_vars, [start_time, end_time],/dynamic',  'varnames = new_vars']
          thm_ui_update_history, cw, history_ext
          thm_ui_update_progress, cw, 'Dynamic Power Spectrum:'
          thm_ui_pwrspc, tvn, vn_new, [st_time, en_time], /dynamic
          thm_ui_update_progress, cw, 'Finished Dynamic Power Spectrum:'
        End
        'DELETE':Begin
          history_ext = 'store_data, varnames, /delete'
          thm_ui_update_history, cw, history_ext
          thm_ui_update_progress, cw, 'Deleting Data'
          store_data, tvn, /delete
          thm_ui_update_progress, cw, 'Done Deleting Data'
          widget_control, cw, get_uval = wstate, /no_copy
          If(ptr_valid(wstate.active_vnames)) Then $
            ptr_free, wstate.active_vnames
          widget_control, cw, set_uval = wstate, /no_copy
        End
        'SAVE': Begin
          xt = time_string(systime(/sec))
          ttt = strmid(xt, 0, 4)+strmid(xt, 5, 2)+strmid(xt, 8, 2)+$
            '_'+strmid(xt,11,2)+strmid(xt,14,2)+strmid(xt,17,2)
          fff = 'themis_saved_'+ttt
          fff = dialog_pickfile(title = 'Filename For Saved Data:', $
                                filter = '*.tplot', file = fff)
          history_ext = 'tplot_save, varnames, filename = '+''''+fff+''''
          thm_ui_update_history, cw, history_ext
          thm_ui_update_progress, cw, 'Saving Data'
          tplot_save, tvn, filename = fff
          thm_ui_update_progress, cw, 'Saved Data in File: '+fff
        End
        'SAVEASCII': Begin
          history_ext = 'tplot_ascii, varnames, trange = [' + $
            ''''+time_string(st_time)+''''+', '+ $
            ''''+time_string(en_time)+''''+']'
          thm_ui_update_history, cw, history_ext
          thm_ui_update_progress, cw, 'Saving Data in Ascii files'
          tplot_ascii, tvn, trange = [st_time, en_time]
          thm_ui_update_progress, cw, 'Finished Saving Data'
        End
        'RENAME': Begin
          ntvn = n_elements(tvn)
          For j = 0, ntvn-1 Do Begin
            pj = thm_ui_par('New Name for variable:'+tvn[j], tvn[j])
            history_ext = ['store_data,'+''''+tvn[j]+''''+$
                           ', newname ='+''''+pj+'''', $
                           'store_data,'+''''+tvn[j]+''''+', /delete']
            thm_ui_update_history, cw, history_ext
            thm_ui_update_progress, cw, 'Renaming Data'
            store_data, tvn[j], newname = pj
            store_data, tvn[j], /delete
            thm_ui_update_progress, cw, 'Renamed: '+tvn[j]+' to '+pj
            vn_new[j] = pj
          Endfor
        End
      Endcase
      thm_ui_update_data_all, cw, vn_new
;Set all buttons back to active
      For j = 0, n_elements(button_arr)-1 Do widget_control, button_arr[j], sensitive = 1
    Endif Else Begin
      widget_control, messw, set_val = 'No Active Dataset, Nothing happened'
      thm_ui_update_progress, cw, 'No Active Dataset, Nothing happened'
    Endelse
    widget_control, event.top, set_uval = state, /no_copy
  Endelse

  Return
End

Pro thm_ui_dproc, gui_id


;build master widget
  master = widget_base(/row, title = 'THEMIS Science Software: Data Processing ', $
                             scr_xsize = 330, group_leader = gui_id)
;button widgets
  buttons = widget_base(master, /col, /align_left, frame = 5)
  buttons1 = widget_base(master, /col, /align_left, frame = 5)

;average subtraction button
  subavgbut = widget_button(buttons, val = ' Subtract Average', $
                            uval = 'SUBAVG', scr_xsize = 120)
;median subtraction button
  submedbut = widget_button(buttons, val = ' Subtract Median', $
                            uval = 'SUBMED', scr_xsize = 120)
;tsmooth2 button
  smoothbut = widget_button(buttons, val = ' Smooth Data', uval = 'SMOOTH', $
                            scr_xsize = 120)
;average button
  avgbut = widget_button(buttons, val = ' Time Average', uval = 'AVG', $
                         scr_xsize = 120)
;clip button
  clipbut = widget_button(buttons, val = ' Clip', uval = 'CLIP', $
                         scr_xsize = 120)
;dflag button
  deflagbut = widget_button(buttons, val = ' Deflag', uval = 'DEFLAG', $
                            scr_xsize = 120)
;degap button
  degapbut = widget_button(buttons, val = ' Degap', uval = 'DEGAP', $
                         scr_xsize = 120)
;dspike button
  spikebut = widget_button(buttons, val = ' Clean Spikes', uval = 'SPIKE', $
                         scr_xsize = 120)
;deriv button
  derivbut = widget_button(buttons, val = ' Time Derivative', uval = 'DERIV', $
                         scr_xsize = 120)
;wavelet button
  wavebut = widget_button(buttons, val = ' Wavelet Transform', uval = 'WV', $
                         scr_xsize = 120)
;power_spectrum button
;  pwrbut = widget_button(buttons, val = ' Power Spectrum', uval = 'PWRSPC', $
;                         scr_xsize = 120)
;dynamic power_spectrum button
  dpwrbut = widget_button(buttons, val = ' Dpwrspec', $
                          uval = 'DPWRSPC', scr_xsize = 120)


;tlimit button
  tlimitbut = widget_button(buttons1, val = ' Time limits ', $
                            uval = 'TLIMIT', /align_center)

;rename button
  renamebut = widget_button(buttons1, val = ' Rename ', uval = 'RENAME', $
                          scr_xsize = 120)
;save button
  savebut = widget_button(buttons1, val = ' Save ', uval = 'SAVE', $
                          scr_xsize = 120)
;restore button
  restorebut = widget_button(buttons1, val = ' Restore ', uval = 'RESTORE', $
                          scr_xsize = 120)
;save ascii button
  asavebut = widget_button(buttons1, val = ' Save Ascii ', uval = 'SAVEASCII', $
                          scr_xsize = 120)
;delete button
  deletebut = widget_button(buttons1, val = ' Delete ', uval = 'DELETE', $
                            scr_xsize = 120)
;exit button
  exitbut = widget_button(buttons1, val = ' Close ', uval = 'EXIT', $
                          scr_xsize = 120)

;message widget
  messw = widget_text(buttons1, value = '', xsize = 20, ysize = 5, /wrap, /scroll)

  cw = gui_id 
  widget_control, cw, get_uval = wstate, /no_copy
  wstate.proc_id = master
  t0 = wstate.st_time & t1 = wstate.en_time
  widget_control, cw, set_uval = wstate, /no_copy

; State structure
  state = {master:master, cw:cw, st_time:t0, en_time:t1, messw:messw, $
           button_arr:[subavgbut, submedbut, smoothbut, avgbut, clipbut, $
                       deflagbut, degapbut, spikebut, derivbut, wavebut, $
                       dpwrbut, tlimitbut, renamebut, savebut, restorebut, $
                       asavebut, deletebut, exitbut]}

  widget_control, master, set_uval = state, /no_copy
  widget_control, master, /realize
  xmanager, 'thm_ui_dproc', master, /no_block

  Return
End