/* Pitch_extensions.c */
/* David Weenink, 8 apr 1997 */

#include "Pitch_extensions.h"

void Pitch_Frame_addPitch (Pitch_Frame me, double f, double strength, int maxnCandidates)
{
	int i, pos = 0;	double weakest = 1e38;
	if (my nCandidates < maxnCandidates) pos = ++ my nCandidates;
	else
	{
		/* Find weakest candidate so far (skip the unvoiced one) */
		for (i=1; i <= maxnCandidates; i++) if (my candidate[i].strength < weakest &&
			my candidate[i].frequency > 0) { weakest = my candidate[i].strength; pos = i; }
		if (strength < weakest) pos = 0;
	}
	if (pos)
	{
		my candidate[pos].frequency = f;
		my candidate[pos].strength = strength;
	}
}

void Pitch_Frame_getPitch (Pitch_Frame me, double *f, double *strength)
{
	int i, pos = 1;
	*strength = -1;
	for (i=1; i <= my nCandidates; i++) if (my candidate[i].strength > *strength && 
		my candidate[i].frequency > 0) { *strength = my candidate[i].strength; pos = i; }
	*f = my candidate[pos].frequency;
}

void Pitch_Frame_resizeStrengths (Pitch_Frame me, double maxStrength,
	double unvoicedCriterium)
{
	int i, pos = 1; double strongest = my candidate[1].strength;
	for (i=2; i <= my nCandidates; i++) if (my candidate[i].strength > strongest)
		{ strongest = my candidate[i].strength; pos = i; }
 	if (strongest != 0) for (i=1; i <= my nCandidates; i++)
 		my candidate[i].strength *= maxStrength / strongest;		
	if (maxStrength < unvoicedCriterium) for (i=1; i <= my nCandidates; i++)
		if (my candidate[i].frequency == 0) { pos = i; break; }
	if (pos != 1)
	{
		double tmp = my candidate[1].frequency;
		my candidate[1].frequency = my candidate[pos].frequency;
		my candidate[pos].frequency = tmp;
		tmp = my candidate[1].strength;
		my candidate[1].strength = my candidate[pos].strength;
		my candidate[pos].strength = tmp;
	}
}

/* End of file Pitch_extensions.c */
