/* nag_mv_orthomax (g03bac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 5, 1998.
 * Mark 8 revised, 2004.
 *
 */

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

#define R(I, J)   r[(I) *tdr + J]
#define FL(I, J)  fl[(I) *tdfl + J]
#define FLR(I, J) flr[(I) *tdfl + J]

int main(void)
{
  Integer             exit_status = 0, i, iter, j, k, maxit, nvar, tdfl, tdr;
  double              acc, *fl = 0, *flr = 0, g, *r = 0;
  char                nag_enum_arg[40];
  Nag_RotationLoading stand;
  NagError            fail;

  INIT_FAIL(fail);

  printf("nag_mv_orthomax (g03bac) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld", &nvar);
  scanf("%ld", &k);
  scanf("%lf", &g);
  scanf("%39s", nag_enum_arg);
  scanf("%lf", &acc);
  scanf("%ld", &maxit);

  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  stand = (Nag_RotationLoading) nag_enum_name_to_value(nag_enum_arg);

  if (k >= 2 && nvar >= k)
    {
      if (!(r = NAG_ALLOC(k*k, double)) ||
          !(fl = NAG_ALLOC(nvar*k, double)) ||
          !(flr = NAG_ALLOC(nvar*k, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
      tdr = k;
      tdfl = k;
    }
  else
    {
      printf("Invalid k or nvar.\n");
      exit_status = 1;
      return exit_status;
    }
  for (i = 0; i < nvar; ++i)
    {
      for (j = 0; j < k; ++j)
        scanf("%lf", &FL(i, j));
    }
  /* nag_mv_orthomax (g03bac).
   * Orthogonal rotations for loading matrix
   */
  nag_mv_orthomax(stand, g, nvar, k, fl, tdfl, flr, r, tdr, acc, maxit, &iter,
                  &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_mv_orthomax (g03bac).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }

  printf("\n     Rotated factor loadings\n\n");
  for (i = 0; i < nvar; ++i)
    {
      for (j = 0; j < k; ++j)
        printf("  %8.3f", FLR(i, j));
      printf("\n");
    }
  printf("\n     Rotation matrix\n\n");
  for (i = 0; i < k; ++i)
    {
      for (j = 0; j < k; ++j)
        printf("  %8.3f", R(i, j));
      printf("\n");
    }

 END:
  NAG_FREE(r);
  NAG_FREE(fl);
  NAG_FREE(flr);

  return exit_status;
}