/* nag_omp_set_nested (x06agc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 25, 2014.
 */

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

int
main(void)
{

  /*  Scalars */
  Integer exit_status = 0;
  Integer nesting, nesting_set, num_inner, num_outer, total;

  /* Nag Types */
  NagError fail;

  INIT_FAIL(fail);

  /* Output preamble */
  printf("nag_omp_set_nested (x06agc)");
  printf(" Example Program Results\n\n");

  nesting_set = 1;
  /* 
   * nag_omp_set_nested (x06agc).
   * Enable the nesting of OpenMP parallel regions 
   */
  nag_omp_set_nested(nesting_set);

  num_inner = 3;
  num_outer = 5;

  /* 
   * nag_omp_set_num_threads (x06aac).
   * Set the number of threads for an outer parallel region
   */
  nag_omp_set_num_threads(num_outer, &fail);

  if (fail.code != NE_NOERROR) {
    printf("Error from nag_omp_set_num_threads (x06aac).\n%s\n", fail.message);
    fflush(stdout);
    exit_status = 1;
    goto END;
  }

  /*  
   * Spawn an OpenMP parallel region and have the master thread check whether
   * nesting of parallel regions has been enabled
   */
  total = 0;

  #pragma omp parallel shared(num_inner,total) private(fail,nesting) \
              reduction(+:exit_status) default(none)
  {

    INIT_FAIL(fail);

    /* 
     * nag_omp_get_nested (x06ahc).
     * Test whether nesting of parallel regions has been enabled
     */
    nesting = nag_omp_get_nested();

    #pragma omp master
    {
      printf("\n%s %11" NAG_IFMT " \n\n", "Nesting enabled:  ", nesting);
    }

    /* 
     * Set the number of threads for an inner parallel region
     */
    nag_omp_set_num_threads(num_inner, &fail);

    if (fail.code != NE_NOERROR)
      {
	printf("Error from nag_omp_set_num_threads (x06aac).\n%s\n",
	       fail.message);
	exit_status++;
      }
    else
      {
      /*  
       * Spawn a nested parallel region and add up the total number of threads 
       * in all teams
       */

        #pragma omp parallel shared(total) default(none)
	{

          #pragma omp atomic
	    total++;

	}
      }

  }
  fflush(stdout);

  if (exit_status == 0)
    {
      printf("\n%s %11" NAG_IFMT " \n\n",
	     "Total number of threads requested ", num_outer * num_inner);
      printf("\n%s %11" NAG_IFMT " \n\n",
	     "Total number of threads from sum: ", total);
      fflush(stdout);
    }

END:
  return exit_status;
}