; Read a bayes.dat file and convert it to bayes.fits
;
; EJ 08/2009

; If input is not set, default is bayes.dat
if n_elements(input) eq 0 then input='bayes'

; Read the header
print, 'Process file '+input+'.dat'
openr, 1, input+'.dat'
i=0
line='#toto'
while strmid(line,0,1) eq '#' do begin readf,1,line & i++ & endwhile
close, 1

; Read data
f=read_ascii(input+'.dat', data_start=i-1, header=hdr)

; Create the FITS column names from bayes.dat header
for i=0, n_elements(hdr)-1 do begin 
	line='' 
    ; analyse each character of hdr[i]
	for j=0, strlen(hdr[i])-1 do begin 
		c = strmid(hdr[i],j,1) 
        if j EQ 1 AND strmatch(c,'[0-9]') then c='P'+c
		if c EQ ' ' OR c EQ '.' then c='_' 
		if c NE '#' AND c NE '(' AND c NE ')' AND c NE ':' AND c NE '/' then line+=c 
	endfor 
	hdr[i]=line 
endfor

; Create an empty IDL structure to be filled with the bayes.dat samples
struct=create_struct(hdr[0],0L)
for i=1, n_elements(hdr)-1 do struct=create_struct(struct, hdr[i],0.);

; Replicate and fill the IDL structure for each row of the bayes.dat
d=f.(0)
nl=n_elements(d[0,*])
data=replicate(struct,nl)
for i=0L,nl-1 do for j=0, n_elements(d[*,0])-1 do data[i].(j)=d[j,i]

; Write the FITS file
spawn, 'rm '+input+'.fits'
mwrfits, data, input+'.fits'

END