;+
; NAME:
;       XCONTROL
; PURPOSE:
;	XCONTROL is the main QL control window. After selecting a file (CCSDS or
;	FITS) this windows opens with information about the data, and control 
;	buttons etc. for the various display methods and data processing 
;	options available for a particular set of data.
;
; CATEGORY:
;       Hansteen/Wikstøl Data analysis SW
;
; CALLING SEQUENCE:
;       xcontrol, data, hdr, auxobj, group_leader = group, $
;                 filename = filename
;
; INPUTS:
;	data: data object of type 'eis_data'
;	hdr: hdr object associated with data object
;	auxobj: auxiliary object associated with data object
;
; KEYWORD PARAMETERS:
;	group_leader: Widget ID of parent widget
;	filename: 
; OUTPUTS:
;
; CALLS:
;	XDETECTOR
;	XRASTER
;	XWHISKER
;	XMAP
;	XCAL
;	Uses methods for objects of type 'eis_data', 'eis_hdr', 'fits_hdr', 
;         'eis_aux', 'eis_moment'
;
; COMMON BLOCKS:
;
; PROCEDURE:
;
; RESTRICTIONS:
;
; MODIFICATION HISTORY:
;       Jul-2002: First version started by Øivind Wikstøl
;       May-2005: Documented and cleaned up after many revisions.
;       Sep-2007: AG: Improved Cleanup. Set image device to Pixmap. Some
;                 modification already made in Jun-2007.
;     6-Nov-2007: AG: Set the eis_prep button to sensitive, and the dc_file 
;                 to default. 
;     9-Nov-2007: AG: Set group_leader in the call of xcaldef. 
;    20-Nov-2007: AG: Addition of dusty pixels in calibration.
;     3-Dec-2007: AG: Freed moment heap variable in cleanup.
;     4-Jan-2008: AG: Set lineselect_a (b) to dummy if not defined.
;     8-Jan-2008: AG: Commented "ff" references.
;    12-Feb-2008: AG: Disabled eis_prep on non level 0 files.
;    15-Feb-2008: AG: Added the Gaussian fit to the moments computation.
;    18-Mar-2007: AG: Added check on line_mask.
;     1-Apr-2008: AG: Uploaded the warm pixels option in calibration.
;                     Already added on 20-Feb-2008.
;     3-Apr-2008: AG: Set the save button to sensitive.
;     4-Apr-2008: AG: Bug fixed.
;    20-May-2008: AG: Added check on moments if retained values are set.
;     2-Jul-2008: AG: Added check on buttons if observations are missing.
;     7-Jul-2008: AG: Added groupl to plot buttons.
;    11-Jul-2008: AG: Added group_leader to eis_moment. Check on info ptr 
;                     if xcontrol closes during xmoment.
;    30-Apr-2009: AG: Fixed 1 pixel error shift.
;    18-Jun-2011: VHH: Invoke options hkwwave_corr and
;                      correct_sensitivity in call to eis_prep.
;
; $Id: xcontrol.pro,v 1.35 2009/04/30 08:58:40 gardini Exp $
;-
;
; Start XControl:
;

; xcontrol close:
pro xcontrol_destroy, event
  widget_control, event.top, get_uvalue = info
  if not (*info).savestat then begin
    answer = dialog_message('Do you want to save calibrated data?', /question)
    case answer of
      'Yes': begin
        pseudoevent={widget_button,id:0L, $
                     top:event.top, handler:0l, select:1}
          xcontrol_save, pseudoevent
          widget_control, event.top,/destroy
       end
       'No': begin
         widget_control, event.top,/destroy
       end
    endcase
  endif else begin
    widget_control, event.top,/destroy
  endelse
end

; xcontrol cleanup
pro xcontrol_cleanup, tlb
   widget_control, tlb, get_uvalue = info
   heap_free,(*info).moment
   heap_free,(*info).auxobj 
   heap_free,(*info).data
   heap_free, info 
end

; put information about data set in string array
pro xcontrol_get_data_info, info
  ; cr = carriage return
  case !version.os of
    'MacOS': cr=string(13b)
    'Win32': cr=string(13b)+string(10b)
    else: cr=string(10b)
  endcase  
  textdump = ''
  line=strarr(256)
  line[0] = 'Data information'
  line[1] = 'Observation mode: '+strtrim((*info).obsmode, 2)
  line[2] = '========================================================'
  line[3] = 'Number of exposures       : '+strtrim((*info).nexp,2)
  line[4] = 'Exposures pr. raster pos. : '+strtrim((*info).nexp_prp,2)
  line[5] = 'Number of raster positions: '+strtrim((*info).nraster,2)
  line[6] = 'Number of slit positions  : '+strtrim((*info).nslit, 2)
  line[7] = 'Number of line windows    : '+strtrim((*info).nwin, 2)
  line[8] = 'Line ID     Wavelength (Å/pix)  Line window width (pixels)'
  line[9] = '========================================================'
  j = 10
  for i = 0, (*info).nwin-1 do begin
    lineid = strtrim((*info).line_id[i], 2)
    wvl = strtrim(string((*info).line_wvl[i]), 2)
    npx = strtrim(string((*info).line_npx[i]),2)

    newline='                                                           '
    strput, newline, lineid, 0
    strput, newline, wvl, 18
    strput, newline, npx, 35
    line[i+j] = newline
  endfor

  (*info).data_textdump = strjoin(line[0:j+i],cr)

end

; Display Header in text window
pro xcontrol_hdrdisp,event
  widget_control, event.top ,get_uvalue = info
  ; open text widget window to dump bytes in
  hdr_widget = widget_base(title = 'Header Contents',  $
                group_leader = (*info).tlb,/row)

  closefield = widget_base(hdr_widget,/column)
  closebutton = widget_button(closefield, value = 'Close', $
                              event_pro = 'xcontrol_hdrdisp_destroy')

  ysz = 60.*n_elements((*info).hdr)
  disp_base = widget_base(hdr_widget,/column)
  disp_field = widget_text(disp_base, group_leader = (*info).tlb, /scroll, $
  xs=100, ysize = 50)

  textall=''

  for i=0, n_elements((*info).hdr)-1 do begin
    ((*info).hdr)[i]->display,textdump
    textall=textall+textdump
  endfor

  widget_control, disp_field, set_value = textall,/append
  widget_control, hdr_widget, /realize

  xmanager, 'Display Header Contents', hdr_widget, /no_block, $
             group_leader = (*info).tlb
end

; close Header Display
pro xcontrol_hdrdisp_destroy, event
 widget_control, event.top,/destroy
end

; Popup window for controlling EIS average spectrum vs synthetic spectrum
pro xcontrol_synspec, event
  widget_control, event.top ,get_uvalue = info
  ; open window for synthetic spectrum parametrer selection
  synspec_top = widget_base(title = 'EIS vs Chianti', $
                group_leader = (*info).tlb,/row)
  closefield = widget_base(synspec_top,/column)
  launchbutton = widget_button(closefield, value = 'OK', $
                              event_pro = 'xcontrol_synspec_launch')
  cancelbutton = widget_button(closefield, value = 'cancel', $
                              event_pro = 'xcontrol_synspec_cancel')

 if (*info).ccd_a[0] ge 0 and (*info).ccd_b[0] ge 0 then begin
    detlist=['Det A', 'Det B']
    det_base = widget_base(synspec_top,/column,/frame)
    det_title = 'Select detector'
    det_list = cw_bgroup(det_base, detlist, /return_index, $
                         label_top = det_title,/nonexclusive, $
                         event_func = 'xcontrol_synspec_det')
  endif
    emm_base = widget_base(synspec_top,/column,/frame)
    emm_title = 'Select emission measure'
    emmlist = ['Quiet Sun', 'Active region', 'Flare']
    emm_list = cw_bgroup(emm_base, emmlist, /return_index, $
                         label_top = emm_title,/exclusive, $
                         event_func = 'xcontrol_synspec_emm')
  widget_control, synspec_top, set_uvalue = info
  widget_control, synspec_top, /realize
  xmanager, 'Select line', synspec_top, $
             /no_block, group_leader = (*info).tlb
end

; get the value of the detector selection
function xcontrol_synspec_det, event
  widget_control, event.top, get_uvalue = info
  if event.value eq 0 then begin
    (*info).deta = 1
    (*info).detb = 0
  endif
  if event.value eq 1 then begin
    (*info).detb = 1
    (*info).deta = 0
  endif
  return, 0
end

; get the value of the emission measure selection
function xcontrol_synspec_emm, event
  widget_control, event.top, get_uvalue = info
  if event.value eq 0 then (*info).emm = 'QS'
  if event.value eq 1 then (*info).emm = 'AR'
  if event.value eq 1 then (*info).emm = 'FL'
  return, 0
end

; close synthetic spectrum parameter selection window and launch xsynspec
pro xcontrol_synspec_launch, event
  widget_control, event.top, get_uvalue = info
  if (*info).deta then $ 
    xsynspec, (*info).data, det = 'A', emm = (*info).emm
  if (*info).detb then $
    xsynspec, (*info).data, det = 'B', emm = (*info).emm
  widget_control, event.top,/destroy
end

; close synthetic spectrum parameter selection window with no action
pro xcontrol_synspec_cancel, event
  widget_control, event.top,/destroy
end

function xcontrol_lineselect_a, event
  widget_control, event.top, get_uvalue = info
  widget_control, (*info).lineselect_a, get_value = lineselect
  (*info).lines[where((*info).line_mask eq 0)] = lineselect
  return,0
end

function xcontrol_lineselect_b, event
  widget_control, event.top, get_uvalue = info
  aux_data=(*info).data->getaux_data()
  widget_control, (*info).lineselect_b, get_value = lineselect
  (*info).lines[where((*info).line_mask)] = lineselect
  return, 0
end

pro xcontrol_xpos, event
  widget_control, event.top, get_uvalue = info
  aux_data=(*info).data->getaux_data()
  xpos=(*info).data->getxpos()
  time=(*info).data->sec_from_obs_start(*(aux_data).ti_1)
  oktime=(*info).data->check_ti()
  time=time[where(oktime ne 0)]
  xpos=xpos[where(oktime ne 0)]
  xlineplot,xpos,xscale=time,xtit='ti_1 since obs start [s]',ytitle='Xpos [arc sec]',groupl=(*info).tlb
end

pro xcontrol_xcen, event
  widget_control, event.top, get_uvalue = info
  aux_data=(*info).data->getaux_data()
  xcen=(*info).data->getxcen()
  time=(*info).data->sec_from_obs_start(*(aux_data).ti_1)
  oktime=(*info).data->check_ti()
  time=time[where(oktime ne 0)]
  xcen=xcen[where(oktime ne 0)]
  xlineplot,xcen,xscale=time,xtit='ti_1 since obs start [s]',ytitle='Xcen [arc sec]',groupl=(*info).tlb
end

pro xcontrol_ycen, event
  widget_control, event.top, get_uvalue = info
  aux_data=(*info).data->getaux_data()
  ycen=(*info).data->getycen()
  time=(*info).data->sec_from_obs_start(*(aux_data).ti_1)
  oktime=(*info).data->check_ti()
  time=time[where(oktime ne 0)]
  ycen=ycen[where(oktime ne 0)]
  xlineplot,ycen,xscale=time,xtit='ti_1 since obs start [s]',ytitle='Ycen [arc sec]',groupl=(*info).tlb
end

pro xcontrol_xycen, event
  widget_control, event.top, get_uvalue = info
  xcen=(*info).data->getxcen()
  ycen=(*info).data->getycen()
  oktime=(*info).data->check_ti()
  xcen=xcen[where(oktime ne 0)]
  ycen=ycen[where(oktime ne 0)]
  xlineplot,ycen,xscale=xcen,xtit='Xcen [arc sec]',ytitle='Ycen [arc sec]',groupl=(*info).tlb
end

pro xcontrol_ccda, event
  widget_control, event.top, get_uvalue = info
  aux_data=(*info).data->getaux_data()
  ccda_temp=*(aux_data).ccda_temp
  time=(*info).data->sec_from_obs_start(*(aux_data).ti_1)
  oktime=(*info).data->check_ti()
  time=time[where(oktime ne 0)]
  ccda_temp=ccda_temp[where(oktime ne 0)]
  xlineplot,ccda_temp,xscale=time,xtit='ti_1 since obs start [s]',ytitle='CCDA Temp [K]',groupl=(*info).tlb
end

pro xcontrol_ccdb, event
  widget_control, event.top, get_uvalue = info
  aux_data=(*info).data->getaux_data()
  ccdb_temp=*(aux_data).ccdb_temp
  time=(*info).data->sec_from_obs_start(*(aux_data).ti_1)
  oktime=(*info).data->check_ti()
  time=time[where(oktime ne 0)]
  ccdb_temp=ccdb_temp[where(oktime ne 0)]
  xlineplot,ccdb_temp,xscale=time,xtit='ti_1 since obs start [s]',ytitle='CCDB Temp [K]',groupl=(*info).tlb
end

function xcontrol_dispselect, event
  widget_control, event.top, get_uvalue = info
  displaymode = event.value

  ; displaymode=0: "Line raster display".
  ;                 This is line profiles as a function of slit position
  ;                 at all raster positions or time (for "sit and stare"
  ;                 studies. Several lines may be displayed in the same
  ;                 window.
  ;
  ; displaymode=1: "Raster Browser" Peter Young's browser
  ;
  ; displaymode=2:  "Line profile evolution". This is line profiles as a
  ;                  function of raster position (or time for "sit and stare"
  ;                  studies) at one slit position. Only one line window in
  ;                  one display window. Slit position can be set and changed
  ;                  in the display widget.
  ;
  ; displaymode=3:  "Intensity map". This is counts/intensity as a function
  ;                  of solar y (slit position) and solar x (for rasters) or
  ;                  time (for "sit and stare".) Intensities are obtained by
  ;                  calculating 0th order intensity moment of the line
  ;                  profile. Only one line map in each window, but lines
  ;                  can be set and changed also within the widget.
  ;
  ; displaymode=4:  "Detector view". This displays the detector by showing
  ;                  all lines as a function of wavelength an slit position.
  ;                  Raster position or time is set, and can be changed in
  ;                  the display widget.
  ;

  warning = 'At least one line must be selected'
  case displaymode of
  0: begin
       for i = 0, (*info).nccd-1 do begin
         if i eq 0 then indx = (*info).ccd_b else indx = (*info).ccd_a
         if indx[0] lt 0 then goto, continue
         xdetector, (*info).data, (*info).hdr, (*info).auxobj, $
                    indx, group_leader = (*info).tlb
         continue:
       endfor
     end
  1: begin
         eis_raster_browser,(*info).data
     end
  2: begin
       lindx = where((*info).lines eq 1)
       if lindx[0] eq -1 then begin
         ok = dialog_message(warning,/center)
         return, 0
       endif   
       xraster, (*info).data, (*info).hdr, (*info).auxobj, lindx, $
                 group_leader = (*info).tlb
     end
  3: begin
       lindx = where((*info).lines eq 1)
       if lindx[0] eq -1 then begin
         ok = dialog_message(warning,/center)
         return, 0
       endif
       for i = 0, n_elements(lindx)-1 do $
       xwhisker, (*info).data, (*info).hdr, (*info).auxobj, lindx[i], $
                 group_leader = (*info).tlb
     end
  4: begin
       lindx = where((*info).lines eq 1)
       if lindx[0] eq -1 then begin
         ok = dialog_message(warning,/center)
         return, 0
       endif
       for i = 0, n_elements(lindx)-1 do $
       xmap, (*info).data, (*info).hdr, (*info).auxobj, $
             linelist = lindx[i], group_leader = (*info).tlb
     end
  endcase
;  widget_control, (*info).dispselect, set_value = [0, 0, 0, 0]
  return,0
end

pro xcontrol_listmoments, event
  widget_control, event.top, get_uvalue = info
  thisevent=tag_names(event,/structure_name)
  case thisevent of
    'WIDGET_DROPLIST': begin
      mode = event.index
      end
      else:
  endcase
  case mode of
    0: begin
         return
       end
    1: begin
         xcontrol_moments, 'moment', event
       end
    2: begin
         xcontrol_moments, 'gauss', event
       end
    else: print,'xcontrol_listmoments: Impossible mode!!'
  endcase
end

; calculate moments
pro xcontrol_moments, fit, event
  widget_control, event.top, get_uvalue = info
  
  calstat=(*info).data->getcalstat()
  if calstat.retain then begin
    ok = dialog_message('Pixels less than 0 retained. Moment computation not allowed.', /information,/center)
    return
  endif 

  lindx = where((*info).lines eq 1)     ; index of selected lines
  if lindx[0] lt 0 then begin
    ok = dialog_message('Please select at least 1 line', /information,/center)
    return
  endif
  nindx = n_elements(lindx)  ; number of lines selected
  nwin = (*info).nwin        ; number of lines in data object (total)
; fit = 'moment'
  ; all lines
  if nindx eq nwin then $
    moment = obj_new('eis_moment', (*info).data, fit = fit, group_leader = (*info).tlb ) $
  else $
    moment = obj_new('eis_moment', (*info).data, iwin = lindx, fit = fit, group_leader = (*info).tlb )
  if not(ptr_valid(info)) then return ; if the xcontrol window closes
  (*info).moment = ptr_new(moment)

  ; launch xmap to display moments:
   xmap, *(*info).moment, (*info).hdr, (*info).auxobj, linelist = lindx, $
           group_leader = (*info).tlb   
  return
end

; save moments
pro xcontrol_save_mom, event
  widget_control, event.top, get_uvalue = info
  mode = event.index
  dirsep = (*info).dirsep
  HOME=getenv('HOME')
  case mode of
    0: begin
       ; save as fits
       fitsdir = HOME+dirsep+'data'+dirsep+'fits'+dirsep
       fitsfile = dialog_pickfile(path=fitsdir, /write, $
                                  title='Select FITS file name', $
                                  dialog_parent = (*info).tlb)
       if fitsfile eq '' then return
       eis_mkfits, *(*info).moment, (*info).hdr, fitsfile = fitsfile
       end
    1: begin
         savesetdir = HOME+dirsep+'data'+dirsep+'saveset'+dirsep
         deffile = 'saveset.idl'
         savesetfile = dialog_pickfile(path=savesetdir, /write, $
                       title='Select IDL Saveset Name', file = deffile, $
                                  dialog_parent = (*info).tlb)
         save, *(*info).moment, (*info).hdr, file = savesetfile
       end
    else:
  endcase
end


; start calibration dialogue:
pro xcontrol_cal, event
  widget_control, event.top, get_uvalue = info
;  xcal, (*info).data, group_leader = (*info).tlb
;  ok=dialog_message('A panel to calibration options appear here!',/info,/center)
  xcaldef,event,group_leader = (*info).tlb   
; widget_control,(*info).despikebutton,sensitive=1
  return
end

; eis prep
pro xcontrol_eis_prep, event
  widget_control, event.top, get_uvalue = info
  widget_control, /hourglass
  if (*info).calinfo.calstat[1] then nohp=0 else nohp=1
  if (*info).calinfo.calstat[2] then nowp=0 else nowp=1
  if (*info).calinfo.calstat[3] then nodp=0 else nodp=1
  if (*info).calinfo.calstat[4] then nocr=0 else nocr=1
  if (*info).calinfo.calstat[5] then noabs=0 else noabs=1
; if (*info).calinfo.calstat[5] then noff=0 else noff=1
  dc_file=(*info).calinfo.dirs.dc_dir+(*info).calinfo.dirs.dc_file
; ff_file=(*info).calinfo.dirs.ff_dir+(*info).calinfo.dirs.ff_file
  if (*info).calinfo.dirs.dc_file eq '        None chosen        ' then begin
    eis_prep,(*info).data,nohp=nohp,nowp=nowp,nodp=nodp,nocr=nocr,noabs=noabs,/def, $
         /hkwavecorr,/correct_sensitivity
  endif else begin
    eis_prep,(*info).data,dc_file=dc_file,nohp=nohp,nowp=nowp,nodp=nodp,nocr=nocr,noabs=noabs, $
         /hkwavecorr,/correct_sensitivity
  endelse
  calstat=(*info).data->getcalstat()
  if calstat.dc then widget_control,(*info).info_dc_label,set_value='DC'
  if calstat.hp then widget_control,(*info).info_hp_label,set_value='HP'
  if calstat.wp then widget_control,(*info).info_wp_label,set_value='WP'
  if calstat.dp then widget_control,(*info).info_dp_label,set_value='DP'
  if calstat.cr then widget_control,(*info).info_cr_label,set_value='CR'
  if calstat.abs then widget_control,(*info).info_abs_label,set_value='ABS'
  if calstat.sens then widget_control,(*info).info_sens_label,set_value='SENS'
; if calstat.ff then widget_control,(*info).info_ff_label,set_value='FF'
  (*info).savestat=0
  widget_control,(*info).info_save_label,set_value='NOT Saved'
  widget_control,(*info).savebutton,sensitive=1
  return
end  

; save data object
pro xcontrol_save, event
  widget_control, event.top, get_uvalue = info
  widget_control, /hourglass
  file=(*info).data->getfilename()
  strput,file,'l1',stregex(file,'_l._')+1
  file=stregex(file,'^.*.fits',/extract)
  (*info).data->save,file=file
  errfile=(*info).data->getfilename()
  strput,errfile,'er',stregex(errfile,'_l._')+1
  errfile=stregex(errfile,'^.*.fits',/extract)
  (*info).data->saveerr,file=errfile
  (*info).savestat=1
  widget_control,(*info).info_save_label,set_value='Saved    '
  return
end

;-----------------------------------------------------------------------------
; start main program
;-----------------------------------------------------------------------------

pro xcontrol, data, hdr, auxobj, group_leader = group, filename = filename

  if n_params() lt 3 then begin
    message, $
      'XControl: A data object, header object and aux object must be given',$
       /cont
    return
  endif

  if n_elements(filename) eq 0 then filename=' '

  dirsep=get_delim()
  ; information about data set
  nwin = data->getnwin()         ; number of line windows
  nraster = data->getnraster()   ; number of raster positions
  nexp = data->getnexp()         ; number of exposures
  nexp_prp = data->getnexp_prp() ; number of exposures pr. raster pos.
  ntime = data-> getntime()      ; number of time steps (for time series data)
  nslit = data-> getyw()         ; nr of slit positions (same for all lines)
  line_npx = (data-> getxw())[0:nwin-1]
  id = hdr[0]-> getline_id()
  line_id = strarr(nwin) 
  line_id = id[0:nwin-1]
  line_mask = intarr(nwin)
  obsmode = data->getobsmode()
  
  dirs={dc_dir:getenv('EIS_CAL_DATA')+dirsep+'dc'+dirsep, $
;       ff_dir:getenv('EIS_CAL_DATA')+dirsep+'ff'+dirsep, $
;       ff_file:'        None chosen        ' $
	dc_file:'        None chosen        '}
; calinfo={calstat_id:['dc','cr','hp','ff','abs'],calstat:intarr(5),dirs:dirs}
  calinfo={calstat_id:['dc','hp','wp','dp','cr','abs'],calstat:[1,1,1,1,1,1],dirs:dirs}
  
  deticon=fltarr(data->getccd_sz())
  for i=0,nwin-1 do begin
    data->getwin, i, wd, pos
    deticon[pos[0]:pos[0]+pos[1]-1,pos[2]:pos[2]+pos[3]-1] = wd[*, *, 0]
  endfor

  ; get information about which side of the detector the 
  ; lines are on:
  datasource = data-> getdatasource()
  nccd = hdr[0]-> getnccd()


  if datasource eq 'fits' then begin
    ccd = hdr[0]-> getccd_nr()
    ccd = ccd[0:nwin-1]
    ; line window information
    wvl = hdr[0]-> getline_wvl()
    line_wvl = wvl[0:nwin-1]
    index=where(line_wvl gt 240.,ct)
    if ct gt 0 then line_mask[where(line_wvl gt 240.)]=1
  endif 

  if datasource eq 'ccsds' then begin
    ; get exposure information from EIS header
    exp_info = hdr[0] ->getexp_info()  
    ccd = exp_info.ccd_nr[0:nwin-1]
    line_wvl = (data-> getxs())[0:nwin-1]
    index=where(line_wvl le 2147,ct)
    if ct gt 0 then line_mask[where(line_wvl le 2147)]=1
  endif

  ccd_b = where(ccd ge 2) ; indexes of lines on CCD B (short wavel. reg.)
  ccd_a = where(ccd le 1) ; indexes of lines on CCD A (long  wavel. reg.)
  
  ; top level base widget:
  tlb = widget_base(/row, mbar=menubar, $
		  title='XControl - '+auxobj->gettitle(), $
		  xoffset=50, yoffset=50)

  lcol = widget_base(tlb, /frame, /column)      ;left column.
  rcol = widget_base(tlb, /frame, /column)      ;right column.

  ; create menu bar:
  filemenu=widget_button(menubar, value='File',/menu, uvalue='file')
  closemenu=widget_button(filemenu, value='Close', $
			 event_pro='xcontrol_destroy')

  optmenu=widget_button(menubar, value='Options',/menu, uvalue='Options')
  hdrdispmenu=widget_button(optmenu, value='Display header', $
			    event_pro='xcontrol_hdrdisp')
  synspecmenu=widget_button(optmenu, value = 'Compare EIS/Chianti spectra', $
			      event_pro = 'xcontrol_synspec')

  ; Select Line window(s)
  lineselect_base = widget_base(lcol, /column, /frame)
  lineselect_row = widget_base(lineselect_base, /row)

  ; data source label field
  lineselect_label = widget_base(lineselect_base, /row)
  title = 'Select Line window(s)'    ; line select label string
  lslabel = widget_label(lineselect_label, value=title)

  index = where(line_mask eq 0,ct)
  if ct gt 0 then begin
    line_id_a=line_id[index]
    lineselect_a = cw_bgroup(lineselect_row, /nonexclusive, $
			   line_id_a, event_func = 'xcontrol_lineselect_a')
  endif else lineselect_a = strarr(1)
  index = where(line_mask,ct)
  if ct gt 0 then begin
    line_id_b=line_id[index]
    lineselect_b = cw_bgroup(lineselect_row, /nonexclusive, $
			   line_id_b, event_func = 'xcontrol_lineselect_b')
  endif else lineselect_b = strarr(1)

  ; Select display mode
  dispselect_base = widget_base(lcol, /column, /frame)

  ; Select display mode label field
  dispselect_label = widget_base(dispselect_base, /row)
  title = 'Select display mode'    ; display mode select label string
  dslabel = widget_label(dispselect_label, value=title)

  modes = (auxobj-> getmenu()).mode[0:(auxobj-> getmenu()).nmode-1]
  if nexp le 1 then modes = modes[0:2]
  dispselect = cw_bgroup(dispselect_label, row = 5, $
			 modes,  event_func = 'xcontrol_dispselect')
  ; Text field to display data information
  disp_base = widget_base(rcol, /row)
  data_info = widget_text(disp_base, xs=60, ys=20,/scroll)
  
  eis_icon_base=widget_base(rcol,/col)
  eis_icon                   = widget_draw(eis_icon_base  ,             $
				retain = 2, $ 
				XSize       = 400,                      $
				YSize       = 400/4.,                      $
				frame       = 1)  
  pos_base=widget_base(rcol,/row)
  
  xpos_base=widget_base(pos_base,/col)
  xposbutton = widget_button(xpos_base, value = 'Xpos', $
			    event_pro = 'xcontrol_xpos')
			    
  xycen_base=widget_base(pos_base,/col)  
  xycenbutton = widget_button(xycen_base, value = 'XYcen', $
			     event_pro = 'xcontrol_xycen')
  
  xcen_base=widget_base(pos_base,/col)  
  xcenbutton = widget_button(xcen_base, value = 'Xcen', $
			    event_pro = 'xcontrol_xcen')
  
  ycen_base = widget_base(pos_base,/col)
  ycenbutton = widget_button(ycen_base, value = 'Ycen', $
			    event_pro = 'xcontrol_ycen')
			    
  ccda_base = widget_base(pos_base,/col)
  ccdabutton = widget_button(ccda_base, value = 'CCDA Temp', $
			    event_pro = 'xcontrol_ccda')
			    
  ccdb_base = widget_base(pos_base,/col)  
  ccdbbutton = widget_button(ccdb_base, value = 'CCDB Temp', $
			    event_pro = 'xcontrol_ccdb')
			    
  calc_xysize,200,200,xs,ys,nxchar=4,nychar=4
  
  pointing_base=widget_base(rcol,/row)  
  pointing_icon= widget_draw(pointing_base  ,             $
				retain = 2, $ 
				XSize       = 200,                      $
				YSize       = 200,                      $
				frame       = 1)  
				
  if datasource eq 'fits' then begin
  
    calstat=data->getinfo('CALSTAT')
    info_base=widget_base(pointing_base,/col)

    if strpos(calstat,'DC') ne -1 then begin
      dc='DC' 
      data->setcalstat,dc,1
    endif else dc='RAW'
    info_dc_label = widget_label(info_base, value=dc)

    if strpos(calstat,'HP') ne -1 then begin
      hp='HP'
      data->setcalstat,hp,1
    endif else hp='  '
    info_hp_label = widget_label(info_base, value=hp)

    if strpos(calstat,'WP') ne -1 then begin
      wp='WP'
      data->setcalstat,wp,1
    endif else wp='  '
    info_wp_label = widget_label(info_base, value=wp)

    if strpos(calstat,'DP') ne -1 then begin
      dp='DP'
      data->setcalstat,dp,1
    endif else dp='  '
    info_dp_label = widget_label(info_base, value=dp)
 
    if strpos(calstat,'CR') ne -1 then begin
      cr='CR'
      data->setcalstat,cr,1
    endif else cr='  '
    info_cr_label = widget_label(info_base, value=cr)

;   if strpos(calstat,'FF') ne -1 then begin
;     ff='FF'
;     data->setcalstat,ff,1
;   endif else ff='  '
;   info_ff_label = widget_label(info_base, value=ff)
 
    if strpos(calstat,'ABS') ne -1 then begin
      abs='ABS'
      data->setcalstat,abs,1
    endif else abs='   '
    info_abs_label = widget_label(info_base, value=abs)
 
    if strpos(calstat,'SENS') ne -1 then begin
      sens='SENS'
      data->setcalstat,sens,1
    endif else sens='   '
    info_sens_label = widget_label(info_base, value=sens)

    info_save_label = widget_label(info_base, value='Saved    ')
	
  endif else begin
    info_base=widget_base(pointing_base,/col)
    info_dc_label = widget_label(info_base, value='  ')	
    info_hp_label = widget_label(info_base, value='  ')
    info_wp_label = widget_label(info_base, value='  ')
    info_dp_label = widget_label(info_base, value='  ')
    info_cr_label = widget_label(info_base, value='  ')
;       info_ff_label = widget_label(info_base, value='  ')
    info_abs_label = widget_label(info_base, value='  ')	
    info_sens_label = widget_label(info_base, value='  ')	
    info_save_label = widget_label(info_base, value='CCSDS    ')
    
  endelse
	  
  ; calibration options
	 
  fitslev = data-> getfitslev()
  if fitslev eq 0 then begin
    lsubcol1 = widget_base(lcol, /row,/frame)
    llsubcol1= widget_base(lsubcol1, /column)      ;left column.
    rlsubcol1= widget_base(lsubcol1, /column)      ;right column.
    calfield = widget_base(llsubcol1,/col)
    calbutton= widget_button(calfield,     value = 'Calibration Def ', $
			      event_pro = 'xcontrol_cal')
    despikefield = widget_base(rlsubcol1,/col)
    despikebutton= widget_button(despikefield, value = 'EIS Prep        ', $
				  event_pro = 'xcontrol_eis_prep')
    save_base = widget_base(rlsubcol1,/col)
    savebutton= widget_button(save_base, value = 'Save            ', $
			       event_pro = 'xcontrol_save',sensitive=0)
  endif else begin
    savebutton = 'dummy'
  endelse

  lsubcol2 = widget_base(lcol, /row,/frame)
  momfield = widget_base(lsubcol2, /col)
  momnames = ['Not selected','Moments     ','Gaussian fit']
  momtitle = 'Line fit           '
  momplot  = widget_droplist(momfield, value = momnames, title=momtitle, $
				     event_pro = 'xcontrol_listmoments')
  ; Close button
  lsubcol3 = widget_base(lcol, /row,/frame)
  llsubcol3= widget_base(lsubcol3, /column)      ;left column.
  rlsubcol3= widget_base(lsubcol3, /column)      ;right column.
  hdrdispfield = widget_base(llsubcol3, /col)
  hdrdispbutton= widget_button(hdrdispfield, value='Display header  ', $
			      event_pro = 'xcontrol_hdrdisp')
  closefield  = widget_base(rlsubcol3, /column)
  closebutton = widget_button(closefield, value = 'Close           ', $
			      event_pro = 'xcontrol_destroy')
				      
  ; realize the top level base widget
  widget_control, tlb, /realize
; widget_control,despikebutton,sensitive=0

  ; Define the info structure, used to send information around
  info= { data:data, $
	  hdr:hdr, $
	  auxobj:auxobj, $
	  moment:ptr_new(), $
	  tlb:tlb, $
	  dirsep:dirsep, $
	  lineselect_a:lineselect_a, $
	  lineselect_b:lineselect_b, $
	  dispselect:dispselect, $
	  datasource:datasource, $
	  nwin:nwin, $
	  nraster:nraster, $
	  nexp:nexp, $
	  nexp_prp:nexp_prp, $
	  obsmode:obsmode, $
	  nslit:nslit, $
	  ntime:ntime, $
	  lines:intarr(nwin), $
	  nccd:nccd, $
	  ccd_b:ccd_b, $
	  ccd_a:ccd_a, $
	  line_id:line_id, $
	  line_mask:line_mask, $
	  line_wvl:line_wvl, $
	  line_npx:line_npx, $
	  data_textdump:'', $
	  deta:0, $
	  detb:0, $
;         despikebutton:despikebutton, $
	  savebutton:savebutton, $
	  momplot:momplot,$
	  dc_done:0,$
	  calinfo:calinfo,$
	  info_dc_label:info_dc_label,$
;         info_ff_label:info_ff_label,$
	  info_hp_label:info_hp_label,$
	  info_wp_label:info_wp_label,$
	  info_dp_label:info_dp_label,$
	  info_cr_label:info_cr_label,$
	  info_abs_label:info_abs_label,$
	  info_sens_label:info_sens_label,$
	  info_save_label:info_save_label,$
	  savestat:1,$
	  emm:''}
  info=ptr_new(info,/no_copy)

  ; Set the info ptr to be the user value of the tlb widget
  widget_control, tlb, set_uvalue=info

  xcontrol_get_data_info, info
  widget_control, data_info, set_value = (*info).data_textdump, /append
				  
  widget_control, eis_icon , get_value = drawID1
  wset,drawID1
; fileName = concat_dir(GETENV('ancillary') , 'eis_logo_sarah_small.jpg')
; read_jpeg , filename , icon
; icon_resized = CONGRID(icon,3,380,190)
; tvscl,icon_resized,true=1
  deticon_resized = congrid(deticon,400,400/4.)
  loadct,9
  tvscl,alog10(deticon_resized>1)
  loadct,0
  
  widget_control, pointing_icon , get_value = drawID2
  wset,drawID2
  solar_radius=960.
  npt=100
  phi=indgen(npt)/(npt-1.)*2.*!pi
  x=solar_radius*sin(phi)
  y=solar_radius*cos(phi)
  plot,x,y,xstyle=4,ystyle=4,xmargin=[2,2],ymargin=[2,2]
  if datasource eq 'fits' then begin
;  xcen=data->getxcen()
;  ycen=data->getycen()
    xcen=data->getxcen()
    ycen=data->getycen()
    oktime=data->check_ti()
    if (where(oktime ne 0))[0] ne -1 then begin
      xcen=xcen[where(oktime ne 0)]
      ycen=ycen[where(oktime ne 0)]
      if n_elements(xcen) gt 1 then oplot,xcen,ycen
      plot_box,xcen[0],ycen[0],data->getinfo('fovx'),data->getinfo('fovy')
    endif
  endif

  xmanager, 'xcontrol', tlb, /no_block, $
	    group_leader = group, cleanup = 'xcontrol_cleanup'
end
