pro medfilt,INcube,nn,OUTcube
;
;Applies median filter for MIPS-Ge data on data cube 
;of stacked BCDs images by subtracting median of the 
;surrounding DCEs per pixel
;(temporal median filter per pixel)
;;
;;INcube = stacked cube of bcd images
;;OUTcube = median filtered output cube
;;nn = full width filter size in DCEs 
;;
;Users need to stack input BCDs into a cube before running.
;After medfilt correction, users need to split OUTcube into
;corrected BCDs and attach pointing information (headers) 
;from the original BCD images before mosaicing the data.
;For small nn, users should not include the stim DCEs in
;the input data cube.  
;;
;Notes:
; JPL and the SSC claim no responsibility for this script.
; From the project point of view, this is unoffical 
; software, provided as an example to users.  
; Your mileage may vary.
;
;Feel free to report any bugs to frayer@ipac.caltech.edu
;Frayer, version 2004 June 22
;;
sizeIN=size(INcube)
xIN=sizeIN(1)
yIN=sizeIN(2)
zIN=sizeIN(3)
OUTcube=INcube
;;Use +/- nn/2 DCEs around current DCE
mm=round(nn/2.)
for zz=0,zIn-1 do begin
  z1=zz-mm
  z2=zz+mm
  z1a=zz-1
  z2a=zz+1
;;handle end-pts
  if (z1 lt 0) then begin
     z1=0
     z2=2*mm
  endif      
  if (z2 gt zIn-1) then begin
     z2=zIN-1          
     z1=z2-2*mm  
  endif
  if (zz eq 0) then begin
     z1=1
     z1a=2
     z2a=3
  endif
  if (zz eq zIn-1) then begin
     z1a=zIn-4
     z2a=zIn-3
     z2=zIn-2
  endif
  st1=z1a-z1+1
  st2=z2-z2a+1
;;explicitly define as vectors
  t1=fltarr(st1)
  t2=fltarr(st2)
  for xx=0,Xin-1 do begin
    for yy=0,Yin-1 do begin
;;do not include current DCE in median
      t1[*]=INcube[xx,yy,z1:z1a]
      t2[*]=INcube[xx,yy,z2a:z2]
      tmp=[t1,t2]
      tmp1=median(tmp,/even)
      OUTcube[xx,yy,zz]=INcube[xx,yy,zz]-tmp1
    endfor
  endfor
endfor
;;IDL ignores NaNs in the median
;
return
end


