
RegimesAssign <- function(var_ano, ref_maps, lats, method = 'distance') {
  posdim <- which(names(dim(ref_maps)) == 'nclust')
  poslat <- which(names(dim(ref_maps)) == 'lat')
  poslon <- which(names(dim(ref_maps)) == 'lon')
  poslat_ano <- which(names(dim(var_ano)) == 'lat')
  poslon_ano <- which(names(dim(var_ano)) == 'lon')
  
  nclust <- dim(ref_maps)[posdim]
  nlat <- dim(ref_maps)[poslat]
  nlon <- dim(ref_maps)[poslon]
  
  
  if (is.null(names(dim(ref_maps))) | is.null(names(dim(var_ano)))) {
    stop(
      'The arrays should include dimensions names ref[nclust,lat,lon]
      and target [lat,lon]'
    )
  }
  
  if (length(lats) != dim(ref_maps)[poslat]) {
    stop('latitudes do not match with the maps')
  }
  
  assign <-
    Apply(
      data = list(target = var_ano),
      margins = c((1:length(dim(
        var_ano
      )))[-c(poslat_ano, poslon_ano)]) ,
      AtomicFun = '.anom2regime',
      ref = ref_maps,
      lat = lats,
      method = method
    )
  
  anom_array <-
    array(var_ano, dim = c(prod(dim(var_ano)[-c(poslat_ano, poslon_ano)]), nlat, nlon))
  rm(var_ano)
  index <- as.vector(assign$output1)
  recon <- Composite(var = aperm(anom_array, c(3, 2, 1)), occ = index)
  freqs <- rep(NA, nclust)
  for (n in 1:nclust) {
    freqs[n] <- (length(which(index == n)) / length(index)) * 100
  }
  output <-
    list(
      composite = recon$composite,
      pvalue = recon$pvalue,
      cluster = assign$output1,
      frequency = freqs
    )
  return(output)
}

