;Writes any fits compatible structue to fits file as a binary extension
;created 
;+
; NAME:
;    wimagr_struct2fits
; PURPOSE:
;    Writes any fits compatible structue to a fits file as a binary extension
; CATEGORY:
;     OVSA 
; CALLING SEQUENCE:
;     wimagr_struct2fits,file,struct,extname,header=header,comments=comments
; INPUTS:
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;
; ROUTINES CALLED:
;
; OUTPUTS:
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
; No structure tags allowed in the input structure
; MODIFICATION HISTORY:
;     Written 14-May-2014 Gelu M. Nita
;    
pro wimagr_struct2fits,file,struct,extname,header=header,comments=comments
  On_error,2                    ;Return to user
  compile_opt idl2
  if N_params() LT 2 then message, 'Synax-wimagr_struct2fits,file,struct[,extname,header=header,comments=comments]'
  ;add a structure to a binary fits extentio table
  if size(struct,/tname) eq 'STRUCT' then begin
    ;Create common extension header
    nrows=n_elements(struct)
    if n_elements(extname) eq 0  then extname='structure'
    if n_elements(comments) eq 0  then comments='structure'
    fxbhmake,header,nrows,extname,comments,/initialize
    ;
    ncol=n_tags(struct)
    tags=tag_names(struct)
    columns=intarr(ncol)
    for i=0,ncol-1 do begin
      fxbaddcol,idx,header,struct[0].(i),tags[i]
      columns[i]=idx
    endfor
    ;Write out structure data
    fxbcreate,unit,file,header
    for i=0,ncol-1 do begin
      for j=1,nrows do fxbwrite,unit,struct[j-1].(i),columns[i],j
    endfor
    ;  Close the binary extension.
    fxbfinish,unit
  end
end