# Log-likelihood 
log.like <- function(y,Time,x,theta,eventA,eventD,pos){
  
  # 15-point Gauss-Legendre quadrature
  xk <- c(-0.98799251802048542849,-0.937273392400705904308,-0.8482065834104272162006,
          -0.7244177313601700474162,-0.5709721726085388475372,-0.3941513470775633698972,
          -0.2011940939974345223006,0,0.2011940939974345223006,0.3941513470775633698972,
          0.5709721726085388475372,0.7244177313601700474162,0.8482065834104272162006,
          0.9372733924007059043078,0.9879925180204854284896)
  
  wk <- c(0.0307532419961172683546,0.070366047488108124709,0.1071592204671719350119,
          0.1395706779261543144478,0.1662692058169939335532,0.1861610000155622110268,
          0.1984314853271115764561,0.2025782419255612728806,0.198431485327111576456,
          0.1861610000155622110268,0.166269205816993933553,0.139570677926154314448,
          0.10715922046717193501,0.07036604748810812471,0.030753241996117268355)  
  
  N <- length(Time)  
  Q <- 250
  library(randtoolbox)
  a <- sobol(Q, dim=2, scrambling=1, seed=sample(100000,1))
  joint.like <- rep(0,N)
  K <- 15
  hA <- rep(0,K); hD <- rep(0,K)
  
  for(i in 1:N){
    jm <- 0
    for(q in 1:Q){
      b0 <- exp(theta[5])*qnorm(a[q,1])
      b1 <- exp(theta[6])*qnorm(a[q,2])
      
      psi <- y[i,which(!is.na(pos[i,]))] - (theta[1]+b0 + (theta[2]+b1)*which(!is.na(pos[i,])) + theta[3]*x[i])
      
      for(j in 1:K){
        hA[j] <- exp(theta[13])*(Time[i]/2*(xk[j]+1))^(exp(theta[13])-1) *
          exp( theta[15] + theta[7]*x[i] + theta[9]*b0 + theta[11]*b1*(Time[i]/2*(xk[j]+1)) )
        
        hD[j] <- exp(theta[14])*(Time[i]/2*(xk[j]+1))^(exp(theta[14])-1) *
          exp( theta[16] + theta[8]*x[i] + theta[10]*b0 + theta[12]*b1*(Time[i]/2*(xk[j]+1)) )
      }
      
      jm <- jm + exp(theta[4])^(-Time[i])*exp(-(1/(2*exp(theta[4])^2))*sum(psi^2)) * (hA[K]^eventA[i])*(hD[K]^eventD[i])*exp(-Time[i]/2*( sum(wk*hA) + sum(wk*hD) ))
      
    }
    joint.like[i] <- jm/Q
  }
  return( sum(log(joint.like)) )
}


# Metropolis-Hastings kernel
MH.kernel <- function(y,Time,x,mu,sigma,eventA,eventD,pos,M,theta,patient.new.obs,fhat.new){
  
  Nsim <- 1
  n.particles <- dim(theta)[1]
  n.thetas <- length(sigma)
  
  for(t in 1:Nsim){
    rate.acept <- 0
    for(i in 1:n.particles){
      
      lpost.curr <- log.like(y[-patient.new.obs,],Time[-patient.new.obs],x[-patient.new.obs],theta[i,],eventA[-patient.new.obs],eventD[-patient.new.obs],pos[-patient.new.obs,]) + log(fhat.new[i])
      theta.new <- mu + rnorm(n.thetas,0,sigma)      # independent
      lpost.prop <- log.like(y,Time,x,theta.new,eventA,eventD,pos)
      
      if(log(runif(1)) < lpost.prop - lpost.curr){theta[i,] <- theta.new; rate.acept <- rate.acept+1}
    }
  }
  theta[,c(4:6,13:16)] <- exp(theta[,c(4:6,13:16)])
  return(list(theta=theta, rate=rate.acept/n.particles))
}