/* -*- c-file-style: "GNU" -*- */
/*
 * Copyright © CNRS, INRIA, Université Bordeaux 1
 * See COPYING in top-level directory.
 */

#define _GNU_SOURCE 1
#define _REENTRANT

#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/timeb.h>
#include <dlfcn.h>
#include <string.h>

#include "mpi.h"
#include "mpi_eztrace.h"
#include "mpi_ev_codes.h"
#include "eztrace.h"

static int MPI_Ibcast_core(void *buffer, int count, MPI_Datatype datatype, int root, MPI_Comm comm, MPI_Request *r)
{
  return libMPI_Ibcast(buffer, count, datatype, root, comm, r);
}

static void MPI_Ibcast_epilog(void *buffer __attribute__((unused)),
			      int count __attribute__((unused)),
			      MPI_Datatype datatype,
			      int root,
			      MPI_Comm comm,
			      MPI_Request *r)
{
  int rank = -1;
  int size = -1;
  libMPI_Comm_size(comm, &size);
  libMPI_Comm_rank(comm, &rank);

  int msize;
  MPI_Type_size(datatype, &msize);
  EZTRACE_EVENT5(FUT_MPI_IBCAST, comm, size, rank, msize*count, r);
}

int MPI_Ibcast(void *buffer, int count, MPI_Datatype datatype, int root, MPI_Comm comm, MPI_Request *r)
{
  FUNCTION_ENTRY;
  int ret = MPI_Ibcast_core(buffer, count, datatype, root, comm, r);
  MPI_Ibcast_epilog(buffer, count, datatype, root, comm, r);
  return ret;
}

void mpif_ibcast_(void *buf, int *count, MPI_Fint *d,
		 int *root, MPI_Fint *c, MPI_Fint*r, int *error)
{
  MPI_Datatype c_type = MPI_Type_f2c(*d);
  MPI_Comm c_comm = MPI_Comm_f2c(*c);
  MPI_Request c_req = MPI_Request_f2c(*r);

  *error = MPI_Ibcast_core(buf, *count, c_type, *root, c_comm, &c_req);
  *r= MPI_Request_c2f(c_req);
  MPI_Ibcast_epilog(buf, *count, c_type, *root, c_comm, r);
}
