/* -----------------------------------------------------!
! The current code has thw purpose:                     !
! (1) how to run miltiple sections.                     !
!-------------------------------------------------------!
! Xiaoxu Guan at LSU HPC.                               !
! March 07, 2016                                        !
!----------------------------------------------------- */

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main () 
{
    int i,j,k,id;
    double temp,time_start,time_end;
    const int nsize_a = 20000, nsize_b = 40000, nsize_c = 2000;

    double **array_a;
    double **array_b;
    double array_c[nsize_c];


   array_a = malloc( nsize_a * sizeof(double) );
   array_b = malloc( nsize_b * sizeof(double) );
   if(array_a == NULL) printf("Failure to allocate array_a!\n");
   if(array_b == NULL) printf("Failure to allocate array_b!\n");


   for(i = 0; i < nsize_a; i++) 
   {
      array_a[i] = malloc( nsize_a * sizeof(double) ); 
      if(array_a[i] == NULL) { printf("Failure to allocate array element a[i] %d\n",i); exit(0); }
   }

   for(i = 0; i < nsize_b; i++) 
   {
      array_b[i] = malloc( nsize_b * sizeof(double) ); 
      if(array_b[i] == NULL) { printf("Failure to allocate array element b[i] %d\n",i); exit(0); }
   }



time_start = omp_get_wtime();


#pragma omp parallel sections
{
#pragma omp section
   {
     id = omp_get_thread_num();
     printf("section 1. My id is %d\n", id);
     for(i = 0; i < nsize_a; i++)  {
     for(j = 0; j < nsize_a; j++)  {
         temp = sin( (double) (i+j) );
         array_a[i][j] = exp(temp);
         }  }
     printf("The last array_a element = %f\n",array_a[nsize_a-1][nsize_a-1]);
   }



#pragma omp section
   {
     id = omp_get_thread_num();
     printf("section 2. My id is %d\n", id);
     for(i = 0; i < nsize_b; i++)  {
     for(j = 0; j < nsize_b; j++)  {
         temp = sqrt( (double) (i+j) );
         array_b[i][j] = cos(temp) - sin(temp);
         }  }
     printf("The last array_b element = %f\n",array_b[nsize_b-1][nsize_b-1]);
   } 

#pragma omp section
   {
     id = omp_get_thread_num();
     printf("section 3. My id is %d\n", id);
     for(i = 0; i < nsize_c; i++)  {
         temp = sin((double) i) - cos((double) i);
         array_c[i] = exp(temp);
         } 
     printf("The last array_c element = %f\n",array_c[nsize_c-1]);
   } 



}  /* end of parallel sections */


time_end = omp_get_wtime();

printf("elapsed time (second) = %.5f\n", time_end - time_start);

}

