function [cost,path] = restrictedDTW(refSample,testSample,delta)

%
% funkce pro vypocet DTW na omezene oblasti constraintM
%

[lengthRef,~]=size(refSample);
[lengthTest,~]=size(testSample);
   
Dist = zeros(lengthRef,lengthTest); % inicializace DTW matice

for i=1:lengthRef        
    for j=1:lengthTest 
        if delta(i,j) == 5 
        %Euklidovska vzdalenost        
        Dist(i,j)=sqrt(sum((refSample(i,:)-testSample(j,:)).^2));           
        end
    end
end

D=Inf(size(Dist));
D(1,1)=Dist(1,1);
 
    
    for n=2:lengthRef
        if(delta(n,1) == 5)
            D(n,1)=Dist(n,1)+D(n-1,1);
        end
    end
    
    for m=2:lengthTest
        if(delta(1,m) == 5)
            D(1,m)=Dist(1,m)+D(1,m-1);
        end
    end
    
    for n=2:lengthRef
        for m=2:lengthTest
            if(delta(n,m) == 5)
                D(n,m)=Dist(n,m)+min([D(n-1,m),(min([D(n-1,m-1),D(n,m-1)]))]);
            end
        end
    end
      
    X = lengthRef;
    Y = lengthTest;
    k=1;
    path(1,:)=[X,Y];
    while ((X>1)||(Y>1))
        if ((X-1)==0)
            Y = Y-1;
        elseif ((Y-1)==0)
            X = X-1;
        else
            [~,place] = min([D(X-1,Y),D(X,Y-1),D(X-1,Y-1)]);
            switch place
                case 1
                    X = X-1;
                case 2
                    Y = Y-1;
                case 3
                    X = X-1;
                    Y = Y-1;
            end
        end
        k=k+1; % pocet kroku potrebnych do bodu [1,1]
        path = cat(1,path,[X,Y]);
    end
    
% normalizovana hodnota cost
cost = (D(lengthRef,lengthTest))/k;
% vysledna optimalni cesta
path = flipud(path);

end