#VAR(4) (Congdon (2003))
model{ 
# priors on coeffiicients for intercepts and cross-lags
# m=no of jointly dep vars, 
# p= lag in jointly dependent vars, 
# q=no of exogenous predictors
for (k in 1:m){
c[k] ~ dnorm(0,0.001)}

# prior on own first lag
for (j in 1:p){
rho[2,2,j] ~ dnorm(0,1)
rho[1,1,j] ~ dnorm(0,1)}

# cross variable lags
for (j in 1:p){
rho[1,2,j] ~ dnorm(0,1)
rho[2,1,j] ~ dnorm(0,1)}

for (k in 1:m){ beta[k,1] <- 0
for (j in 2:q){ beta[k,j] ~ dnorm(0,0.01)}}

# define dependent vars + exogenous predictors
for ( i in 2:N) {
y[i,1] <- UNEMP[i+56]-UNEMP[i+55]
y[i,2] <- INDPROD[i+56]-INDPROD[i+55]

# seasonal dummies
x[i,1] <- S1[i+56] 
x[i,2] <- S2[i+56] 
x[i,3] <- S3[i+56]
x[i,4] <- S4[i+56]}

# prior scale matrix
T[1:m,1:m] ~ dwish(P[1:m,1:m],m);
for (k in 1:m){ 
P[k,k] <- 0.1
for(l in (k+1):m) {
P[k,l] <- 0.005
P[l,k] <- 0.005}}

# seasonal effects
for (t in p+1:N) {
for (k in 1:m)   { 
for (j in 1:q)   {
Exo[t,k,j] <- beta[k,j]*x[t,j]}}}

# effect of lagged endogenous variables 
for (t in p+2:n+p){
for (k1 in 1:m){ 
for (k2 in 1:m){
for (j in 1:p){ 
Endo[t,k1,k2,j] <- rho[k1,k2,j]*y[t-j,k2]}}}}

# conditional model for VAR(p) up to t=n; observed data likelihood
for (t in p+2:n)  { 
for (k in 1:m){   
mu[t,k] <- c[k]+sum(Endo[t,k,1:m,1:p]) + sum(Exo[t,k,1:q])
resid[t,k] <- y[t,k] - mu[t,k];    
L1[k,t] <- inprod(T[k,], resid[t,]) } 
sumsq[t] <-  inprod(resid[t,], L1[,t]) 
G[t] <- 1/exp(L[t])
L[t] <-  -log(6.28) -0.5*logdet(V[,]) - 0.5*sumsq[t]
y[t,1:m] ~ dmnorm(mu[t,1:m], T[1:m,1:m])
y.new[t,1:m] ~ dmnorm(mu[t,1:m], T[1:m,1:m])
e.lc[t,1] <- pow(y[t,1]-y.new[t,1],2)
e.lc[t,2] <- pow(y[t,2]-y.new[t,2],2)} 

# Forecasts between t=n+1 and t=N
# sum Endo over lags on own and other dependent variables
for (t in n+1:N){
for (k in 1:m)  { 
mu.new[t,k] <- c[k] +  sum(Endo[t,k,1:m,1:p]) + sum(Exo[t,k,1:q])}
y.new[t,1:m] ~ dmnorm(mu.new[t,1:m], T[1:m,1:m])} 

# white noise covariance matrix
for (i in 1:m) {for (j in 1:m) {   
V[i,j] <- inverse(T[,],i,j); 
R[i,j] <- V[i,j]/sqrt(V[i,i]*V[j,j])}}

# predictive loss
E[1] <- sum(e.lc[p+2:n,1])
E[2] <- sum(e.lc[p+2:n,2]) }

