/* nag_ddot (f16eac) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

#include <stdio.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagf16.h>

int main(void)
{
  /* Scalars */
  Integer exit_status = 0;
  double alpha, beta, r;
  Integer call, i, incx, incy, ix, iy, n;

  /* Arrays */
  double *x = 0, *y = 0;

  /* Nag Types */
  Nag_ConjType conj = Nag_NoConj;
  NagError fail;

  INIT_FAIL(fail);
  printf("nag_ddot (f16eac) Example Program Results\n\n");

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

  /* Accumulate two dot products, set beta=zero initially. */
  beta = 0.0;
  for (call = 1; call <= 2; call++) {
    /* Read data for dot product. */
    scanf("%" NAG_IFMT "%*[^\n] ", &n);
    scanf("%" NAG_IFMT "%" NAG_IFMT "%*[^\n] ", &incx, &incy);
    if (!(x = NAG_ALLOC(1 + (n - 1) * ABS(incx), double)) ||
        !(y = NAG_ALLOC(1 + (n - 1) * ABS(incy), double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
    scanf("%lf%*[^\n] ", &alpha);

    /* Read the vectors x and y and store forwards or backwards 
     * as determined by incx (resp. incy). */
    for (i = 0, ix = (incx > 0 ? 0 : (1-n)*incx); i < n; i++, ix += incx)
      scanf("%lf", &x[ix]);
    scanf("%*[^\n] ");

    for (i = 0, iy = (incy > 0 ? 0 : (1-n)*incy); i < n; i++, iy += incy)
      scanf("%lf", &y[iy]);
    scanf("%*[^\n] ");

    /* nag_ddot computes r = beta*r + alpha*(x^T*y). */
    nag_ddot(conj, n, alpha, x, incx, beta, y, incy, &r, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_ddot (f16eac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
    /* Reset beta for accumulation and deallocate x, y. */
    beta = 1.0;
    NAG_FREE(x);
    NAG_FREE(y);
  }
  printf("Accumulated dot product, r = %9.4f\n", r);
END:
  NAG_FREE(x);
  NAG_FREE(y);
  return exit_status;
}