
#include "hexfin.h"
#include "wavreader.h"

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

#define BLOCK_SIZE 128

static const float lowest_frequency = 27.5f; // Note A0
static const float highest_frequency = 1567.98206f; // Note G6

int main(int argc, char* argv[])
{
  const char* wav_filepath = "res/guitar-input.wav";

  if (argc >= 2)
    wav_filepath = argv[1];

  unsigned int sample_rate = 0;
  unsigned int data_bytes = 0;
  FILE* file = fopen_wav_file_seek_to_audio_data(wav_filepath, &sample_rate, &data_bytes);
  if (file == NULL || data_bytes == 0)
  {
    fprintf(stderr, "Error: File reading aborted.\n");
    return -1;
  }

  const float sample_rate_f = (float)sample_rate;

  struct hexfin_context ctx = hexfin_create_context(sample_rate_f, lowest_frequency, highest_frequency);

  for (;;)
  {
    float block[BLOCK_SIZE];
    const size_t readBlockSize = fread(block, sizeof(float), BLOCK_SIZE, file);

    if (readBlockSize <= 0)
      break;

    const float frequency = hexfin_processBlock(&ctx, block, readBlockSize, sample_rate_f, lowest_frequency, highest_frequency);

    printf("%f Hz\n", frequency);
  }

  hexfin_destroy_context(&ctx);
  fclose(file);

  return 0;
}
