;+
; NAME:
;    wimagr_data2fits
; PURPOSE:
;    Writes wimagr map data array into multidimensional fits file with binary extensions
; CATEGORY:
;     OVSA
; CALLING SEQUENCE:
;     wimagr_data2fits,file,data,header,maps=maps,info=info,_extra=_extra
; INPUTS:
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;
; ROUTINES CALLED:
;
; OUTPUTS:
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 14-May-2014 Gelu M. Nita
;
pro wimagr_data2fits,file,data,header,maps=maps,info=info,_extra=_extra
  On_error,2                    ;Return to user
  compile_opt idl2
 if size(maps,/tname) eq 'STRUCT' then begin
  ;Check data and header for compatibility
   n=n_elements(maps)
   dim=size(maps,/dim)
   np=dim[0]
   nf=dim[1]
   nt=dim[2]
   data=maps.data
   header=maps[0].header
   index=add_tag(maps.index,header,'header')
   ntags=n_tags(maps.index)
   for i=0, n_elements(index)-1 do begin
    for j=0, ntags-1 do index[i].(j)=maps[i].index.(j)
    index[i].(j)=maps[i].header
   endfor
   fxhmake,hdr,data,/extend,/date,/initialize
   ;Write image header and data
   if n_elements(header) gt 2 then data_header=[hdr[0:where(strcompress(hdr,/rem) eq 'END')-1],header[5:*]] else data_header=hdr
   fxwrite,file,data_header,data
   wimagr_struct2fits,file,info,'info',comments='common parameters'
   wimagr_struct2fits,file,index,'index',comments='map ependent parameters'
  endif else begin
    ;Here we modify fits records
    if N_params() LT 2 then begin
      message,string(13b)+'Syntax to create a new fits file- ' + $
        'wimagr2fits, Filename, maps'+string(13b)+$
        'Syntax to modify an xisting fits file- ' + string(13b)+$
        'wimagr2fits, Filename, data, header, extname/ext_no=extname/ext_no,/modify'
    endif
    MODFITS, file, data, header,_extra=_extra
  endelse
end