function chi_norm,cflux,oflux,eflux,back,norm=norm,bnorm=bnorm,subs=subs
;+
; NAME:
;       CHI_NORM
; PURPOSE:
;       compute chi^2 between observed and computed data
; CALLING SEQUENCE:
;       chi2=chi_norm(cflux,oflux,eflux,norm=norm)
;       chi2=chi_norm(cflux,oflux,eflux,back,subs=subs,norm=norm,bnorm=bnorm)
; INPUTS:
;       cflux  = computed data
;       oflux  = observed data
;       eflux  = sigma error on oflux
; OPTIONAL INPUTS:
;       back   = Background data (assumed to be a vector the same length as oflux, clfux)
; OUTPUTS:
;       chi2   = chi^2 = total [ (oflux-norm*cflux)^2/eflux^2 ]
;       chi2   = chi^2 = total [ (oflux-norm*cflux-bnorm*back)^2/eflux^2 ]
; OPTIONAL OUTPUT KEYWORDS:
;       norm   = normalization to make cflux = oflux 
;       bnorm  = normalization for the background
;       subs   = indicies to include in chi^2 calculation
; HISTORY:
;   18-sep-93, J. R. Lemen (LPARL) and D. M. Zarro (ARL), Written.
;	
;-


on_error,1

if (n_params() lt 3) then $
 message,'---> CHI=CHI_NORM(CFLUX,OFLUX,EFLUX,NORM=NORM,SUBS=SUBS)

if n_elements(subs) eq 0 then subs=indgen(n_elements(oflux))

sigma2=eflux(subs)^2

if n_params() eq 3 then	begin				; No background supplied
   norm = total(cflux(subs)*oflux(subs)/sigma2)/ 	$ 
   total(cflux(subs)^2/sigma2) 

   return,total((oflux(subs)-norm*cflux(subs))^2/sigma2)
endif else begin

   if n_elements(back) ne n_elements(cflux) then message,'Length of back must match cflux'

   A0 = total(oflux(subs)*cflux(subs)/sigma2)
   A1 = total(cflux(subs)^2/sigma2)
   A2 = total(cflux(subs)*back(subs)/sigma2)
   B0 = total(oflux(subs)*back(subs)/sigma2)
   B2 = total(back(subs)^2/sigma2)

   bnorm = (A0*A2 - B0*A1) / (A2^2-A1*B2)
   norm  = (A0 - bnorm*A2) / A1   
   return,total((oflux(subs)-norm*cflux(subs)-bnorm*back(subs))^2/sigma2)
endelse

end
