
FUNCTION eis_sat_windata, filename, wvl, refill=refill, quiet=quiet

;+
; NAME:
;     EIS_SAT_WINDATA
;
; PURPOSE:
;     This routine was created as a fix to a specific problem. For
;     eis_getwindata, the /refill option refills all missing data,
;     including saturated data. However, saturated data should be left
;     as missing. 
;
;     The present routine fixes this problem by reading both the
;     level-1 and level-0 files. The level-0 file is used to identify
;     saturated data, and so the refill-ed level-1 windata is modified
;     to reset the saturated data back to missing.
;
; CATEGORY:
;     Hinode/EIS, data formatting.
;
; INPUTS:
;     Filename:   The name of an EIS level-1 file.
;     Wvl:        The wavelength of the window to be extracted.
;
; KEYWORDS:
;     REFILL:   The eis_getwindata routine will be called with /refill
;               when loading the level-1 windata structure.
;
; OUTPUT:
;     A windata structure of the form returned by eis_get_windata. The
;     'err' and 'int' tags will be modified from the standard
;     eis_get_windata if saturated data are identified in the level-0
;     files.
;
; MODIFICATION HISTORY:
;     Ver.1, 8-Dec-2014, Peter Young
;-


;
; Here I set the saturation threshold. Note that a saturated pixel
; will have a value of 16383 (=2^14 - 1), but I think JPEG compression
; means that the value that acutally appears in the data file differs
; from this value.
;
IF n_elements(sat_threshold) EQ 0 THEN sat_threshold=16000

;
; Given the input filename, which is assumed to be the level-1 file, I
; need to find the associated level-0 file.
;
basename=file_basename(filename)
t=fid2time(basename)
type=strmid(basename,4,2)

IF type NE 'l1' THEN BEGIN
  print,'% EIS_SAT_WINDATA:  The input filename should be the level-1 data file. Returning...'
  return,-1
ENDIF 

wd1=eis_getwindata(filename,wvl,/refill)

l0file=eis_find_file(t,count=count)
IF count EQ 0 THEN BEGIN
  print,'%EIS_SAT_WINDATA: The level-0 file was not found. Please download the level-0 file to your computer before calling eis_sat_windata.'
  return,-1
ENDIF

wd0=eis_getwindata(l0file,wvl)

k=where(wd0.int GE sat_threshold,nk)

IF NOT keyword_set(quiet) THEN BEGIN
  print,'Saturation threshold: '+trim(sat_threshold)+' DN'
ENDIF 

IF nk EQ 0 THEN BEGIN
  print,'% EIS_SAT_WINDATA: no saturated pixels found. Standard level-1 windata is returned.'
  return, wd1
ENDIF ELSE BEGIN
  wd1.int[k]=wd1.missing
  wd1.err[k]=wd1.missing
 ;
  print,'% EIS_SAT_WINDATA: '+trim(nk)+' saturated pixels found. These have been set to missing in the level-1 windata structure.'
  return,wd1
ENDELSE 

END
