#include "../lib.h"

#define REPLICA_COUNT 3

static plain_t vote_res;
static plain_t sum_out[REPLICA_COUNT];

#define XC sum_out[0]
#define YC sum_out[1]
#define ZC sum_out[2]

// The prints here can't happen because they're disabled under test ¯\_(ツ)_/¯

static void naive_vote(void) {
  if (XC == YC || XC == ZC) {
    vote_res = XC;
  } else if (YC == ZC) {
    vote_res = YC;
  } else {
    PRINT("all replicas differ.\n");
    fail_marker_detected();
  }
}

template <const unsigned int N> static INLINE void sum(void) {
  int sum = 0;
  for (int i = 0; i < 5; ++i) {
    sum += 1;
  }

  sum_out[N] = sum;
}

extern "C" EXPORT("wasm_module") int wasm_module(void) {
  XC = 0;
  YC = 0;
  ZC = 0;

  // "early" starts trace here
  fail_start_trace();

  sum<0>();
  sum<1>();
  sum<2>();

  // "late" starts trace here

  naive_vote();

  fail_stop_trace();

  if (vote_res == 5) {
    PRINT("vote success.\n");
    fail_marker_positive();
    return 0;
  } else {
    PRINT("undetected error.\n");
    fail_marker_negative();
    return 1;
  }
}
