/* nag_sparse_nsym_matvec (f11xac) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

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

int main(void)
{
  /* Scalars */
  Integer exit_status = 0;
  Integer i, j, n, nnz;
  /* Arrays */
  char nag_enum_arg[40];
  Integer *irow = 0, *icol = 0;
  double *a = 0, *x = 0, *y = 0;
  /* NAG types */
  NagError fail;
  Nag_TransType trans;
  Nag_SparseNsym_CheckData check;

  INIT_FAIL(fail);

  printf("nag_sparse_nsym_matvec (f11xac) Example Program Results\n");

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

  /* Read order of matrix and number of nonzero entries */
  scanf("%" NAG_IFMT "%*[^\n]", &n);
  scanf("%" NAG_IFMT "%*[^\n]", &nnz);

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

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

  /* Read the vector x */
  for (j = 0; j < n; j++)
    scanf("%lf" "%*[^\n]", &x[j]);
  /* Nag_NoTrans */
  scanf("%39s%*[^\n]", nag_enum_arg);
  trans = (Nag_TransType) nag_enum_name_to_value(nag_enum_arg);

  /* Nag_SparseNsym_Check */
  scanf("%39s%*[^\n]", nag_enum_arg);
  check = (Nag_SparseNsym_CheckData) nag_enum_name_to_value(nag_enum_arg);

  /* nag_sparse_nsym_matvec (f11xac)
   * Calculate matrix-vector product without transposed matrix.
   */
  nag_sparse_nsym_matvec(trans, n, nnz, a, irow, icol, check, x, y, &fail);

  if (fail.code != NE_NOERROR) {
    printf("Error from nag_sparse_nsym_matvec (f11xac)\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Output results */
  printf("\n Matrix-vector product\n");
  for (j = 0; j < n; j++)
    printf("%16.4e\n", y[j]);

  /* Calculate transposed matrix-vector product */
  /* Nag_Trans */
  scanf("%39s%*[^\n]", nag_enum_arg);
  trans = (Nag_TransType) nag_enum_name_to_value(nag_enum_arg);

  /* Nag_SparseNsym_NoCheck */
  scanf("%39s%*[^\n]", nag_enum_arg);
  check = (Nag_SparseNsym_CheckData) nag_enum_name_to_value(nag_enum_arg);

  /* nag_sparse_nsym_matvec (f11xac)
   * Calculate matrix-vector product with transposed matrix.
   */
  nag_sparse_nsym_matvec(trans, n, nnz, a, irow, icol, check, x, y, &fail);

  if (fail.code != NE_NOERROR) {
    printf("Error from nag_sparse_nsym_matvec (f11xac)\n%s\n", fail.message);
    printf("%s\n", fail.message);
    exit_status = 2;
    goto END;
  }

  /* Output results */
  printf("\nTransposed matrix-vector product\n");
  for (j = 0; j < n; j++)
    printf("%16.4e\n", y[j]);

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

  return exit_status;
}