darr = [];
data = [];
x = [];
phi = [];
badphi = [];
npt = 50;
ndim = 10;
dtot=0;
data = randn(npt,ndim);

plot(data(:,1), data(:,2), 'x');

for i = 1:npt
	dist = 0;
	sinblob = 1;
	for d = 1:ndim
		dist = dist + (data(i,d)^2);
	end
	r = sqrt(dist);
	for d = ndim:-1:2
		phi(i, d-1) = acos(data(i,d)/(r*sinblob));
		if((data(i,d) < 0))
			phi(i,d-1) = phi(i,d-1)*-1;
		end
		sinblob = sinblob * sin(phi(i,d-1));
	end
	phi(i, ndim) = r;
	dtot = dtot +r;
end

rad = dtot/npt;

for i = 1:npt
	r = phi(i, ndim);
	r = rad;

	sinblob = 1;
	for d = ndim:-1:2
		x(i,d) = r*cos(phi(i, d-1))*sinblob;
		sinblob = sinblob*sin(phi(i,d-1));
	end

	x(i, 1) = r*sinblob;
	if((phi(i,1) > (pi/2)) | (phi(i,1) < (-pi/2)))
%		x(i,1) = -1*x(i,1);
	end
	if(data(i,1) ~= x(i,1))
		badphi(i,:) = phi(i,:);
	end
end

%plot(phi(:,1), x(:,1), 'x')
plot(data(:,5), x(:,5), 'x');
