// 
//  Project: Experiment 7.6.3 ETSI normalized LMS filter - Chapter 7
//  File name: ETSI_nlmsTest.c   
//
//  Description: This is the ETSI normalized LMS experiment test program
//               The input is an 1kHz sine wave sampling rate 8kHz with noise
//               The output is the sine wave 
//               The error is the noise 
//
//  For the book "Real Time Digital Signal Processing: 
//                Implementation and Application, 2nd Ed"
//                By Sen M. Kuo, Bob H. Lee, and Wenshun Tian
//                Publisher: John Wiley and Sons, Ltd
//
//  Tools used: CCS v.2.12.07
//              TMS320VC5510 DSK Rev-C
//

#include <stdio.h>
#include <stdlib.h>
#include "ETSI_nlms.h"

LMS lmsObj;
LMS *lms = &lmsObj;

short w[L+1];
short x[L+1];


void main()
{  
  short  i;
  FILE   *fpIn,*fpDes,*fpOut,*fpErr;
  char   temp1[2],temp2[2];

  // Open input file for read input data
  if ((fpIn = fopen("..\\data\\input.pcm", "rb"))== NULL)
  {
    printf("Can't open input data file\n");
    exit(0);
  }

  // Open desired file for read desired input data
  if ((fpDes = fopen("..\\data\\desired.pcm", "rb"))== NULL)
  {
    printf("Can't open desired data file\n");
    exit(0);
  }

  // Open file for write output 
  fpOut = fopen("..\\data\\output.pcm", "wb");

  // Open file for write error 
  fpErr = fopen("..\\data\\error.pcm", "wb");

  lms->order = L;
  lms->alpha = ALPHA;
  lms->power = (short)0x32767;
  lms->c = C;
  lms->w = w;
  lms->x = x;	

  // Clear data and tap delay lines
  for (i=0; i<=lms->order; i++)
  {
    lms->w[i] = 0;
    lms->x[i] = 0;
  }
	
  // Filter test
  while ((fread(temp1, sizeof(char), 2, fpIn) == 2)&&
         (fread(temp2, sizeof(char), 2, fpDes)== 2) )
  {
    // Get 16-bit PCM input and desired data 
    lms->in  = (temp1[0]&0xFF)|(temp1[1]<<8);
    lms->des = (temp2[0]&0xFF)|(temp2[1]<<8);

    // Filter the data
    intrinsic_nlms(lms);

    // Write the output and error data  to 16-bit PCM
    temp1[0] = (lms->out&0xFF);
    temp1[1] = (lms->out>>8)&0xFF;
    temp2[0] = (lms->err&0xFF);
    temp2[1] = (lms->err>>8)&0xFF;
    fwrite(temp1, sizeof(char), 2, fpOut);        
    fwrite(temp2, sizeof(char), 2, fpErr);
  }
  
  fclose(fpIn);
  fclose(fpDes);
  fclose(fpOut);
  fclose(fpErr);
}
