;+
; NAME
;
;     EIS_FIT_VIEWER_OLD
;
; PROJECT
;
;     HINODE/EIS
;
; EXPLANATION
;
;     **This is the old version of eis_fit_viewer which is compatible
;     **with the outputs of eis_auto_fit_old and eis_auto_fit_gen. It
;     **was renamed eis_fit_viewer_old in Jan 2010.
;
;     Widget-based routine for studying the Gaussian fits produced by
;     EIS_AUTO_FIT.PRO.
;
;     The top 3 graphics windows show the line intensity, line shift and
;     line width, respectively, from the Gaussian fits stored in FITDATA.
;
;     You will notice the buttons in the top left that give the choice of
;     'Zoom' or 'Pixel'. With Zoom selected, you can click-and-drag on any
;     of the three upper windows to draw a rubberband box that will
;     highlight an area in the images. Letting go of the mouse button
;     will then zoom in on the selected area.
;
;     With 'Pixel' selected you can click with the left mouse button at any
;     point in any of the three images. The line profile from the selected
;     image pixel will then be plotted in the bottom left graphics window,
;     together with the fit to the emission line (drawn as a thick line).
;
;     The three text boxes to the left of the line profile window give:
;       Int  - Line intensity, erg cm^-2 s^-1 sr^-1
;       Vel  - Velocity shift, km/s  (negative=blueshift, postive=redshift)
;       Wid  - Line width (FWHM), milli-Angstroms
;
;     The bottom right plot shows the distribution of either intensity,
;     velocity or line width (use buttons to select) for the plotted image.
;
; INPUTS
;
;     WINDATA  Output from eis_getwindata.pro
;
;     FITDATA  Output from eis_auto_fit.pro.
;
; INTERNAL ROUTINES
;
;     VIEW_FONT, FITVIEW_PROFILE, FITVIEW_DRAWBOX, PLOT_HISTOGRAM,
;     PLOT_EXPOSURE, EIS_FIT_WIDGET, FIT_BASE_EVENT
;
; CALLS
;
;     EIS_CONVERT_FITDATA
;
; NOTES
;
;     The code for this routine was adapted from that of eis_spike_viewer
;     so you may notice anomalies in the naming of variables (e.g., the
;     appearance of the word 'spike').
;
; HISTORY
;
;     Ver.1, 11-Jul-2007, Peter Young
;        revised to take output from eis_getwindata
;     Ver.2, 18-Jul-2007, Peter Young
;        activated histogram plot; converted line widths to milli-angstroms;
;        updated header.
;     Ver.3, 23-Nov-2007, Peter Young
;        now checks for uniform_backg in FITDATA
;     Ver.4, 16-Jan-2008, Peter Young
;        corrected bug in implementation of uniform_backg; added 
;        'Full wavelength range' button for line profile display; takes
;        account of new pix_all tag in fitdata.
;     Ver.5, 30-Jan-2008, Peter Young
;        Corrected equation for deriving amplitude from intensity.
;     Ver.6, 12-Feb-2008, Peter Young
;        Allowed negative points to be displayed in line profile plot.
;     Ver.7, 6-Nov-2008, Peter Young
;        Modified to allow the output from eis_auto_fit_gen to be
;        input, while still retaining compatibility with eis_auto_fit.
;     Ver.8, 20-Nov-2008, David Perez-Suarez, Peter Young
;        Performed check to see if offset is set to missing; a
;        backwards compatibility was missing in v.7 so this has been
;        added. 
;     Ver.9, 20-Jan-2010, Peter Young
;        Has been renamed as eis_fit_viewer_old.pro.
;-


;------------------
PRO view_font, font, big=big, fixed=fixed
;+
;  Defines the fonts to be used in the widgets. Allows for Windows and Unix 
;  operating systems.
;-
CASE !version.os_family OF

  'unix': BEGIN
    IF keyword_set(fixed) THEN fstr='-*-courier-' ELSE $
         fstr='-adobe-helvetica-'
    IF keyword_set(big) THEN str='18' ELSE str='12'
    font=fstr+'bold-r-*-*-'+str+'-*'
  END

  ELSE: BEGIN
    IF keyword_set(fixed) THEN fstr='Courier' ELSE $
         fstr='Arial'
    IF keyword_set(big) THEN str='20' ELSE str='16'
    font=fstr+'*bold*'+str
  END

ENDCASE

END



;----------------
PRO fitview_profile, state, wid, event=event
;
; Plots the line profile in the bottom-left window for the user-selected 
; pixel.
;
;  EVENT   If fitview_profile is called after a new spatial pixel has been
;          selected with the mouse, then EVENT is used to convert the chosen
;          mouse position into a pixel position in the image array and update
;          the WID_DATA.XPIX and WID_DATA.YPIX values.
;
int=state.fitdata.int
err=state.fitdata.interr
vel=state.fitdata.vel
width=state.fitdata.wid
chi2=state.fitdata.chi2
cen=state.fitdata.cen
pix=state.fitdata.pix
IF tag_exist(state.fitdata,'pix_all') THEN pix_all=state.fitdata.pix_all ELSE pix_all=-1
bg1=state.fitdata.bg1
bg2=state.fitdata.bg2
xr=state.fitdata.xrange
yr=state.fitdata.yrange
IF tag_exist(state.fitdata,'uniform_backg') THEN uniform_backg=state.fitdata.uniform_backg

lambda=state.windata.wvl
windata=state.windata
int_arr=state.windata.int[*,xr[0]:xr[1],yr[0]:yr[1]]
err_arr=state.windata.err[*,xr[0]:xr[1],yr[0]:yr[1]]
;int_arr=state.windata.int
;err_arr=state.windata.err
missing=state.windata.missing
nl=state.windata.nl

missing2=-1e5

i=where(err_arr EQ missing,ni)
IF ni NE 0 THEN int_arr[i]=missing2


tst_prof=state.wid_data.tst_prof


wset,wid
plot_exposure,state

IF n_tags(event) EQ 0 THEN BEGIN
  x=state.wid_data.xpix
  y=state.wid_data.ypix
ENDIF ELSE BEGIN
  x=event.x
  y=event.y
  result=convert_coord(x,y,/device,/to_data)
  x=result[0]
  y=result[1]
  IF x LT !x.crange[0] OR x GT !x.crange[1] OR y LT !y.crange[0] OR y GT !y.crange[1] OR event.release NE 1 THEN BEGIN
    return
  ENDIF ELSE BEGIN
    x=round(x)
    y=round(y)
    state.wid_data.xpix=x
    state.wid_data.ypix=y
    widget_control,state.fit_base,set_uvalue=state
  ENDELSE
ENDELSE

;
; Modify the lambda array for the wavelength offset at (x,y)
; For backward compatability, check that offset tag exists.
;
IF tag_exist(state.fitdata,'offset') THEN BEGIN
  IF state.fitdata.offset[x,y] NE missing THEN lambda=lambda-state.fitdata.offset[x,y]
ENDIF 

wset,state.wid_data.prof_id

;
; If 'Full wavelength range' button set, then use full wavelength range 
;
IF tst_prof[2] EQ 1 THEN pix=[0,nl-1]

prof=int_arr[pix[0]:pix[1],x,y]
err=err_arr[pix[0]:pix[1],x,y]
lamb=lambda[pix[0]:pix[1]]

;
; Generate fit profile
; 
p0=int[x,y]/sqrt(2.*!pi)/width[x,y]   ; generate amplitude from intensity + width
p1=cen[x,y]
p2=width[x,y]
;
; Calculating the background for the full wavelength range needs to be done
; carefully due to the definition I use for the background.
;
IF keyword_set(uniform_backg) THEN BEGIN
  background=bg1[x,y] 
ENDIF ELSE BEGIN
  l1=lambda[state.fitdata.pix[0]]
  l2=lambda[state.fitdata.pix[1]]
  cc=linfit([l1,l2],[bg1[x,y],bg2[x,y]])
  background=cc[0]+lamb*cc[1]
ENDELSE
;
fit_profile=background + $
     gauss_sg(lamb,[p0,p1,p2])

; get offset of wavelength scale
IF tag_exist(state.fitdata,'offset') THEN offset=state.fitdata.offset[x,y]

;
; Only plot points greater than zero to prevent missing data appearing.
;
i=where(prof NE missing2,ni)
IF ni NE 0 THEN minmax=[min(prof[i]),max(fit_profile)]
plot,lamb,prof,psym=10,/xsty, $
     tit='Line profile', $
     xtit='Wavelength / '+string(197b), $
     ytit='Intensity / erg cm!u-2!n s!u-1!n sr!u-1!n '+string(197b)+'!u-1!n',$
     yrange=minmax,ysty=3

;
; Overplot fit profile
; 
oplot,lamb,fit_profile,th=2

;
; Overplot the error bars
;
IF tst_prof[1] EQ 1 THEN BEGIN
  oploterr,lamb,prof,err,psym=10
ENDIF

;
; If pix_all has been used, then the pixels used for the fit are over-plotted.
;
IF tag_exist(state.fitdata,'pix_all') THEN BEGIN
  pix_all=state.fitdata.pix_all
  IF total(pix_all GE 0) THEN BEGIN
    k=where(pix_all EQ 1)
    xx=lambda[k]
    yy=int_arr[k,x,y]
    oplot,xx,yy,psym=7
  ENDIF
ENDIF


text1=trim(string(format='(f10.1)',int[x,y]))
widget_control,state.text1_txt,set_val=text1
;
text2=trim(string(format='(f10.1)',vel[x,y]))
widget_control,state.text2_txt,set_val=text2
;
text3=trim(string(format='(f10.1)',width[x,y]*1000.*2.35))
widget_control,state.text3_txt,set_val=text3
;
text4=trim(string(format='(f10.1)',chi2[x,y]))
widget_control,state.text4_txt,set_val=text4

plot_exposure,state,point=[x,y]

END


;----------------
PRO fitview_drawbox, event, state, wid

CASE 1 OF
  event.press EQ 1 AND state.box.flag EQ 0: BEGIN
    state.box.flag=1
    state.box.x0=event.x
    state.box.y0=event.y
    state.box.wid=wid
    wset,wid
    plot_exposure,state
    Window, /Pixmap, /Free, XSize=state.box.xsiz, YSize=state.box.ysiz
    state.box.pixid = !D.Window
    Device, Copy=[0, 0, state.box.xsiz, state.box.ysiz, 0, 0, wid]
    wset,wid
    widget_control,state.fit_base,set_uvalue=state
  END

  event.release EQ 1 AND state.box.flag EQ 1: BEGIN
    WDelete, state.box.pixid
    state.box.flag=0
    state.box.x1=event.x
    state.box.y1=event.y
    widget_control,state.fit_base,set_uvalue=state
    result=convert_coord([state.box.x0,state.box.x1], $
                         [state.box.y0,state.box.y1],/device,/to_data)
    result=fix(result)
    xra=[result[0,0],result[0,1]]
    xra=xra[sort(xra)]
    yra=[result[1,0],result[1,1]]
    yra=yra[sort(yra)]
    IF xra[0] NE xra[1] AND yra[0] NE yra[1] THEN BEGIN
      state.wid_data.xrange=xra
      state.wid_data.yrange=yra
      widget_control,state.fit_base,set_uvalue=state
    ENDIF
    plot_exposure,state
    plot_histogram,state
  END

  state.box.flag EQ 1: BEGIN
    Device, Copy=[0, 0, state.box.xsiz, state.box.ysiz, 0, 0, state.box.pixid]
    PlotS, [state.box.x0, state.box.x0, event.x, event.x, state.box.x0], $
         [state.box.y0, event.y, event.y, state.box.y0, state.box.y0], $
         /Device
  END
  
  ELSE:
  
ENDCASE

END

;----------------
PRO plot_histogram, state
  
xra=state.wid_data.xrange
yra=state.wid_data.yrange

int=state.fitdata.int
wid=state.fitdata.wid
vel=state.fitdata.vel

miss=state.windata.missing

CASE state.wid_data.hist_flag OF
  0: BEGIN
    y=int[xra[0]:xra[1],yra[0]:yra[1]]
    xtit='Intensity / erg cm!u-2!n s!u-1!n sr!u-1!n'
    i=where(y NE miss,ni)
    IF ni NE 0 THEN y=y[i]
  END
  1: BEGIN
    y=vel[xra[0]:xra[1],yra[0]:yra[1]]
    xtit='Velocity / km s!u-1!n'
    i=where(y NE miss,ni)
    IF ni NE 0 THEN y=y[i]
  END
  2: BEGIN
    y=wid[xra[0]:xra[1],yra[0]:yra[1]]
    xtit='FWHM / m'+string(197b)
    i=where(y NE miss,ni)
    IF ni NE 0 THEN y=y[i]
    y=y*2.35*1000.
  END
ENDCASE


wset,state.wid_data.hist_id

binsize=(max(y)-min(y))/50.
miny=min(y)
x=findgen(51)*binsize + miny

plot,x,histogram(y,binsize=binsize,min=miny),psym=10,xtit=xtit, $
     ytit='No. of pixels', $
     xticklen=-0.015,yticklen=-0.015, $
     tit='Histogram'

END


;----------------
PRO plot_exposure, state, reset=reset, point=point

;+
; Plots the intensity, velocity and line width images.
;
;  RESET   Sets the XRANGE and YRANGE of the image plots to their full size.
;  POINT   When Pixel is set, shows location of the selected pixel.
;-

windata=state.windata
fitdata=state.fitdata

int=fitdata.int
width=fitdata.wid
vel=fitdata.vel

; IF state.wid_data.orb_corr EQ 1 THEN BEGIN
;   vel=state.orbdata.vel
; ENDIF ELSE BEGIN
;   vel=fitdata.vel
; ENDELSE


siz=size(int)
IF keyword_set(reset) THEN BEGIN
  xrange=[0,siz[1]-1]
  yrange=[0,siz[2]-1]
  state.wid_data.xrange=xrange
  state.wid_data.yrange=yrange
  widget_control,state.fit_base,set_uval=state
ENDIF ELSE BEGIN
  xrange=state.wid_data.xrange
  yrange=state.wid_data.yrange
  IF xrange[0] LT 0 THEN xrange[0]=0
  IF xrange[1] GT siz[1]-1 THEN xrange[1]=siz[1]-1
  IF yrange[0] LT 0 THEN yrange[0]=0
  IF yrange[1] GT siz[2]-1 THEN yrange[1]=siz[2]-1
  state.wid_data.xrange=xrange
  state.wid_data.yrange=yrange
  widget_control,state.fit_base,set_uval=state
ENDELSE

orig=[xrange[0],yrange[0]]

int=int[xrange[0]:xrange[1],yrange[0]:yrange[1]]
vel=vel[xrange[0]:xrange[1],yrange[0]:yrange[1]]
width=width[xrange[0]:xrange[1],yrange[0]:yrange[1]]

IF state.wid_data.autoint EQ 1 THEN BEGIN
  intmin=min(int(where(int NE windata.missing)))
  intmax=max(int(where(int NE windata.missing)))
  state.wid_data.int_min=intmin
  state.wid_data.int_max=intmax
  widget_control,state.in_min_text, $
       set_value=trim(string(format='(f10.1)',intmin))
  widget_control,state.in_max_text, $
       set_value=trim(string(format='(f10.1)',intmax))
  widget_control,state.fit_base,set_uvalue=state
ENDIF

IF state.wid_data.autovel EQ 1 THEN BEGIN
  velmin=min(vel(where(vel NE windata.missing)))
  velmax=max(vel(where(vel NE windata.missing)))
  state.wid_data.vel_min=velmin
  state.wid_data.vel_max=velmax
  widget_control,state.out_min_text, $
       set_value=trim(string(format='(f10.1)',velmin))
  widget_control,state.out_max_text, $
       set_value=trim(string(format='(f10.1)',velmax))
  widget_control,state.fit_base,set_uvalue=state
ENDIF

IF state.wid_data.autowid EQ 1 THEN BEGIN
  widmin=min(width(where(width NE windata.missing)))
  widmax=max(width(where(width NE windata.missing)))
  state.wid_data.wid_min=widmin*2.35*1000.
  state.wid_data.wid_max=widmax*2.35*1000.
  widget_control,state.spike_min_text, $
       set_value=trim(string(format='(f10.1)',widmin*2.35*1000.))
  widget_control,state.spike_max_text, $
       set_value=trim(string(format='(f10.1)',widmax*2.35*1000.))
  widget_control,state.fit_base,set_uvalue=state
ENDIF


xtl=-0.02
ytl=-0.02

wset,state.wid_data.in_id
plot_image,int,xticklen=xtl,yticklen=ytl,orig=orig, $
     title='Intensity',min=state.wid_data.int_min, $
     max=state.wid_data.int_max
IF n_elements(point) NE 0 THEN plots,point[0],point[1],psym=1
;
wset,state.wid_data.out_id
plot_image,vel,xticklen=xtl,yticklen=ytl,orig=orig, $
     title='Velocity',min=state.wid_data.vel_min, $
     max=state.wid_data.vel_max
IF n_elements(point) NE 0 THEN plots,point[0],point[1],psym=1
;
wset,state.wid_data.spike_id
plot_image,width,xticklen=xtl,yticklen=ytl,orig=orig, $
     title='Width',min=state.wid_data.wid_min/2.35/1000., $
     max=state.wid_data.wid_max/2.35/1000.
IF n_elements(point) NE 0 THEN plots,point[0],point[1],psym=1

END


;------------------
PRO fit_base_event, event
;
;  Event handler for EIS_FIT_VIEWER
;

WIDGET_CONTROL,Event.top, get_uvalue=state


CASE event.id OF

  state.zoom_pix: BEGIN
   ;
   ; Toggles between whether the mouse is used for zooming or selecting
   ; pixels.
   ;
    widget_control,state.zoom_pix,get_val=val
    state.wid_data.zm_pix=val
    widget_control,state.fit_base,set_uval=state
    IF val EQ 1 THEN BEGIN
      widget_control,state.in_plot,draw_motion_events=0
      widget_control,state.out_plot,draw_motion_events=0
      widget_control,state.spike_plot,draw_motion_events=0
    ENDIF ELSE BEGIN
      widget_control,state.in_plot,draw_motion_events=1
      widget_control,state.out_plot,draw_motion_events=1
      widget_control,state.spike_plot,draw_motion_events=1
    ENDELSE
  END

  state.in_plot: BEGIN
    IF state.wid_data.zm_pix EQ 0 THEN BEGIN
      fitview_drawbox, event, state, state.wid_data.in_id
    ENDIF ELSE BEGIN
      fitview_profile, state, state.wid_data.in_id, event=event
    ENDELSE
  END

  state.out_plot: BEGIN
    IF state.wid_data.zm_pix EQ 0 THEN BEGIN
      fitview_drawbox, event, state, state.wid_data.out_id
    ENDIF ELSE BEGIN
      fitview_profile, state, state.wid_data.out_id, event=event
    ENDELSE
  END

  state.spike_plot: BEGIN
    IF state.wid_data.zm_pix EQ 0 THEN BEGIN
      fitview_drawbox, event, state, state.wid_data.spike_id
    ENDIF ELSE BEGIN
      fitview_profile, state, state.wid_data.spike_id, event=event
    ENDELSE
  END

  state.unzoom: BEGIN
    plot_exposure,state,/reset
    plot_histogram,state
  END

  state.in_min_text: BEGIN
    widget_control,state.in_min_text,get_value=val
    state.wid_data.int_min=val
    state.wid_data.autoint=0
    widget_control,state.fit_base,set_uvalue=state
    plot_exposure,state
  END

  state.in_max_text: BEGIN
    widget_control,state.in_max_text,get_value=val
    state.wid_data.int_max=val
    state.wid_data.autoint=0
    widget_control,state.fit_base,set_uvalue=state
    plot_exposure,state
  END

  state.out_min_text: BEGIN
    widget_control,state.out_min_text,get_value=val
    state.wid_data.vel_min=val
    state.wid_data.autovel=0
    widget_control,state.fit_base,set_uvalue=state
    plot_exposure,state
  END

  state.out_max_text: BEGIN
    widget_control,state.out_max_text,get_value=val
    state.wid_data.vel_max=val
    state.wid_data.autovel=0
    widget_control,state.fit_base,set_uvalue=state
    plot_exposure,state
  END

  state.spike_min_text: BEGIN
    widget_control,state.spike_min_text,get_value=val
    state.wid_data.wid_min=val
    state.wid_data.autowid=0
    widget_control,state.fit_base,set_uvalue=state
    plot_exposure,state
  END

  state.spike_max_text: BEGIN
    widget_control,state.spike_max_text,get_value=val
    state.wid_data.wid_max=val
    state.wid_data.autowid=0
    widget_control,state.fit_base,set_uvalue=state
    plot_exposure,state
  END

  state.prof_butts: BEGIN
    widget_control,state.prof_butts,get_value=tst_prof
;    print,'**',tst_prof,event.value
;    tst_prof[event.value]=1-tst_prof[event.value]
;    print,'**',tst_prof
    state.wid_data.tst_prof=tst_prof
    widget_control,state.fit_base,set_uvalue=state
    fitview_profile, state, state.wid_data.out_id
  END

  state.auto_int: BEGIN
    state.wid_data.autoint=1
    widget_control,state.fit_base,set_uvalue=state
    plot_exposure,state
  END

  state.auto_vel: BEGIN
    state.wid_data.autovel=1
    widget_control,state.fit_base,set_uvalue=state
    plot_exposure,state
  END

  state.auto_wid: BEGIN
    state.wid_data.autowid=1
    widget_control,state.fit_base,set_uvalue=state
    plot_exposure,state
  END

  state.hist_butts: BEGIN
    widget_control,state.hist_butts,get_value=val
    state.wid_data.hist_flag=val
    widget_control,state.fit_base,set_uvalue=state
    plot_histogram,state
  END

  state.exit: widget_control, event.top, /destroy

ENDCASE

END


;----------------------------------------
PRO eis_fit_widget, windata, fitdata, group=group

siz=size(fitdata.int)
xrange=[0,siz[1]-1]
yrange=[0,siz[2]-1]

view_font,font
view_font,bigfont,/big
view_font,fixfont,/fixed

;
; Apply scale factors to the plot windows if the screen size is small
;
ss=get_screen_size()
CASE 1 OF 
  ss[0] LT 1024: plot_scale=0.7
  ss[0] GE 1024 AND ss[0] LT 1600: plot_scale=1.0
  ss[0] GE 1600 AND ss[0] LT 1900: plot_scale=1.3
  ss[0] GE 1900: plot_scale=1.5
ENDCASE


;
; WID_DATA is a structure for storing various pieces of information used in
; controlling the widgets and for setting what is displayed in the plot
; windows.
;
wid_data={in_id: 0, $
          out_id: 0, $
          spike_id: 0, $
          prof_id: 0, $
          hist_id: 0, $
          zm_pix: 0, $
          xrange: xrange, $
          yrange: yrange, $
          int_min: 0., $
          int_max: max(fitdata.int), $
          vel_min: -30, $
          vel_max: 30 ,$
          wid_min: 55, $
          wid_max: 90, $
          tst_prof: intarr(3), $
          xpix: 0, ypix: 0, $
          autoint: 0, $
          autovel: 0, $
          autowid: 0, $
          hist_flag: 0}
;          orb_corr: 0}

fit_base=widget_base(/col,map=1,title='FIT_VIEWER')


img_base=widget_base(fit_base,/row,map=1)


img_butts_base=widget_base(img_base,/col,map=1)

zoom_pix=cw_bgroup(img_butts_base,/exclusive,['Zoom','Pixel'], $
                  set_value=wid_data.zm_pix,/col,/frame,font=font)

unzoom=widget_button(img_butts_base,value='UNZOOM',font=font)

exit=widget_button(img_butts_base,value='EXIT',font=bigfont)


;
; Set size of plot windows
;
xsiz=fix(300*plot_scale)
ysiz=fix(300*plot_scale)
xsiz2=fix(400*plot_scale)   ; use for profile plot


;
; WIDGETS FOR PLOTTING INTENSITY IMAGE
; -------------------------------------
plot_base1=widget_base(img_base,/row)
in_base=widget_base(plot_base1,/col)
in_plot=widget_draw(in_base,xsiz=xsiz,ysiz=ysiz,/sens, $
                    /motion_events,/button_events)
in_base2=widget_base(in_base,/row)
in_min_lbl=widget_label(in_base2,value='Min:',font=font)
in_min_text=widget_text(in_base2,value=trim(wid_data.int_min), $
                       font=font,xsiz=8,/editable)
in_max_lbl=widget_label(in_base2,value='Max:',font=font)
in_max_text=widget_text(in_base2,value=trim(wid_data.int_max), $
                       font=font,xsiz=8,/editable)
auto_int=widget_button(in_base2,value='Auto',font=font)

;
; WIDGETS FOR PLOTTING VELOCITY IMAGE
; -------------------------------------
out_base=widget_base(plot_base1,/col)
out_plot=widget_draw(out_base,xsiz=xsiz,ysiz=ysiz,/sens, $
                    /motion_events,/button_events)
out_base2=widget_base(out_base,/row)
out_min_lbl=widget_label(out_base2,value='Min:',font=font)
out_min_text=widget_text(out_base2,value=trim(wid_data.vel_min), $
                       font=font,xsiz=8,/editable)
out_max_lbl=widget_label(out_base2,value='Max:',font=font)
out_max_text=widget_text(out_base2,value=trim(wid_data.vel_max), $
                       font=font,xsiz=8,/editable)
auto_vel=widget_button(out_base2,value='Auto',font=font)


;
; WIDGETS FOR PLOTTING LINE WIDTH IMAGE
; -------------------------------------
spike_base=widget_base(plot_base1,/col)
spike_plot=widget_draw(spike_base,xsiz=xsiz,ysiz=ysiz,/sens, $
                    /motion_events,/button_events)
spike_base2=widget_base(spike_base,/row)
spike_min_lbl=widget_label(spike_base2,value='Min:',font=font)
spike_min_text=widget_text(spike_base2,value=trim(wid_data.wid_min), $
                       font=font,xsiz=8,/editable)
spike_max_lbl=widget_label(spike_base2,value='Max:',font=font)
spike_max_text=widget_text(spike_base2,value=trim(wid_data.wid_max), $
                       font=font,xsiz=8,/editable)
auto_wid=widget_button(spike_base2,value='Auto',font=font)
;

;
; WIDGETS FOR PLOTTING LINE PROFILE
; ---------------------------------
sub_base=widget_base(fit_base,/row,map=1)
prof_base=widget_base(sub_base,/row,map=1)
prof_butts_base=widget_base(prof_base,/col,map=1)

prof_butts=cw_bgroup(prof_butts_base,/nonexclusive, $
                ['Average profile','Error bars','Full wavelength range'], $
                /col,/frame,font=font)
text1_base=widget_base(prof_butts_base,/row,map=1)
text1_lbl=widget_label(text1_base,value='Int: ',font=font)
text1_txt=widget_text(text1_base,value='',font=font,xsiz=10)
;
text2_base=widget_base(prof_butts_base,/row,map=1)
text2_lbl=widget_label(text2_base,value='Vel: ',font=font)
text2_txt=widget_text(text2_base,value='',font=font,xsiz=10)
;
text3_base=widget_base(prof_butts_base,/row,map=1)
text3_lbl=widget_label(text3_base,value='Wid: ',font=font)
text3_txt=widget_text(text3_base,value='',font=font,xsiz=10)
;
text4_base=widget_base(prof_butts_base,/row,map=1)
text4_lbl=widget_label(text4_base,value='Chi^2: ',font=font)
text4_txt=widget_text(text4_base,value='',font=font,xsiz=10)

prof_plot=widget_draw(prof_base,xsiz=xsiz2,ysiz=ysiz)

;
; WIDGETS FOR PLOTTING HISTOGRAM DATA
; -----------------------------------
hist_base=widget_base(sub_base,/row,map=1)
hist_butts_base=widget_base(hist_base,/col,map=1)
hist_butts=cw_bgroup(hist_butts_base,/exclusive, $
                     ['Intensity','Velocity','Width'], $
                     set_val=wid_data.hist_flag,/col,/frame,font=font)
hist_plot=widget_draw(hist_base,xsiz=xsiz,ysiz=ysiz)


;
; Structure for defining the rubber-band box used for selecting sub-images
;
box={flag: 0, wid: 0, x0: 0, y0: 0, x1:0, y1:0, $
     xsiz:xsiz, ysiz: ysiz, pixid:0}

;
; Correct data for orbital variation and store in the orbdata tag
;
; eis_remove_orb_var,fitdata,outdata=outdata
; orbdata={vel: outdata.vel}
; junk=temporary(outdata)

;
; The state structure for passing data around the sub-routines and for
; controlling the widgets. 
;
state={windata: windata, $
       fitdata: fitdata, $
       wid_data: wid_data, $
       box:box, $
       fit_base:fit_base, $
       in_plot: in_plot, $
       out_plot: out_plot, $
       spike_plot: spike_plot, $
       zoom_pix: zoom_pix, $
       hist_butts: hist_butts, $
       prof_butts: prof_butts, $
       unzoom: unzoom, $
       exit: exit, $
       in_min_text: in_min_text, $
       in_max_text: in_max_text, $
       out_min_text: out_min_text, $
       out_max_text: out_max_text, $
       spike_min_text: spike_min_text, $
       spike_max_text: spike_max_text, $
       auto_wid: auto_wid, $
       auto_vel: auto_vel, $
       auto_int: auto_int, $
       text1_txt: text1_txt, $
       text2_txt: text2_txt, $
       text3_txt: text3_txt, $
       text4_txt: text4_txt}


WIDGET_CONTROL, fit_base, /REALIZE, set_uvalue=state

WIDGET_CONTROL, in_plot, GET_VALUE=in_plot_id
WIDGET_CONTROL, out_plot, GET_VALUE=out_plot_id
WIDGET_CONTROL, spike_plot, GET_VALUE=spike_plot_id
WIDGET_CONTROL, prof_plot, GET_VALUE=prof_plot_id
WIDGET_CONTROL, hist_plot, GET_VALUE=hist_plot_id
;
wid_data.in_id=in_plot_id
wid_data.out_id=out_plot_id
wid_data.spike_id=spike_plot_id
wid_data.prof_id=prof_plot_id
wid_data.hist_id=hist_plot_id


state.wid_data=wid_data
widget_control,fit_base,set_uvalue=state

plot_exposure, state
plot_histogram, state

XMANAGER, 'fit_base', fit_base, group=group

END


;-----------------
PRO eis_fit_viewer_old, windata, fitdata, line=line

IF NOT tag_exist(fitdata,'vel') THEN BEGIN 
  IF n_elements(line) EQ 0 THEN line=0
  fitdata2=eis_convert_fitdata(fitdata,line)
ENDIF ELSE BEGIN
  fitdata2=fitdata
ENDELSE 

IF n_params() EQ 0 THEN BEGIN
  print,'Use: IDL> eis_fit_viewer_old, windata, fitdata [, line= ]'
  return
ENDIF

eis_fit_widget,windata,fitdata2

END
