// fm4_FIR_intr_GUI.c

#include "fm4_wm8731_init.h"
#include "FM4_slider_interface.h"

int32_t rand_int32(void);

// Create (instantiate) GUI slider data structure
struct FM4_slider_struct FM4_GUI;

float32_t x_old[4] = {0, 0, 0, 0};

void PRGCRC_I2S_IRQHandler(void) 
{
  union WM8731_data sample;
	int16_t xL, xR;
	float32_t x, y;
	
  gpio_set(DIAGNOSTIC_PIN,HIGH);
	// Get L/R codec sample
  sample.uint32bit = i2s_rx();
	
	// Do more processing on LEFT and RIGHT channels
	x = (float32_t) sample.uint16bit[LEFT];
	//x = (float32_t)(((int16_t)rand_int32())>>2); 

	// FIR filter the left channel using FIR_filters module
	// Brute force 4-tap solution
	
	
	// No processing done to the right channel

	// Return L/R samples to codec via C union with slider gain
	xL = (int16_t) (FM4_GUI.P_vals[0] * y);
	xR = (int16_t) (FM4_GUI.P_vals[1] * y);
	sample.uint16bit[LEFT] = xL;
	sample.uint16bit[RIGHT] = xR;
  i2s_tx(sample.uint32bit);

  NVIC_ClearPendingIRQ(PRGCRC_I2S_IRQn);
	
	gpio_set(DIAGNOSTIC_PIN,LOW);
}

int main(void)
{
	
	// Initialize the slider interface by setting the baud rate (460800 or 921600)
	// and initial float values for each of the 6 slider parameters

	init_slider_interface(&FM4_GUI,460800, 1.0, 1.0, 0.25, 0.25, 0.25, 0.25);
	
	// Send a string to the PC terminal
	write_uart0("Hello FM4 World!\r\n");
	
	// Some #define options for initializing the audio codec interface:
	// FS_8000_HZ, FS_16000_HZ, FS_24000_HZ, FS_32000_HZ, FS_48000_HZ, FS_96000_HZ
	// IO_METHOD_INTR, IO_METHOD_DMA
	// WM8731_MIC_IN, WM8731_MIC_IN_BOOST, WM8731_LINE_IN
  fm4_wm8731_init (FS_48000_HZ,               // Sampling rate (sps)
	                 WM8731_LINE_IN,            // Audio input port
	                 IO_METHOD_INTR,            // Audio samples handler
	                 WM8731_HP_OUT_GAIN_0_DB,   // Output headphone jack Gain (dB)
	                 WM8731_LINE_IN_GAIN_0_DB); // Line-in input gain (dB) 
	
	while(1){
		// Update slider parameters
		update_slider_parameters(&FM4_GUI);	
	}
}

// Uniformly distributed noise generator
int32_t rand_int32(void)
{
	static int32_t a_start = 100001;
	
	a_start = (a_start*125) % 2796203;
	return a_start;
}
