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

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

#define BLOCK_SIZE 128


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;

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

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

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

    if (readBlockSize <= 0)
      break;

    if (i == 1000)
    {
      lowest_frequency = 100.0f;
      highest_frequency = 1000.0f;
    }
    else if (i == 2000)
    {
      lowest_frequency = 200.0f;
      highest_frequency = 1500.0f;
    }
    else if (i == 3000)
    {
      lowest_frequency = 300.0f;
      highest_frequency = 1000.0f;
    }
    else if (i == 4000)
    {
      lowest_frequency = 700.0f;
      highest_frequency = 1000.0f;
    }
    else if (i == 5000)
    {
      lowest_frequency = 1000.0f;
      highest_frequency = 2000.0f;
    }

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

    if (frequency != frequencyExpected)
      fprintf(stderr, "Error: Comparison failed. Hexfin returned different result than reference implementation.\n");

    ++i;
  }

  hexfin_destroy_context(&ctx);
  fclose(file);

  return 0;
}
