
FUNCTION eis_clean_windata, windata, swtch=swtch, verbose=verbose, nocr=nocr, nowp=nowp, $
                            nofill=nofill


;+
; NAME:
;     EIS_CLEAN_WINDATA
;
; PURPOSE:
;     Removes residual warm pixels and cosmic rays from a WINDATA
;     structure. Note that EIS_PREP *must* be run with the /nocr and
;     /noabs keywords for this routine to work (the routine will check
;     this). 
;
; CATEGORY:
;     Hinode/EIS; despike
;
; CALLING SEQUENCE:
;     Result = EIS_CLEAN_WINDATA( Windata )
;
; INPUTS:
;     Windata:  An EIS windata structure, as returned by
;               eis_getwindata.
;
; KEYWORD PARAMETERS:
;     VERBOSE: Print information about the de-spiking to the screen.
;     NOCR:    If set, then the cosmic ray removal is not performed.
;     NOWP:    If set, then the warm pixel removal is not performed.
;     NOFILL:  If set, then the flagged pixels will be set to missing
;              rather than replaced with a value interpolated from
;              neighboring pixels.
;
; OUTPUTS:
;     A copy of the input windata structure, with the 'int' and 'err'
;     tags modified. 
;
; OPTIONAL OUTPUTS:
;     Swtch:    A byte array of same size as windata.int, with
;               1's indicating the pixels that have been
;               flagged as spikes (0 otherwise).
;
; CALLS:
;     EIS_PREP_RESIDUAL_WPS, EIS_PREP_CLEAN_CRS
;
; EXAMPLE:
;     IDL> eis_prep,l0name,/quiet,/save,/default,/retain,/nocr,/noabs
;     IDL> wd=eis_getwindata(l1name,195.12)
;     IDL> wdout=eis_clean_windata(wd)
;
; MODIFICATION HISTORY:
;     Version 1, 5-Nov-2019, Peter Young
;-

IF n_params() LT 1 THEN BEGIN
  print,'Use:  IDL> wdout=eis_getwindata(wd [, swtch=, /verbose, /nofill, /nocr, /nowp ])'
  return,wd
ENDIF 

;
; Do a check on the calibration status of WINDATA.
;
calstat=windata.hdr.calstat
p1=strpos(calstat,'CR')
p2=strpos(calstat,'ABS')
IF p1 GT 0 OR p2 GT 0 THEN BEGIN
  print,'% EIS_CLEAN_WINDATA: The input data needs to be prepped with the /nocr and /noabs options.'
  print,'                     Please prep the data again with these options'
  print,'    windata.hdr.calstat = '+trim(calstat)
  return,-1
ENDIF 


wdout=windata
int=windata.int
err=windata.err
missing=windata.missing

s=size(int,/dim)

;
; Clean the residual warm pixels.
;
IF NOT keyword_set(nowp) THEN BEGIN 
  eis_prep_residual_wps,int,err,missing=missing,swtch=swtch_wp,nofill=nofill,/verbose,/swap_xy
  swtch=swtch_wp
ENDIF ELSE BEGIN
  swtch=make_array(s,/byte,value=0b)
ENDELSE 


;
; Now clean the regular cosmic rays
;
IF NOT keyword_set(nocr) THEN BEGIN 
  eis_prep_clean_crs,int,err,missing=missing,swtch=swtch_cr,nofill=nofill,/verbose,/swap_xy
  swtch=swtch OR swtch_cr
ENDIF

wdout.int=temporary(int)
wdout.err=temporary(err)

return,wdout

END
