pro spartan_pb2fits
read_spartan,index,file=file
ssgood=where(index.img_qual eq 1,nraw)          ; filter bad (night,cal,saturated)
sspb=sel_spartan_pb(index(ssgood))          ; jrl triplet paring routines
npb = n_elements(sspb(*,0))             ; number of composite images

for i=0,npb-1 do begin                  ; for every triplet
   ssx=reform(ssgood(sspb(i,*)))            ; SS for triplet
   read_spartan,indx,datax,ss=ssx           ; read raw data triplet
   make_spartan_pb,datax,indgen(3),b_img,pb_img     ; make the corresponding b and pb images
;  get raw FITs info and update header information
   file_zero=file(ssx(0))
   head=headfits(file_zero)             ; start with FITS header from first member

;  --------- add some comments about input images       ;
   text= get_infox(indx,header=header,/fmt_tim, $
         'id,polpos,halfwave') + '  ' + strsplit(file(ssx),'/',/last,/tail) ; text summary for triplet
   text=[' SPARTAN 3 Image Composite...',header + '  Raw File',text]
   for j=0,n_elements(text)-1 do $          ; add comments
       fxaddpar,head,'COMMENT',text(j)   
   fxaddpar,head,'TELESCOP','SPARTAN'           
;
;  --------- write the B file ------------
   fxaddpar,head,'OBJECT','Brightness Image'
   bfile=str_replace(file_zero,'gsp','spa__b')
   fxaddpar,head,'FILENAME',(strsplit(bfile,'/',/last,/tail))(0)
   message,/info,"Writing file: " + bfile(0)
   writefits, bfile, b_img, head   

;  -------- write the PB file ------------
   fxaddpar,head,'OBJECT','PB Image'
   pbfile=str_replace(file_zero,'gsp','spa_pb')
   fxaddpar,head,'FILENAME',(strsplit(pbfile,'/',/last,/tail))(0)
   message,/info,"Writing file: " + pbfile(0)
   writefits, pbfile, pb_img, head   

endfor
end