#include <assert.h>
#include <stdlib.h>

#include "mpitypes.h"

#include "configuration.h"
#include "box.h"

// --------------------------------------------- Helper function declarations

// ==========================================================================

void mpitype_box_init(MPI_Datatype *new_type)
{
   box_t dummy;
   int i;

   // BOX_T_* constants defined in box.h
   int blocklengths[] = {BOX_T_N_INT_MEMBERS, BOX_T_N_LONG_MEMBERS};
   MPI_Datatype types[] = {MPI_INT, MPI_LONG};
   MPI_Aint displacements[2];
   MPI_Aint base;

   MPI_Get_address(&dummy, &base);
   MPI_Get_address(&dummy.BOX_T_FIRST_INT_MEMBER, &displacements[0]);
   MPI_Get_address(&dummy.BOX_T_FIRST_LONG_MEMBER, &displacements[1]);

   for(i = 0; i < 2; i++) displacements[i] -= base;

   MPI_Type_create_struct(2, blocklengths, displacements, types, new_type);
   MPI_Type_commit(new_type);
}

void mpitype_box_free(MPI_Datatype *type)
{
#ifndef OMPI_BUG_1304 // see https://github.com/open-mpi/ompi/issues/1304
   MPI_Type_free(type);
#endif
}

void mpitype_conf_init(MPI_Datatype *new_type)
{
   conf_t dummy;
   int i;
   MPI_Datatype box_type;

   mpitype_box_init(&box_type);

   // CONF_T_* constants defined in configuration.h
   int blocklengths[] = {CONF_T_N_INT_MEMBERS, CONF_T_N_BOX_MEMBERS};
   MPI_Datatype types[] = {MPI_INT, box_type};
   MPI_Aint displacements[2];
   MPI_Aint base;

   MPI_Get_address(&dummy, &base);
   MPI_Get_address(&dummy.CONF_T_FIRST_INT_MEMBER, &displacements[0]);
   MPI_Get_address(&dummy.CONF_T_FIRST_BOX_MEMBER, &displacements[1]);

   for(i = 0; i < 2; i++) displacements[i] -= base;

   MPI_Type_create_struct(2, blocklengths, displacements, types, new_type);
   MPI_Type_commit(new_type);

   mpitype_box_free(&box_type);
}

void mpitype_conf_free(MPI_Datatype *type)
{
#ifndef OMPI_BUG_1304 // see https://github.com/open-mpi/ompi/issues/1304
   MPI_Type_free(type);
#endif
}

// --------------------------------------------------------- Helper functions

void mpitype_indexed_int(int count, int *displacements, MPI_Datatype *type)
{
   MPI_Type_create_indexed_block(count, 1, displacements, MPI_INT, type);
   MPI_Type_commit(type);
}

void mpitype_indexed_double(int count, int *displacements, MPI_Datatype *type)
{
   MPI_Type_create_indexed_block(count, 1, displacements, MPI_DOUBLE, type);
   MPI_Type_commit(type);
}


