/* nag_inteq_volterra_weights (d05bwc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */
#include <nag.h>
#include <nag_stdlib.h>
#include <nagd05.h>

int main(void)
{
  /* Scalars */
  Integer exit_status = 0;
  Integer i, iorder, j, nomg, p, n;
  char methodstring[10];
  /* Arrays */
  double *omega = 0, *sw = 0;
  /* NAG types */
  NagError fail;
  Nag_ODEMethod method;

  INIT_FAIL(fail);

  printf("nag_inteq_volterra_weights (d05bwc) Example Program Results\n");

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

  /*
   * nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value.
   */
  method = (Nag_ODEMethod) nag_enum_name_to_value(methodstring);
  scanf("%" NAG_IFMT "%*[^\n] ", &iorder);
  scanf("%" NAG_IFMT "%*[^\n] ", &nomg);

  switch (method) {
  case Nag_Adams:
    p = iorder - 1;
    break;
  case Nag_BDF:
    p = iorder;
    break;
  }

  n = nomg + p - 1;

  if (!(omega = NAG_ALLOC(nomg, double)) || !(sw = NAG_ALLOC(p * n, double))
         )
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /*
     nag_inteq_volterra_weights (d05bwc).
     Generate weights for use in solving Volterra equations.
   */
  nag_inteq_volterra_weights(method, iorder, nomg, omega, sw, &fail);

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

  printf("\nThe convolution weights\n\n  n-j        omega\n");
  for (j = 0; j < nomg; j++)
    printf("%3" NAG_IFMT "     %10.4f\n", j + 1, omega[j]);

  printf("\nThe weights W\n");
  printf("\n  i ");
  for (j = 0; j < p; j++)
    printf("%11s%" NAG_IFMT " ", "j = ", j);
  printf("\n");

#define SW(I, J) sw[J * n + I]

  for (i = 0; i < n; i++) {
    printf("%3" NAG_IFMT "", i + 1);
    for (j = 0; j < p; j++)
      printf("%13.4f", SW(i, j));
    printf("\n");
  }

#undef SW

END:

  NAG_FREE(sw);
  NAG_FREE(omega);

  return exit_status;
}