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

int main(int argc, char **argv) {
	MPI_Init(&argc, &argv);

	int rank, size;
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	MPI_Comm_size(MPI_COMM_WORLD, &size);

	std::string data = "xyyzzz";
	int length[3] = { 1, 2, 3 };
	MPI_Aint displacement[3] = { rank, size + 2 * rank, 3 * size + 3 * rank };

	MPI_Datatype dtype;
	MPI_Type_create_hindexed(3, length, displacement, MPI_CHAR, &dtype);
	MPI_Type_commit(&dtype);

	MPI_File MPIfile;

	if (MPI_File_open(MPI_COMM_WORLD, "output.txt", MPI_MODE_WRONLY | MPI_MODE_CREATE, MPI_INFO_NULL, &MPIfile)) {
		printf("MPI cannot create file\n");
	} else {
		MPI_File_set_view(MPIfile, 0, MPI_CHAR, dtype, "native", MPI_INFO_NULL);
		MPI_File_write_all(MPIfile, data.c_str(), data.size(), MPI_CHAR, MPI_STATUS_IGNORE);
		MPI_File_close(&MPIfile);
	}

	MPI_Finalize();
	return 0;
}