Module Output
#ifdef useMPI
   use MPI
#endif
   implicit none
   integer, parameter :: Tag = 100
#ifdef useMPI
   integer :: status(MPI_Status_size)
#endif
!   Private

   contains
   subroutine writefield(UnitWrite, Field, counter, peOut, mpiTag)
   
     integer,           intent(in) :: UnitWrite
     real,              intent(in) :: Field(:)
     integer, optional, intent(in) :: counter
     integer, optional, intent(in) :: peOut
     integer, optional, intent(in) :: mpiTag


     real, allocatable :: buff(:)
     integer :: sizebuff
     integer :: i
     integer :: iPe
     integer :: oPe
     integer :: nPe
     integer :: iret
     integer :: mTag

      sizebuff = size(field)

      if(present(peOut))then
         oPe = peOut
      else
         oPe = 0
      endif

      if(present(counter))then
         nPe = counter
      else
         nPe = 1
         oPe = 0
      endif

      if(present(mpiTag))then
         mTag = mpiTag
      else
         mTag = Tag
      endif

      DO i = 1, nPe

         iPe = i - 1

         if (iPe .eq. oPe)then

            write(UnitWrite)Field

         else

#ifdef useMPI
            allocate(buff(sizebuff))
            call mpi_recv(buff, sizebuff, MPI_REAL, iPe, mTag, MPI_COMM_WORLD, status, iret)

            write(UnitWrite)buff

            deallocate(buff)
#else
            print*,'no MPI process! abort ...'
            stop    
#endif
         endif

      enddo

   end subroutine

   subroutine sendfield(Field, toPe, mpiTag)
      integer,           intent(in   ) :: toPe
      real,              intent(in   ) :: field(:)
      integer, optional, intent(in   ) :: mpiTag

      
      integer :: iret
      integer :: sizefield
      integer :: mTag

      if(present(mpiTag))then
         mTag = mpiTag
      else
         mTag = Tag
      endif

#ifdef useMPI
      sizefield = size(field)
      call mpi_send(field, sizefield, MPI_REAL, toPe, mTag, MPI_COMM_WORLD, iret)
      if (iret .ne. 0)then
         print*,'some think wrong, abort:',iret
         stop
      endif
#else
      print*,'only use sendfield for MPI program! abort ...'
      stop
#endif

   end subroutine
end Module Output
