%--------------------------------------------------------------------------
% FUNKCE PRO NALEZENÍ QRS OFFSET
%--------------------------------------------------------------------------

function [QRSoffset] = QRSoffsetdetect(nuly,hladiny,prah,RRmed,QRSpol,bands)

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

QRSoffsetpol = zeros(1,length(QRSpol)-1);
pozice = zeros(1,length(QRSpol)-1);

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

const1 = 0.2;
const2 = 5;
const3 = 3;
const4 =0.75;

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

for i = 1:length(QRSpol)-1
    podminka = 0;
    while podminka ~= -1
        podminka = podminka + 1;
        xxxx = abs(hladiny(QRSpol(i)+podminka-1));
        xxxx2 = abs(hladiny(QRSpol(i)+podminka));
        xxx = nuly(QRSpol(i) + (podminka - 1)) - nuly(QRSpol(i));
        xxx2 = nuly(QRSpol(i) + podminka) - nuly(QRSpol(i));
        if  (xxxx < prah*const1 || xxx > RRmed/const2) && ... % *0.25 /6
            (xxxx2 < const3*xxxx || xxxx2 < prah*const4 || xxx2 > RRmed/const2)    % 2* *0.5 /6
            QRSoffsetpol(i) = QRSpol(i) + (podminka - 1);
            podminka = -1;
        end
        if  podminka == -1
            x = find(abs(bands(1,nuly(QRSoffsetpol(i)-1):nuly(QRSoffsetpol(i))))>const1*prah); % 0.28*
        if  length(x)==1
            pozice(i)= x;
        else
            if x(1) ==1
               x(1) = [];
            end
            d = diff(x);
            c = find(d == 1);
            xx = x;
            xx(c) = [];
            if  length(xx) ==2
                pom = max(abs(bands(1,nuly(QRSoffsetpol(i)-1):nuly(QRSoffsetpol(i)-1)+xx(1))));
                pom2 = max(abs(bands(1,nuly(QRSoffsetpol(i)-1)+xx(1)+1:nuly(QRSoffsetpol(i)-1)+xx(2))));
                if  pom2 >= 3*pom
                    pozice(i) = xx(2);
                else
                    pozice(i) = xx(1);
                end
            else
                pozice(i) = xx(1);
            end
        end
        end
    end
end
QRSoffset = nuly(QRSoffsetpol-1)+pozice;

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