#include <stdint.h>
#include <arm_math.h>
#include <stm32g4xx_ll_cordic.h>

#include "bassofono.h"
#include "tx.h"

q31_t tx_nco1_increment;
uint8_t tx_signal, tx_signal_last;

volatile uint8_t half_tx_dac_buffer_empty, tx_dac_buffer_toggle;
volatile uint8_t tx_adc_buffer_ready;

// FILTRO
arm_fir_instance_q31 tx_audio_filter_I_struct, tx_audio_filter_Q_struct;
q31_t tx_audio_filter_I_state[TX_AUDIO_FILTER_BLOCK_SIZE + TX_AUDIO_FILTER_TAP_NUM - 1];
q31_t tx_audio_filter_Q_state[TX_AUDIO_FILTER_BLOCK_SIZE + TX_AUDIO_FILTER_TAP_NUM - 1];
int32_t tx_audio_filter_coeffs[TX_AUDIO_FILTER_TAP_NUM];


void tx_mixer(uint16_t *out, uint16_t size, q31_t *I_in, q31_t *Q_in, int32_t nco_freq){
        uint16_t i = 0;
        int32_t sin, cos, tmp;
        static int32_t phase_accu;
	// perche?
	nco_freq = nco_freq>>2;
        LL_CORDIC_WriteData(CORDIC, phase_accu);
        while(i < (size * 2)){
                tmp = LL_CORDIC_ReadData(CORDIC);
                phase_accu += nco_freq;
                LL_CORDIC_WriteData(CORDIC, phase_accu);
                sin = (int16_t)tmp;
                cos = tmp>>16;
//		out[i] = (int32_t)cos;
//			out[i] = 2000;
			out[i] = cos>>4;
//		out[i] = (I_in[i] * sin) + (Q_in[i] * cos);
                i++;
        }
        tmp = LL_CORDIC_ReadData(CORDIC);
}

// modulatori

void ssb_modulator(q31_t *out_I, q31_t *out_Q, uint16_t size, q31_t *in, q31_t nco_freq){
        uint16_t i;
        static int32_t phase_accu;
        int32_t sin, cos, tmp;
        LL_CORDIC_WriteData(CORDIC, phase_accu);
        i = 0;
        while(i < size){
                tmp = LL_CORDIC_ReadData(CORDIC);
                phase_accu += nco_freq;
                LL_CORDIC_WriteData(CORDIC, phase_accu);
                sin = (int16_t)tmp;
                cos = tmp>>16;
                out_I = sat_mult_q31(sin, in[i]);
                out_Q = sat_mult_q31(cos, in[i]);
                i++;
        }
        tmp = LL_CORDIC_ReadData(CORDIC);

}

void dc_modulator(q31_t *in, uint16_t size, q31_t *out){
        uint16_t i;
        i = 0;
        while(i < LF_BUFFER_SIZE){
                out[i] = ((in[i]*(int32_t)mic_gain))/4096;
                i++;
        }
}

void am_modulator(q31_t *out_I, q31_t *out_Q, uint16_t size, q31_t *in){
        // SQRT (I * I + Q * Q)
        uint16_t i;
        q31_t acc0, acc1;
        i = 0;
        while(i < size){
                out_I[i] = in[i];
                out_Q[i] = 0;
                i++;
        }
}

void tx_audio_filter_init(void){
	arm_fir_interpolate_init_q15 (&tx_audio_filter_I_struct, TX_AUDIO_FILTER_INTERPOLATION_FACTOR, TX_AUDIO_FILTER_TAP_NUM, tx_audio_filter_coeffs, &tx_audio_filter_I_state[0], TX_AUDIO_FILTER_BLOCK_SIZE);
	arm_fir_interpolate_init_q15 (&tx_audio_filter_Q_struct, TX_AUDIO_FILTER_INTERPOLATION_FACTOR, TX_AUDIO_FILTER_TAP_NUM, tx_audio_filter_coeffs, &tx_audio_filter_Q_state[0], TX_AUDIO_FILTER_BLOCK_SIZE);
}
