      program main
      include "mpif.h"
      double precision  mypi, sumpi
      double precision  h, sum, x, f, a
      double precision  pi
      parameter (pi=3.14159265358979323846)
      integer n, rank, procs, i, ierr
      character*16 argv
      integer argc
      f(a) = 4.d0 / (1.d0 + a*a)

      argc = COMMAND_ARGUMENT_COUNT() 
      n=0
      if (argc .ge. 1) then
	call getarg(1, argv)
        read(argv,*) n
      endif

      call MPI_INIT(ierr)
c     COMM
      call MPI_COMM_RANK(MPI_COMM_WORLD,
     &                   rank, ierr)
      call MPI_COMM_SIZE(MPI_COMM_WORLD,
     &                   procs, ierr)

      call MPI_BCAST(n,1,MPI_INTEGER,0,
     &               MPI_COMM_WORLD,ierr)
      if ( n .le. 0 ) goto 30
      h = 1.0d0/n
      sum  = 0.0d0
      do 20 i = rank+1, n, procs
         x = h * (dble(i) - 0.5d0)
         sum = sum + f(x)
 20   continue
      mypi = h * sum

      call MPI_REDUCE(mypi,sumpi,1,
     &                MPI_DOUBLE_PRECISION,
     &                MPI_SUM,0, 
     &                MPI_COMM_WORLD,ierr)

      if (rank .eq. 0) then
         print *, 'pi = ', sumpi
      endif
 30   call MPI_FINALIZE(ierr)
      stop
      end
