function batchDTW(t1,t2,ref,sectionName)
% batchDTW
%
% Funkce pro vyber useku z interpretaci pomoci rychleho DTW
% t1 - pocatek useku v referencni nahravce v sekundach
% t2 - konec useku v referencni nahravce v sekundach
% ref - ciselne poradi referencni nahravky v databazi
% sectionName - string pro oznaceni useku
%
% Stepan Miklanek, 2018

%% Kontrola vstupnich parametru

if nargin < 1
    error('Chyba. Nebyly zadany zadne vstupni parametry.')
elseif nargin < 3
    error('Chyba. Zadej zacatek a konec useku v sekundach a cislo referencni nahravky.')
elseif nargin == 3
    sectionName = 'cut'; 
    fprintf('Nebyl zadan nazev useku.\n')
    fprintf('Nastavuji vychozi nazev useku "cut".\n')
end    

%% Inicializace

DBpath = uigetdir('title','Vyber slozku s pitch parametry');
if DBpath == 0
fprintf('Chyba. Zadej cestu k pitch parametrum nahravek.\n')
return
end

DBinfo = dir(DBpath);
filenames = extractfield(DBinfo(3:end),'name');

ADBpath = uigetdir('title','Vyber slozku s nahravkami');
if ADBpath == 0
fprintf('Chyba. Zadej cestu k databazi nahravek.\n')
return
end

ADBinfo = dir(ADBpath);
Afilenames = extractfield(ADBinfo(3:end),'name');

mkdir(ADBpath,sectionName);

nAudio = length(filenames);

refFile = filenames{ref}; 
refPath = [DBpath,'\',refFile];
load(refPath,'p')

refInterpretation = p;
clearvars p

costAll = zeros(nAudio,1);

%% Strih vybraneho useku

for n = 1:nAudio    

    if n == ref
    currentAudio = Afilenames{n};
    audiofilename = [ADBpath,'\',currentAudio];
    [~,name,~] = fileparts(audiofilename);
    
    audio = miraudio(audiofilename,'Extract',t1,t2);
    cutPath = [ADBpath,'\',sectionName,'\',sectionName,'_',name,'.wav'];
    mirsave(audio,cutPath);
    
    else   
    currentFile = filenames{n};  
    filename = [DBpath,'\',currentFile];
    load(filename,'p')
    
    testInterpretation = p;
    clearvars p
    
    [cost, wp] = multiLevelDTW(refInterpretation,testInterpretation,0);
    
    costAll(n,1) = cost;
    
    iStart = wp(:,1) == round(t1,1)*10;
    iEnd = wp(:,1) == round(t2,1)*10;
    
    tStart = wp(iStart,2);
    tStart = tStart(1)/10;
    tEnd = wp(iEnd,2);
    tEnd = tEnd(1)/10;
    
    currentAudio = Afilenames{n};
    audiofilename = [ADBpath,'\',currentAudio];
    [~,name,~] = fileparts(audiofilename);
    
    audio = miraudio(audiofilename,'Extract',tStart,tEnd);
    cutPath = [ADBpath,'\',sectionName,'\',sectionName,'_',name,'.wav'];
    mirsave(audio,cutPath);
    end
    
end

%% Ulozeni informace o parametru cost vsech synchronizaci

save([ADBpath,'\',sectionName,'\','costAll.mat'],'costAll');

end