#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "../WAV/wav.h"

// Fréquence d'échantillonage
#define FS 44100 
// Temps d'échantillonage
#define TS 0.05
// Nombre d'échantillions
#define NS (int)(FS*TS)
// Amplitude du signal
#define A 22767 
// Fréquence de la porteuse
#define FC 400 

// Fonction de concaténation deux tableau
double* concat_tab(double **t, int a, int b) {
    double* tf = malloc(sizeof(double) * a * b);

    int pos = 0;
    for (int i = 0; i < b; i++) {
        for (int j = 0; j < a; j++) {
            tf[pos] = t[i][j];
            pos++;
        }
    }

    return tf;
}

// Fontion permetant la modulation d'une paire de bits
double* modulation_unique(int b0, int b1) {
    double* s = (double*)malloc(NS * sizeof(double));

    //double p = (M_PI / 2) * (2 * b0 + b1);
    int eps0 = 2 * b0 - 1; // Negatif si b = 0 et positif si b = 1
    int eps1 = 2 * b1 - 1; // Negatif si b = 0 et positif si b = 1
    
    for (int n = 0; n < NS; n++) {
        s[n] = A * eps0 * cos(2 * M_PI * FC * ((double)n / FS)) + A * eps1 * sin(2 * M_PI * FC * ((double)n / FS));
    }
    return s;
}

// Fonction permetant la modulation d'un suite de bits
double* modulation(int* b, int nb_symbole) {
    double** s = (double**)malloc(sizeof(double*) * nb_symbole );
   
    for (int k = 0; k < 2 * nb_symbole - 1; k += 2) {
        s[k / 2] = modulation_unique(b[k], b[k + 1]);
    }

    double *sf = concat_tab(s, NS, nb_symbole);

    for (int i = 0; i < nb_symbole; i++) {
        free(s[i]);
    }
    free(s);

    return sf;
}

int* qpskdemodulation(double* r, int nb_symbole) {
    int* sb = (int*)malloc(sizeof(int) * 2 * nb_symbole);

    for (int k = 0; k < nb_symbole; k++) {
       double I = 0;
       double Q = 0;

       for (int n = 0 ; n < NS; n++) {
           I += r[k * (int)NS + n] * A * cos(2 * M_PI * FC * ((double)n / (double)FS));
           Q += r[k * (int)NS + n] * A * sin(2 * M_PI * FC * ((double)n / (double)FS));
       }
       sb[2 * k] = (I > 0) ? 1 : 0;
       sb[2 * k + 1] = (Q > 0) ? 1 : 0;
    }
    return sb;
}

int main() {
    int bits[] = {0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1};

    int nb_symbole = (sizeof(bits) / sizeof(bits[0])) / 2;

    for (int i = 0; i < 2 * nb_symbole; i++) {
       printf("%d ", bits[i]);
    }
    printf("\n");

    double* sf = modulation(bits, nb_symbole);

    write_wav("signal.wav", sf, (double)NS * (double)nb_symbole);
    
    int wav_len;
    double* wav_data = read_wav("signal.wav", &wav_len);

    int* dbits = qpskdemodulation(wav_data, nb_symbole);

    for (int i = 0; i < 2 * nb_symbole; i++) {
       printf("%d ", dbits[i]);
    }
    printf("\n");

    free(sf);
    return 0;
}

