/* TunerApp.m -- copyright 1992, 1993, 1994 by C.D.Lane */

#import "ZeroFrequency.h"

#define ERROR (0.25) /* just guestimated for this algorithm */

@implementation ZeroFrequency : Frequency

- (double) computeFrequency:sample
{
	short *pointer = (short *) [(Sound *) sample data];
	unsigned int start, end = 0, i = 0, transitions = 0, size = [sample sampleCount];

	while(i < size && pointer[end = i++] == 0);

	while(i < size && !((pointer[end] > 0 && pointer[i] < 0) || (pointer[end] < 0 && pointer[i] > 0))) ++i;

	end = i++;

	if(i >= size) return FREQUENCY_UNSTABLE;

	for(start = i; i < size; i++) {
		if((pointer[end] > 0 && pointer[i] < 0) || (pointer[end] < 0 && pointer[i] > 0)) {
			transitions++;
			end = i;
			}
		}

	if(start > end) return FREQUENCY_UNSTABLE;

	return (transitions * [sample samplingRate]) / (2 * ((end - start) + 1));
}

- (double) toleranceAtFrequency:(double) freq;
{
	return(ERROR / freq);
}

@end

