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

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

#include "sion.h"

#define FNAMELEN 255
#define BUFSIZE (1024*1024)

int main(int argc, char **argv)
{

  int       rank, size, globalrank, sid, i;
  char          fname[FNAMELEN], *newfname=NULL;
  int           numFiles;
  MPI_Comm      gComm, lComm;
  sion_int64    chunksize,left;
  sion_int32    fsblksize;
  size_t        btoread, bread, bwrote;
  char          *localbuffer;
  FILE          *fileptr;

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

  /* allocate and initalize a buffer  */
  localbuffer = (char *) malloc(BUFSIZE);
  srand(time(NULL));
  for (i = 0; i < BUFSIZE; i++) localbuffer[i] = (char) rand() % 256;

  /* inital parameters */
  strcpy(fname, "parfile.sion");
  numFiles   = 1;  
  gComm=lComm= MPI_COMM_WORLD;  
  chunksize  = 10*1024*1024;  
  fsblksize  = 1*1024*1024; 
  globalrank = rank;

  /* write */
  sid = sion_paropen_mpi(fname, "bw", &numFiles, gComm, &lComm, &chunksize, &fsblksize, &globalrank, &fileptr, &newfname);
  left=BUFSIZE;
  while (left > 0) {
    sion_ensure_free_space(sid, left);
    bwrote = fwrite(localbuffer, 1, left, fileptr);
    left -= bwrote;
  }
  sion_parclose_mpi(sid);  
  printf("Task %02d: wrote sionfile -> %s\n",rank,newfname);


  /* read */
  sid=sion_paropen_mpi(fname,"br",&numFiles,MPI_COMM_WORLD,&lComm,&chunksize,&fsblksize, &globalrank, &fileptr, &newfname);
  while((!sion_feof(sid))) { 
    btoread=sion_bytes_avail_in_block(sid);         
    bread=fread(localbuffer,1,btoread,fileptr);     
  }             
  sion_parclose_mpi(sid);  
  printf("Task %02d: read sionfile -> %s\n",rank,newfname);

  MPI_Finalize();

  return (0);
}
