#include "pls/pls.h"

#include "benchmark_runner.h"
#include "benchmark_base/fft.h"

using namespace comparison_benchmarks::base;

void pls_conquer(fft::complex_vector::iterator data, fft::complex_vector::iterator swap_array, int n) {
  if (n < 2) {
    return;
  }

  fft::divide(data, swap_array, n);
  if (n <= fft::RECURSIVE_CUTOFF) {
    fft::conquer(data, swap_array, n / 2);
    fft::conquer(data + n / 2, swap_array + n / 2, n / 2);
  } else {
    pls::spawn([data, n, swap_array]() {
      pls_conquer(data, swap_array, n / 2);
    });
    pls::spawn([data, n, swap_array]() {
      pls_conquer(data + n / 2, swap_array + n / 2, n / 2);
    });
    pls::sync();
  }

  fft::combine(data, n);
}

constexpr int MAX_NUM_TASKS = 16;
constexpr int MAX_STACK_SIZE = 4096 * 1;

int main(int argc, char **argv) {
  auto settings = benchmark_runner::parse_parameters(argc, argv);

  fft::complex_vector data(settings.size_);
  fft::complex_vector swap_array(settings.size_);
  fft::fill_input(data);

  string test_name = to_string(settings.num_threads_) + ".csv";
  string full_directory = settings.output_directory_ + "/PLS_v3/";
  benchmark_runner runner{full_directory, test_name};

  pls::scheduler scheduler{(unsigned) settings.num_threads_, MAX_NUM_TASKS, MAX_STACK_SIZE};

  if (settings.type_ == benchmark_runner::benchmark_settings::ISOLATED) {
    printf("Running isolated measurement...\n");
    runner.enable_memory_stats();
    runner.pre_allocate_stats();

    runner.run_iterations(settings.iterations_, [&]() {
      scheduler.perform_work([&]() {
        pls_conquer(data.begin(), swap_array.begin(), settings.size_);;
      });
    }, [&]() {
      fft::fill_input(data); // Reset data before each run
    });
    runner.commit_results(true);
  } else {
    printf("Running periodic measurement...\n");
    runner.enable_wall_time_stats();
    runner.pre_allocate_stats();

    runner.run_periodic(settings.iterations_, settings.interval_period_, settings.interval_deadline_, [&]() {
      scheduler.perform_work([&]() {
        pls_conquer(data.begin(), swap_array.begin(), settings.size_);;
      });
      fft::fill_input(data); // Reset data before each run
    });
    runner.commit_results(true);
  }

  return 0;
}
