#Example 7.6
### Data ### 
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)

theta = c(0.5,0.5) ## parameters for the prior fixed

M = 100000                         # length of chain 
alpha.sim = matrix(nrow=M,ncol=I)  # result vector
N.sim = rep(NA,N)                  # result vector


## Gibbs-sampler loop ##
alpha.sim[1,]=rep(0.5,I)            # initialize alpha
p = 1-prod(1-alpha.sim[1,])         # compute p from alpha, this is the quantity that defines the distribution of N given alpha
N.sim[1] = r + rnbinom(1,r+1,p)     # sample N (given alpha and data) 

for(j in 2:M)
{
   alpha.sim[j,] = rbeta(I,n.c+theta[1],N.sim[j-1]-n.c+theta[2]) # sample alpha given N and data
   p = 1-prod(1-alpha.sim[j,])                                   # compute p from alpha 
   N.sim[j] = r + rnbinom(1,r+1,p)                               # sample N (given alpha and data) 
}


## plot results ## 

#Discarding first 10000 simulations
#N.sim = N.sim[-c(1:10000)]
#alpha.sim = alpha.sim[-c(1:10000),]

alpha.bar = rowMeans(alpha.sim)
par(mfrow=c(1,2))
hist(N.sim)
boxplot(alpha.bar~N.sim)
#plot(N.sim,alpha.bar)
