
pro mwritefits, iindex, data, $
    outfile=outfile, outdir=outdir, $
    NaNvalue=NaNvalue, $
    flat_fits=flat_fits, fitstype=fitstype,   $
    append=append, nocomment=nocomment, loud=loud,  quiet=quiet, $
    prefix=prefix, extension=extension, incsize=incsize, $
    comments=comments, fcomments=fcomments, history=history, temp=temp
    
;+
;   Name: mwritefits
;
;   Purpose: index/data to specified type of FITS file 
;
;   Input Parameters:
;      index - index structures 
;      data  - corresponding 2d/3d data array
;  
;   Keyword Parameters:
;      NaNvalue - passed through to writefits
;      outfile - if supplied, use this/these file names (including outdir/path)
;                if not supplied, files are auto-named based on DATE_OBS
;      outdir  - if supplied, direct files to this directory (names derived)
;      prefix  - if supplied, 'PREFIX' prepended to autonamed files (def='mwf')
;      extension - if supplied, appended to auto-named files (def='.fits')
;      fitstype - type of file:
;                0 => 'mxf' (trace-like)
;                1 => N-dimensional FITS data, 1 index per data rec
;      nocomment - switch, if set, dont add comment from this routine
;      flat_fits - switch, if set, fitstype=1
;                (N-dimensional FITS data, 1 index per data rec)
;  
;   Calling Sequence:
;      mwritefits, index, data           ; 1 image per index/data pair  
;
;      mwritefits, index, data [,outfile=outfile, outdir=outdir,  $
;                                prefix=prefix, extension=extension]
;   Calls:
;      data_chk, time2file, fxhmake, struct2fitshead, writefits, 
;      box_message, required_tags, str_taginfo
;
;   TODO:
;      Handle 'mxf' (tracelike) files
;
;   History:
;      24-Jun-1998 - S.L.Freeland - from write_trace
;      19-Nov-1998 - S.L.Freeland - include SECONDs in auto named files
;                                   (via time2file(/sec)
;                                   strip nested structure tags 
;      06-dec-2009 - S.L.Freeland - allow 'date_obs' only index
;-

version  = '2.0'
pcomment = 'mwritefits, Version:' + version + '  ' + systime()
nocomment = keyword_set(nocomment)

case 1 of
  nocomment:
  data_chk(fcomments,/string):fcomments=[fcomments,pcomment]
  else: fcomments=pcomment
endcase

index = iindex

loud = keyword_set(loud)
named = data_chk(outfile,/string)
nooutdir = 1-data_chk(outdir,/string)
n_index = n_elements(index)
n_dim_index = index[0].naxis
siz_data = size(data)
n_dim_data = siz_data[0]

; index/data consistency check:
if ( (n_index eq 1) and (n_dim_index ne n_dim_data) ) then begin
     error_flag = 1
     print, 'Inconsistent index structure and data array.  Returning.'
     return
endif

case n_dim_index of
   1 : n_image = n_elements(data[0,*])
   2 : n_image = n_elements(data[0,0,*])
   3 : n_image = n_elements(data[0,0,0,*])
   4 : n_image = n_elements(data[0,0,0,0,*])
   5 : n_image = n_elements(data[0,0,0,0,0,*])
   else : begin
             error_flag = 2
             print, 'Arrays with more than 5 dimensions not handled.  Returning.'
             return
   end
endcase

if n_index ne n_image then begin
   error_flag = 3
   box_message, 'Mismatch between n_index and n_image.  Returning.'
   return
endif

if n_elements(fitstype) eq 0 then fitstype=1          ; default = 2D 

case 1 of
   named:                                             ; fully specified
   data_chk(outdir,/string): outdir=outdir(0)
   nooutdir: outdir=curdir()
   else: box_message, 'I thought it would never get here???'
endcase

if not data_chk(outdir,/string) then outdir=curdir()

if not file_exist(outdir) then begin
  box_message,['Requested output directory',outdir(0), 'does not exist'],/center
  return
end  

flat=keyword_set(flat_fits) or fitstype(0) eq 1 

suggested='naxis1, naxis2, crpix1, crval1, cdelt1, date_obs'
if not required_tags(index,suggested,missing=missing) and loud then $
   box_message,'Suggested tags: ' + arr2str(missing) +' are missing from input structures...'

tnames=tag_names(index)
tagstructs=where(str_taginfo(index,/type) eq 8,scnt)

if scnt gt 0 then begin
   box_message,['Stripping nested structures from index: ', tnames(tagstructs)]
   index=str_subset(index,tnames(tagstructs),/exclude)
endif  

case fitstype of
   1: begin
   if not data_chk(prefix,/string) then prefix='mwf'
   if not data_chk(extension,/string) then extension=(['.fits','.fts'])(keyword_set(soho))
   if 1-named then begin
      tindex=index
      case 1 of
         required_tags(tindex,'mjd,time') or required_tags(tindex,'day,time'):
         required_tags(tindex,'date_obs'): $
            tindex=join_struct(anytim(tindex.date_obs,/utc_int),tindex)
         else: box_message,'unexpected ssw times?'
      endcase
      outfile = concat_dir(outdir, prefix + time2file(tindex,/sec) +  extension)
   endif

   n_outfile = n_elements(outfile)
   if n_index ne n_outfile then begin
      error_flag = 4
      box_message, 'Mismatch between n_index and n_outfile.  Returning.'
      return
   endif

; Loop through index/data pairs, constructing header and data record for each file,
;   and write file:

   for i=0,n_index-1 do begin

; Extract data record for this file (handles sub-arrrays) :
      case n_dim_index of
         1 : data_rec = data[0:index(i).naxis1-1, i]
         2 : data_rec = data[0:index(i).naxis1-1, 0:index(i).naxis2-1, i]
         3 : data_rec = data[0:index(i).naxis1-1, 0:index(i).naxis2-1, 0:index(i).naxis3-1, i]
         4 : data_rec = data[0:index(i).naxis1-1, 0:index(i).naxis2-1, 0:index(i).naxis3-1, 0:index(i).naxis4-1, i]
         5 : data_rec = data[0:index(i).naxis1-1, 0:index(i).naxis2-1, 0:index(i).naxis3-1, 0:index(i).naxis4-1, 0:index(i).naxis5-1, i]
         else : begin
                   error_flag = 2
                   print, 'Arrays with more than 5 dimensions not handled.  Returning.'
                   return
         end
      endcase

      header_rec = struct2fitshead(index[i], /allow, comments=comments)
; Clean and add data info:
      fxhmake, header_rec, data_rec
; Write FITS file (N dimensional flat)
      writefits, outfile[i], data_rec, header_rec, NaNvalue=NaNvalue

      if loud then box_message, 'Wrote>> ' + outfile[i]
   endfor	

   endcase
   else: box_message, 'Only N-dimensional FITS data rec, 1 index per data rec, handled.'
endcase

return
end
