#Example 7.7
n.c = c(30,22,29,26,31,32,35)
n.m = c(30,8,17,7,9,8,5)
r = sum(n.m)
I = length(n.c)
N = 500000
alpha.sim = matrix(nrow=N,ncol=I)
N.sim = rep(NA,N)
theta.sim = matrix(nrow=N,ncol=2)

alpha.sim[1,]=rep(0.5,I)
theta.sim[1,]=rexp(2,1/1000)
p = 1-prod(1-alpha.sim[1,])
N.sim[1] = r + rnbinom(1,r+1,p)

for(j in 2:N)
{
   alpha.sim[j,] = rbeta(I,n.c+theta.sim[j-1,1],N.sim[j-1]-n.c+theta.sim[j-1,2])
   p = 1-prod(1-alpha.sim[j,])
   N.sim[j] = r + rnbinom(1,r+1,p)
   theta.prop = rexp(2,1/1000)
   l.prop = I*(lgamma(sum(theta.prop))-sum(lgamma(theta.prop)))+
      sum(theta.prop[1]*log(alpha.sim[j,])+theta.prop[2]*log(1-alpha.sim[j,]))-
            sum(theta.prop)/1000
   l = I*(lgamma(sum(theta.sim[j-1,]))-sum(lgamma(theta.sim[j-1,])))+
                    sum(theta.sim[j-1,1]*log(alpha.sim[j,])+
                        theta.sim[j-1,2]*log(1-alpha.sim[j,]))-
                    sum(theta.sim[j-1,])/1000
   R = exp(l.prop-l)*prod(dexp(theta.sim[j-1,],1/1000))/prod(dexp(theta.prop,1/1000))
   if(runif(1)<R)
     theta.sim[j,] = theta.prop
   else
     theta.sim[j,] = theta.sim[j-1,]
#   show(c(j,N.sim[j],theta.sim[j,],alpha.sim[j,]))
}

#Discasrding first 10000 simulations
N.sim = N.sim[-c(1:10000)]
alpha.sim = alpha.sim[-c(1:10000),]
theta.sim = theta.sim[-c(1:10000),]
alpha.bar = rowMeans(alpha.sim)
par(mfrow=c(2,2))
hist(N.sim)
boxplot(alpha.bar~N.sim)
plot(density(theta.sim[,1]))
plot(density(theta.sim[,2]))
