;takes stime format to time_string format, only start of day...
Function temp_stime2daystr, time_in
  mon = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', $
         'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
  mm = ['01', '02', '03', '04', '05', '06', $
        '07', '08', '09', '10', '11', '12']
  mx = strupcase(strmid(time_in, 3, 3))
  this_month = where(mon Eq mx)
  yy = strmid(time_in, 7, 4)
  dd = strmid(time_in, 0, 2)
  time_out = yy+'-'+mm[this_month]+'-'+dd+'/00:00:00'
  Return, time_out
End
;+
;NAME:
; thm_gui
;PURPOSE:
; GUI for THEMIS data analysis
;CALLING SEQUENCE:
; thm_gui
;INPUT:
; none
;OUTPUT:
; none
;HISTORY:
; Version 2.0 jmm, jimm@ssl.berkeley.edu 25-apr-2007
;             jmm, 21-may-2007, Currently Only Loads data
;             jmm, 7-jun-2007, all buttons are now defined
;$LastChangedBy$
;$LastChangedDate$
;$LastChangedRevision$
;$URL$
;-
@tplot_com                      ;this is available from the main level
Pro thm_gui_event, event
@tplot_com

  Common thm_gui_private, instr0, master

;Put a catch here to insure that the state remains defined
  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
      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
    thm_ui_update_history, event.top, [';*** FYI', ';'+err_msg]
    thm_ui_update_progress, event.top, 'Error--See history'
    thm_ui_error
    Return
  Endif

;what happened?
  widget_control, event.id, get_uval = uval
  loading = where(uval Eq instr0, nloading)
  If(nloading Gt 0) Then Begin
;disable the buttons
    widget_control, event.top, get_uval = state, /no_copy
    For j = 0, n_elements(state.button_arr)-1 Do widget_control, $
      state.button_arr[j], sensitive = 0  
    widget_control, event.top, set_uval = state, /no_copy
    thm_ui_update_progress, event.top, 'Choosing Data Quantities to Load'
    thm_ui_choose_dtype, event.top, uval 
    widget_control, event.top, get_uval = state, /no_copy
    If(ptr_valid(state.dtyp_1)) Then Begin
;Check to see if there are duplicates
      If(ptr_valid(state.dtyp)) Then Begin
        ndtyp = [*state.dtyp, *state.dtyp_1]
        ndtyp = ndtyp[sort(ndtyp)]
        ndtyp = ndtyp[uniq(ndtyp)]
        ptr_free, state.dtyp
      Endif Else ndtyp = *state.dtyp_1
      ptr_free, state.dtyp_1
      state.dtyp = ptr_new(ndtyp)
;update the history
      h1 = thm_ui_multichoice_history('dtyp = ', ndtyp)
      widget_control, event.top, set_uval = state, /no_copy
      thm_ui_update_history, event.top, h1
      thm_ui_update_progress, event.top, 'Finished Choosing Data Quantities to Load'
    Endif Else Begin
      widget_control, event.top, set_uval = state, /no_copy
      thm_ui_update_progress, event.top, 'No Data Quantities Chosen'
    Endelse
;enable the buttons
    widget_control, event.top, get_uval = state, /no_copy
    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
    Case uval Of
      'EXIT': Begin
;this is necessary because of file_retrieve's _extra=!themis
        If(obj_valid(!themis.progobj)) Then Begin
;you actually need to redefine !themis, because you cannot destroy the
;progress object
          themis_old = !themis
          themis_new = {retrieve_struct, init:1, $
                        local_data_dir:themis_old.local_data_dir, $
                        remote_data_dir:themis_old.remote_data_dir, $
                        progress: themis_old.progress, $
                        progobj: obj_new(), $ 
                        no_download:themis_old.no_download, $
                        no_update:themis_old.no_update, $
                        downloadonly:themis_old.downloadonly, $
                        verbose:themis_old.verbose}
          defsysv,'!themis', themis_new
          obj_destroy, themis_old.progobj
        Endif
        widget_control, event.top, /destroy
      End
      'LOAD':Begin
        widget_control, event.top, get_uval = state, /no_copy
        If(ptr_valid(state.dtyp)) Then dtype = *state.dtyp $
        Else If(ptr_valid(state.dtyp_pre)) Then dtype = *state.dtyp_pre $
        Else Begin
          widget_control, event.top, set_uval = state, /no_copy
          thm_ui_update_progress, event.top, 'Please Choose a data type'
          Return
        Endelse
        If(ptr_valid(state.station)) Then station = *state.station $
        Else station = '*'
        If(ptr_valid(state.astation)) Then astation = *state.astation $
        Else astation = '*'
        If(ptr_valid(state.probe)) Then probe = *state.probe $
        Else probe = ['a', 'b', 'c', 'd', 'e']
        t0 = state.st_time & t1 = state.en_time
        If(t0 Eq 0.0 Or t1 Eq 0.0) Then Begin
          widget_control, event.top, set_uval = state, /no_copy
          thm_ui_update_progress, event.top, 'Please Choose a Time Range'
          Return
        Endif
        progobj = state.progobj
        widget_control, event.top, set_uval = state, /no_copy
        h1 = 'varnames = thm_ui_load_data_fn('+ $
          ''''+time_string(t0)+''''+', '+ $
          ''''+time_string(t1)+''''+', '+ $
          'dtype=dtyp, station=station, astation=asi_station, probe=probe)'
        thm_ui_update_history, event.top, h1
        thm_ui_update_progress, event.top, 'Loading data...'
        tv_names = thm_ui_load_data_fn(t0, t1, dtype = dtype, $
                                       station = station, $
                                       astation = astation, $
                                       progobj = progobj, $
                                       probe = probe)
        If(is_string(tv_names)) Then Begin
          thm_ui_update_data_all, event.top, tv_names
;Clear out the dtype pointer, set dtyp_pre
          widget_control, event.top, get_uval = state, /no_copy
          If(ptr_valid(state.dtyp)) Then ptr_free, state.dtyp
          If(ptr_valid(state.dtyp_pre)) Then ptr_free, state.dtyp_pre
          state.dtyp_pre = ptr_new(dtype)
          widget_control, event.top, set_uval = state, /no_copy
          thm_ui_update_progress, event.top, 'Finished Loading data...'
        Endif Else Begin
          thm_ui_update_progress, event.top, 'LOAD_DATA FAILED: No Data found for requested data and time interval'
        Endelse
      End
      'CLEARLOAD': Begin
        thm_ui_update_progress, event.top, 'Choosing Active Data Sets'
        widget_control, event.top, get_uval = state, /no_copy
        If(ptr_valid(state.dtyp)) Then ptr_free, state.dtyp
        If(ptr_valid(state.dtyp_1)) Then ptr_free, state.dtyp_1
        If(ptr_valid(state.dtyp_pre)) Then ptr_free, state.dtyp_pre
        If(ptr_valid(state.probe)) Then ptr_free, state.probe
        If(ptr_valid(state.station)) Then ptr_free, state.station
        If(ptr_valid(state.astation)) Then ptr_free, state.astation
        widget_control, event.top, set_uval = state, /no_copy
        history_ext = ['dtyp = ''''', $
                       'probe = ''''', $
                       'gmag_station = ''''', $
                       'asi_station = ''''']
        thm_ui_update_history, event.top, history_ext
        thm_ui_update_progress, event.top, 'Choosing Active Data Sets'
      End
      'DATALIST':Begin
        thm_ui_update_progress, event.top, 'Choosing Active Data Sets'
        widget_control, event.top, get_uval = state, /no_copy
        pindex = widget_info(state.datalist, /list_select)
        pindex = pindex+1
        tv_names = tnames()
        newnames = tv_names[pindex-1]
        If(ptr_valid(state.active_vnames)) Then ptr_free, state.active_vnames
        state.active_vnames = ptr_new(newnames)
        history_ext = thm_ui_multichoice_history('varnames = ', newnames)
        widget_control, event.top, set_uval = state, /no_copy
        thm_ui_update_history, event.top, history_ext
        thm_ui_update_data_display, event.top, /only_active
        thm_ui_update_progress, event.top, 'Finished Choosing Active Data Sets' 
      End
      'DATASTRINP':Begin
        thm_ui_update_progress, event.top, 'Choosing Active Data Sets'
      End
      'SETDATATOSTRING':Begin
        thm_ui_update_progress, event.top, 'Choosing Active Data Sets'
        widget_control, event.top, get_uval = state, /no_copy
        dstxt = state.datastrinp
        widget_control, event.top, set_uval = state, /no_copy
        widget_control, dstxt, get_val = temp_string
        newnames = tnames(temp_string)
        If(is_string(newnames)) Then Begin
          history_ext = thm_ui_multichoice_history('varnames = ', newnames)
          thm_ui_update_history, event.top, history_ext
          widget_control, event.top, get_uval = state, /no_copy
          If(ptr_valid(state.active_vnames)) Then ptr_free, state.active_vnames
          state.active_vnames = ptr_new(newnames)
          widget_control, event.top, set_uval = state, /no_copy
          thm_ui_update_data_display, event.top, /only_active
          thm_ui_update_progress, event.top, 'Finished Choosing Active Data Sets'
        Endif Else Begin
          thm_ui_update_progress, event.top, 'Choosing Active Data Set using string failed'
        Endelse
      End
      'TR': Begin
        thm_ui_update_progress, event.top, 'Choosing Time Range'
        thm_ui_set_trange, event.top
      End
      'HELP': thm_ui_help
      'ERROR': thm_ui_error
;      'STOP': stop
      'HSAVE': Begin
        thm_ui_update_progress, event.top, 'Saving History'
        widget_control, event.top, get_uval = state, /no_copy
        hist = *state.history
        If(strcompress(strupcase(hist[0]), /remove_all) Ne 'NONE') Then Begin
          nhist = n_elements(hist)
          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)
          ofile = 'thm_gui_history_'+ttt+'.pro'
          osf = strupcase(!version.os_family)
          If(osf Eq 'WINDOWS') Then ofile = file_expand_path('')+'\'+ofile $
          Else ofile = file_expand_path('')+'/'+ofile
          openw, unit, ofile, /get_lun
          For j = 0, nhist-1 Do printf, unit, hist[j]
          printf, unit, 'End'
          free_lun, unit
          hist = [temporary(hist), ';History saved in file: '+ofile]
          ptr_free, state.history
          state.history = ptr_new(hist)
          widget_control, state.historylist, set_val = hist
          widget_control, event.top, set_uval = state, /no_copy
          thm_ui_update_progress, event.top, 'History saved in file: '+ofile
        Endif Else Begin
          widget_control, event.top, set_uval = state, /no_copy
          thm_ui_update_progress, event.top, 'No History to save'
        Endelse
      End
      'HCLR':Begin
        thm_ui_update_progress, event.top, 'Clearing History'
        widget_control, event.top, get_uval = state, /no_copy
        ptr_free, state.history
        state.history = ptr_new('NONE')
        widget_control, state.historylist, set_val = 'None'
        widget_control, event.top, set_uval = state, /no_copy
        thm_ui_update_progress, event.top, 'Finished Clearing History'
      End
      'CFG':Begin
        thm_ui_config
      End
      'CAL':Begin
;For the next four, only call a new one if there is no valid one up
        widget_control, event.top, get_uval = state, /no_copy
        cal_id = state.cal_id
        widget_control, event.top, set_uval = state, /no_copy
        If(widget_valid(cal_id)) Then widget_control, cal_id, /show $
        Else thm_ui_call_cal_data, event.top
      End
      'CTO':Begin
        widget_control, event.top, get_uval = state, /no_copy
        cto_id = state.cto_id
        widget_control, event.top, set_uval = state, /no_copy
        If(widget_valid(cto_id)) Then widget_control, cto_id, /show $
        Else thm_ui_cotrans, event.top
      End
      'PROC':Begin
        widget_control, event.top, get_uval = state, /no_copy
        proc_id = state.proc_id
        widget_control, event.top, set_uval = state, /no_copy
        If(widget_valid(proc_id)) Then widget_control, proc_id, /show $
        Else thm_ui_dproc, event.top
      End
      'PLT':Begin
        widget_control, event.top, get_uval = state, /no_copy
        plt_id = state.plt_id
        widget_control, event.top, set_uval = state, /no_copy
        If(widget_valid(plt_id)) Then widget_control, plt_id, /show $
        Else thm_ui_call_tplot, event.top
      End
      'SUMMP':Begin
        widget_control, event.top, get_uval = state, /no_copy
        summp_id = state.summp_id
        widget_control, event.top, set_uval = state, /no_copy
        If(widget_valid(summp_id)) Then widget_control, summp_id, /show $
        Else thm_ui_summplot, event.top
      End
      Else:thm_ui_update_progress, event.top, uval+' Not Implemented'
    Endcase
  Endelse
  Return
End
Pro thm_gui
@tplot_com

  Common thm_gui_private, instr0, master


  thm_init
;build master widget
  master = widget_base(/row, title = 'THEMIS Science Software Main Menu', $
                       /align_top)

;Initial start and end times
  tt0x = temp_stime2daystr(!stime)
  tt0 = time_double(tt0x)-86400.0d0
  tt1 = tt0+86400.0d0
  tt0x = time_string(tt0)
  tt1x = time_string(tt1)
;Initial history
  init_history = ['; **** Starting THM_GUI', $
                  'Master widget id'+string(master), $
                  'plot_type = ''SCREEN''']
;3 widgets in a row
  load_master = widget_base(master, /col, /align_center)
  flabel = widget_label(load_master, value = 'Data Choices')
  middle_master = widget_base(master, /col)
  flabel = widget_label(middle_master, value = 'Process/Plot Data', /align_center)
;  otp_master = widget_base(master, /col, frame = 5)
;  flabel = widget_label(otp_master, value = 'Output', /align_center)
;the middle master has 3 rows
;buttons widget on top this time
  buttons_master = widget_base(middle_master, /row, /align_center)
;lists of stuff in the middle
  lists_master = widget_base(middle_master, /row, /align_center)
;information-help-exit on the bottom
  info_master =  widget_base(middle_master, /row, /align_center)
;Ok, what goes in the widgets:
;load widget
  loadw = widget_base(load_master, /col, /align_center)
;what buttons in the load widget? All of the different types of data,
;of course:
  instr0 = ['ASI', 'ASK', 'ESA', $
           'EFI', 'FBK', 'FFT', 'FGM', $
           'FIT', 'GMAG', 'MOM', 'SCM', 'SST', 'STATE']
  ninstr0 = n_elements(instr0)
  loadbut = lonarr(ninstr0)
  For j = 0, ninstr0-1 Do $
    loadbut[j] = widget_button(loadw, val = instr0[j], uval = instr0[j])
;Separate out the load button, and time buttons
  loadx = widget_base(load_master, /col)
  timebut = widget_button(loadx, val = 'Time Range', uval = 'TR')
  loadbut_do = widget_button(loadx, val = 'Load Data', uval = 'LOAD')
  clearload = widget_button(loadx, val = 'Clear Load Queue', $
                            uval = 'CLEARLOAD')
;cal widget
;  calw = widget_base(buttons_master, /col)
;  calbut = widget_button(calw, val = 'Calibrate Data', uval = 'CAL')
;cotrans widget
  ctow = widget_base(buttons_master, /col)
  ctobut = widget_button(ctow, val = 'Coordinate Transform', uval = 'CTO')
;data procesisng widget
  procw = widget_base(buttons_master, /col)
  procbut = widget_button(procw, val = 'Data Processing', uval = 'PROC')
;plot widget
  pltw = widget_base(buttons_master, /col)
  pltbut = widget_button(pltw, val = 'Plot Data', uval = 'PLT')
;summary plot widget
  summpbut = widget_button(pltw, val = 'Overview Plot', uval = 'SUMMP')
;the middle of the middle, the lists_master holds the data_list and
;history list widgets
;  start a state array
  state_x = {datalist:0, data_id:ptr_new()}
;If there is data loaded already, you want to have it here
  thm_ui_set_data_id, state_x
  val_data = *state_x.data_id     ;you know this will work
  If(n_elements(val_data) Gt 1) Then val_data = val_data[1:*] $
  Else val_data = 'None'
  datadisp = widget_base(lists_master, /col)
  flabel = widget_label(datadisp, value = 'Loaded Data', /align_center)
  state_x.datalist = widget_list(datadisp, value = val_data, $
                                 uval = 'DATALIST', xsiz = 25, ysiz = 15, $
                                 frame = 5, /multiple)
  dstringbase = widget_base(datadisp, /row)
;  flabel = widget_label(dstringbase, val = 'String for Active Data', $
;                        /align_left)
  datastrinp = widget_text(dstringbase, value = '*', uval = 'DATASTRINP', $
                           xsiz = 15, ysiz = 1, /editable, /all_events)
  datastrbut = widget_button(dstringbase, val = 'Set Active Data to String', $
                             uval = 'SETDATATOSTRING')
;A widget the shows the Active datasets
  adatadisp = widget_base(lists_master, /col)
  flabel = widget_label(adatadisp, value = 'Active Data (Coordinates)', /align_center)
  adatalist = widget_text(adatadisp, value = 'None', xsiz = 25, ysiz = 15, $
                          /scroll, frame = 5)
;The history widget is now on the front
  historyw = widget_base(lists_master, /col)
  flabel = widget_label(historyw, value = 'History', /align_center)
  historylist = widget_text(historyw, value = init_history, xsiz = 50, $
                            ysiz = 15, $
                            /scroll, frame = 5)
  hbuttons = widget_base(historyw, /row, /align_center)
  hsavebut = widget_button(hbuttons,  val = ' Save History', uval = 'HSAVE', $
                          /align_center)
  hclearbut = widget_button(hbuttons,  val = ' Clear History', uval = 'HCLR', $
                          /align_center)

;Ok, now the bottom row of the widget
  progress_text = widget_text(info_master, value = 'Nothing is happening', $
                              xsize = 100, ysize = 1, /scroll)
;  stopbut = widget_button(info_master, value = 'STOP', uvalue = 'STOP', $
;                          /align_center)
  helpbut = widget_button(info_master, val = ' HELP ', uval = 'HELP', $
                        /align_center)
  errbut = widget_button(info_master, val = ' ERROR ', uval = 'ERROR', $
                         /align_center)
  cfgbut = widget_button(info_master, val = '  Config ', uval = 'CFG', $
                         /align_center)
  exitbut = widget_button(info_master, val = ' Exit ', uval = 'EXIT', $
                        /align_center)

;create a progress object
  progobj = obj_new('thm_ui_progobj')
  progobj -> set, gui_id = master
  If(obj_valid(!themis.progobj)) Then obj_destroy, !themis.progobj
  !themis.progobj = progobj

  button_arr = [exitbut, cfgbut, errbut, helpbut, hsavebut, hclearbut, $
                datastrbut, datastrinp, pltbut, procbut, ctobut, summpbut, $
                clearload, loadbut_do, timebut, loadbut]

  state = {wmaster:master, $    ;master widget id
           progobj:progobj, $
           datalist:state_x.datalist, $ ;datalist id
           datastrinp:datastrinp, $
           adatalist:adatalist, $
           st_time:0.0d0, $     ;start_time, double
           en_time:0.0d0, $     ;end_time
           data_id:state_x.data_id, $ ;a pointer to an array of strings, 1 for each loaded dataset
           active_vnames:ptr_new(), $ ;the tplot variable names that are active
           history:ptr_new(init_history), $ ;a string array with the analysis history
           historylist:historylist, $ ;the history list widget
           progress_text:progress_text, $ ;tells you what's happenin'
           dtyp_1:ptr_new(), $ ;the datatype from the last choose_data
           dtyp:ptr_new(), $    ;the datatype to load, must be cleared
           dtyp_pre:ptr_new(), $ ;the dtyp for the last load call,
                                ;so that you can load those types for
                                ;a different time range or probe,
                                ;without choosing dtyp's again
           probe:ptr_new(), $ ;probe_id
           station:ptr_new(), $
           astation:ptr_new(), $
           cal_id:-1l, $      ;id of the cal_data widget
           cto_id:-1l, $      ;id of the cotrans_data widget
           proc_id:-1l, $     ;id of the data process widget
           plt_id:-1l, $      ;id of the tplot widget
           summp_id:-1l, $    ;id of the summplot widget
           button_arr:button_arr} ;all of the buttond


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

Return
End