model {
  for(i in 1:N) {
    #measurement model
    for(j in 1:P) {
      y[i,j]~dnorm(mu[i,j],errorprec[j])
    }
    mu[i,1]<-a[1] + xi[i,1]
    mu[i,2]<-a[2] + lam[1]*xi[i,1]
    mu[i,3]<-a[3] + lam[2]*xi[i,1]
    mu[i,4]<-a[4] + xi[i,2]
    mu[i,5]<-a[5] + lam[3]*xi[i,2]
    mu[i,6]<-a[6] + lam[4]*xi[i,2]
    mu[i,7]<-a[7] + eta[i]
    mu[i,8]<-a[8] + lam[5]*eta[i]
    mu[i,9]<-a[9] + lam[6]*eta[i]
    #structural model
    xi[i,1:2]~dmnorm(u[1:2],latprec[1:2,1:2])
    nu[i] <- gamma[1]*xi[i,1] + gamma[2]*xi[i,2]
    eta[i] ~ dnorm(nu[i], preceta) 
  } #end of i
  for(j in 1:6) {  
    # uninformative priors on loadings
    lam[j]~dnorm(0,0.0001)
  }
  for(j in 1:P) {  
    # uninformative priors on intercepts
    a[j]~dnorm(0,0.0001)
    # uninformative priors on errors
    errorprec[j] ~ dgamma(1, 1)
    errorvar[j]<-1/errorprec[j]
  }
  #priors on latent errors
  preceta ~ dgamma(1, 1)
  vareta <- 1/preceta
  #priors on latent (co-)variances
  latprec[1:2,1:2] ~ dwish(V[,], 4)
  latcov[1:2,1:2] <- inverse(latprec[,])
  latcor <- latcov[1,2]/(sqrt(latcov[1,1])*sqrt(latcov[2,2]))
  V[1,1] <- 1
  V[1,2] <- 0
  V[2,1] <- 0
  V[2,2] <- 1
  u[1] <- 0
  u[2] <- 0
  #priors on structural coefficients
  gamma[1] ~ dnorm(0, 0.0001)
  gamma[2] ~ dnorm(0, 0.0001)
} #end of model

