#include <fishtalk.h>

void ft_synth_main(FT_HANDLE handle, int ph) {
	signed char* ptr;
	unsigned int ptr_len = -1;

	if(ph == FT_P_SPACE) {
		int l	    = handle->rate * 0.05;
		int samples = sizeof(handle->audio_buffer) / sizeof(handle->audio_buffer[0]);

		memset(handle->audio_buffer, 0, sizeof(handle->audio_buffer));

		while(l > 0) {
			int n = (l > samples) ? samples : l;

			if(handle->sample != NULL) handle->sample(handle, handle->audio_buffer, n);

			l -= n;
		}

		return;
	}

#define FT_PHONEME(X) \
	case FT_P_##X: \
		ptr	= phon_##X; \
		ptr_len = phon_##X##_length; \
		break;
	switch(ph) {
		FT_PHONEMES
	}
#undef FT_PHONEME

	if(ptr_len > 0) {
		int  sc = handle->rate / 11025;
		int  i;
		long n;
		long l	     = (ptr_len * 0.90) * sc;
		long s	     = (ptr_len * 0.10) * sc;
		int  samples = sizeof(handle->audio_buffer) / sizeof(handle->audio_buffer[0]);

		while(l > 0) {
			n = (l > samples) ? samples : l;

			for(i = 0; i < n; i++) {
				handle->audio_buffer[i] = (int)ptr[(s + i) / sc] * 256;
			}

			if(handle->sample != NULL) handle->sample(handle, handle->audio_buffer, n);

			l -= n;
			s += n;
		}
	}
}
