/* nag_wfilt_3d (c09acc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 24, 2013.
 */
#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagc09.h>
#include <nagx02.h>

#define A(I,J,K) a[I-1 + (J-1)* lda + (K-1)* lda * sda]
#define B(I,J,K) b[I-1 + (J-1)* ldb + (K-1)* ldb * sdb]
#define D(I,J,K) d[I-1 + (J-1)* ldd + (K-1)* ldd * sdd]

int main(void)
{
  /* Scalars */
  Integer         exit_status = 0;
  Integer         i, j, k, lda, ldb, ldd, lenc, nwlmax, m, n, fr;
  Integer         nwcfr, nwcm, nwcn, nwct, nwl, sda, sdb, sdd, nf;
  Integer         want_coeffs, want_level;
  double          frob, esq, eps;
  /* Arrays */
  char            mode[25], wavnam[25];
  double          *a = 0,  *b = 0,  *c = 0,  *d = 0;
  Integer         *dwtlvfr = 0,  *dwtlvm = 0,  *dwtlvn = 0;
  Integer         icomm[260];
  /* Nag Types */
  Nag_Wavelet     wavnamenum;
  Nag_WaveletMode modenum;
  Nag_MatrixType  matrix = Nag_GeneralMatrix;
  Nag_OrderType   order = Nag_ColMajor;
  Nag_DiagType    diag = Nag_NonUnitDiag;
  NagError        fail;

  INIT_FAIL(fail);

  printf("nag_wfilt_3d (c09acc) Example Program Results\n\n");
  fflush(stdout);

  /* Skip heading in data file and read problem parameters */
  scanf("%*[^\n] %ld%ld%ld%*[^\n]", &m, &n, &fr);
  lda = m;
  sda = n;
  ldb = m;
  sdb = n;
  scanf("%24s%24s%*[^\n]\n", wavnam, mode);

  if (!(a = NAG_ALLOC((lda)*(sda)*(fr), double)) ||
      !(b = NAG_ALLOC((ldb)*(sdb)*(fr), double)))
  {
    printf( "Allocation failure\n");
    exit_status = 1;
    goto END;
  }

  printf("Parameters read from file :: \n");
  printf(" MLDWT :: Wavelet  : %s\n", wavnam);
  printf("          End mode : %s\n", mode);
  printf("          m  : %4ld\n", m);
  printf("          n  : %4ld\n", n);
  printf("          fr : %4ld\n\n", fr);

  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  wavnamenum = (Nag_Wavelet) nag_enum_name_to_value(wavnam);
  modenum = (Nag_WaveletMode) nag_enum_name_to_value(mode);

  /* Read data array */
  for (k=1; k<=fr; k++) {
    for (i=1; i<=m; i++) {
      for (j=1; j<=n; j++) scanf("%lf", &A(i, j, k));
    }
    scanf("%*[^\n] ");
  }

  /* Print out the input data */
  printf("Input Data :\n\n");
  for (k=1; k<=fr; k++) {
    /* nag_gen_real_mat_print_comp (x04cbc).
     * Prints out a matrix.
     */
    fflush(stdout);
    nag_gen_real_mat_print_comp(order, matrix, diag, m, n, &A(1, 1, k), lda,
                                "%6.2f"," ", Nag_NoLabels, 0,
                                Nag_NoLabels, 0, 80, 0, 0, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_gen_real_mat_print_comp (x04cbc).\n%s\n",
             fail.message);
      exit_status = 2;
      goto END;
    }
    printf("\n");
  }

  /* 
   * nag_wfilt_3d (c09acc).
   * Three-dimensional wavelet filter initialization
   */ 
  nag_wfilt_3d(wavnamenum, Nag_MultiLevel, modenum, m, n, fr, &nwlmax, &nf,
               &nwct, &nwcn, &nwcfr, icomm, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_wfilt_3d (c09acc).\n%s\n", fail.message);
    exit_status = 3;
    goto END;
  }

  /* Transform one less than the max possible number of levels. */
  nwl = nwlmax - 1;
  lenc = nwct;
  if (!(c = NAG_ALLOC((lenc), double)) || 
      !(dwtlvm = NAG_ALLOC((nwl), Integer)) ||
      !(dwtlvn = NAG_ALLOC((nwl), Integer)) ||
      !(dwtlvfr = NAG_ALLOC((nwl), Integer)))
  {
    printf( "Allocation failure\n");
    exit_status = 4;
    goto END;
  }

  /* nag_mldwt_3d (c09fcc).
   * Three-dimensional multi-level discrete wavelet transform
   */ 
  nag_mldwt_3d(m, n, fr, a, lda, sda, lenc, c,
               nwl, dwtlvm, dwtlvn, dwtlvfr, icomm, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_mldwt_3d (c09fcc).\n%s\n", fail.message);
    exit_status = 5;
    goto END;
  }

  /* nag_wfilt_3d (c09acc) returns nwct based on max levels, so recalculate
   * for the number of levels required, nwl.
   */
  nwct = dwtlvm[0] * dwtlvn[0] * dwtlvfr[0];
  for (i=0; i<nwl; i++)
    nwct += 7*dwtlvm[i] * dwtlvn[i] * dwtlvfr[i];

  printf("Number of Levels :         %4ld\n", nwl);
  printf("Length of wavelet filter : %4ld\n", nf);
  printf("Total number of wavelet coefficients : %4ld\n", nwct);
  printf("Number of coefficients in 1st dimension for each level:\n");
  for (i=0; i<nwl; i++) {
    printf("%4ld%s", dwtlvm[i], i+1%8 ? "" : "\n");
  }
  printf("\nNumber of coefficients in 2nd dimension for each level:\n");
  for (i=0; i<nwl; i++) {
    printf("%4ld%s", dwtlvn[i], i+1%8 ? "" : "\n");
  }
  printf("\nNumber of coefficients in 3rd dimension for each level:\n");
  for (i=0; i<nwl; i++) {
    printf("%4ld%s", dwtlvfr[i], i+1%8 ? "" : "\n");
  }
  printf("\n\n");

  /* Select the deepest level.*/
  want_level = nwl;
  /* Select the approximation coefficients.*/
  want_coeffs = 0;

  /* Use the extraction routine c09afc to retrieve the required
   * coefficients.
   */
  nwcm = dwtlvm[nwl - want_level];
  nwcn = dwtlvn[nwl - want_level];
  nwcfr = dwtlvfr[nwl - want_level];
  ldd = nwcm;
  sdd = nwcn;
  if (!(d = NAG_ALLOC((ldd)*(sdd)*(nwcfr), double)))
  {
    printf("Allocation failure\n");
    exit_status = 6;
    goto END;
  }

  /* nag_wav_3d_coeff_ext (c09fcc).
   * Extract the desired coefficients.
   */
  nag_wav_3d_coeff_ext(want_level,want_coeffs,lenc,c,d,ldd,sdd,icomm,&fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_wav_3d_coeff_ext (c09afc).\n%s\n", fail.message);
    exit_status = 7;
    goto END;
  }

  /* Print the details of the level */
  printf("-----------------------------------------------------\n");
  printf("Level : %4ld", want_level);
  printf("; output is %4ld", nwcm);
  printf(" by %4ld", nwcn);
  printf(" by %4ld\n", nwcfr);
  printf("-----------------------------------------------------\n\n");
 
  /* Print out the selected set of coefficients*/
  switch (want_coeffs)
  {
    case 0:
      printf("Approximation coefficients (LLL)\n");
      break;
    case 1:
      printf("Detail coefficients (LLH)\n");
      break;
    case 2:
      printf("Detail coefficients (LHL)\n");
      break;
    case 3:
      printf("Detail coefficients (LHH)\n");
      break;
    case 4:
      printf("Detail coefficients (HLL)\n");
      break;
    case 5:
      printf("Detail coefficients (HLH)\n");
      break;
    case 6:
      printf("Detail coefficients (HHL)\n");
      break;
    case 7:
      printf("Detail coefficients (HHH)\n");
      break;
  }

  printf("Level %4ld:\n", want_level);
  for (k=1; k<=nwcfr; k++) {
    printf(" Frame %4ld :\n", k);
    for (i=1; i<=nwcm; i++) {
      for (j=1; j<=nwcn; j++) {
        printf("%9.3f%s", D(i, j, k), j%8 ? "" : "\n");
      }
      printf("\n");
    }
  }

  /* nag_imldwt_3d (c09fdc).
   * Three-dimensional inverse multi-level discrete wavelet transform
   */ 
  nag_imldwt_3d(nwl, lenc, c, m, n, fr, b, ldb, sdb, icomm, &fail);
  if (fail.code != NE_NOERROR)
  {
    printf("Error from nag_imldwt_3d (c09fdc).\n%s\n", fail.message);
    exit_status = 8;
    goto END;
  }

  /* Check reconstruction matches original*/
  eps = 40.0 * (double)(m+n+fr) * nag_machine_precision;

  frob = 0.0;
  for (k=1; k<=fr; k++) {
    esq = 0.0;
    for (j=1; j<=n; j++) {
      for (i=1; i<=m; i++)
        esq = esq + pow(B(i, j, k) - A(i, j, k), 2);
    }
    frob = MAX(frob, sqrt(esq));
  }

  if (frob>eps) {
    printf("\nFail: Frobenius norm of B-A, where A is the original \n"
           "data and B is the reconstrucion, is too large.\n");
  } else {
    printf("\nSuccess: the reconstruction matches the original.\n");
  }

  END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(c);
  NAG_FREE(d);
  NAG_FREE(dwtlvfr);
  NAG_FREE(dwtlvm);
  NAG_FREE(dwtlvn);
  return exit_status;
}