/*___________________________________________________________________________________________________________*/

function extendedBinTail (ebn, ebp, ebx)
/* 
	returns the LEFT-tail probability for the extended binomial distribution 
	with ebn observations, ebp probability of success and ebx successes 
	i.e, Pr (X <= ebx | enb, ebp)

*/
{
	if (ebp == 0)
	{
		return 0;	
	}

	ebr = ebx$1; /* rounded to nearest integer */
	
	currentBinCoeff = (1-ebp)^ebn; /*compute the first binomial coefficient */
	
	binHead = 0;
	
	for (ebk=0; ebk<=ebr; ebk=ebk+1)
	{
		binHead			= binHead + currentBinCoeff;
		currentBinCoeff = currentBinCoeff * (ebn-ebk) / (ebk+1) * ebp / (1-ebp);
	}
	
	if (ebx <= ebn$1)
	{
		binHead = binHead + currentBinCoeff*(ebx-ebr);
	}
	else
	{
		binHead = binHead + (1-binHead)*(ebx-ebr)/(ebn-ebn$1);	
	}
		
	return binHead;
}

/*----------------------------------------------------------------------------*/

function computeBinTail   (m,n,p)
/*
n - number of trials
m - cutoff point
p - probability of success
*/
{
	if (m==0)
	{
		lastBinTerm = (1-p)^n;
		return 1-lastBinTerm;
	}
	if (m==n)
	{
		lastBinTerm = p^n;
		return 0;
	}
	
	upToTerm = m;
	if (m>n$2)
	{
		m 	= n-m;
		omp	= 1-p;
		binTail = p^n;
		binTerm = n*omp*p^(n-1);
		for (s=1; s<=m; s=s+1)
		{
			binTail = binTail + binTerm;
			lastBinTerm = binTerm;
			binTerm	= binTerm * (n-s) * omp / (p*(s+1)); 
		}
	}
	else
	{	
		omp	= 1-p;
		binTail = omp^n;
		binTerm = n*p*omp^(n-1);
		for (s=1; s<=m; s=s+1)
		{
			binTail = binTail + binTerm;
			lastBinTerm = binTerm;
			binTerm	= binTerm * (n-s) * p / (omp*(s+1)); 
		}
		binTail = 1-binTail;
	}

	return binTail;
}
