function p = konfintp(x,n)

  pmin = x/n;
  pmax = 1;

while (pmax-pmin>1e-10)
  p = mean([pmin pmax]);
  if binomial_cdf(x,n,p) < 0.025 pmax = p; else pmin= p; end
end
pupper = p;

  pmin = 0;
  pmax = x/n;
while (pmax-pmin>1e-10)
  p = mean([pmin pmax]);
  if binomial_cdf(x-1,n,p) > 0.975 pmin = p; else pmax= p; end
end
plower = p;

p = [plower pupper];

function cdf = binomial_cdf (x, n, p)

  if (prod(size(n)) ~= 1 | prod(size(p)) ~= 1)
    error('Arguments p and n should be scalar')
  end

  sz = size (x);
  cdf = zeros (sz);

  k = find (isnan (x) | ~(n >= 0) | (n ~= round (n)) ...
	    | ~(p >= 0) | ~(p <= 1));
  if (any (k))
    cdf(k) = NaN;
  end

  k = find ((x >= n) & (n >= 0) & (n == round (n)) ...
	    & (p >= 0) & (p <= 1));
  if (any (k))
    cdf(k) = 1;
  end

  k = find ((x >= 0) & (x < n) & (n == round (n)) ...
	    & (p >= 0) & (p <= 1));
  if (any (k))
    tmp = floor (x(k));
    cdf(k) = 1 - betainc (p, tmp + 1, n - tmp);
  end

