# --------------------------------------------------------------------
# function to calculate corr of WMM whose weights are corr skill
# --------------------------------------------------------------------




# INPUT ARGUMENT MUST BE THE OUTPUT OF S2DVERIFICATION'S ANO FUNCTION


corr_WMM_CorrWgts <- function(Anom) {
  
  
  # seasonal average of anomalies per model
  library(s2dverification)
  AvgExp <- MeanListDim(Anom$ano_exp, narm = T, c(2,4))
  AvgObs <- MeanListDim(Anom$ano_obs, narm = T, c(2,4))
  
  # rearrange
  Data <- aperm(abind::abind(AvgExp, AvgObs, along = 1), c(2,1,3,4)) # 21x5xlatxlon
  
  # predictions based on on CAWM
  source("YOUR_PATH/corr_as_wgts/corr_as_wgts_cv.R") 
  corrPred <- apply(Data, c(3,4), function(x) corr_as_wgts_cv(x[,1:4], x[,5])) # 21xlatxlon
  
  
  # weighted multi model correlation - Corr as weights         # 1x1x4xlatxlon
  corr_WMM_corrPred <- s2dverification::Corr(var_exp=InsertDim(corrPred, 1, 1), # 1x21xlatxlon
                                             var_obs=AvgObs,                        # 1x21xlatxlon
                                             posloop = 1, poscor = 2)
  
  
  return(list(corrPred, corr_WMM_corrPred))
  
}