function F = sExtend( M, iex, jex )
% sExtend - extends spline coeficient matrix applying edge conditions
%	   F = sExtend( M, [Up Down], [Left Right] )
%	       in the spherical coordinate system:
%	       M(az=pi, el)   = M( az=-pi, el)
%	   and M(az, el=pi/2) = M(-az, el=pi/2)
%	   M - spline coeficient matrix in a spherical coordinate system
%	       a column corresponds to a parallel -pi..pi
%	       a row    corresponds to a meridian -pi/2..pi/2
%	   [Up Down]   -number of rows added to the upper and lower side
%	   [Left Right]-number of rows added to the left and right side
%	   F - extended matrix. If  [m,n]=size(M)
%	       [m+Up+Down, n+Left+Right] == size(F)


[m,n] = size(M);
if( nargin == 1 ), iex=[1 1]; jex=[1 1]; end;

% adding points on left and right
% they are from the oposite side in reversed order (reversed azimuth)
% M(az, el=pi/2) = M(-az, el=pi/2)

if m == 1,   t = 1; else, t = [ (m/2+1:m) (1:m/2) ]; end
F = [ M(t,(jex(1):-1:1)+1 ) M M(t, (n-1:-1:n-jex(2)) ) ];

% adding points up and down
% upper edge equals the lower one 
% ( zeroth meridian in spherical coordinate system)
% M(az=pi, el)   = M( az=-pi, el)

if (iex(1)>m | iex(2)>m)
   % wrapping around the matrix more than once
   Jup  = rem( iex(1)*m+(m-iex(1)+1:m)-(1), m) + (1);
   Jdown= rem( (1:iex(2))-(1),              m) + (1);
   F = [ F(Jup,:); F ; F(Jdown,:) ];
else
   F = [ F(m-iex(1)+1:m,:); F ; F(1:iex(2),:) ];
end;


return
