function [ChunkBeatVec, ChunkBeatVecr, L, Lr] = genAFIBchunks(ecgSig, Rpeaks, VM)
L = 0;
Lr = 0;
RpeaksChunk = Rpeaks.*VM;
totalBeats = sum(RpeaksChunk);
rind = find(RpeaksChunk == 1);

diffR = diff(rind);

%% diff greater than 250

rind1 = rind;

id = find(diffR<200);
id1 = find(rind<66);
id2 = find(rind+10>length(ecgSig));
remId = unique([id; id1; id2]);
rind1(remId) = [];

beatVec = [];
for ind = 1:length(rind1)
    bv = ecgSig(rind1(ind)-65:rind1(ind)+10);
    beatVec(:,ind) = bv;%resample(bv, 200, length(bv));
end

ChunkBeatVec = [];
if(numel(beatVec)~=0)
    L = size(beatVec,2);
    if(L>30)
        ChunkBeatVec(:,1) =  median(beatVec(:,1:round(3*L/7)),2);
        ChunkBeatVec(:,2) =  median(beatVec(:,round(2*L/7):round(5*L/7)),2);
        ChunkBeatVec(:,3) =  median(beatVec(:,round(4*L/7):L),2);
    elseif(L>5)
        ChunkBeatVec(:,1) = median(beatVec,2);
    end
end

%% diff less than 250

rind2 = rind;
diffRr = diffR;

idr = find(diffR>200);
remIdr = idr;
rind2(remIdr) = [];
diffRr(remIdr) = [];
beatVecr = [];
for ind = 1:length(diffRr)
    bvr = ecgSig(rind2(ind):rind2(ind)+diffRr(ind));
    beatVecr(:,ind) = resample(bvr, 150, length(bvr));
end

ChunkBeatVecr = [];
if(numel(beatVecr)~=0)
    Lr = size(beatVecr,2);
    if(Lr>30)
        ChunkBeatVecr(:,1) =  median(beatVecr(:,1:round(3*Lr/7)),2);
        ChunkBeatVecr(:,2) =  median(beatVecr(:,round(2*Lr/7):round(5*Lr/7)),2);
        ChunkBeatVecr(:,3) =  median(beatVecr(:,round(4*Lr/7):Lr),2);
    elseif(Lr>5)
        ChunkBeatVecr(:,1) = median(beatVecr,2);
    end
end


