

FUNCTION eis_flag_night, fitdata, threshold=threshold, quiet=quiet

;+
; NAME
;
;     EIS_FLAG_NIGHT()
;
; PROJECT
;
;     Hinode/EIS
;
; EXPLANATION
;
;     Takes the fit structure from eis_auto_fit and estimates which 
;     data-columns fall into orbital night. Any columns identified are set
;     to missing data in the fitdata data arrays, and the new structure is
;     returned.
;
;     Night data are identified by averaging the intensity array in the
;     Solar-Y dimension. If any of the data-points are then found to lie
;     below the THRESHOLD intensity then these points are assumed to be
;     night data.
;
;     The average intensity array is plotted, and the threshold level
;     indicated. The user can adjust THRESHOLD to ensure the correct
;     data-points are flagged.
;
;     Note that this routine is intended to be used for running
;     eis_orbit_spline to correct for the orbital variation.
;
; INPUTS
;
;     FITDATA  Fit structure produced by eis_auto_fit. It is left unaltered
;              by this routine.
;
; OPTIONAL INPUTS
;
;     THRESHOLD  The threshold intensity for identifying night-time data.
;                Default: 50 erg/cm2/s/sr.
;
; KEYWORDS
;
;     QUIET    If set, then do not plot data or print out information.
;
; OUTPUT
;
;     A structure of identical format to FITDATA is returned, but with any
;     columns identified to lie in orbital night flagged as missing data.
;     The arrays (tags) affected are INT, WID, VEL and CEN, and their
;     associated error arrays.
;
; HISTORY
;
;     Ver.1, 4-Mar-2008, Peter Young
;-


IF n_params() LT 1 THEN BEGIN
  print,'Use: IDL> outdata=eis_flag_night(fitdata [,threshold=, /quiet])'
  return,-1
ENDIF


outdata=fitdata
miss=outdata.missing

;
; Average intensity array along Solar-Y
;
av_int=average(fitdata.int,2,missing=miss)

;
; Set threshold value
;
IF n_elements(threshold) EQ 0 THEN BEGIN
  threshold=50.
  th_str=trim(string(threshold,format='(f10.1)'))
  IF NOT keyword_set(quiet) THEN print,'%EIS_FLAG_NIGHT: using threshold intensity of '+th_str
ENDIF


;
; Find data-columns lying below threshold
;
i=where(av_int LT threshold,ni)

;
; Plot data, with threshold overlaid
;
IF NOT keyword_set(quiet) THEN BEGIN
  plot,av_int,psym=1,xsty=3,symsiz=2.,xticklen=-0.015,yticklen=-0.015, $
       xtit='X-pixels', $
       ytit='Average intensity along slit / erg cm!u-2!n s!u-1!n sr!u-1!n'
  oplot,[-1e5,1e5],[1,1]*threshold,th=2
ENDIF


;
; Set night-time regions to be missing data
;
IF ni GT 0 THEN BEGIN
  outdata.int[i,*]=miss
  outdata.interr[i,*]=miss
;
  outdata.cen[i,*]=miss
  outdata.cenerr[i,*]=miss
;
  outdata.wid[i,*]=miss
  outdata.widerr[i,*]=miss
;
  outdata.vel[i,*]=miss
  outdata.velerr[i,*]=miss
;
  outdata.chi2[i,*]=miss
 ;
  IF NOT keyword_set(quiet) THEN print,'%EIS_FLAG_NIGHT:  '+trim(ni)+' columns flagged as night.'
ENDIF ELSE BEGIN
  IF NOT keyword_set(quiet) THEN print,'%EIS_FLAG_NIGHT: no night data found.'
ENDELSE

return,outdata

END
