pro jailbar,infile,outfile, VERBOSE=verbose
;
; NAME:
;    JAILBAR
; PURPOSE:
;    Remove column-wise additive offsets in IRAC data
;
; CALLING SEQUENCE:
;    jailbar,infile,outfile
;
; INPUTS:
;    infile = ASCII string containing an input image filename
;    outfile = ASCII string containng an output image filename
;    /verbose = print columns-wise stats
;
; OUTPUTS:
;    A copy of the input image to which a set of median levels have
;    been fit to every 4th column. The four sets of columns are set
;    equal to their arithmetic mean. A single additive constant is applied
;    to every column.
;
; EXAMPLES:
;
;    jailbar,'IRAC.4.5878016.0064.0000.3.colorcorr.fits','test.fits'
;
; MODIFICATION HISTORY
;    originally developed for IRAC-IST and SWIRE, J.Surace, (4/8/06)

verbose = keyword_set(VERBOSE)

; read the input image
bcd=readfits(infile,hd)
   naxis1=sxpar(hd,'NAXIS1')
   naxis2=sxpar(hd,'NAXIS2')
    columns=naxis1/4
out=bcd

; make 4 subarrays containing the individual amplifiers
readout=fltarr(columns,naxis2,4)
for i=0,columns-1 do begin
    readout[i,*,0]=bcd[i*4,*]
    readout[i,*,1]=bcd[(i*4)+1,*]
    readout[i,*,2]=bcd[(i*4)+2,*]
    readout[i,*,3]=bcd[(i*4)+3,*]
endfor

; get the column-wise median values
back=fltarr(4)
 back[0]=median(readout[*,*,0])
 back[1]=median(readout[*,*,1])
 back[2]=median(readout[*,*,2])
 back[3]=median(readout[*,*,3])
if verbose then print,'Column-wise medians:',back

; compute columnwise offsets
offset=fltarr(4)
 offset[0]=mean(back)-back[0]
 offset[1]=mean(back)-back[1]
 offset[2]=mean(back)-back[2]
 offset[3]=mean(back)-back[3]
if verbose then print,'Offsets:',offset


; apply the offsets
for i=0,columns-1 do begin
    out[i*4,*]=bcd[i*4,*]+offset[0]
    out[(i*4)+1,*]=bcd[(i*4)+1,*]+offset[1]
    out[(i*4)+2,*]=bcd[(i*4)+2,*]+offset[2]
    out[(i*4)+3,*]=bcd[(i*4)+3,*]+offset[3]
endfor

; write the output image
sxaddhist,'Jailbar corrector applied',hd
writefits,outfile,out,hd


end

