;+
; NAME:
;	IPS_hlevel_w
; PURPOSE:
;	Calculates weights for integrating IPS g-level
; CATEGORY:
;	sat/idl/toolbox
; CALLING SEQUENCE:
	FUNCTION IPS_hlevel_w, rr_earth, R, F, w3darg,	$
		ut_earth	= ut_earth	, $
		pa_earth	= pa_earth	, $
		elo_earth	= elo_earth , $
		elo_sun 	= elo_sun	, $
		degrees 	= degrees
; INPUTS:
;	rr_earth	array[3]			for 'plain' sky map
;				array[3,N]			for 'transit' sky map
;									location of Earth for all lines of sight
;									in same spherical coordinates as R.
;	R			array[3,N,L,M]		(N,L may be 1 or absent)
;									locations of all segments for all lines of sight
;									in same spherical coordinates as rr_earth
;									(usually heliographic)
;									This can be a grid of NxL lines of sight with M
;									segments along each line of sight
;									R[0,*,*,*] : longitude
;									R[1,*,*,*] : latitude
;									R[2,*,*,*] : heliocentric distance
;	F								not used
;	w3darg		array[4]			w3darg[0] = observing freq (MHz)
;									w3darg[1] = source size (arcsec)
;									w3darg[2] = extra source size scale factor
;									w3darg[3] = beta_r
; OPTIONAL INPUT PARAMETERS:
;	/degrees						if set all input angles should be in degrees (default: radians)
;	ut_earth						not used
;	pa_earth						not used
;	elo_earth						not used
;	elo_sun							not used
; OUTPUTS:
;	R			array[N,L,M]		weight factors
; INCLUDE:
	@compile_opt.pro			; On error, return to caller
; CALLS:
;	SuperArray, IPS_WeightFnc
; RESTRICTIONS:
;	For each line of sight segment the weight is the product of a factor
;	which is a function heliocentric distance and a factor which is a
;	function of the geocentric distance. The second factor is calculated
;	for one line of sight only on the assumption that it's the same for
;	all lines of sight.
; PROCEDURE:
; MODIFICATION HISTORY:
;	SEP-1999, Paul Hick (UCSD/CASS)
;	FEB-2007, Paul Hick (UCSD/CASS; pphick@ucsd.edu
;		Modified to work with list of los specified in any configuration
;		(not just as a 2D skymap) 
;-

G = SubArray(R,element=2)				; Heliocentric distance (AU)
G = 1.0/(G*G)^(2.0-w3darg[3])			; r-dependence

S = size(G)
nseg = S[S[0]]							; Number of segments along each line of sight
nlos = S[S[0]+2]/nseg					; Number of lines of sight

; IPS_WeightFnc does a Simpson integration which can take a
; while to converge. IPS_WeightFnc is only applied to one
; line of sight, and the result is used for all others.

S = R
WHILE size(S,/n_dim) GT 2 DO S = SubArray(S,dimension=1,element=0)

E = rr_earth[0:2]						; Position Earth for 1st los
S = cv_coord(from_sphere=S,/to_rect,degrees=degrees); Convert to Cartesian coordinates
E = cv_coord(from_sphere=E,/to_rect,degrees=degrees); Same for Earth

S -= E#replicate(1.0,nseg)				; Geocentric Cartesian coordinates of los segments
S  = sqrt(total(S*S,1))					; Distance los segment from Earth

W = IPS_WeightFnc(S,w3darg[0:2])
W = SuperArray(W,nlos,/lead)			; Apply result to all lines of sight
W = reform(W,size(G,/dim),/overwrite)

RETURN, W*G  &  END
