function [pdf, poiss, cumpdf] = binpdf(n,p);
%function [pdf, poiss, cumpdf] = binpdf(n,p);

k = [0:n]';%col
lnp = log(p);lnq = log(1-p);
bico = gammaln(n+1)-gammaln(k+1)-gammaln(n-k+1);
pdf = exp(bico +k.*lnp +(n-k).*lnq);
x = n*p;lnx = log(x);
poiss = exp(-x +k.*lnx -gammaln(k+1) );


cumpdf = cumsum(pdf);
cumpoiss = cumsum(poiss);
cumpoiss = checkrange(cumpoiss);
cumpoiss1 = 1-cumpoiss;
cumpdf = checkrange(cumpdf);
cumpdf1 = 1-cumpdf;
Cums = [cumpdf';cumpdf1';cumpoiss';cumpoiss1']';

subplot(211),plot(k,pdf,'r*-',k,poiss,'b*-');grid
subplot(212),semilogy(k,pdf, 'r*-',k,poiss,'b*-');grid
title('PDFs:   Binomial(red)  Poisson(blue)');subplot(111)
pause;

subplot(211),plot(k,cumpdf, 'r*-',k,cumpoiss,'g*-');grid
subplot(212),semilogy(k*[1 1 1 1],Cums, '*-');grid
title('Cumulative PDF tails');subplot(111)

