/*
 * Wrap Data onto Sphere -- Modeler ARexx transform.
 *
 * 8/93  Stuart Ferguson
 */

	mxx="LWModelerARexx.port"
	signal on error
	signal on syntax
	check = addlib("rexxmathlib.library",0,-30,0)
	mxx_add = addlib(mxx,0)
	call main
	if (mxx_add) then call remlib(mxx)
	exit

	syntax:
	error:
	t=Notify(1,'!Rexx Script Error','@'ErrorText(rc),'Line 'SIGL)
	if (mxx_add) then call remlib(mxx)
	exit


main:

syscode = "Wrap Sphere"


/* Get size and thickness of sphere from user.
 */
call req_begin syscode

id_inr = req_addcontrol("Inner Radius", 'n', 1)
id_otr = req_addcontrol("Outer Radius", 'n', 1)
id_sel = req_addcontrol("Points", 'c', 'All Selected')
call req_setval id_inr, 1.0, 1.0
call req_setval id_otr, 2.0, 2.0
call req_setval id_sel, 2

if (~req_post()) then return

r1 = req_getval(id_inr)
r2 = req_getval(id_otr)
call sel_mode word('global user',req_getval(id_sel))

call req_end


/* Get extent of data area.  This will just take the extent in
 * X and Y and map it to lat and long on the sphere, and the
 * extent in Z and map it to r1 and r2.
 */
parse value boundingbox() with n x1 x2 y1 y2 z1 z2 .
dx = x2 - x1
dy = y2 - y1
dz = z2 - z1
if (n <= 0 | dx <= 0 | dy <= 0) then return
d2r = 3.1415926 / 180

/* Transform loop
 */
n = xfrm_begin()
call meter_begin n, syscode
do i = 1 to n
    parse value xfrm_getpos(i) with x y z .

    lat = d2r * ((y - y1) / dy * 180 - 90)
    lon = d2r * ((x - x1) / dx * 360)
    if (dz <= 0) then rad = r1
                 else rad = (z - z1) / dz * (r2 - r1) + r1

    y = rad * sin(lat)
    p = rad * cos(lat)
    x = p * sin(lon)
    z = p * cos(lon)

    call xfrm_setpos i, x y z
    call meter_step
end
call meter_end
call xfrm_end

return