function [beats]=lucky_picking_cinc2014(potbeats,ebbi,plotten)
pickthose=potbeats; 

  Lp=5;% exakt Lp aufeinanderfolgende beats werden evaluiert, also 4 BBIs muessen "plausibel" sein

 Groups=zeros(10000,Lp+1);
 nz=0; 

 counter=0;
 for bbi_var=[1 ]
      %%  PICKING PICKING PICKING PICKING ++++++++++++++++++
          counter=counter+1;
          initial_search_bbi=ebbi*bbi_var;
        for loc=pickthose
        nz=nz+1;
         amount=7;
         [pibeats]=pick_some(potbeats,loc,[initial_search_bbi,-initial_search_bbi],amount);
         if(size(pibeats,2)<Lp)
             continue; 
         end
         [ev,evpbeat]=eval_group(pibeats,ebbi,Lp); % evaluate the just picked beats by mean of "Plausibilitaet" of their tachogram
           Groups(nz+(1:size(ev,1)),1)=ev; % evaluation , Wertung dieser Gruppe
            Groups(nz+(1:size(ev,1)),2:(Lp+1))=evpbeat; %beats dieser Gruppe
            
        end
 end
        % -- make Groups unique
         Groups=Groups(Groups(:,1)~=0,:); 
         equalitytest=sum(Groups(:,2:end),2)+sum(Groups(:,2:end).^2,2); 
         [~,u_ind]=unique(equalitytest);
          temp=Groups(u_ind,1:(Lp+1));
         [~,u_ind]=unique(-temp(:,1));
         sorted_Groups=temp(u_ind,:);

         %%
        if(plotten==1), figure(222); 
            plot(sorted_Groups(:,3:end)',[ diff(sorted_Groups(:,2:end)')]+0.4*randn( size(sorted_Groups,2)-2 , size(sorted_Groups,1) ) );
        end
        
        %% ASSEMBLING
        icbeats(1,:)=potbeats(1,1:3); 
        icbeats(2,:)=potbeats(1,end+[-2:0]);
        [beats]=assembl_groups(sorted_Groups,icbeats,plotten); 
       if(plotten==1), figure(222); hold on; plot(beats(1,2:end),diff(beats(1,:)), 'Linewidth',2);  end

%% Rueckgewinnung der similarities
for k=1:size(beats,2)
    dort=potbeats(1,:)==beats(1,k);
    if(sum(dort,2)>0)
    beats(2,k)=potbeats(2,dort); 
    else
        beats(2,k)=0.2;
    end
    
    
end


end



function [ev,evpbeat]=eval_group(pbeat,ebbi,L)
bbi=diff(pbeat(1,:));bbi=[bbi(1,1),bbi];
pconf=pbeat(2,:);
Lh=floor(L/2);
% abweichung von erwartetem BBI (ebbi)
abw=(bbi-ebbi);
abw(1,abw<0)=-abw(1,abw<0)*3;
mabw=conv(abw,ones(1,L)/L,'same');
mabw=mabw(1,(Lh+1):(end-Lh)); 
% deviations
dev=[0,abs(diff(bbi))];%abs(abs(bbi-mbbi);
%dev(1,dev<
very_big=dev>100; 
dev(1,very_big)=10*sqrt(dev(1,very_big));
mdev=conv(dev,ones(1,L)/L,'same');
mdev=mdev(1,(Lh+1):(end-Lh));
% conformities
mc=conv(pconf,ones(1,L)/L,'same');
mc=mc(1,(Lh+1):(end-Lh)); 
% evaluation
ev=(2*mc-0.005*mdev-0.004*mabw)';%.*exp(-0.5*(dev/20).^2);

for k=1:size(pbeat,2)-L+1
evpbeat(k,:)=pbeat(1,Lh+k+(-Lh:Lh));

end
end

function [cbeats]=assembl_groups(sorted_Groups,icbeats,plotten) 
%% ASSEMBLING :ASSEMBLING :ASSEMBLING :ASSEMBLING : Zusammensetzen der kleinen "Gruppen" von Schlaegen 
% icbeats = initially chosen beats, die an den linken und rechten
% Randbereich
  cbeats(1,:)=[icbeats(1,:), icbeats(2,:)]; % linke und rechte Randbreichs-beats
  cbeats(2,:)=[zeros(1,size(icbeats,2)-1),1,-1,zeros(1,size(icbeats,2)-1)]; 
  for k=1:size(sorted_Groups,1) % loop through Groups
      pnG=sorted_Groups(k,2:end); % potentially new Group ## aktuell (eventuell) hinzuzufuegende Gruppe
      
      for kk=1:size(pnG,2) % look out for beats which are already there 
          there=abs(pnG(1,kk)-cbeats(1,:))<10;% 10 entsprich 40 ms bei fa=250Hz
          alth(1,kk)=sum(there,2)>0;  
            if(alth(1,kk)==1)
                temp=cbeats(1,there);
                pnG(1,kk)=temp(1,1); 
            end
      end
 
        
              overl_left=alth(1,1)&&(sum(diff(alth)==-1,2)==1); % if the first (very left ) beat is already there :: there must exactly be on down-flanke
              overl_right=alth(1,end)&&(sum(diff(alth)==1,2)==1); % if the last ( very right) beats is already there:: there must exactly be one up-flanke 
                     
      
     
      %% wachstums-fuge
      pnG_cut=[];
      if(sum(alth,2)==0) % nix overlap, somit links und rechts Wachstumsfuge
          pnG_cut=pnG;
          temp=[cbeats(1,:),pnG_cut ; cbeats(2,:), zeros(1,size(pnG_cut,2))];
          [~, s_ind]=sort(temp(1,:)); % hinzufuegen der neuen beschnittenen ( cut) Gruppe, also genauer der beats
          cbeats=temp(:,s_ind); 
      
          cbeats(2,cbeats(1,:)==pnG_cut(1,1))=-1; 
          cbeats(2,cbeats(1,:)==pnG_cut(1,end))=1; 
           
      elseif(overl_left&&~overl_right) %  nur links overlap, somit rechts WF
          kante=[diff(alth),0]==-1; 
          if(cbeats(2,cbeats(1,:)==pnG(1,kante))==1)
               pnG_cut=pnG(1,~alth); 
               temp=[cbeats(1,:),pnG_cut ; cbeats(2,:), zeros(1,size(pnG_cut,2))];
               [~, s_ind]=sort(temp(1,:)); % hinzufuegen der neuen beschnittenen ( cut) Gruppe, also genauer der beats
               cbeats=temp(:,s_ind); 
               
            cbeats(2,cbeats(1,:)==pnG(1,kante))=0;
            cbeats(2,cbeats(1,:)==pnG_cut(1,end))=1; 
            
          end
      elseif(~overl_left&&overl_right) % nur recht overlap somit links WF
          
            kante=[0, diff(alth)]==1; 
             if(cbeats(2,cbeats(1,:)==pnG(1,kante))==-1)
               pnG_cut=pnG(1,~alth); 
               temp=[cbeats(1,:),pnG_cut ; cbeats(2,:), zeros(1,size(pnG_cut,2))];
               [~, s_ind]=sort(temp(1,:)); % hinzufuegen der neuen beschnittenen ( cut) Gruppe, also genauer der beats
               cbeats=temp(:,s_ind); 
            
            cbeats(2,cbeats(1,:)==pnG(1,kante))=0;
            cbeats(2,cbeats(1,:)==pnG_cut(1,1))=-1; 
           
             end
      elseif(overl_left&&overl_right)
          
                      rechtskante=[diff(alth),0]==-1; 
                      linkskante=[0, diff(alth)]==1; 
                 
                       if(cbeats(2,cbeats(1,:)==pnG(1,rechtskante))==1&&cbeats(2,cbeats(1,:)==pnG(1,linkskante))==-1)
                            pnG_cut=pnG(1,~alth); 
                            temp=[cbeats(1,:),pnG_cut ; cbeats(2,:), zeros(1,size(pnG_cut,2))];
                            [~, s_ind]=sort(temp(1,:)); % hinzufuegen der neuen beschnittenen ( cut) Gruppe, also genauer der beats
                            cbeats=temp(:,s_ind); 
                            
                           cbeats(2,find(pnG(1,1)==cbeats(1,:)):find(pnG(1,end)==cbeats(1,:)))=0;
                      
                       end
              
      elseif(sum(alth,2)==size(alth,2))
          cbeats(2,(1+find(pnG(1,1)==cbeats(1,:)) ):( find(pnG(1,end)==cbeats(1,:))-1 ) )=0;
        
      end
        
    
      if(~isempty(pnG_cut)&&plotten==1)
          figure(111); hold on; plot(cbeats(1,:),0.01*k,'m+'); plot(pnG_cut,0.01*k,'r+');%plot([sorted_Groups(1,2)*ones(1,2)], [0 1]);
      end
      
  end

if(plotten==1)
    figure(111); hold on; plot(cbeats(1,:),1.1,'m+');
end

end