function CDF = BinomCDF(model,v);
% CDF(model,v)
% Cumulative distribution of simple binomial with noise, quantal variance and stim failure
% evaluated at position v

if model.p<0 | model.p>1 | model.pstim<0 | model.pstim>1 | model.q<0 | model.qsigma<0 
   CDF = 0;
else
   % Remove offset:
   v = v - model.offset;
   nv=length(v);
   CDF=zeros(1,nv);
   m=[0:model.n];
   probterms=zeros(1,model.n+1);
   for j=1:length(m)
      probterms(j) =  prod([model.n-m(j)+1:model.n]) / prod([1:m(j)]) * model.p^m(j) * (1-model.p)^(model.n-m(j)) ;
   end
   v2d = repmat(v,[model.n+1 1]);
   m2d = repmat(m',[1 nv]);
   probterms2d = repmat(probterms',[1 nv]);
   
   if (model.QVtype==1)
      sd = sqrt(model.noise.^2+m.*model.qsigma.^2);
      sd2d = repmat(sd',[1 nv]);
   elseif model.QVtype==2 % "flat"
      % SD = noise for zeroth peak, = (noise+qsig) for subsequent peaks
      var = model.noise.^2+(m>0).*model.qsigma.^2;
      sd = sqrt(var);
      sd2d = repmat(sd',[1 nv]);
   end
   CDF =  model.pstim * sum(probterms2d .* ( 1 - 0.5 .* erfc( (v2d-m2d.*model.q)./sqrt(2)./sd2d ) ) )...
      + (1-model.pstim) .* ( 1 - 0.5 * erfc( v./sqrt(2)./model.noise ) );
end