/* nag_matop_real_gen_matrix_cond_std (f01jac) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagf01.h>
#include <nagx02.h>
#include <nagx04.h>

#define A(I,J) a[J*lda + I]

int main(void)
{
  /* Scalars */
  Integer exit_status = 0;
  Integer i, j, n, lda;
  double conda, cond_rel, eps, norma, normfa;
  /* Arrays */
  double *a = 0;
  char function_name[100];
  /* Nag Types */
  Nag_OrderType order = Nag_ColMajor;
  Nag_MatFunType fun;
  NagError fail;

  INIT_FAIL(fail);

  /* Output preamble */
  printf("nag_matop_real_gen_matrix_cond_std (f01jac) ");
  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, function_name);

  lda = n;
  if (!(a = NAG_ALLOC((lda) * (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(function_name);

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

  /* Print matrix A 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, lda, "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;
  }

  /* Find absolute condition number estimate using
   * nag_matop_real_gen_matrix_cond_std (f01jac) 
   * Condition number for the exponential, logarithm, sine, cosine,
   * sinh or cosh of a real matrix
   */
  nag_matop_real_gen_matrix_cond_std(fun, n, a, lda, &conda,
                                     &norma, &normfa, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_matop_real_gen_matrix_cond_std (f01jac)\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Print absolute condition number estimate */
  printf("\nf(A) = %s(A)\n", function_name);
  printf("Estimated absolute condition number is: %7.2f\n", conda);

  /* nag_machine_precision (x02ajc) The machine precision  */
  eps = nag_machine_precision;

  /* Find relative condition number estimate */
  if (normfa > eps) {
    cond_rel = conda * norma / normfa;
    printf("Estimated relative condition number is: %7.2f\n", cond_rel);
  }
  else {
    printf("The estimated norm of f(A) is effectively zero and so\n");
    printf("the relative condition number is undefined.\n");
  }

END:
  NAG_FREE(a);
  return exit_status;
}