;******************************************************************************
;Make one coadded image for each subset of the input list of BCD
;images that share the same module, aorkey, and expid.  (See the IRS
;Data Handbook for definitions of these quantities.)
;
;INPUTS:
;
;masterlist = required list of BCD images to coadd, one image name per
;row.  This can contain images with different modules, aorkeys, and
;expids.  
;
;verbose = optional keyword.  If set, information about the processing
;will be printed to the screen.
;
;fatalbits = optional keyword allowing the user to set the bits
;considered to be fatal.  These will be set to NaN in the BCD and
;uncertainty files before coaddition.  The input keyword should be an
;array containing the fatal bits.  The default is 
;fatalbits = [7, 8, 12, 13, 14].  If a user wishes to have no fatal
;bits, they should set fatalbits = [999].
;
;OUTPUTS:
;
;coadded images - *coa2d.fits
;
;uncertainty images - *c2unc.fits
;
;mask files - *c2msk.fits
;
;BCD subsample lists = *bcdlist.txt.  These can be used as input to
;coad.pro, if the user wishes to re-create a single coad with different fatal
;bits, for instance.
;
;******************************************************************************
pro doall_coads, masterlist, verbose=verbose, fatalbits=fatalbits

;Read in the list of BCDs of all nod positions.
readcol, masterlist, filenames, format = '(a)', /silent

;Initialize arrays to hold nod position and other information.
num = n_elements(filenames)

module = strarr(num)
aorkey = strarr(num)
expid = strarr(num)
dcenum = strarr(num)
version = strarr(num)
type = strarr(num)

;Determine nod position and other information for each input filename.
for i = 0, num - 1 do begin

   nameparts = strsplit(filenames[i], '_', /extract)

   module[i] = nameparts[1]

   aorkey[i] = nameparts[2]

   expid[i] = nameparts[3]

   dcenum[i] = nameparts[4]

   version[i] = nameparts[5]

   type[i] = repstr(nameparts[6], '.fits', '')

endfor

;Figure out which BCDs go together.
coadd_num_array = dblarr(num)

coadd_num = 1

for i = 0, num - 1 do begin

   if coadd_num_array[i] eq 0 then begin

      index = where(module eq module[i] and $
                    aorkey eq aorkey[i] and $
                    expid eq expid[i], count)

      coadd_num_array[index] = coadd_num

      coadd_num = coadd_num + 1.

   endif

endfor

;Do the coads.
for i = 1, coadd_num - 1 do begin

   index = where(coadd_num_array eq i, count)

   bcdlist = 'SPITZER'+'_'+module[index[0]]+'_'+aorkey[index[0]]+'_'+expid[index[0]]+'_bcdlist.txt'

   openw, i+1, bcdlist

   for j = 0, count - 1 do begin

      printf, i+1, filenames[index[j]]

   endfor

   close, i+1

   coad, bcdlist, verbose=verbose, fatalbits=fatalbits

endfor

end
