function [ cellPbg_r, cellPend_r, Pbg_final_all, Pend_final_all ] = P( DERFI, PQ, Databaze )
% Tato funkce má za úkol rozměření vlny P. Vstupem je filtrovaný signál
% určený k rozměření vlny P, pozice kmitů Q a počet rozměřovaných svodů.
% Výstupem jsou pak pozice začátků a konců vlny P v každém svodu, dále
% pozice začátků a konců vlny P po aplikaci shlukové analýzy.

    db = sum(Databaze);
    cellQ_r = cell(db,1);

    winlength = 50;
    winlength2 = 8;
    v1 = [];
    v2 = [];
    [nic delka] =  size (PQ);

    %% Zpřesnění pozice kmitu Q z důvodů odlišné filtrace, než při její první detekci + Detekce vlny P
    for k = 1:db;
        Qfinal = [];
        final_loc = [];
        for i = 1:delka
            q = PQ(k,i);
            if q+winlength <4999 & q-winlength >0
                win = DERFI(k,q-winlength:q+winlength2);
                [val1,loc1] = max(win);
                [val2,loc2] = min(win);
                loc1 = loc1+q-winlength;
                loc2 = loc2+q-winlength;
                if loc1 > loc2
                    for i = loc2:loc1;
                        if ((DERFI(k,i)>0 && DERFI(k,i+1)<0) || (DERFI(k,i)<0 && DERFI(k,i+1)>0));
                            final_loc = (i);
                        end
                    end
                end
                if loc1 < loc2;
                    for i = loc1:loc2;
                        if ((DERFI(k,i)>0 && DERFI(k,i+1)<0) || (DERFI(k,i)<0 && DERFI(k,i+1)>0))
                            final_loc = (i);
                        end
                    end
                end
            end
            Qfinal = [Qfinal final_loc];
            final_loc = [];
        end
        cellQ_r{k,1} = Qfinal;
        final_loc = [];
        Qfinal = [];
    end
    cellP = cell(db,1);
    Plength = [];
    Plength2 = cell(db,1);
    locP = [];
    refr = 24;
    winlength = 100;
    for k = 1:db;
        Pfinal = [];
        for q = cellQ_r{k,1};
            if q-winlength > 0;
                win = DERFI(k,q-winlength:q-refr);
                [val1,loc1] = max(win);
                [val2,loc2] = min(win);
                loc1 = loc1+q-winlength;
                loc2 = loc2+q-winlength;
                if loc1 > loc2
                    for i = loc2:loc1;
                        if((DERFI(k,i)>0 && DERFI(k,i+1)<0) || (DERFI(k,i)<0 && DERFI(k,i+1)>0))
                            final_loc = (i);
                        end
                    end
                end
                if loc2 > loc1
                    for i = loc1:loc2
                        if((DERFI(k,i)>0 && DERFI(k,i+1)<0) || (DERFI(k,i)<0 && DERFI(k,i+1)>0))
                            final_loc = (i);
                        end
                    end
                end
            end
            Pfinal = [Pfinal final_loc];
        end
        cellP{k,1}= Pfinal;
    end

%%  Detekce začátku P
    cellPbg = cell(db,1);
    sizePbg_pk = cell(db,1);
    locPbg = [];
    for k = 1:db;
        values = [];
        locPbg = [];
        winlength = 45; 
        for q = cellP{k,1};
            if q > winlength
                win = DERFI(k,q-winlength:q);
                [val, loc] = max(abs(win));
                locPbg = [locPbg, (q-winlength)+loc];
                values = [values val];
            end
        end
        cellPbg{k,1} = locPbg;
        sizePbg_pk{k,1} = values;
    end
    locPbg_r = [];
    locPbg_r2 = [];
    konst = 1.2;
    for k = 1:db;
        for q = cellPbg{k,1};
            if q-15>0
                win = DERFI(k,q-15:q-1);
                win = fliplr(win);
                locPbg_r = find(abs(win) < abs(DERFI(k,q))/(konst), 1);
                locPbg_r2 = [locPbg_r2 (q-1-locPbg_r)];
                kontrola = isempty(locPbg_r);
                if kontrola == 1;
                    locPbg_r2 = [locPbg_r2 (q)];
                end
            end
        end
        cellPbg_r{k,1} =  locPbg_r2;
        locPbg_r = [];
        locPbg_r2 = [];
    end
    
    %% Vícesvod začátek P
    vzdalenost = 45;
    m = sort(cell2mat(cellPbg_r'));
    if length(m)>=2
        Y = pdist(m');
        Z = linkage(Y);
        T = cluster(Z,'cutoff', vzdalenost, 'criterion', 'distance')';
        [uT,oT] = unique(T,'first');
        [~,pos] = sort(oT);
        skupinky = cell(1,length(uT));
        for i = uT;
            skupinky{i} = sort(m(T==pos(i)));
        end
    else
        skupinky = {m};
    end
    pom2 = [];
    pom = skupinky;
    for i = 1:length(pom);
        if length(pom{1,i}) > length(cellPbg_r')/2
            pom2 = [pom2 round(median(pom{1,i})) ];
        end
    end
    Pbg_final = pom2;
    Pbg_final_all{1,:} = Pbg_final;

    %% Detekce konce P

    cellPend = cell(db,1);
    size_Pend_pk = cell(db,1);

    for k = 1:db;
        values = [];
        locPend = [];
        winlength = 25;
            for q = cellP{k,1};
                win = DERFI(k,q:q+winlength);
                [val,loc] = max(abs(win));
                locPend = [locPend q+loc];
                values = [values val];
            end
        cellPend{k,1} = locPend;
        size_Pedn_pk{k,1} = values;
    end
    cellPend_r = cell(db,1);
    locPend1 = [];
    locPend2 = [];
    konst = 1.35;
    for k = 1:db;
        for q = cellPend{k,1};
            win = DERFI(k,q:q+15);
            locPend1 = find(abs(win) < abs(DERFI(k,q))/(konst), 1);
            locPend2 = [locPend2 (q+locPend1)];
            kontrola = isempty(locPend2);
            if kontrola == 1;
                locPend2 = [locPend2 (q)];
            end
        end
        cellPend_r{k,1} = locPend2;
        locPend1 = [];
        locPend2 = [];
    end


    %% Vícesvod konec P    
    vzdalenost = 45;
    m = sort(cell2mat(cellPend_r'));
    if length(m)>=2
        Y = pdist(m');
        Z = linkage(Y);
        T = cluster(Z,'cutoff', vzdalenost, 'criterion', 'distance')';
        [uT,oT] = unique(T,'first');
        [~,pos] = sort(oT);
        skupinky = cell(1,length(uT));
        for i = uT;
            skupinky{i} = sort(m(T==pos(i)));
        end
    else
        skupinky = {m};
    end
    pom2 = [];
    pom = skupinky;
    for i = 1:length(pom);
        if length(pom{1,i}) > length(cellPend_r')/2
            pom2 = [pom2 round(median(pom{1,i})) ];
        end
    end
    Pend_final = pom2;
    Pend_final_all{1,:} = Pend_final;

end   