pro make_3plane,dirname=dirname,pu=pu,outdir=outdir

; IDL procedure to create a SMART readable 3plane format file
;
; Input is the directory which contains the bcd.fits, func.fits, bmask.fits
; SYNTAX: make_3plane,dirname="/home/joe/data/bcd"
;
; If you have peak-up imaging data in the same directory, set the pu keyword
; and that will reject the first 8 files which are the PU acquisition and
; sweet spot files
;
; If you set the outdir keyword to "/home/joe/bcd3p", then the bcd3p files 
; will be written to the /home/joe/bcd3p directory. It is your responsibility
; to ensure that the output directory exists.
;
; made a minor correction to avoid truncation of file names
;
; March 2005, v. 1.0, R. Chary

if not keyword_set(dirname) then begin
  print,'Options for usage'
  print,'Syntax with no peak-up data: make_3plane,dirname="/home/joe/data/bcd"'
  print,'Syntax with peak-up data: make_3plane,dirname="/home/joe/data/bcd",/pu'
  print,'Syntax with peak-up data and writing to a different output directory: make_3plane,dirname="/home/joe/data/bcd",/pu,outdir="/home/joe/bcd3p" but be sure to create the output directory using mkdir'
  return
endif

rootdir = dirname

infname = file_search(rootdir+'/*_bcd.fits')

nfile = n_elements(infname)
if (keyword_set(pu)) then infname = infname[8:nfile-1]
nfile = n_elements(infname)

for ct=0,nfile-1 do begin
  rootfname = strmid(infname[ct],0,strlen(infname[ct])-8)

  if keyword_set(outdir) then begin
       bval = strpos(infname[ct],'SPI',/reverse_search)
       eval = strpos(infname[ct],'bcd',/reverse_search)
       outfname = outdir+'/'+strmid(infname[ct],bval,eval-bval)
  endif else begin
       outfname = rootfname
       outdir = rootdir
  endelse

  bcdname = rootfname+'bcd.fits'
  buncname = rootfname+'func.fits'
  bmaskname = rootfname+'bmask.fits'

  bcdfile = readfits(bcdname,hdr1,/silent)
  buncfile = readfits(buncname,hdr2,/silent)
  bmaskfile = readfits(bmaskname,hdr3,/silent)

  fits_open,outfname+'bcd3p.fits',fcb,/write
  fits_write,fcb,bcdfile,hdr1
  fits_write,fcb,buncfile,hdr2
  fits_write,fcb,bmaskfile,hdr3
  fits_close,fcb

endfor
print,'Done creating bcd3p.fits files in directory ',outdir

end
