function [PPlocs,QQlocs,RRlocs,SSlocs,TTlocs,UUlocs,PPvals,QQvals,RRvals,SSvals,TTvals,UUvals,PRinterval,QRSinterval,QTinterval]=findPQRSTintervals(ecg,RR)
% usedRR=RR(2:end-1);
PPlocs=[];QQlocs=[];SSlocs=[];TTlocs=[];UUlocs=[];
PPvals=[];QQvals=[];SSvals=[];TTvals=[];UUvals=[];
RRlocs=[];RRvals=[];
PRinterval=[];QRSinterval=[];QTinterval=[];TQinterval=[];
for i=1:length(RR)-2
    % i
    
    currentLength=RR(i);
    currentInterval1=ecg(RR(i)+1:RR(i+1)-1);%2RR intervals
    currentInterval2=ecg(RR(i+1)+1:RR(i+2)-1);
    %     currentIntervalRR=ecg(RR(i:i+2)+1);
    currentInterval1N=-currentInterval1;
    currentInterval2N=-currentInterval2;
    [ppks1,plocs1]=findpeaks(currentInterval1(1:end-1));
    %     pp=pp1(end);
    if isempty(ppks1)==0
        ppks=ppks1(end);
        plocs=plocs1(end)+currentLength;
    else
        [ppks,plocs]=max(currentInterval1(round(end/1.3):end) );
        plocs=plocs+currentLength;
    end
    
    PPlocs=[PPlocs,plocs];PPvals=[PPvals,ppks];
    
    
    [qpks1,qlocs1]=findpeaks(currentInterval1N(1:end-1));
    if isempty(qpks1)==0
        qpks=-qpks1(end);
        qlocs=qlocs1(end)+currentLength;
    else
        [qpks,qlocs1]=min(currentInterval1(round(end/1.3):end));
        qlocs=qlocs1+currentLength;
    end
    QQlocs=[QQlocs,qlocs];QQvals=[QQvals,qpks];
    [spks1,slocs1]=findpeaks(currentInterval2N(1:end));
    if isempty(spks1)==0
        spks=-spks1(1);
        slocs=slocs1(1)+RR(i+1);
    else
        [spks,slocs1]=min(currentInterval2(1:round(end/3)));
        slocs=slocs1+RR(i+1);
    end
    SSlocs=[SSlocs,slocs];SSvals=[SSvals,spks];
    [tpks1,tlocs1]=findpeaks(currentInterval2(1:end));
    if isempty(tpks1)==0
        tpks=tpks1(1);
        tlocs=tlocs1(1)+RR(i+1);
    else
        [tpks,tlocs1]=max(currentInterval2(1:round(end/1.7)) );
        tlocs=tlocs1+RR(i+1);
    end
    
    TTlocs=[TTlocs,tlocs];TTvals=[TTvals,tpks];
    if length(tpks1)>1
        upks=tpks1(2);
        ulocs1=tlocs1(2);
        ulocs=ulocs1+RR(i+1);
    else
        upks=tpks;
        ulocs=tlocs;
    end
    %     ulocs=ulocs1+RR(i+1);
    UUlocs=[UUlocs,ulocs];UUvals=[UUvals,upks];
    RRlocs=[RRlocs,RR(i+1)];RRvals=[RRvals,ecg(RR(i+1))];
    
    PRinterval=[PRinterval,RR(i+1)-plocs];
    QRSinterval=[QRSinterval,slocs-qlocs];
    QTinterval=[QTinterval,tlocs-qlocs];
    
    %     PPvals=
end

for i=1:length(RR)-2
    
%     TQinterval=[TQinterval,tlocs-qlocs];
end