function [QRSo,diffo]=findBestQRSnewPD(yp)
% [averageDiff,~,~]=findPCGpeaksNewFeatures2(yp);
% Diffv=abs(diff(Indexes(:,1)));
fs=300;
lle=length(yp);
[QRS,sign,en_thres] = qrs_detect2(yp',0.25,0.6,fs);
[QRS1,sign,en_thres] = qrs_detect2(yp(1:round(end/3))',0.25,0.6,fs);
[QRS2,sign,en_thres] = qrs_detect2(yp(round(end/3):round(2*end/3))',0.25,0.6,fs);
[QRS3,sign,en_thres] = qrs_detect2(yp(round(2*end/3):round(end))',0.25,0.6,fs);
[QRS4,sign,en_thres] = qrs_detect2(yp(1:round(end/2))',0.25,0.6,fs);
[QRS5,sign,en_thres] = qrs_detect2(yp(round(end/2):end)',0.25,0.6,fs);


QRSa=QRS;
QRSc=[QRS1,round(lle/3)-1+QRS2,round(2*lle/3)-1+QRS3];
QRSb=[QRS4,round(lle/2)-1+QRS5];
lena=length(QRSa);lenb=length(QRSb);lenc=length(QRSc);
[maxlen,maxlenI]=max([lena,lenb,lenc]);
% [maxlen,maxlenI]=max([lena,lenc]);
diffa=diff(QRSa);
diffb=diff(QRSb);
diffc=diff(QRSc);
QRSo=QRSa;
switch maxlenI
    case 1
        QRSo=QRSa;
        diffo=diffa;
    case 2
        %45
        [mindiff,mindiffi]=min(diffb);
        meandiff=mean(diffb);
        if mindiff<0.2*meandiff
            QRSb(mindiffi+1)=[];
        end
        QRSo=QRSb;
        diffo=diffc;
    case 3
        %123
        meandiff=mean(diffc);
        ff=find(diffc<0.2*meandiff);
        QRSc(ff+1)=[];
        QRSo=QRSc;
        diffo=diffc;
end
% if isempty(QRSo)==1
%     [~,QRSo] = findpeaks(yp,'MinPeakHeight',abs(mean(yp)),...
%         'MinPeakDistance',200);
% end
if length(QRSo)<= 5
% if length(QRSo)<=floor(length(yp)/600) %5
%       [~,QRSo1,~]=pt(yp,300);
    diff1=abs(diff(QRSo));
    minDiff=round(abs(min(diff1))*0.8);
    minPeakHeight=min(yp(QRSo));
    if minPeakHeight<0 
        minPeakHeight=abs(mean(yp));
    end
    if isempty(minPeakHeight)==1
         minPeakHeight=abs(mean(yp));
    end
    if isnan(minPeakHeight)
        minPeakHeight=abs(mean(yp));
    end
    if isempty(minDiff)==1 || isnan(minDiff)
        minDiff=200;
    end
    [~,QRSo1] = findpeaks(yp,'MinPeakHeight',minPeakHeight,'MinPeakDistance',minDiff);
    if length(QRSo1)>length(QRSo)
        QRSo=QRSo1;
    end
end
thresh=7;
x=yp;
for kk=1:length(QRSo)
    aroundQRS=x(max(QRSo(kk)-thresh,1):min(QRSo(kk)+thresh,length(x)));
    if x(QRSo(kk))>0
        [~,v1i]=max(aroundQRS);
        QRSo(kk)=QRSo(kk)-thresh+v1i-1;
    else
        [~,v1i]=min(aroundQRS);
        QRSo(kk)=QRSo(kk)-thresh+v1i-1;
    end
    if QRSo(kk)<1
        QRSo(kk)=1;
    end
    if QRSo(kk)>length(x)
        QRSo(kk)=length(x);
    end
end
