;+
; radial_bkg
;
; Use the Source, Luke!
;
; BUGS -
;	Only works on co-registered data cubes.
; HISTORY - Modified CRPIX usage for (1,1)-offset, 13-Mar-98
;-
function radial_bkg,pcube,pcubehdr_in,smooth=sm,av=av1,mask=mask
	pcubehdr = ztweak_datum(pcubehdr_in,/disk)
	av = keyword_set(av1)
	nx = n_elements(pcube(*,0,0))
	ny = n_elements(pcube(0,*,0))

	indx = indgen(nx) # replicate(1,ny)
	indy = replicate(1,nx) # indgen(ny)

	radii =  sqrt( (indx(*,*)-(pcubehdr(0).CRPIX1-1))^2 + $
		       (indy(*,*)-(pcubehdr(0).CRPIX2-1))^2 )
	rf = fix(radii+0.5)

	rmax = max(radii,min=rmin)
	rmin=fix(rmin+0.5)
	rmax=fix(rmax+0.5)

	rvals = fltarr(1+ rmax - rmin)

	stack = lindgen(nlm(pcube(0,0,*)))*nlm(pcube(*,*,0))
	
	for i=rmin,rmax do begin
		if isvalid(mask) then $
			w = where(rf eq i and mask) $
		else $
			w = where(rf eq i)
		w0 = w
		for j=1,nlm(stack)-1 do w=[w,w0+stack(j)]
		if(total(w) lt 0) then 					$
			rvals(i-rmin) = -1 else 			$
			if(av) then rvals(i-rmin) = total(pcube(w))/nlm(w) $
			       else rvals(i-rmin) =  min(pcube(w))
		print,rmin,i,rmax,nlm(w)
	end

	if(not isvalid(sm)) then sm=4
	if(sm gt 1) then srvals = smooth(rvals,sm) else srvals = rvals

	return,interpolate(srvals,(radii - rmin))

end







