function [PPlocs,QQlocs,RRlocs,SSlocs,TTlocs,UUlocs,PPvals,QQvals,RRvals,SSvals,TTvals,UUvals,PRinterval,QRSinterval,QTinterval,meanBeats,TTPlocs,TQinterval]=findPQRSTintervalsNewA(ecg,RR)
% usedRR=RR(2:end-1);
PPlocs=[];QQlocs=[];SSlocs=[];TTlocs=[];UUlocs=[];
PPvals=[];QQvals=[];SSvals=[];TTvals=[];UUvals=[];
RRlocs=[];RRvals=[];
PRinterval=[];QRSinterval=[];QTinterval=[];TQinterval=[];TTPlocs=[];
meanBeats=[];
%%TQ interval , set the ECG to 0 mean,
for i=1:length(RR)-2
    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(round(end/2)+1:end-1));
    %     pp=pp1(end);
    meanBeat=0.0001;
    qflag=0;pflag=0;sflag=0;tflag=0;uflag=0;tpflag=0;
    if isempty(ppks1)==0
        ppks=ppks1(end);
        plocs=plocs1(end)+currentLength+round(length(currentInterval1)/2);
        pflag=1;
        [qpks1,qlocs1]=findpeaks(currentInterval1N(plocs1(end):end-1));
        
        if isempty(qpks1)==0
            qpks=-qpks1(end);
            qlocs=qlocs1(end)+plocs1(end)+currentLength;            
            meanBeat=qpks/2+ppks/2; 
            qpks=qpks-meanBeat;
            QQlocs=[QQlocs,qlocs];QQvals=[QQvals,qpks];
            qflag=1;
        end
        meanBeats=[meanBeats,meanBeat];
        ppks=ppks-meanBeat;
        PPlocs=[PPlocs,plocs];PPvals=[PPvals,ppks];
        PRinterval=[PRinterval,RR(i+1)-plocs];
    end
    
    
    
    [tpks2,tlocs2]=findpeaks(currentInterval1(1:round(end/2)));
    if isempty(tpks2)==0  && qflag==1
%         tpks=tpks2(1);
        tlocsp=tlocs2(1)+RR(i);
%         tpks=tpks-meanBeat;
        TTPlocs=[TTPlocs,tlocsp];%TTvals=[TTvals,tpks];
        tpflag=1;
    end
    if tpflag==1
        TQinterval=[TQinterval,qlocs-tlocsp];
    end
    
    [spks1,slocs1]=findpeaks(currentInterval2N(1:round(end/3)));
    if isempty(spks1)==0
        spks=-spks1(1);
        slocs=slocs1(1)+RR(i+1);
        spks=spks-meanBeat;
        SSlocs=[SSlocs,slocs];SSvals=[SSvals,spks];
        if qflag==1
        QRSinterval=[QRSinterval,slocs-qlocs];
        end
    end
    
    [tpks1,tlocs1]=findpeaks(currentInterval2(1:round(end/2)));
    if isempty(tpks1)==0
        tpks=tpks1(1);
        tlocs=tlocs1(1)+RR(i+1);
        tpks=tpks-meanBeat;
        TTlocs=[TTlocs,tlocs];TTvals=[TTvals,tpks];
    end
    
    
    if length(tpks1)>1
        upks=tpks1(2);
        ulocs1=tlocs1(2);
        ulocs=ulocs1+RR(i+1);
        upks=upks-meanBeat;
        UUlocs=[UUlocs,ulocs];UUvals=[UUvals,upks];
        if qflag==1
            QTinterval=[QTinterval,tlocs-qlocs];
        end
        
    end
    %     ulocs=ulocs1+RR(i+1);
    
    RRlocs=[RRlocs,RR(i+1)];RRvals=[RRvals,ecg(RR(i+1))-meanBeat];
end

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