#ifndef BEATRAT_WAV_H
#define BEATRAT_WAV_H

#include <stdint.h>
#include <stdio.h>
#include <stddef.h>

typedef struct {
    FILE *fp;
    uint32_t sample_rate;
    uint16_t channels;
    uint16_t bits_per_sample;
    uint32_t data_bytes_written;
    long data_size_field_pos;  /* offset of the "data" chunk size field, for patch-on-close */
    long riff_size_field_pos;  /* offset of the RIFF chunk size field, for patch-on-close */
} WavWriter;

typedef struct {
    FILE *fp;
    uint32_t sample_rate;
    uint16_t channels;
    uint16_t bits_per_sample;
    uint32_t data_bytes_total;
    uint32_t data_bytes_read;
} WavReader;

/* Writes a PCM WAV header immediately (with placeholder size fields)
 * and leaves the file positioned ready for sample data. */
int wav_writer_open(WavWriter *w, const char *path, uint32_t sample_rate,
                     uint16_t channels, uint16_t bits_per_sample);

/* count = number of int16_t samples (interleaved if channels > 1), not frames. */
int wav_writer_write(WavWriter *w, const int16_t *samples, size_t count);

/* Patches the RIFF and data chunk sizes now that the true length is known. */
int wav_writer_close(WavWriter *w);

/* Parses the header and leaves the file positioned at the start of the
 * "data" chunk's sample bytes. Only handles 16-bit PCM (format code 1). */
int wav_reader_open(WavReader *r, const char *path);

/* Returns the number of int16_t samples actually read (may be less than
 * count at end of file). */
size_t wav_reader_read(WavReader *r, int16_t *samples, size_t count);

int wav_reader_close(WavReader *r);

#endif
