%--------------------------------------------------------------------------
% FUNKCE PRO NALEZENÍ P VLN
%--------------------------------------------------------------------------

function [P,Ppol] = Pdetect(nuly,hladiny,prah,QRSonset,QRSoffset,RRmed)

%------ PREALOKACE --------------------------------------------------------

P = zeros(1,length(QRSonset));
Ppol = zeros(1,length(QRSonset));

%------ PARAMETRY ---------------------------------------------------------

const1 = 0.55;      % vzdalenost v procentech RRmed
const2 = 0.5;       % vzdalenost v procentech RRmed
const3 = 0.05;      % vzdalenost v procentech RRmed
const4 = 0.1;       % krok prahu
prah = 0.20*prah;   % prepocet prahu

%------ ALGORITMUS --------------------------------------------------------

for i = 1:length(QRSonset)
    waves = [];
    Vpol = [];
    delka = QRSonset(i) - QRSoffset(i);
    if  delka > const1*RRmed
        waves = find(nuly > QRSoffset(i)+const2*RRmed & nuly < QRSonset(i)-const3*RRmed);
    end
  if ~isempty(waves)
      k = 0;
    while isempty(Vpol)
        counter = 1;
        k = k+const4;
    for j = 1:length(waves)
        if  abs(hladiny(waves(j)-1)) > prah*(1-k) && abs(hladiny(waves(j))) > prah*(1-k)
            Vpol(counter) = j;
            counter = counter + 1;
        end
    end
    
    end
    
    if  ~isempty(Vpol)
        P(i) = nuly(waves(Vpol(ceil(length(Vpol)/2))));
        Ppol(i) = waves(Vpol(ceil(length(Vpol)/2)));
%         P(i) = nuly(waves(Vpol(end)));
%         Ppol(i) = waves(Vpol(end));
    end
  end
end

%------ NALEZENÍ P VLN NA NENULOVÝCH POZICÍCH -----------------------------

pom = find(P);
P = P(pom);
Ppol = Ppol(pom);

%--------------------------------------------------------------------------