#include "pls/internal/scheduling/scheduler.h"
#include "pls/internal/scheduling/static_scheduler_memory.h"

using namespace pls::internal::scheduling;

#include <iostream>
#include <cstdio>

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

using namespace comparison_benchmarks::base;

int pls_fib(int n) {
  if (n == 0) {
    return 0;
  }
  if (n == 1) {
    return 1;
  }

  int a, b;
  scheduler::spawn([n, &a]() {
    a = pls_fib(n - 1);
  });
  scheduler::spawn([n, &b]() {
    b = pls_fib(n - 2);
  });
  scheduler::sync();

  return a + b;
}

constexpr int MAX_NUM_THREADS = 4;
constexpr int MAX_NUM_TASKS = 32;
constexpr int MAX_STACK_SIZE = 1024 * 32;

static_scheduler_memory<MAX_NUM_THREADS,
                        MAX_NUM_TASKS,
                        MAX_STACK_SIZE> global_scheduler_memory;

int main(int argc, char **argv) {
  int num_threads;
  string directory;
  benchmark_runner::read_args(argc, argv, num_threads, directory);

  string test_name = to_string(num_threads) + ".csv";
  string full_directory = directory + "/PLS_v3/";
  benchmark_runner runner{full_directory, test_name};

  scheduler scheduler{global_scheduler_memory, (unsigned) num_threads, false};

  volatile int res;
  scheduler.perform_work([&]() {
    for (int i = 0; i < fib::NUM_WARMUP_ITERATIONS; i++) {
      res = pls_fib(fib::INPUT_N);
    }
  });

  scheduler.perform_work([&]() {
    for (int i = 0; i < fib::NUM_ITERATIONS * 100; i++) {
      runner.start_iteration();
      res = pls_fib(fib::INPUT_N);
      runner.end_iteration();
    }
  });
  runner.commit_results(true);

  return 0;
}
