/****************************************************************************
**  SIONLIB     http://www.fz-juelich.de/jsc/sionlib                       **
*****************************************************************************
**  Copyright (c) 2008-2019                                                **
**  Forschungszentrum Juelich, Juelich Supercomputing Centre               **
**                                                                         **
**  See the file COPYRIGHT in the package base directory for details       **
****************************************************************************/

#define _XOPEN_SOURCE 700

#include <mpi.h>
#include <stdlib.h>

#include "sion_const.h"
#include "sion_debug.h"
#include "sion_enums.h"
#include "sion_error_handler.h"

#ifdef SION_MPI

#include "sion_mpi.h"
#include "sion_mpi_internal_gen.h"

struct _sion_file_check_par_args_mpi_struct {
  sion_open_mode mode;
  MPI_Comm comm;
  sion_mpi_options options;
};

sion_file_check_par_args_mpi *sion_file_check_par_args_init_mpi(
  sion_open_mode mode, MPI_Comm comm, const sion_mpi_options *options)
{
  sion_file_check_par_args_mpi *cb_args = malloc(sizeof(sion_file_check_par_args_mpi));

  if (cb_args) {
    cb_args->mode = mode;
    cb_args->comm = comm;
    cb_args->options = (options) ? *options : SION_MPI_OPTIONS_INIT;
  } else {
    _sion_errorprint(SION_NOT_SUCCESS, _SION_ERROR_RETURN,
      "cannot allocate cb_args structure of size %lu (sion_file_check_par_args), aborting ...\n",
      (unsigned long)sizeof(sion_file_check_par_args_mpi));
  }

  return cb_args;
}

void sion_file_check_par_args_free_mpi(sion_file_check_par_args_mpi *cb_args)
{
  free(cb_args);
}

int sion_file_check_par_cb_mpi(char *fname, void *v_args)
{
  sion_file_check_par_args_mpi *cb_args = v_args;
  int grank;
  MPI_Comm_rank(cb_args->comm, &grank);

  // FIXME
  // DPRINTFP((1, __func__, grank, "enter parallel check of file %s with mode %s\n", fname, cb_args->file_mode));
  DPRINTFP((1, __func__, grank, "enter parallel check of file %s\n", fname));

  _sion_errorprint_set_flag(_SION_ERROR_FLAG_SUPPRESS_MSG);
  int sid = sion_paropen_mpi(fname, cb_args->mode, cb_args->comm, &cb_args->options);
  _sion_errorprint_set_flag(_SION_ERROR_FLAG_NONE);
  int rc;
  if (sid < 0) {
    rc = SION_NOT_SUCCESS;
  } else {
    rc = SION_SUCCESS;
    sion_parclose_mpi(sid);
  }

  // FIXME
  // DPRINTFP((1, __func__, grank, "leave parallel check of file %s with mode %s rc=%d\n", fname, cb_args->file_mode, rc));
  DPRINTFP((1, __func__, grank, "leave parallel check of file %s rc=%d\n", fname, rc));
  return rc;
}

#endif
