update_U <- function(Z,fixed_effects,ni_vector,group_info,
                     global_error_variance,
                     random_effects_variance) {
  Zstar <- Z - fixed_effects
  sum_Zstar_ij <- as.numeric(tapply(Zstar, group_info, sum))
  loc <- (random_effects_variance) * sum_Zstar_ij / (ni_vector * random_effects_variance + global_error_variance)
  variance <- (global_error_variance * random_effects_variance) / (ni_vector*random_effects_variance + global_error_variance)
  N <- length(ni_vector)
  output <- rnorm(n = N) * sqrt(variance) + loc
  return(output)
}

update_global_error_variance <- function(Z,fixed_effects,random_effects) {
  # prior is Gamma(1,1) - shape, rate
  lambda <- 1.0 - 0.5*length(Z) #p
  psi <- 1.0*2 #a


  residuals_value <- Z - fixed_effects - random_effects
  SSR <- sum(residuals_value^2)
  chi <- SSR #b

  output <- rgig(n = 1, lambda = lambda, chi = chi, psi = psi)
  return(output)
}

update_random_effects_variance <- function(U_value, ni_vector) {
  # prior is Gamma(1,1) - shape, rate
  lambda <- 1.0 - 0.5*length(ni_vector) #p
  psi <- 1.0*2 #a
  chi <- sum(U_value^2) #b

  output <- rgig(n = 1, lambda = lambda, chi = chi, psi = psi)
  return(output)
}
