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

#include <nag.h>
#include <nag_stdlib.h>
#include <naga02.h>
#include <nagf11.h>

int main(void)
{
  /* Scalars */
  Integer exit_status = 0;
  double omega;
  Integer i, n, nnz;
  /* Arrays */
  char nag_enum_arg[100];
  Complex *a = 0, *x = 0, *y = 0;
  double *rdiag = 0;
  Integer *icol = 0, *irow = 0;
  /* NAG types */
  Nag_SparseSym_CheckData check;
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_sparse_herm_precon_ssor_solve (f11jrc) Example Program Results");
  printf("\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  /* Read algorithmic parameters */
  scanf("%" NAG_IFMT "%*[^\n] ", &n);
  scanf("%" NAG_IFMT "%*[^\n] ", &nnz);

  /* Allocate memory */
  if (!(a = NAG_ALLOC(nnz, Complex)) ||
      !(x = NAG_ALLOC(n, Complex)) ||
      !(y = NAG_ALLOC(n, Complex)) ||
      !(rdiag = NAG_ALLOC(n, double)) ||
      !(icol = NAG_ALLOC(nnz, Integer)) || !(irow = NAG_ALLOC(nnz, Integer))
         )
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  scanf("%99s%*[^\n] ", nag_enum_arg);
  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  check = (Nag_SparseSym_CheckData) nag_enum_name_to_value(nag_enum_arg);
  scanf("%lf%*[^\n]", &omega);
  /* Read the matrix a */
  for (i = 0; i < nnz; i++)
    scanf(" ( %lf , %lf ) %" NAG_IFMT "%" NAG_IFMT "%*[^\n]",
          &a[i].re, &a[i].im, &irow[i], &icol[i]);
  /* Read rhs vector y */
  for (i = 0; i < n; i++)
    scanf(" ( %lf , %lf ) ", &y[i].re, &y[i].im);
  scanf("%*[^\n]");
  /* Fill in the diagonal part */
  for (i = 0; i < nnz; i++)
    if (irow[i] == icol[i])
      rdiag[irow[i] - 1] = 1.0 / (double) (a[i].re);

  /* nag_sparse_herm_precon_ssor_solve (f11jrc).
   * Solution of linear system involving preconditioning matrix
   * generated by applying SSOR to complex sparse Hermitian matrix
   */
  nag_sparse_herm_precon_ssor_solve(n, nnz, a, irow, icol, rdiag,
                                    omega, check, y, x, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_sparse_herm_precon_ssor_solve (f11jrc)\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Output x */
  printf("     Converged Solution\n");
  for (i = 0; i < n; i++)
    printf(" (%13.4e, %13.4e) \n", x[i].re, x[i].im);

END:
  NAG_FREE(a);
  NAG_FREE(x);
  NAG_FREE(y);
  NAG_FREE(rdiag);
  NAG_FREE(icol);
  NAG_FREE(irow);
  return exit_status;
}