module gsl_int
  use, intrinsic :: iso_c_binding
! Value taken from /usr/include/gsl/gsl_integration.h
  integer, parameter :: GSL_INTEG_GAUSS15 = 1

  type, bind(c) :: gsl_function
     type (c_funptr) :: func
     type (c_ptr) :: params
  end type gsl_function

  interface
     function gsl_integration_workspace_alloc(wlen) bind(c)
       use, intrinsic :: iso_c_binding
       integer(c_size_t),value :: wlen
       type(c_ptr) :: gsl_integration_workspace_alloc
     end function gsl_integration_workspace_alloc
  end interface
  interface
     subroutine gsl_integration_workspace_free(work) bind(c)
       use, intrinsic :: iso_c_binding
       type(c_ptr),value :: work
     end subroutine gsl_integration_workspace_free
  end interface

  interface
     function gsl_integration_qag(F,xmin,xmax,epsabs,epsrel,limit, &
       key,work,out,abserr) bind(c)
       use, intrinsic :: iso_c_binding
       import :: gsl_function
       real(c_double), value :: xmin,xmax,epsabs,epsrel
       real(c_double) :: out,abserr
       integer(c_size_t), value :: limit
       integer(c_int),value :: key
       integer(c_int) :: gsl_integration_qag
       type(c_ptr),value :: work
       type(gsl_function) :: F
     end function gsl_integration_qag
  end interface
end module gsl_int
  
module integrand
  use, intrinsic :: iso_c_binding
  contains
    real(c_double) function g(x,v) bind(c)
      real (c_double), value :: x
      type (c_ptr),value :: v
      g=exp(-x*x)
    end function g
end module integrand

program int
  use, intrinsic :: iso_c_binding
  use gsl_int
  use integrand
  real (c_double) :: integral,err,xmin,xmax,tol
  integer(c_int) :: itmp
  type (c_ptr) :: work
  type (gsl_function) :: F

  work=gsl_integration_workspace_alloc(100000_c_size_t)
  F%func=c_funloc(g)
  F%params=c_null_ptr
  xmin=0
  xmax=10
  tol=1e-4

  itmp=gsl_integration_qag(F,xmin,xmax,0.0_c_double,tol,100000_c_size_t, &
       GSL_INTEG_GAUSS15,work,integral,err)

  write(*,*)"Integral is ",integral
  call gsl_integration_workspace_free(work);
end program int
