/* nag_sparse_sym_sol (f11jec) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 *
 */

#include <nag.h>
#include <stdio.h>
#include <nag_stdlib.h>
#include <nag_string.h>
#include <nagf11.h>

int main(void)
{
  double *a = 0, *b = 0, *x = 0;
  double omega;
  double rnorm;
  double tol;
  Integer exit_status = 0;
  Integer *icol, *irow;
  Integer i, n, maxitn, itn, nnz;
  char nag_enum_arg[40];
  Nag_SparseSym_Method method;
  Nag_SparseSym_PrecType precon;
  Nag_Sparse_Comm comm;
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_sparse_sym_sol (f11jec) Example Program Results\n");

  /* Skip heading in data file  */
  scanf(" %*[^\n]");

  /* Read algorithmic parameters */
  scanf("%" NAG_IFMT "%*[^\n]", &n);
  scanf("%" NAG_IFMT "%*[^\n]", &nnz);
  scanf("%39s", nag_enum_arg);
  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  method = (Nag_SparseSym_Method) nag_enum_name_to_value(nag_enum_arg);
  scanf("%39s%*[^\n]", nag_enum_arg);
  precon = (Nag_SparseSym_PrecType) nag_enum_name_to_value(nag_enum_arg);
  scanf("%lf%*[^\n]", &omega);
  scanf("%lf%" NAG_IFMT "%*[^\n]", &tol, &maxitn);

  /* Allocate memory */
  x = NAG_ALLOC(n, double);
  b = NAG_ALLOC(n, double);
  a = NAG_ALLOC(nnz, double);
  irow = NAG_ALLOC(nnz, Integer);
  icol = NAG_ALLOC(nnz, Integer);
  if (!irow || !icol || !a || !x || !b) {
    printf("Allocation failure\n");
    exit_status = 1;
    goto END;
  }

  /* Read the matrix a */
  for (i = 1; i <= nnz; ++i)
    scanf("%lf%" NAG_IFMT "%" NAG_IFMT "%*[^\n]", &a[i - 1], &irow[i - 1],
          &icol[i - 1]);

  /* Read right-hand side vector b and initial approximate solution x */
  for (i = 1; i <= n; ++i)
    scanf("%lf", &b[i - 1]);
  scanf(" %*[^\n]");

  for (i = 1; i <= n; ++i)
    scanf("%lf", &x[i - 1]);
  scanf(" %*[^\n]");

  /* Solve Ax = b  */
  /* nag_sparse_sym_sol (f11jec).
   * Solver with Jacobi, SSOR, or no preconditioning
   * (symmetric)
   */
  nag_sparse_sym_sol(method, precon, n, nnz, a, irow, icol, omega, b, tol,
                     maxitn, x, &rnorm, &itn, &comm, &fail);

  printf(" %s%10" NAG_IFMT "%s\n", "Converged in", itn, " iterations");
  printf(" %s%16.3e\n", "Final residual norm =", rnorm);

  /* Output x */
  for (i = 1; i <= n; ++i)
    printf(" %16.4e\n", x[i - 1]);

END:
  NAG_FREE(irow);
  NAG_FREE(icol);
  NAG_FREE(a);
  NAG_FREE(x);
  NAG_FREE(b);

  return exit_status;
}