model{

# WinBUGS model for catch-curve analysis
# Case 4 for the Dirichlet distribution

# Data (in a separate file):
# k, B, b0, m, b[1:m] -- the control vector
# (A is not used directly, although ai[g]=A)
# g -- number of age groups
# ai[1:g] -- cut points (as in equation 5, with ai[g]=A)
# y[1:g] -- grouped proportions (observed)

# Parmaters:
# Z, alpha, betak, tau, rho[1..m], n

# *************************************************

# Priors for the parameters (Table 7)
Z ~ dunif(0,10)
betak ~ dunif(0,1)
alpha ~ dunif(2,25)
for (i in 1:m) {rho[i] ~ dunif(0,20)}
tau ~ dunif(0,5)
n ~ dunif(10,1000)

# *************************************************

# Model proportions by age (Table 2)
# Includes intermediate quantities S[k:B], R[k:B], beta[k:B] 
# Gives pa[k:B] and ppi[1:g]
# (name ppi avoids potential conflict with pi=3.14159)

# Calculation for k:B
# R[k:B] and S[k:B]
for (a in k:B) { for (h in 1:m) {
  Rah[a,h] <- rho[h] * exp(-(a - b[h])*(a-b[h])/(2*tau*tau)) } }
for (a in k:B) {
  S[a] <- exp(-Z*(a-k))
  R[a] <- 1 + sum(Rah[a,1:m]) }
# beta[k:B]
for (a in k:(b0-1)) { 
  beta[a] <- 1 - (1 - betak)*pow((b0 - a)/(b0 - k),alpha) }
for (a in b0:B) { beta[a] <- 1 }
# pa[k:B]
for (a in k:B) { xa[a] <- S[a]*beta[a]*R[a] }
xsum <- sum(xa[k:B])
for (a in k:B) { pa[a] <- xa[a]/xsum }

# Grouped proportions (equation 7)
ppi[1] <- sum(pa[k:ai[1]])
for (i in 2:(g-1)) {
  ppi[i] <- sum(pa[(ai[i-1]+1):ai[i]])}
ppi[g] <- sum(pa[(ai[g-1]+1):B])

# *************************************************

# Dirichlet distribution
for (i in 1:g) {alp[i] <- n * ppi[i]}  # standard Dirichlet alphas
y[1:g] ~ ddirch(alp[1:g])

}
