      program Comm
      implicit none
      include "mpif.h"

      integer ierror, rank, size, rankh, sizeh, key
      integer ALL_GROUP, color, HALF_COMM, HALF_COMM2
      integer N, M
      integer, dimension(MPI_STATUS_SIZE) :: status

 
      call MPI_Init(ierror)
  
      call MPI_Comm_rank(MPI_COMM_WORLD, rank, ierror)
      call MPI_Comm_size(MPI_COMM_WORLD, size, ierror)
      
      if (size .ne. 4) then
          write(*,*) 'Runs with 4 PEs only.'
	  goto 999
      endif
      
      N = rank
      M = rank+10
      call MPI_COMM_GROUP(MPI_COMM_WORLD, ALL_GROUP, ierror)

      color=rank/2
      key=0

      call MPI_COMM_SPLIT(MPI_COMM_WORLD,color,key,HALF_COMM, ierror)

      call MPI_BARRIER(MPI_COMM_WORLD, ierror)

      call MPI_Comm_rank(HALF_COMM, rankh, ierror)
      call MPI_Comm_size(HALF_COMM, sizeh, ierror)
      
c      write(*,*) 'New size ',sizeh, '(from ',rank,' ',rankh
      
      write(*,*) 'Global ', rank,' is now local rank ',rankh,' ',color
      write(*,*) 'Global ',rank,' local ',rankh, ' has ',N,' and ',M

      call MPI_BARRIER(MPI_COMM_WORLD, ierror)

      if (rankh.eq.0) then   
      call MPI_SENDRECV(N,1,MPI_INTEGER,1,1,
     .                  N,1,MPI_INTEGER,1,2,HALF_COMM,status,ierror)
      else
      call MPI_SENDRECV(N,1,MPI_INTEGER,0,2,
     .                  N,1,MPI_INTEGER,0,1,HALF_COMM,status,ierror)
      endif
      
      write(*,*) 'Global ',rank,' local ',rankh, ' new ',N,' and ',M
      
      call MPI_COMM_FREE(HALF_COMM,  ierror)
      call MPI_GROUP_FREE(ALL_GROUP, ierror)
    
999   call MPI_Finalize(ierror)

      stop
      end 

