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

#define _XOPEN_SOURCE 700

#include <ctype.h>
#include <inttypes.h>
#include <math.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "sion.h"

int main(int argc, char **argv)
{
  int rank, size;

  /* -------------------------- */
  /* PROLOG */
  /* -------------------------- */

  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &size);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);

  /* -------------------------- */
  /* TEST A: write a empty file and get info */
  /* -------------------------- */
  {
    int sid;
    sion_mpi_options options = sion_mpi_options_new();

    sion_mpi_options_set_chunksize(&options, 1000);
    sion_mpi_options_set_fsblksize(&options, 10);

    sid = sion_paropen_mpi_with_options("testA.out", SION_OPEN_WRITE, MPI_COMM_WORLD, &options);

    sion_parclose_mpi(sid);
  }

  /* -------------------------- */
  /* TEST A: write a small file and get info */
  /* -------------------------- */
  {
    int sid;
    int i;
    char buffer[1000];

    int64_t bytes_written = -1;
    sion_mpi_options options = sion_mpi_options_new();

    for (i = 0; i < 1000; i++) {
      buffer[i] = 'A' + rank;
    }

    sion_mpi_options_set_chunksize(&options, 1000);
    sion_mpi_options_set_fsblksize(&options, 10);

    sid = sion_paropen_mpi_with_options("testB.out", SION_OPEN_WRITE, MPI_COMM_WORLD, &options);

    /* write small first chunk */
    sion_fwrite(buffer, 1, 40 + rank * 14, sid);
    bytes_written = sion_get_bytes_written(sid);
    printf("on rank %d: bytes_written=%" PRId64 "\n", rank, bytes_written);

    /* write full second chunk */
    sion_fwrite(buffer, 1, 1000, sid);
    bytes_written = sion_get_bytes_written(sid);
    printf("on rank %d: bytes_written=%" PRId64 "\n", rank, bytes_written);

    /* write half full third chunk */
    sion_fwrite(buffer, 1, 512, sid);
    bytes_written = sion_get_bytes_written(sid);
    printf("on rank %d: bytes_written=%" PRId64 "\n", rank, bytes_written);

    /* write small 4th chunk */
    sion_fwrite(buffer, 1, 40 + rank * 14, sid);
    bytes_written = sion_get_bytes_written(sid);
    printf("on rank %d: bytes_written=%" PRId64 "\n", rank, bytes_written);

    sion_parclose_mpi(sid);
  }

  /* -------------------------- */
  /* EPILOG */
  /* -------------------------- */
  MPI_Finalize();

  return 0;
}
