
model{
# 3 CP Regression model

  ###Data Loop
    for(j in 1:n_obs)
  {
  y[j] ~ dnorm(mu_y[j],tau[j])
  t[j] ~ dnorm(mu_t[j],t_err[j]^-2)

  A[j] <- step(mu_t[j]-cp[1])
  B[j] <- step(mu_t[j]-cp[2])
  C[j] <- 1+step(mu_t[j]-cp[3])

  mu_y[j] <- alpha[B[j] + C[j]] + beta[A[j] + B[j] + C[j]]*(mu_t[j]-cp[B[j] + C[j]])
  mu_t[j] ~ dnorm(0,0.5^-2)

  tau[j] <- (y_err[j]^2 + sigma_y^2)^-1
  }

  ##Priors
  alpha[1] ~ dnorm(0.0,0.01)
  alpha[2] ~ dnorm(0.0,0.01)
  alpha[3] ~ dnorm(0.0,0.01)

  beta[1]~dnorm(0.0,0.01)
  beta[2] <- (alpha[2] - alpha[1])/(cp[2]-cp[1])
  beta[3] <- (alpha[3] - alpha[2])/(cp[3]-cp[2])
  beta[4]~dnorm(0.0,0.01)

  sigma_y ~ dt(0,4^-2,1)T(0,)

  cp.temp[1] ~ dunif(t_min,t_max)
  cp.temp[2] ~ dunif(t_min,t_max)
  cp.temp[3] ~ dunif(t_min,t_max)

  cp[1:3]<-sort(cp.temp)

    for(i in 1:n_pred){
      Astar[i] <- step(t_pred[i]-cp[1])
      Bstar[i] <- step(t_pred[i]-cp[2])
      Cstar[i] <- 1+step(t_pred[i]-cp[3])
      mu_pred[i] <- alpha[Bstar[i] + Cstar[i]] + beta[Astar[i] + Bstar[i] + Cstar[i]]*(t_pred[i]-cp[Bstar[i] + Cstar[i]])
    }


  }
