#include <ncbi.h>
#include "blastapp.h"

/*
	cutoffs.c
	
	Calculate the cutoff score, S, and the highest expected score.

	WRG
*/
void
cutoffs(S, E, highs, Lambda, K, H, dblen, qlen, decayrate)
	Score_t	*S;		/* cutoff score */
	double	*E;		/* Expected number of HSPs scoring above S */
	Score_t	*highs;	/* Expected high score */
	double	Lambda, K, H; /* parameters for Karlin statistics */
	unsigned long	dblen;	/* length of database */
	unsigned long	qlen;	/* length of query sequence */
	double	decayrate;
{
	register Score_t	s = *S, es;
	register double	e = *E;
	Nlm_Boolean	s_changed = FALSE;
	double	esave, etest;

	/*
	Calculate a cutoff score, S, from the Expected
	(or desired) number of reported HSPs, E.
	*/
	es = 1;
	esave = e;
	if (e > 0.) {
		e = gapdecay_inverse(1, e, decayrate);
		es = etos(e, Lambda, K, H, dblen, qlen);
	}
	/*
		Pick the larger cutoff of the user's choice
		vs. that calculated from the value of E.
	*/
	if (es > s) {
		s_changed = TRUE;
		*S = s = es;
	}

	/*
		Re-calculate E from the cutoff score, if E going in was too high.
	*/
	if (esave <= 0. || !s_changed) {
		e = stoe(s, Lambda, K, H, dblen, qlen);
		e = gapdecay(1, e, decayrate);
		*E = e;
	}
		
	/* Calculate the expected high score */
	*highs = ehighs(Lambda, K, H, dblen, qlen);

	return;
}
