function [cost,path] = multiLevelDTW(refPitch,testPitch,visualize)
% multiLevelDTW
%
% funkce pro vypocet DTW v omezene oblasti Cost matrix
% vstupnimi parametry jsou referencni a testovaci Pitch parametry vypocitane
% ze dvou nahravek 
% vystupni promenna obsahuje synchronizacni cestu mezi dvema nahravkami
%
% Stepan Miklanek, 2018

%% Kontrola vstupnich parametru

if nargin < 1
    error('Chyba. Nebyly zadany zadne vstupni parametry.')
elseif nargin < 3
    visualize = 0; 
elseif visualize < 1
    visualize = 0; 
end

%% Vypocet rychleho DTW

tic;
%% Uroven 4

censL4_1 = pitchCENS(testPitch,271,90);
censL4_2 = pitchCENS(refPitch,271,90);

[~,path4,~] = dtwSakoe(censL4_2,censL4_1,1); % vypocet prvni urovne pomoci klasickeho DTW

%% Uroven 3

censL3_1 = pitchCENS(testPitch,121,30);
censL3_2 = pitchCENS(refPitch,121,30);

factorL3 = 3;
ppathL3 = [1 1; path4(2:end-1,1)*factorL3 path4(2:end-1,2)*factorL3;...
length(censL3_2) length(censL3_1)];
[ppathL3] = pathProject(ppathL3,censL3_2,censL3_1);

constraintM3 = delta(censL3_2,censL3_1,ppathL3,30);

[~,pathL3] = restrictedDTW(censL3_2',censL3_1',constraintM3);

%% Uroven 2

censL2_1 = pitchCENS(testPitch,41,10);
censL2_2 = pitchCENS(refPitch,41,10);

factorL2 = 3;
ppathL2 = [1 1; pathL3(2:end-1,1)*factorL2 pathL3(2:end-1,2)*factorL2;...
length(censL2_2) length(censL2_1)];
[ppathL2] = pathProject(ppathL2,censL2_2,censL2_1);

constraintM2 = delta(censL2_2,censL2_1,ppathL2,30);

[~,pathL2] = restrictedDTW(censL2_2',censL2_1',constraintM2);

%% Uroven 1

censL1_1 = pitchCENS(testPitch,41,1);
censL1_2 = pitchCENS(refPitch,41,1);

factorL1 = 10;
ppathL1 = [1 1; pathL2(2:end-1,1)*factorL1 pathL2(2:end-1,2)*factorL1;...
length(censL1_2) length(censL1_1)];
[ppathL1] = pathProject(ppathL1,censL1_2,censL1_1);

constraintM1 = delta(censL1_2,censL1_1,ppathL1,30);

[cost,path] = restrictedDTW(censL1_2',censL1_1',constraintM1);
elapsedTime = toc;

fprintf('Doba trvani synchronizace byla: %f s.\n',elapsedTime)

%% Vizualizace synchronizace

M = censL1_2'*censL1_1;

if visualize == 1
figure(1)
imagesc(M);
set(gca,'Ydir','normal')
colormap gray
title('Synchronizacni cesta mezi nahravkami')
xlabel(inputname(1))
ylabel(inputname(2))
hold on
plot(path(:,2),path(:,1),'b','lineWidth',1.5)
end

end

