/* nag_sparse_sym_sort (f11zbc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 5, 1998.
 *
 */

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

int main(void)
{
  double              *a = 0;
  Integer             *icol = 0;
  Integer             *irow = 0, *istr = 0;
  Integer             exit_status = 0, i, n, nnz;
  Nag_SparseSym_Zeros zero;
  Nag_SparseSym_Dups  dup;
  NagError            fail;

  INIT_FAIL(fail);

  printf("nag_sparse_sym_sort (f11zbc) 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 */
  istr = NAG_ALLOC(n+1, Integer);
  a = NAG_ALLOC(nnz, double);
  irow = NAG_ALLOC(nnz, Integer);
  icol = NAG_ALLOC(nnz, Integer);

  if (!istr || !irow || !icol || !a)
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read and output the original non-zero elements */
  for (i = 1; i <= nnz; ++i)
    scanf("%lf%ld%ld%*[^\n]", &a[i-1], &irow[i-1], &icol[i-1]);
  printf(" Original elements \n");
  printf(" nnz =  %6ld\n", nnz);
  for (i = 1; i <= nnz; ++i)
    printf(" %8ld%16.4e%8ld%8ld\n", i, a[i-1],
           irow[i-1], icol[i-1]);

  /* Reorder, sum duplicates and remove zeros */
  dup = Nag_SparseSym_SumDups;
  zero = Nag_SparseSym_RemoveZeros;

  /* nag_sparse_sym_sort (f11zbc).
   * Sparse sort (symmetric)
   */
  nag_sparse_sym_sort(n, &nnz, a, irow, icol, dup, zero, istr, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_sparse_sym_sort (f11zbc).\n%s\n",
             fail.message);
      exit_status = 1;
      goto END;
    }

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

  for (i = 1; i <= nnz; ++i)
    printf(" %8ld%16.4e%8ld%8ld\n", i, a[i-1],
           irow[i-1], icol[i-1]);

 END:
  NAG_FREE(istr);
  NAG_FREE(irow);
  NAG_FREE(icol);
  NAG_FREE(a);
  return exit_status;
}