

function eis_mask_get_ypos, mask, wvl, yip

;+
; NAME
;
;     EIS_MASK_GET_YPOS()
;
; PROJECT
;
;     Hinode/EIS
;
; EXPLANATION
;
;     When working with spectra obtained with EIS_MASK_SPECTRUM,
;     extracting the non-thermal broadening requires knowing the
;     Y-position of the spatial region on the detector so that the
;     instrumental width can be correctly
;     subtracted. EIS_MASK_GET_YPOS allows the Y position to be
;     obtained for any wavelength WVL by using the pixel mask (MASK).
;
;     The Y-position of the selected region is obtained by doing a
;     "center-of-mass" calculation for all of the Y-locations of the
;     selected pixels. This works fine if the spatial region is
;     compact, but if it's large or there are multiple spatial
;     regions then it will be inaccurate. 
;
; INPUTS
;
;     MASK    An EIS pixel mask as obtained with the routine
;             EIS_PIXEL_MASK. 
;
;     WVL     The wavelength for which the Y position is required.
;
;     YIP     The Y initial position (YIP) for the raster. This is the
;             detector Y-pixel number that corresponds to the bottom
;             row of the raster.
;
; OUTPUTS
;
;     The Y-position, in CCD Y-pixel numbers, of the spatial region
;     identified in the pixel mask. A value of -1 is returned if the
;     routine is not able to process the inputs.
;
; HISTORY
;
;     Ver.1, 6-Sep-2012, Peter Young
;-


IF n_params() LT 3 THEN BEGIN
  print,'Use:  IDL> ypos=eis_mask_get_ypos(mask,wvl,yip [date_obs=])'
  print,''
  print,'  The YIP value can be obtained from a windata structure or the EIS object as follows:'
  print,'        IDL> yip=windata.hdr.yws'
  print,"        IDL> yip=obj->getinfo('yws')"
  return,-1
ENDIF 

;
; Note that date_obs isn't important since it only affects the
; X-offset between pixel masks, thus not affecting the final YPOS
; value. For this reason I just used today's date.
;
date_obs=systim()
newmask=eis_adjust_mask(mask,wvl)

maskim=newmask.image
siz=size(maskim)
nx=siz[1]
ny=siz[2]

k=where(maskim EQ 1,nk)

yvals=0
FOR i=0,nk-1 DO BEGIN
  ij=get_ij(k[i],nx)
  yvals=[yvals,ij[1]]
ENDFOR 

yvals=yvals[1:*]

;
; This is the "center-of-mass" in the y-direction
;
y_com=mean(yvals)

return,yip+round(y_com)

END
