/* nag_reorder_vector (m01esc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 2 revised, 1992.
 * Mark 5 revised, 1998.
 * Mark 7 revised, 2001.
 * Mark 8 revised, 2004.
 *
 */

#include <nag.h>
#include <stdio.h>
#include <nag_stdlib.h>
#include <nag_stddef.h>
#include <nagm01.h>


#ifdef __cplusplus
extern "C" {
#endif
static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b);
#ifdef __cplusplus
}
#endif

#define A(I, J) a[(I) *tda + J]
int main(void)
{
  Integer  exit_status = 0, tda;
  NagError fail;
  double   *a = 0;
  size_t   i, *indices = 0, j, k, m, n;

  INIT_FAIL(fail);

  /* Skip heading in data file */
  scanf("%*[^\n]");
  printf("nag_reorder_vector (m01esc) Example Program Results\n");
  scanf("%u%u%"NAG_UFMT, &m, &n, &k);
  if (m >= 1 && n >= 1 && k >= 1 && k <= n)
    {
      if (!(a = NAG_ALLOC(m*n, double)) ||
          !(indices = NAG_ALLOC(m, size_t)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
      tda = n;
    }
  else
    {
      printf("Invalid m or n or k.\n");
      exit_status = 1;
      return exit_status;
    }
  for (i = 0; i < m; ++i)
    for (j = 0; j < n; ++j)
      scanf("%lf", &A(i, j));
  /* nag_rank_sort (m01dsc).
   * Rank sort of set of values of arbitrary data type
   */
  nag_rank_sort((Pointer) &A(0, k-1), m, (ptrdiff_t)(n*sizeof(double)),
                compare, Nag_Ascending, indices, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_rank_sort (m01dsc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
  /* nag_make_indices (m01zac).
   * Inverts a permutation converting a rank vector to an
   * index vector or vice versa
   */
  nag_make_indices(indices, m, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_make_indices (m01zac).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }
  for (j = 0; j < n; ++j)
    {
      /* nag_reorder_vector (m01esc).
       * Reorders set of values of arbitrary data type into the
       * order specified by a set of indices
       */
      nag_reorder_vector((Pointer) &A(0, j), m, sizeof(double),
                         (ptrdiff_t)(n*sizeof(double)), indices, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf("Error from nag_reorder_vector (m01esc).\n%s\n",
                  fail.message);
          exit_status = 1;
          goto END;
        }
    }
  printf("\nMatrix with column %u sorted\n", k);
  for (i = 0; i < m; ++i)
    {
      for (j = 0; j < n; ++j)
        printf("  %7.1f  ", A(i, j));
      printf("\n");
    }
 END:
  NAG_FREE(a);
  NAG_FREE(indices);
  return exit_status;
}

static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b)
{
  double x = *((const double *) a) - *((const double *) b);
  return(x < 0.0?-1:(x == 0.0?0:1));
}