#include "common.h"
#include "sig_test.h"

using namespace stk;

bool done = false;
static unsigned int counter = 0;

int tick( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
		  double streamTime, RtAudioStreamStatus status, void *dataPointer )
{
	sig_test *sig = (sig_test *) dataPointer;
	register StkFloat *samples = (StkFloat *) outputBuffer;

	//printf("tick nFrames=%ud, %f, %ud", nBufferFrames, streamTime, status);
	DebugFile("debug.log", "tick nFrames=%u, %f, %u\n", nBufferFrames, streamTime, status);
	
	for ( unsigned int i = 0; i < nBufferFrames; i++ ) {
		*samples++ = sig->tick();
		counter++;
	}

	if(counter++ > 48000) {
		done = true;
	}

	return 0;
}

int main(int argc, char *argv[])
{
	Stk::setSampleRate(48000);
	
	RtAudio dac;
	sig_test sigT;

	RtAudio::StreamParameters parameters;
	parameters.deviceId = dac.getDefaultOutputDevice();
	parameters.nChannels = 1;

	RtAudioFormat format = ( sizeof(StkFloat) == 8 ) ? RTAUDIO_FLOAT64 : RTAUDIO_FLOAT32;
	unsigned int bufferFrames = RT_BUFFER_SIZE;
	try {
		dac.openStream( &parameters, NULL, format,
						(unsigned int)Stk::sampleRate(),
						&bufferFrames, &tick, (void*)&sigT );
	}
	catch ( RtError &error ) {
		error.printMessage();
		goto cleanup;
	}

	try {
		dac.startStream();
	}
	catch ( RtError &error ) {
		error.printMessage();
		goto cleanup;
	}

	// Block waiting here.
	// char keyhit;
	// std::cout << "\nPlaying ... press <enter> to quit.\n";
	// std::cin.get( keyhit );
	while( done == false ) {
		Stk::sleep(50);
	}

	// Shut down the output stream.
	try {
		dac.closeStream();
	}
	catch ( RtError &error ) {
		error.printMessage();
	}

cleanup:
	
	return 0;
}
