ARCHmX_anova_test_univariate <- function(X, Y, k_n)   # include the edges
{
  # VCA: X is the covariate we are testing, contains the x_t
  # VCA: Y is the vector of residuals v_t corresponding to each x_{t-1}
  n = length(X)
  xi = Y
  # VCA: the residuals v_t must be ordered in terms of increasing x_{t-1} per Paper_EJS pg. 4
  # 10/21 - when called from choosek, the random permutation of v_t means that the
  # order is still randomized even after this sort.
  xi = Y
  xi[!is.finite(xi)] = 0 # added this 4/2 - [AI]
  xi = xi[order(X)]
  
  # VCA: Each k_n-long window is a row in matrix V
  V = matrix(0, n-k_n+1, k_n)
  for(ind in ((k_n+1)/2):(n-(k_n+1)/2+1))                # AZZ: I am excluding the edges
    V[ind-(k_n+1)/2+1,] = xi[(ind-(k_n+1)/2+1):(ind+(k_n+1)/2-1)]
  
  nv = dim(V)[1] # VCA: This is the number of rows / windows
  t_mean = mean(V) # VCA: This is the overall mean v..
  # 10/19 checked this matches the definition under (2.6) on Paper_EJS pg 5
  
  MST = sum((rowMeans(V) - t_mean)^2)*k_n/(nv-1)
  MSE = sum((V - rowMeans(V))^2)/(nv*k_n - nv)
  
  #   tau = sum((xi[2:(n-2)] - xi[1:(n-3)])^2*(xi[4:n] - xi[3:(n-1)])^2)/(4*(n-3))
  tau = sum((xi[2:n] - xi[1:(n-1)])^2)/(2*(n-1))
  # added is.na(tau) check - [AI]
  if (is.na(tau) || tau == 0) ### when the estimate interpolates, tau = 0, and an error would occur, so we set it > 0
    tau = 0.0000000000001
  
  
  #   p_value = (1-pnorm((sqrt(nv)*(MST-MSE))/(sqrt(2*k_n*(2*k_n-1)*tau/(3*(k_n-1))))))
  p_value = (1-pnorm((sqrt(nv/k_n)*(MST-MSE))/(sqrt(4*tau^2/3))))
  
  return(p_value)
}