function sM = sFitCart( x,y,z, maxn, epsilon)
% sFitCart - fits a spline surface in spherical coordinate system
%	       through points given in cartesian coordinate system
%	       splineMesh = sFitCart( x,y,z, maxn, epsilon)
%      or      splineMesh = sFitCart( xyz, maxn, epsilon )
%	   x,y,z - k*1 vectors with carthesian coordinates
%	   maxn - maximal mesh size (optional, see sMBA)
%	   epsilon - maximal error  (optional, see sMBA)
%
%	   splineMesh - matrix for use with sPlotSurfM
%	       n*(n+1) matrix with spline coeffitients 
%	       splineMesh(1,1) corresponds to fi=-pi, teta=-pi/2
%          fi-space is in 2*pi/n wide segments (-pi  :2*pi/n: pi  ) 
%          teta-space is in pi/n wide segments (-pi/2 : pi/n: pi/2)
%
%
% see also: sFit, sPlotSurfM 

if (nargin == 3) & ( min(size(x))==3 ),	       % xyz, maxn, epsilon 
   flag = 2;
   maxn = y; epsilon = z; y=x(:,2); z=x(:,3); x=x(:,1);
elseif (nargin == 2) & ( min(size(x))==3 ),    % xyz, maxn
   flag = 1;
   maxn = y; y=x(:,2); z=x(:,3); x=x(:,1);
elseif (nargin == 1),			       % xyz
   flag = 0;
   maxn = 16; y=x(:,2); z=x(:,3); x=x(:,1); 
elseif (nargin == 3) & ( min(size(x))==1 ),    % x,y,z
   flag = 0;
elseif (nargin == 4),			       % x,y,z, maxn
      flag = 1;
elseif (nargin == 5),
      flag = 2;
else,
   disp('sFitCart:Wrong number/size of parameters'); return;
end;

[az, el, r] = cart2sph(x(:),y(:),z(:));

if (flag==2),				       % xyz, maxn, epsilon 
   sM = sFit(az,el, r, maxn, epsilon);
elseif (flag==1),			       % xyz, maxn
   sM = sFit(az,el, r, maxn);
elseif (flag == 0),			       % xyz
   sM = sFit(az,el, r);
else,
   disp('sFitCart:Wrong number/size of parameters(2)'); return;
end;


sPlotSurf(sM);

return
