% Finds the error probability after 1 iteration, given the initial error
% probability.
function [peafter1iter]=newerrprob(pinitial)

global p;
global dv;
global dc;
global iter;

term = 0;
plusterm =   0.5 *  (  1  +   ( 1 - 2*pinitial  )^(dc-1)  );

double minusterm;

minusterm =   1-plusterm;%0.5 *  (  1  -   ( 1 - 2*pinitial  )^(dc-1)  );

%minusterm
if minusterm == 0  
   minusterm = 0.5*(nchoosek(dc-1,1)*2*pinitial   -    nchoosek(dc-1,2) * 4 * pinitial^2  + nchoosek(dc-1,3) * 8 * pinitial^3 ) ; % 2 comes from 2*pinitial, 0.5 is there in the minus term.
   plusterm = 1-minusterm;
end

%plusterm
%minusterm


if minusterm >1e-15 & plusterm~=minusterm

    bl = ceil(    0.5*( (  log((1-p)/p)  )/log(plusterm/minusterm) + dv - 1 )      );

else bl = 1;
    
end
%bl

if bl<2
    
   bl = 2;
end

%bl = dv-1;

term1 = 0;
double term2;
term2 = 0;
%bl
for k=bl:1:dv-1
    
    term1 = term1 + nchoosek(dv-1,k) * plusterm^k * minusterm^(dv-1-k);
    term2 = term2 + nchoosek(dv-1,k) * (minusterm)^k * plusterm^(dv-1-k);
end
 
if term1>1
    term1=1;
end

peafter1iter = p - p*term1 + (1-p)*term2  ;

