/*
* SDR - ESIM Project 2009 (Software Defined Radio)
* students Work with help of LESIM Group.
* 
* Students:
* Delli Veneri Luca, Espresso Giovanni, Facchiano Giambattista, Gramazio Paolo, Varricchio Giuseppe 
*/

#include "dsplib.h"
#include <stdio.h>
#include <c6x.h>				//C6000 compiler definitions
#include <csl.h>				//Chip - CSL headers
#include <csl_irq.h>
#include <csl_mcbsp.h>
#include <bsl.h>				//Board - BSL headers
#include <bsl_ad535.h>


//PROTOTYPES
void codec_init(void);
void init_HWI(void);
void isr(void);


//GLOBAL VARIABLES
int i = 0;
int j = 0;
int k = 0;
int acq = 0;
float x[N];
float std_AM, std_FM;
struct complex c;
float y[N], z[NN];

AD535_Handle hAD535;
AD535_Config my_AD535_Config = {
  AD535_LOOPBACK_DISABLE,
  AD535_MICGAIN_OFF,
  AD535_GAIN_0DB,
  AD535_GAIN_0DB
};


//MAIN FUNCTION
void main() {
  CSL_init();
  BSL_init();
  codec_init();
  init_HWI();
  
  while(1);
}

void codec_init() {
  hAD535 = AD535_open(AD535_localId);
  AD535_reset(hAD535);
  AD535_config(hAD535, &my_AD535_Config);
}

void init_HWI(void) {
  IRQ_globalEnable();				//Enable ints globally
  IRQ_enable(IRQ_EVT_RINT0);		//Enable the recive INT0
}

void isr(void) {
    int h;
    short sample = (short) AD535_read(hAD535);
    if(acq) {
		if(j < N) {
			x[j] = sample;
			j++;
		}
		else {
			//printf("\nacquisito %d\n",j);
			k = 0;
			j = 0;
			acq = 0; //end of acquisition
			IRQ_globalDisable();
			LED_off(LED_ALL);
    		//printf("\n %f \n ",std(x,N));
    		if(std(x,N) < B) printf("\nsignal too low\n");
    		else {
    			norm_by_std(x,y,N);
    			c=hilbert(y,N);
    			module(c,x,N);
    			rmvq(x,z,N,LB);
    			std_AM=std(z,NN);
    			//printf("STD_AM: %f ",std_AM);
   		 		angle(c,x,N);
    			unwrap(x,y,N);
    			diff(y,x,N);
    			rmvq(x,z,N,LB);
    			std_FM = std(z,NN);
    			//printf("STD_FM: %f ",std_FM);
    			h = clas(std_AM,std_FM);
                if(h == 1) {
                //printf("\n AM\n"); //LED 1
	    		LED_on(LED_1);
	    		}
	    		else if(h == 2) {
	    		//printf("\n FM or PM\n"); //LED 2
	    		LED_on(LED_2);
   				}
   				else if(h == 3) {
   				//printf("\n No modulation\n"); //LED 3
   				LED_on(LED_3);
   				}
   				else {
   				//printf("\n error \n"); //LED 0
   				LED_on(LED_ALL);
   				}
   				for(i = 0; i < N; i++) {
					x[i] = 0;
				}				
				IRQ_globalEnable();
			}
		}
	}
		else {
			acq = 1;
			x[0] = sample;
			j=1;
		}
	
}

