;+
; NAME:
;        sb_readfits
; PURPOSE:
;       - Single point for reading FITS files within sbrowser.
;       - Reads a FITS file and returns the data and header index.
;       - Does work with TRACE, but only one 2D image at a time.
;       - Alternatively, returns a structure vector with short header info
;         for a series of files, including multi-image TRACE files
; CATEGORY:
;        image processing, widgets
; CALLING SEQUENCE:
;        sb_readfits,file,index,data
;        sb_readfits,file,index
;        sb_readfits,files,shortindex,/shortindex
; INPUTS:
;        file: string.  If TRACE: file+'#'+nnnn , nnnn = 4 digit dset#
;              Must be a string element unless /shortindex is set
; KEYWORDS (INPUT):
;        /shortindex: returns a short index structure with select tags
;                     for use in sbrowser
;            If /shortindex is set, the following rules apply:
;            - file may be a vector
;            - names of (multi-image) TRACE files must have '#xxxx' appended
;              - a short index is returned for all images in the file(s),
;                i.e., the value of the dset number 'xxxx' is ignored
;            - shortindex may be a vector, with one element per image
;            - tags provided in index:
;              .naxis1
;              .naxis2
;              .summed   = int.   1: no pixel summing, >1: pixels summed
;              .tt       = dbl.   time in seconds ("anytim" format)
;              .exptime  = float. exptime in seconds
;              .obsrvtry = string: 'S', 'A', 'B', or ''
;              .detector = string, e,g, 'EUVI','EIT','C2','MDI','COR1','TRACE'
;              .wave_len = string.
;              .filename = string.  path to FITS file on disk.
;            - no data is returned
; OUTPUTS:
;        index: fits header (index structure)
;        data : 2D image data array.     Read head only if not present
; KEYWORDS (OUTPUT):
; COMMON BLOCKS:
; SIDE EFFECTS:
; RESTRICTIONS:
;        Only for a single 2D image (except for shortindex feature)
; PROCEDURE:
; MODIFICATION HISTORY:
;        JPW, 9/1/2006
;        JPW, 1/16/2007  added call to sb_icerdiv2 to fix SECCHI images
;        JPW, 2/16/2007  added call to euvi_point.pro
;-

PRO sb_readfits,f,i,d,shortindex=shin

if keyword_set(shin) then begin

; /shortindex set: extract specific header information and return
  i = -1
  ; define the output structure:
  io0 = {naxis1:0L,naxis2:0L,summed:0,tt:0d,exptime:0., $
         obsrvtry:'',detector:'',wave_len:'',filename:''}

  ; treat (multi-image) TRACE files separately:
  ww = where(strmid(f,4,1,/reverse) eq '#',nn)
  if nn gt 0 then begin
    ; loop through files, each with possibly multiple images
    for j=0,nn-1 do begin
      ftr = f[ww[j]]
      ftr = strmid(ftr,0,strlen(ftr)-5)
      read_trace,ftr,-1,itn
      nim = n_elements(itn)
      ion = replicate(io0,nim)
      ion.naxis1 = itn.naxis1
      ion.naxis2 = itn.naxis2
      ion.summed = itn.cdelt1/0.49          ; summed rounded to integer
      ion.tt = anytim(itn.date_obs)
      ion.exptime = itn.sht_mdur
      ion.detector = strupcase(itn.instrume)
      ion.wave_len = strupcase(itn.wave_len)
      ion.filename = ftr+'#'+string(indgen(nim),f='(i4.4)')
      s_i = size(i)
      if s_i[s_i[0]+1] eq 8 then i = [i,ion] else i = ion
    endfor
  endif
  ; non-TRACE images in flat FITS files:
  ww = where(strmid(f,4,1,/reverse) ne '#' and f ne '',nn)
  if nn gt 0 then begin
    ff = f[ww]
    ; index template:
    it0={naxis1: 0L, naxis2: 0L,        $
         date_obs:'',                   $
         date_d$obs:'', time_d$obs:'',  $    ; LASCO+mreadfits workaround
         cdelt1: 0.0,                   $
         obsrvtry: '',                  $
         instrume: '', detector: '',    $
         wavelnth: 0,                   $
       ; obs_type: '',                  $    ; MDI vis. or mag.
         exptime: 0.0}
   ; mreadfits,ff,ii,strtemplate=it0,/nocom,/nohis  ; read just headers
   ; ; check if one index element per file, if not then something isn't right:
   ; if n_elements(ii) ne nn then return
   ii = sb_qmheadfits(ff,it0)
    ; output structure:
    ion = replicate(io0,nn)

    ; fix up various keywords and populate output structure
    ion.naxis1 = ii.naxis1
    ion.naxis2 = ii.naxis2
    ; date_obs:
    ww = where(ii.date_obs eq '',nww)
    if nww gt 0 then ii[ww].date_obs = ii[ww].date_d$obs
    ww = where(strlen(ii.date_obs) eq 10,nww)
    if nww gt 0 then ii[ww].date_obs = ii[ww].date_obs+'T'+ii[ww].time_d$obs
    ion.tt = anytim(ii.date_obs)
    ion.exptime = ii.exptime
    ; detector, obsrvtry, summed:
    ii.detector = strupcase(ii.detector)
    ii.instrume = strupcase(ii.instrume)
    ii.obsrvtry = strupcase(ii.obsrvtry)
  ; ii.obs_type = strupcase(ii.obs_type)
    ww = where(strmid(ii.instrume,0,3) eq 'EIT',nww)
    if nww gt 0 then begin
      ion[ww].obsrvtry = 'S'
      ion[ww].detector = 'EIT'
      ion[ww].summed   = ii[ww].cdelt1/2.5     ; summed rounded to integer
    endif
    ww = where(strmid(ii.instrume,0,3) eq 'MDI',nww)
    if nww gt 0 then begin
      ion[ww].obsrvtry = 'S'
      ion[ww].detector = 'MDI'
      ion[ww].summed   = ii[ww].cdelt1/1.9     ; summed rounded to integer
    endif
    ww = where(strmid(ii.detector,0,2) eq 'C2',nww)
    if nww gt 0 then begin
      ion[ww].obsrvtry = 'S'
      ion[ww].detector = 'C2'
      ion[ww].summed   = ii[ww].cdelt1/11.     ; summed rounded to integer
    endif
    ww = where(strmid(ii.detector,0,2) eq 'C3',nww)
    if nww gt 0 then begin
      ion[ww].obsrvtry = 'S'
      ion[ww].detector = 'C3'
      ion[ww].summed   = ii[ww].cdelt1/55.     ; summed rounded to integer
    endif
    ww = where(strmid(ii.obsrvtry,0,6) eq 'STEREO',nww)
    if nww gt 0 then ion[ww].obsrvtry = strmid(ii[ww].obsrvtry,7,1)
    ww = where(strmid(ii.detector,0,4) eq 'EUVI',nww)
    if nww gt 0 then begin
      ion[ww].detector = 'EUVI'
      ion[ww].summed   = ii[ww].cdelt1/1.5     ; summed rounded to integer
    endif
    ww = where(strmid(ii.detector,0,4) eq 'COR1',nww)
    if nww gt 0 then begin
      ion[ww].detector = 'COR1'
      ion[ww].summed   = ii[ww].cdelt1/3.6     ; summed rounded to integer
    endif
    ww = where(strmid(ii.detector,0,4) eq 'COR2',nww)
    if nww gt 0 then begin
      ion[ww].detector = 'COR2'
      ion[ww].summed   = ii[ww].cdelt1/14.     ; summed rounded to integer
    endif
    ; wave_len:
    ww = where(ion.detector eq 'EUVI' or ion.detector eq 'EIT',nww)
    if nww gt 0 then ion[ww].wave_len = strtrim(ii[ww].wavelnth,2)
 ;  ww = where(ion.detector eq 'MDI',nww)
 ;  if nww gt 0 then ion[ww].wave_len = strmid(ii[ww].obs_type,0,1)
    ; detector for other instruments:
    ww = where(ion.detector eq '' and ii.detector ne '',nww)
    if nww gt 0 then ion[ww].detector = strtrim(ii[ww].detector)
    ww = where(ion.detector eq '',nww)
    if nww gt 0 then ion[ww].detector = strtrim(ii[ww].instrume)
    ; filename:
    ion.filename = ff
    s_i = size(i)
    if s_i[s_i[0]+1] eq 8 then i = [i,ion] else i = ion
  endif

endif else begin

; /shortindex not set: read a single 2D image
  d = -1
  i = -1
  f1 = f[0]
  flen = strlen(f1)
  if strmid(f1,flen-5,1) eq '#' then begin        ; is TRACE multi-image file
    tfil = strmid(f1,0,flen-5)
    inum = fix(strmid(f1,flen-4,4))
    if file_test(tfil) eq 0 then return           ; does file exist?
    read_trace,tfil,inum,i,d,/quiet               ; read image
    i = trace_wave2point(i,/quiet)                ; adjust pointing
    if tag_exist(i,'NAXIS') eq 0 $                ; trace index lacks NAXIS
      then i = add_tag(i,2L,'NAXIS')
    if tag_exist(i,'EXPTIME') eq 0 and tag_exist(i,'SHT_MDUR') $
      then i = add_tag(i,i.sht_mdur,'EXPTIME')    ; SHT_MDUR -> EXPTIME
  endif else begin
    if n_params() gt 2 then begin
      d = readfits(f1,h,/silent)   ; or sccreadfits? no reason (prob. slower)
    endif else begin
      h = headfits(f1)
    endelse
    if n_elements(h) le 1 then return
    i = fitshead2struct(h)
    sb_icerdiv2,i,d      ; fixes ICER compressed SECCHI images with DIV2
    euvi_point,i,/quiet  ; update pointing in header
  endelse
endelse

end
