
FUNCTION eis_get_av_spec, wd, wvl

;+
; NAME
;
;   EIS_GET_AV_SPEC()
;
; PROJECT
;
;   Hinode/EIS
;
; EXPLANATION
;
;   Using a rubber-band box this routine allows the user to draw a box
;   on an EIS image (created from the input window data) that defines
;   the area to be averaged to create an average spectrum.
;
;   The intention is to study the average spectrum to identify the
;   best wavelength region to use for fitting an emission line with
;   eis_auto_fit.pro.
;
; INPUTS
;
;   WD    Window data structure produced by eis_getwindata.pro.
;
; OPTIONAL INPUTS
;
;   WVL   Specify wavelength (within data window) with which to form
;         an image (the routine eis_make_image is called). If not
;         set, then the entire wavelength window is used.
;
; OUTPUTS
;
;   Returns a 1D spectrum from the input WD structure that has been
;   averaged over the spatial region selected by the user.
;
; CALLS
;
;   EIS_MAKE_IMAGE, CH_DRAWBOX, SIGRANGE
;
; HISTORY
;
;   Ver. 1, 26-Oct-2009, Peter Young
;   Ver. 2, 30-Oct-2009, Peter Young
;      changed method of averaging data
;-

IF n_params(eis_get_av_spec) LT 1 THEN BEGIN
  print,'Use  IDL> spec=eis_get_av_spec(wd [, wvl] )'
  return,-1
ENDIF 

print,''
print,'To select a spatial region, go to image in plot window. Click-and-hold the'
print,'left mouse button to draw a rubber-band box on the spatial feature you are'
print,'interested in. When you let go of the mouse button the averaged spectrum will'
print,'be returned to the IDL session.'
print,''

IF n_elements(wvl) THEN BEGIN
  eis_make_image,wd,wvl,im
ENDIF ELSE BEGIN
  int=wd.int
  im=total(int,1)
ENDELSE 

siz=size(im)

!p.multi=0
plot_image,sigrange(im)

result=ch_drawbox(/data)

x0=round(result[0])
y0=round(result[1])
x1=round(result[2])
y1=round(result[3])

IF x0 LT 0 THEN x0=0
IF y0 LT 0 THEN y0=0
IF x1 LT 0 THEN x1=0
IF y1 LT 0 THEN y1=0
IF x0 GE siz[1] THEN x0=siz[1]-1
IF y0 GE siz[2] THEN y0=siz[2]-1
IF x1 GE siz[1] THEN x1=siz[1]-1
IF y1 GE siz[2] THEN y1=siz[2]-1

IF x0 EQ x1 OR y0 EQ y1 THEN BEGIN
  print,'%EIS_GET_AV_SPEC:  Selected region invalid. Returning...'
  return,-1
ENDIF 

print,'Region selected: ['+trim(x0)+':'+trim(x1)+','+trim(y0)+':'+trim(y1)+']'

int=wd.int[*,x0:x1,y0:y1]
spec=average(int,[2,3],missing=wd.missing)

return,spec

END
