#include <BeagleRT.h> 
#include <Scope.h>
#include <cmath>

float gPhase1, gPhase2;
float gFrequency1, gFrequency2;
float gInverseSampleRate;

Scope scope(1);    //create a scope object with numChannels

// initialise_render() is called once before the audio rendering starts.
// Use it to perform any initialisation and allocation which is dependent
// on the period size or sample rate.
//
// userData holds an opaque pointer to a data structure that was passed
// in from the call to initAudio().
//
// Return true on success; returning false halts the program.
bool setup(BeagleRTContext *context, void *userData)
{
	scope.setup(context->audioSampleRate);  //call this once in setup to initialise the scope
	 
	gInverseSampleRate = 1.0/context->audioSampleRate;
	
	gPhase1 = 0.0;
	gPhase2 = 0.0;
	
	gFrequency1 = 200.0;
	gFrequency2 = 201.0;
	return true; 
}

// render() is called regularly at the highest priority by the audio engine.
// Input and output are given from the audio hardware and the other
// ADCs and DACs (if available). If only audio is available, numMatrixFrames
// will be 0.

void render(BeagleRTContext *context, void *userData)
{
	static int count=0;
	for(unsigned int n = 0; n < context->audioFrames; n++) {
	    
		float chn1 = sinf(gPhase1);
	    float chn2 = sinf(gPhase2);
	    
	    float chn3 = context->audioIn[n*2 + 0];
	    float chn4 = context->audioIn[n*2 + 1];
	    
	    float chn5 = context->analogIn[(int)n/2*8 + 0];
	    float chn6 = context->analogIn[(int)n/2*8 + 1];
		if((n&1)==0)
		    scope.log(0, chn1);
	    
//	    scope.log(chn1, chn2, chn3, chn4, chn5, chn6);
	    //call this once every audio frame
	    //takes six or fewer floats as parameters
	    //first parameter becomes channel 1 etc
	    //to view, click the 'oscilloscope' button on the toolbar while BeagleRT is NOT running
	    //then click the big red button on the toolbar on this page
	    
	    gPhase1 += 2.0 * M_PI * gFrequency1 * gInverseSampleRate * ((count&4095)/4096.0+1);
	    gPhase2 += 2.0 * M_PI * gFrequency2 * gInverseSampleRate;
		if(gPhase1 > 2.0 * M_PI)
			gPhase1 -= 2.0 * M_PI;
		if(gPhase2 > 2.0 * M_PI)
			gPhase2 -= 2.0 * M_PI;
		
	}
	count++;
}

// cleanup_render() is called once at the end, after the audio has stopped.
// Release any resources that were allocated in initialise_render().

void cleanup(BeagleRTContext *context, void *userData)
{
    
}
