#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'un bit
double* modulation_unique(int b) {
    double* s = (double*)malloc(NS * sizeof(double));
    
    int c = (b == 0) ? A / 2 : A; 

    for (int n = 0; n < NS; n++) {
        s[n] = c * cos(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 < nb_symbole; k++) {
        s[k] = modulation_unique(b[k]);
    }

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

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

    return sf;
}

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

    double thr = (A + A / 2.0) / 4.0;

    for (int k = 0; k < nb_symbole; k++) {
        double sum = 0;
       for (int n = 0 ; n < NS; n++) {
           sum += fabs(r[k * NS + n]);
       }
       double avg = sum / NS;
       sb[k] = (avg > thr) ? 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, 2 * 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 = askdemodulation(wav_data, 2 * nb_symbole);

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

    free(sf);
    return 0;
}


