#include "mpi.h"
#include "PLA.h"
                       /* macro define storage of x and y to be FORTRAN-like */
#define X(i)       x[ (i)-1 ]
#define Y(i)       y[ (i)-1 ]
                        /* define y to be external, to allow it to be passed 
                                                       from routine A_x_fill */
extern double *y;

#define dabs( x )  ( (x) < 0 ?  -(x) : (x) )

void process_vector( PLA_Obj x_global )
{
  int me, n, i, zero_or_one;
  double *x, max_diff, d_one = 1.0;
  PLA_Template template;

                                             /* extract global vector length */
  PLA_Obj_global_length( x_global, &n ); 
                                            /* extract alignment information */
  PLA_Obj_template( x_global, &template );      
  PLA_Temp_zero_or_one( template, &zero_or_one );     /* extract zero_or_one */
  PLA_Temp_comm_all_rank( template, &me );      /* extract this nodes's rank */
                                  /* Enter application interface (API) state */
  PLA_API_begin( );
                                    /* open vector x for reading and writing */
    PLA_Obj_API_open( x_global );                /* retrieve global vector x */
    if ( me == 0 ){
                              /* create local vector to be used on node zero 
                                                   to retrieve global vector */
      x = ( double * ) malloc( n * sizeof( double ) );
      for ( i=1; i<=n; i++ ) X(i) = 0.0;
                                                       /* retrieve vector x  */
      PLA_API_axpy_global_to_vector( n, &d_one, x_global, zero_or_one, x, 1 );
    }                      /* NOTICE, error in the book!  this must be added */
    PLA_Obj_API_close( x_global );
    if( me == 0) {         /* NOTICE, error in the book!  this must be added */
      max_diff = 0.0;
      for (i=1; i<=n; i++) 
      {
        if ( dabs( X(i) - Y(i) ) > max_diff ) max_diff = dabs( X(i) - Y(i) );
      }
      printf("infinity norm of x-y = %lf\n", max_diff);
      free( y ); 
      free( x );
    }
  PLA_API_end( );
}
