Viewing contents of file '../idllib/astron/contrib/varosi/vlibm/allpro/chi_auto_corr.pro'
function chi_Auto_Corr, image, auto_corr, mode, SIGMA_NOISE=sigma, $
						LAG_AUTO_CORR=Lag_ac, $
						RATIO=ratio, SPECTRUM=spectrum
;Frank Varosi NASA/GSFC 1992.

  common chi_Auto_Corr, Lag_switch

	if N_elements( Lag_switch ) NE 1 then Lag_switch = 3
	if N_elements( Lag_ac ) EQ 1 then Lag = Lag_ac else Lag = 8
	if N_elements( Lag0 ) NE 1 then Lag0=0

	sim = size( image )
	npix = sim(sim(0)+2)
	Lag = (Lag > 1) < ( min( sim(1:2) )/2 -1 )

	if (Lag LE Lag_switch) then begin

		auto_corr = fltarr( 2*Lag+1, Lag+1 )
		if (Lag0) then auto_corr(Lag,0) = total( image * image )

		for i=Lag+1,2*Lag do $
		   auto_corr(i,0) = total( image * shift( image, i-Lag, 0 ) )

		for j=1,Lag do begin
		  for i=0,2*Lag do $
		     auto_corr(i,j) = total( image * shift( image, i-Lag, j ) )
		  endfor

	  endif else begin

		auto_corr = convolve( image, /AUTO_CORREL )

		s = sim/2 - Lag
		s(2) = s(2) + Lag
		L = sim/2 + Lag		;get the non-redundant elements only.

		auto_corr = auto_corr(s(1):L(1),s(2):L(2))
		auto_corr(0:Lag-1,0) = 0
	   endelse

	if N_elements( sigma ) NE 1 then sigma = stdev( image )
	sig2 = npix * sigma^2
	sig4 = npix * sigma^4

	if (Lag0) then auto_corr(Lag,0) = (auto_corr(Lag,0)-sig2)/sqrt(2) $
		  else auto_corr(Lag,0)=0

	if keyword_set( spectrum ) then begin

		Lags = indgen( Lag ) + 1
		modes = (2*Lags+1)*(Lags+1) - Lags - 3
		if (Lag0) then modes = modes+1
		chis = fltarr( Lag )
	    	for j=1,Lag do $
			chis(j-1) = total( auto_corr( Lag-j:Lag+j, 0:j )^2 )
		chis = chis/sig4
		if keyword_set( ratio ) then chis = chis/modes
		return, [ [modes], [chis] ]

	  endif else begin

		mode = (2*Lag+1)*(Lag+1) - Lag - 3
		if (Lag0) then mode = mode+1
		chisq = total( auto_corr * auto_corr )/sig4
		if keyword_set( ratio ) then return, chisq/mode $
					else return, chisq
	   endelse
end