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

#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagf01.h>
#include <nagx02.h>
#include <nagx04.h>

int main(void)
{

  /* Scalars */
  Integer exit_status = 0;
  Integer i, j, n, pda;
  double imnorm;

  /* Arrays */
  double *a = 0;
  char nag_enum_arg[100];

  /* Nag Types */
  Nag_OrderType order;
  Nag_MatFunType fun;
  NagError fail;

  INIT_FAIL(fail);

#ifdef NAG_COLUMN_MAJOR
#define A(I, J)  a[(J-1)*pda + I-1]
  order = Nag_ColMajor;
#else
#define A(I, J)  a[(I-1)*pda + J-1]
  order = Nag_RowMajor;
#endif

  /* Output preamble */
  printf("nag_matop_real_gen_matrix_fun_std (f01ekc) ");
  printf("Example Program Results\n\n");
  fflush(stdout);

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

  /* Read in the problem size and the required function */
  scanf("%" NAG_IFMT "%99s%*[^\n]", &n, nag_enum_arg);

  pda = n;

  if (!(a = NAG_ALLOC((pda) * (n), double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /*
   * nag_enum_name_to_value (x04nac)
   * Converts Nag enum member name to value
   */
  fun = (Nag_MatFunType) nag_enum_name_to_value(nag_enum_arg);

  /* Read in the matrix a from data file */
  for (i = 1; i <= n; i++)
    for (j = 1; j <= n; j++)
      scanf("%lf", &A(i, j));
  scanf("%*[^\n]");

  /* Find the matrix function using
   * nag_matop_real_gen_matrix_fun_std (f01ekc)
   * Real matrix function
   */
  nag_matop_real_gen_matrix_fun_std(order, fun, n, a, pda, &imnorm, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_matop_real_gen_matrix_fun_std (f01ekc)\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
  if (fabs(imnorm) > pow(nag_machine_precision, 0.8)) {
    printf("\nWARNING: the error estimate returned in imnorm is larger than"
           " expected;\n");
    printf("         the matrix solution printed below is suspect:\n");
    printf("         imnorm = %13.4e.\n\n", imnorm);
  }

  /* Print solution using
   * nag_gen_real_mat_print (x04cac)
   * Print real general matrix (easy-to-use)
   */
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag,
                         n, n, a, n, "f(A)", NULL, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_gen_real_mat_print (x04cac)\n%s\n", fail.message);
    exit_status = 2;
    goto END;
  }

END:
  NAG_FREE(a);
  return exit_status;
}