!*****************************************************************************
!
!    Subroutine: MCIntegrate
!
!    Purpose: Calculates an integral using a monte-carlo routine.
!
!    Author: Ben Malin
!
!    Date: 6/04
!    Revised: 6/07
!
!*****************************************************************************

subroutine MCIntegrate(nc, IntResult)

  ! inputs:
  !   nc -- Index of country.
  !
  ! output:
  !   IntResult -- The value of the integral. 
  !
  ! remarks:
  !   The subroutines constructs the integral on the RHS of the Euler Equation
  !   for country nc.
  !
  
  use Params
  
  implicit none

  !Variable Declaration
  integer,intent(in) :: nc
  real(prec),intent(out) :: IntResult 
  
  integer :: i
  integer,parameter :: MCcount = 10000
  integer,parameter :: num = (N+1) * MCcount		
  real(prec),dimension(num) :: nr
  real(prec),dimension(N+1) :: techshock
  real(prec) :: Integrand
  
  !Returns Integrand on RHS of Euler Equation at specified points
  real(prec), external :: ExpectFOC_MCsimul
  
  !Draw a bunch of random numbers
  call rnset(1)
  call DRNNOA(num,nr)	!IMSL random number generator (normal distribution)
  
  !Initialize Integral
  IntResult = 0.0

  !Compute Integral
  do i = 1, MCcount
     techshock = nr((i-1)*(N+1) + 1 : i*(N+1))
     
     !Calculate values of integrand at MCcount # of points
     Integrand = ExpectFOC_MCsimul(N, techshock, nc)
     
     !Weight and Sum values of integrand 
     IntResult = IntResult + Integrand
  end do
  
  IntResult = IntResult/MCcount
  
end subroutine MCIntegrate
