integrate<-function(functn, lower,upper,minpts=100,maxpts=500,eps=0.01,...){
adapt(1,lower,upper,minpts,maxpts,functn,eps,...)
}

adapt <- function(ndim,lower,upper,minpts,maxpts,functn,eps,...)
{
# This function has way too many comments and checks. It is written so
# that someone other than me can use it as a template for future functions.

# fudge for 1-d functions 
   if (ndim==1) {
	ff<-function(x) functn(x[1],...)
	lower<-c(lower,0)
	upper<-c(upper,1)
	ndim<-2
	}
   else
	ff<-function(x) functn(x,...)

# Check to make sure that upper and lower are reasonable lengths
# Both the upper and lower limits should be at least of length ndim
#
  if( length(lower) < ndim || length(upper) < ndim) {
     cat("The lower and upper vectors need to have at least ndim elements\n")
     cat("Your parameters are,  ndim ",ndim, " length(lower) ",length(lower),
         "length(upper) ",length(upper), "\n")
     return()
     }
# rulcls and lenwrk are mandated in the adapt source
#
  rulcls <-  2**ndim+2*ndim**2+6*ndim+1
  lenwrk <- (2*ndim+3)*(1+maxpts/rulcls)/2

  if( minpts > maxpts ){
	cat("maxpts must be > minpts. Maxpts has be increased to\n")
	cat("minpts + 1\n")
	maxpts <- minpts + 1
	}
# maxpts should be large enough.  Prefer 10*rulclc, but use 2*rulclc.
#
  if ( maxpts < 2*rulcls) {
	cat("You have maxpts (= ", maxpts, " too small\n")
	cat("It needs to be at least 2 times 2**ndim+2*ndim**2+6*ndim+1\n")
	cat("It has been reset to ", 2*rulcls,"\n")
	maxpts <- 2*rulcls
	}
  relerr <- finest <- 0.0
  ifail <- 0
  storage.mode(ifail) <- "integer"
#/* TSL changed list(functn) to functn in next line, then to ff */
  answ _ .C("cadapt", as.integer(ndim), lower, upper,
            minpts=as.integer(minpts), as.integer(maxpts),ff,
            eps,relerr = relerr, as.integer(lenwrk),
	    finest = finest,ifail=ifail)
			  # Finest is the value of the function.
  switch( answ$ifail,
          cat("Ifail is 1, maxpts was too small. Check the returned relerr\n"),
          cat("Ifail is 2, lenwrk was too small. Check the returned relerr\n"),
          cat("Ifail is 3, This should not happen\n")
	 )
   result <- list(finest=answ$finest,relerr=answ$relerr,minpts=answ$minpts,
		 ifail=answ$ifail)
	result
  }
