/* nag_sparse_herm_sort (f11zpc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 */

#include <nag.h>
#include <nag_stdlib.h>
#include <nagf11.h>

int main(void)
{
  /* Scalars */
  Integer             exit_status = 0;
  Integer             i, n, nnz;
  /* Arrays */
  char                nag_enum_arg[40];
  Integer             *irow = 0, *icol = 0, *istr = 0;
  Complex             *a = 0;
  /* NAG types */
  NagError            fail;
  Nag_SparseSym_Dups  dup;
  Nag_SparseSym_Zeros zero;

  INIT_FAIL(fail);

  printf("nag_sparse_herm_sort (f11zpc) Example Program Results\n");

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

  /* Read order of matrix and number of non-zero entries */
  scanf("%ld%*[^\n]", &n);
  scanf("%ld%*[^\n]", &nnz);

  /* Allocate memory */
  if ( !(a = NAG_ALLOC(nnz, Complex)) ||
       !(icol = NAG_ALLOC(nnz, Integer)) ||
       !(irow = NAG_ALLOC(nnz, Integer)) ||
       !(istr = NAG_ALLOC((n+1), Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read and output the original non-zero elements */
  for (i = 0; i < nnz; i++)
    scanf(" ( %lf , %lf ) %ld%ld%*[^\n]", &a[i].re, &a[i].im,
          &irow[i], &icol[i]);

  /* Reorder, sum duplicates and remove zeros */
  /* Nag_SparseSym_SumDups */
  scanf("%39s %*[^\n]", nag_enum_arg);
  dup = (Nag_SparseSym_Dups) nag_enum_name_to_value (nag_enum_arg);

  /* Nag_SparseSym_RemoveZeros */
  scanf("%39s %*[^\n]", nag_enum_arg);
  zero = (Nag_SparseSym_Zeros) nag_enum_name_to_value (nag_enum_arg);

  /* Output original */
  printf("\nOriginal elements\n");
  printf("%s%4ld\n"," n   =", n);
  printf("%s%4ld\n"," nnz =", nnz);

  printf("%9s%14s%22s%9s\n","i","a","irow","icol");
  for (i = 0; i < nnz; i++)
    printf("%9ld (%13.4e, %13.4e)%9ld%9ld\n",
           i, a[i].re, a[i].im, irow[i], icol[i]);

  /* nag_sparse_herm_sort (f11zpc).
   * Complex sparse Hermitian matrix reorder function.
   */
  nag_sparse_herm_sort(n, &nnz, a, irow, icol, dup, zero, istr, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_sparse_herm_sort (f11zpc)\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  /* Output results */
  printf("\nReordered elements\n");
  printf("%s%4ld\n"," nnz =", nnz);

  printf("%9s%14s%22s%9s\n","i","a","irow","icol");
  for (i = 0; i < nnz; i++)
    printf("%9ld (%13.4e, %13.4e)%9ld%9ld\n",
           i, a[i].re, a[i].im, irow[i], icol[i]);

 END:
  NAG_FREE(a);
  NAG_FREE(icol);
  NAG_FREE(irow);
  NAG_FREE(istr);

  return exit_status;
}