pro chi2,vis,mvis,svis,circles,chi2,phase=phase,help=help

if keyword_set(help) then begin
	print,'PURPOSE: '
	print,' Calculate chi^2 using RHESSI and MEM (Model) Visibilities'
	print,' Can be used for phases and visibilities'
	print,'HELP: '
	print,'	pro chi2,vis,mvis,svis,circles,chi2,help=help'
	print,'	inputs: vis (RHESSI Visibilities)'
	print,'		mvis (Model Visibilities)'
	print,'		svis (Standard deviation used in MEM)'
	print,'		circles (zero offset 2-element array with starting and ending uv circle)'
	print,'		phase (default: no, /phase determines chi^2 for phases)'
	print,'	outputs:chi2 (Non-normalized and normalized chi^2 array)'
	print,'AUTHOR:'
	print,'	Rick Pernak, Goddard Space Flight Center'
	return
endif

size_vis = size(vis,/n_elements)		;number of array elements
size_mvis = size(mvis,/n_elements)	;for looping purposes (see n)
size_svis = size(svis,/n_elements) 	

if (size_vis ne size_mvis) or (size_vis ne size_svis) then begin
	print,'Dimensions do not agree, returning'
	return
endif

ncircles = (circles[1]-circles[0])+1 ; number of circles
n = size_vis ;number of data points
chi2 = dblarr(2) ;chi2 array, un-normalized and normalized

if keyword_set(phase) then begin
	print,'Calculating chi^2 for phases'
	;mvis and vis here are actually model phase and observed phase
	num = mvis-vis ;numerator or chi^2
	chi2_arr = num^2/svis^2
	chi2[0] = total(chi2_arr)
	chi2[1] = chi2[0]/n
endif else begin
	print,'Calculating chi^2 for amplitudes'
	num = abs(mvis-vis) ;numerator or chi^2
	chi2_arr = num^2/svis^2
	chi2[0] = total(chi2_arr)
	chi2[1] = chi2[0]/n
endelse

return
end