#include "mpi.h"
#include <pthread.h>

typedef struct {
    MPI_File fh;
    void *buf;
    int count;
    MPI_Datatype *datatype;
    MPI_Request *request;
    MPI_Status *status;
} params_struct;

void *write_thread(void *ptr);

int MPI_File_iwrite(MPI_File fh, void *buf, int count, 
                    MPI_Datatype datatype, MPI_Request *request)
{
    pthread_t thread;
    params_struct *params;
    MPI_Status *status;

    status = (MPI_Status *) malloc(sizeof(MPI_Status));
    params = (params_struct *) malloc(sizeof(params_struct));
    params->fh = fh;
    params->buf = buf;
    params->count = count;
    params->status = status;
    MPI_Type_dup(datatype, params->datatype);

    MPI_Grequest_start(query_fn, free_fn, cancel_fn, 
		       (void *) params, request);
    params->request = request;
    pthread_create(&thread, NULL, write_thread, (void *) params);
    return MPI_SUCCESS;
}
