/*************************************************************************
 * This code is written by N. Kehtarnavaz and N. Kim as part of the 
 * textbook "Digital Signal Processing System-Level Design Using LabVIEW".
 *************************************************************************/
 
#include <rtdx.h>                      /* RTDX                      */
#include "target.h"                    /* TARGET_INITIALIZE()       */

#define kBUFFER_SIZE 128
#define N 15

float b[N] = {-0.008773, 0.0246851, 0.0217041, -0.0396942, -0.0734726,
    0.0560876, 0.305969, 0.437322, 0.305969, 0.0560876, -0.0734726,
   -0.0396942, 0.0217041, 0.0246851, -0.008773};

short samples[N];
short coeff[N];

RTDX_CreateInputChannel(cinput);
RTDX_CreateOutputChannel(coutput);

void FIR(short *input, short *output)
{
	int i, j; 
	int result;
	
	for( j = 0; j < kBUFFER_SIZE; j++ )
	{
		for(i = N-1; i > 0; i-- )
			samples[i] = samples[i-1];
		
		samples[0] = input[j];

		result = 0;	
		for( i = 0 ; i < N ; i++ )
			result += ( samples[i] * coeff[i] ) << 1;
		
		result = result >> 16;
		
		// Scale the Output to Compensate Scaling of Coefficients.
		output[j] = (short) ( result << 1 );
	}
}

void main()
{	
	short input[kBUFFER_SIZE];
	short output[kBUFFER_SIZE];
	int i;
	
	for( i = 0; i < N ; i++ )
		samples[i] =0;

	// Convert to Q-15
	for( i = 0; i < N ; i++ )
		coeff[i] = b[i] * 0x7fff;
		
	// Scale by Half
	for( i = 0; i < N ; i++ )
		coeff[i] = coeff[i] >> 1;		
	
	// Target initialization for RTDX
	TARGET_INITIALIZE();

	/*enable RTDX channels*/
	RTDX_enableInput(&cinput);
	RTDX_enableOutput(&coutput);
	
	for (;;)	/* Infinite message loop. */
	{
		while(!RTDX_read(&cinput, input, sizeof(input)));
		
		FIR(input, output);
		
		/* Write filtered data back to host. */
		RTDX_write(&coutput, output, sizeof(output));
	}
}
