#include "ComputeSPMV.hpp"
#include "ComputeSPMV_ref.hpp"

#include <algorithm>
#include <array>
#include <cmath>
#include <iostream>

int main() {
  constexpr int rows = 28;
  constexpr int columns = 31;
  std::array<std::array<double, columns>, rows> coefficients{};
  std::array<std::array<local_int_t, columns>, rows> indices{};
  std::array<double*, rows> coefficient_rows{};
  std::array<local_int_t*, rows> index_rows{};
  std::array<char, rows> nonzeros{};
  std::array<double, columns> input{};
  std::array<double, rows> expected{}, actual{};

  for (int column = 0; column < columns; ++column) {
    input[column] = (column - 15) / 7.0;
  }
  for (int row = 0; row < rows; ++row) {
    nonzeros[row] = static_cast<char>(row);
    coefficient_rows[row] = coefficients[row].data();
    index_rows[row] = indices[row].data();
    for (int j = 0; j < row; ++j) {
      indices[row][j] = (row + 7 * j) % columns;
      coefficients[row][j] = (2.0 * j - row) / 9.0;
    }
  }

  SparseMatrix matrix{};
  matrix.localNumberOfRows = rows;
  matrix.localNumberOfColumns = columns;
  matrix.nonzerosInRow = nonzeros.data();
  matrix.matrixValues = coefficient_rows.data();
  matrix.mtxIndL = index_rows.data();
  Vector x{}, reference{}, optimized{};
  x.localLength = columns;
  x.values = input.data();
  reference.localLength = optimized.localLength = rows;
  reference.values = expected.data();
  optimized.values = actual.data();

  if (ComputeSPMV_ref(matrix, x, reference) || ComputeSPMV(matrix, x, optimized)) {
    return 1;
  }
  double largest_difference = 0.0;
  for (int row = 0; row < rows; ++row) {
    const double error = std::abs(expected[row] - actual[row]);
    if (!(error <= 1e-12 * (1.0 + std::abs(expected[row])))) {
      std::cerr << "Mismatch in row with " << row << " entries\n";
      return 1;
    }
    largest_difference = std::max(largest_difference, error);
  }
  std::cout << "Compared rows with 0-27 entries. Maximum absolute difference: "
            << largest_difference << '\n';
}
