MODULE MOD_PRECISION
integer, parameter :: dp = selected_real_kind(p=16)
ENDMODULE

PROGRAM PROVA_STRUCT
USE MOD_PRECISION
IMPLICIT NONE
INCLUDE 'mpif.h'
!
TYPE tMPI
    INTEGER  :: myrank, nCPU, iErr, status
END TYPE tMPI
!
type particle
 sequence
 integer          :: ip
 real(dp)         :: rp(2)
 real(dp)         :: QQ(4)
end type particle
!
TYPE(tMPI)         :: MPI
INTEGER            :: COMM_CART
INTEGER            :: MPI_PARTICLE_TYPE_OLD
INTEGER            :: MPI_PARTICLE_TYPE

INTEGER              :: nstruct

INTEGER,ALLOCATABLE  :: TYPES(:)
INTEGER,ALLOCATABLE  :: LENGTHS(:)
INTEGER(MPI_ADDRESS_KIND),ALLOCATABLE,DIMENSION(:)   ::DISPLACEMENTS

type(particle) :: dummy(2)  ! Used for calculation of displacement



   CALL MPI_INIT(MPI%iErr)
   CALL MPI_COMM_RANK(MPI_COMM_WORLD, MPI%myrank, MPI%iErr)
   CALL MPI_COMM_SIZE(MPI_COMM_WORLD, MPI%nCPU,   MPI%iErr)
   !
   !
   nstruct=3
   ALLOCATE(TYPES(nstruct))
   ALLOCATE(LENGTHS(nstruct))
   ALLOCATE(DISPLACEMENTS(0:nstruct+1))
   !
   TYPES(1)=MPI_INTEGER
   TYPES(2)=MPI_DOUBLE_PRECISION
   TYPES(3)=MPI_DOUBLE_PRECISION
   !
   LENGTHS(1)=1
   LENGTHS(2)=2
   LENGTHS(3)=4
   ! 
   !
   CALL MPI_GET_ADDRESS(DISPLACEMENTS(0),dummy(1),MPI%iErr)
   CALL MPI_GET_ADDRESS(DISPLACEMENTS(1),dummy(1)%ip,MPI%iErr)
   CALL MPI_GET_ADDRESS(DISPLACEMENTS(2),dummy(1)%RP(1),MPI%iErr)
   CALL MPI_GET_ADDRESS(DISPLACEMENTS(3),dummy(1)%QQ(1),MPI%iErr)
   CALL MPI_GET_ADDRESS(DISPLACEMENTS(4),dummy(2),MPI%iErr)
   !
   DISPLACEMENTS(1:nstruct+1)= DISPLACEMENTS(1:nstruct+1)-DISPLACEMENTS(0)
   !
   CALL MPI_TYPE_CREATE_STRUCT(nstruct,lengths,displacements,types,MPI_PARTICLE_TYPE_OLD,MPI%iErr)
   CALL MPI_TYPE_COMMIT(MPI_PARTICLE_TYPE_OLD,MPI%iErr)
   !
   !
   CALL MPI_TYPE_CREATE_RESIZED(MPI_PARTICLE_TYPE_OLD, DISPLACEMENTS(1), DISPLACEMENTS(4), MPI_PARTICLE_TYPE)
   CALL MPI_TYPE_COMMIT(MPI_PARTICLE_TYPE,MPI%iErr)
   
ENDPROGRAM
