function [S, suma, atstum] = Splainai(koord, ciklas)
n=length(koord);

atstum=zeros(1,n-1);
suma=zeros(1,n);
for i=1:n-1
   atstum(i)=atstumas(koord(i,1), koord(i+1,1), koord(i, 2), koord(i+1,2)); 
   suma(i+1)=suma(i)+atstum(i);
end

for i=1:n
   suma(i)=suma(i)/suma(n); 
end
x=zeros(n,2);
y=zeros(n,2);
for i=1:n
   x(i,:)=[suma(i) koord(i,1)];
   y(i,:)=[suma(i) koord(i,2)];
end
%skirtumas 
H=zeros(n-1,1);
hx=zeros(n-1,1);
hy=zeros(n-1,1);
for i=1:n-1
    H(i)=suma(i+1)-suma(i);
    hx(i)=koord(i+1,1) - koord(i,1);
    hy(i)=koord(i+1,2) - koord(i,2);
end
% sudaroma matricos diagonale
diagonale=ones(1,n);
xk=zeros(1,n);

M=zeros(n, n);
if ciklas==1
    yk=zeros(1,n);
    xk(1)=hx(1)/H(1)-hx(n-1)/H(n-1);
    yk(1)=hy(1)/H(1)-hy(n-1)/H(n-1);
    
    for i=1:n-2
        diagonale(i+1)=2*(H(i)+H(i+1));
        xk(i+1)=hx(i+1)/H(i+1)-hx(i)/H(i);
        yk(i+1)=hy(i+1)/H(i+1)-hy(i)/H(i);
    end
    diagonale(1)=2*H(1);
    diagonale(n)=(-1)*H(n-1);
    
else
    yk=ones(1,n);
    for i=1:n-2
        diagonale(i+1)=2*(H(i)+H(i+1));
        xk(i+1)=hx(i+1)/H(i+1)-hx(i)/H(i);
        yk(i+1)=hy(i+1)/H(i+1)-hy(i)/H(i);
    end
    
end
M=diag(diagonale);
    pagalbine1=zeros(1,n-1);
    pagalbine2=zeros(1,n-1);
    for i=1:n-2
        pagalbine1(i)=H(i);
        pagalbine2(i+1)=H(i+1);
    end
M1=diag(pagalbine1, -1);
M2=diag(pagalbine2, 1);
Matrica=M1+M+M2;
if ciklas==1
    Matrica(1,2)=H(1);
    Matrica(1,n-1)=H(n-1);
    Matrica(1,n)=2*H(n-1);
    Matrica(n,1)=H(1);
end
Bx=6*xk;
By=6*yk;
x2=Matrica\Bx';   % Bx ir By yra transponuota matrica (')
y2=Matrica\By';
m=1;
%apskai2iuojami koeficientai
for i=1:n-1
    Kx(i,1)=(x2(i+1)-x2(i))/(6*H(i));
    Kx(i,2)=x2(i)/2;
    Kx(i,3)=(koord(i+1,1)-koord(i,1))/H(i) - x2(i+1)*H(i)/6 - x2(i)*H(i)/3;
    Kx(i,4)=koord(i,1);
    
    Ky(i,1)=(y2(i+1)-y2(i))/(6*H(i));
    Ky(i,2)=y2(i)/2;
    Ky(i,3)=(koord(i+1,2)-koord(i,2))/H(i) - y2(i+1)*H(i)/6 - y2(i)*H(i)/3;
    Ky(i,4)=koord(i,2);
    
    syms t x y 
    S(i,1)=Kx(i,1)*(t-suma(i))^3+ Kx(i,2)*(t-suma(i))^2+Kx(i,3)*(t-suma(i))+Kx(i,4);
    S(i,2)=Ky(i,1)*(t-suma(i))^3+ Ky(i,2)*(t-suma(i))^2+Ky(i,3)*(t-suma(i))+Ky(i,4);
    
end

