      program example22b
      include 'mpif.h'
      integer ierr, rank, size, color, i, rank1
      integer newcomm, newintercomm
      call MPI_INIT(ierr)
      call MPI_COMM_SIZE(MPI_COMM_WORLD, size, ierr)
      call MPI_COMM_RANK(MPI_COMM_WORLD, rank, ierr)
      if(rank .eq. 0) color=1
      else color=0
      call MPI_COMM_SPLIT(MPI_COMM_WORLD, color, rank, newcomm,
     &                    ierr)
      call MPI_INTERCOMM_CREATE(newcomm, 0, MPI_COMM_WORLD,
     &                          color, 1, newintercomm, ierr)
      if(rank .eq. 0) then
         call master(newintercomm)
      else
         call slave(newcomm, newintercomm)
      end if
      call MPI_COMM_FREE(newintercomm, ierr)
      call MPI_COMM_FREE(newcomm, ierr)
      call MPI_FINALIZE(ierr)
      end
      subroutine master(comm)
      include 'mpif.h'
      integer comm
      integer size, i, r, ierr
      integer status(MPI_STATUS_SIZE)
      call MPI_COMM_REMOTE_SIZE(comm, size, ierr)
      do i = 1, size
         call MPI_SEND(i-1, 1, MPI_INTEGER, i-1, 5, comm, ierr)
      end do
      call MPI_RECV(r, 1, MPI_INTEGER, 0, 6, comm, status, ierr)
      print *, 'sum = ', r
      end
      subroutine slave(comm, intercomm)
      include 'mpif.h'
      integer comm, intercomm
      integer s, r, rank, ierr
      integer status(MPI_STATUS_SIZE)
      call MPI_COMM_RANK(comm, rank, ierr)
      call MPI_RECV(s, 1, MPI_INTEGER, 0, 5, intercomm, status,
     &              ierr)
      call MPI_REDUCE(s, r, 1, MPI_INTEGER, MPI_SUM, 0, comm,
     &                ierr)
      if(rank .eq. 0) call MPI_Send(r, 1, MPI_INTEGER, 0, 6,
     &                              intercomm, ierr)
      end
