#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define FS 44100

// Fonction pour écrire un fichier WAV 16 bits PCM
void write_wav(const char* filename, double* data, int len) {
    FILE* f = fopen(filename, "wb");
    if (!f) {
        return;
    }

    int32_t chunk_size = 36 + len * 2;
    int16_t audio_format = 1; // PCM
    int16_t num_channels = 1;
    int32_t sample_rate = FS;
    int32_t byte_rate = FS * num_channels * 2;
    int16_t block_align = num_channels * 2;
    int16_t bits_per_sample = 16;
    int32_t subchunk2_size = len * 2;

    // En-tête WAV
    fwrite("RIFF", 1, 4, f);
    fwrite(&chunk_size, 4, 1, f);
    fwrite("WAVE", 1, 4, f);
    fwrite("fmt ", 1, 4, f);

    int32_t subchunk1_size = 16;
    fwrite(&subchunk1_size, 4, 1, f);
    fwrite(&audio_format, 2, 1, f);
    fwrite(&num_channels, 2, 1, f);
    fwrite(&sample_rate, 4, 1, f);
    fwrite(&byte_rate, 4, 1, f);
    fwrite(&block_align, 2, 1, f);
    fwrite(&bits_per_sample, 2, 1, f);

    fwrite("data", 1, 4, f);
    fwrite(&subchunk2_size, 4, 1, f);

    for (int i = 0; i < len; i++) {
        int16_t sample = (int16_t)(data[i]);
        fwrite(&sample, sizeof(int16_t), 1, f);
    }

    fclose(f);
}


double* read_wav(const char* filename, int* out_len) {
    FILE* f = fopen(filename, "rb");
    if (!f) {
        perror("Fail to open .wav");
        return NULL;
    }

    fseek(f, 0, SEEK_END);
    long filesize = ftell(f);
    fseek(f, 0, SEEK_SET);

    fseek(f, 44, SEEK_SET);

    int len = (filesize - 44) / 2;
    double* data = malloc(sizeof(double) * len);
    int16_t sample;

    for (int i = 0; i < len; i++) {
        fread(&sample, sizeof(int16_t), 1, f);
        data[i] = (double)sample;
    }

    fclose(f);

    *out_len = len;
    return data;
}
