function corFRET=errorcorr(unFRET)
%% corrects discrete photon streams for background and crosstalk given in
%% the $unFRET structure in .bg and .cross
frets=length(unFRET);

corFRET=unFRET;
for i=1:frets
corFRET(3,i).counts=unFRET(1,i).counts;    
%% find nonzero values
      
        nonZD=find(unFRET(1,i).counts(:,1));
        nonZA=find(unFRET(1,i).counts(:,2));
        
%% caluclate probabilities for bg and x-talk photons to occur        
        
        DchancesBG=rand(length(nonZD),1);
        AchancesBG=rand(length(nonZA),1);
        % there is assumend to be no crosstalk to the Donor channel!
        AchancesCROSS=rand(length(nonZA),1);
        
        del_bg_D=DchancesBG<unFRET(1,i).bg(1,1);
        del_bg_A=AchancesBG<unFRET(1,i).bg(1,2);
        
        del_cross_A=AchancesCROSS<unFRET(1,i).cross;
        toDelA_cross=nonZA(del_cross_A);
        
        toDelD_bg=nonZD(del_bg_D);
        toDelA_bg=nonZA(del_bg_A);
       
        lA_bg=length(toDelA_bg);
        lD_bg=length(toDelD_bg);
        
        lA_cross=length(toDelA_cross);
       
        winner_bg=max(lA_bg,lD_bg);
      
      %  corFRET(1,i).Del_BGphotons(:,1:2)=zeros(winner_bg,2);
        corFRET(1,i).Del_CROSSphotons=zeros(lA_cross,1);

%% delete photons from timeseries (and store deleted positions)    

        corFRET(1,i).Del_BGphotons(1:lD_bg,1)=toDelD_bg;
        corFRET(1,i).Del_BGphotons(1:lA_bg,2)=toDelA_bg;

        corFRET(1,i).Del_CROSSphotons(1:lA_cross,2)=toDelA_cross;
       
        corFRET(3,i).counts(toDelD_bg,1)=unFRET(1,i).counts(toDelD_bg,1)-1;
        corFRET(3,i).counts(toDelA_bg,2)=unFRET(1,i).counts(toDelA_bg,2)-1;
        
        corFRET(3,i).counts(toDelA_cross,2)=unFRET(1,i).counts(toDelA_cross,2)-1;
        corFRET(3,i).counts(toDelA_cross,1)=unFRET(1,i).counts(toDelA_cross,1)+1;
        
end

%%   
%corFRET(1,i).counts(nonZA(find(del_bg_A)),2)=unFRET(1,i).counts(nonZA(find(del_bg_A)),2)-1;
%corFRET(1,i).counts(nonZD(find(del_bg_D)),1)=unFRET(1,i).counts(nonZD(find(del_bg_D)),1)-1;