NAO <- function(ano_exp, ano_obs, lon, lat, fcavt = 2:4, fcsys = 1, 
                obsproj = TRUE) {
  nlon <- length(lon)
  nlat <- length(lat)
  ny <- dim(ano_exp)[5]
  nx <- dim(ano_exp)[6]
  nyr <- dim(ano_exp)[3]
  nfc <- dim(ano_exp)[2]
  lt <- dim(ano_exp)[4]
  # Security check nlon==nx & nlat==ny
  if (ny != nlat) {
    stop("Inconsistent number of latitudes and input field dimensions")
  }
  if (nx != nlon) {
    stop("Inconsistent number of longitudes and input field dimensions")
  }
  ## Target period mean
  ano_exp <- ano_exp[fcsys, , , fcavt, , ]
  dim(ano_exp) <- c(1, nfc, nyr, dim(array(fcavt)), nlat, nlon)
  ano_obs <- ano_obs[1, 1, , fcavt, , ]
  dim(ano_obs) <- c(1, 1, nyr, dim(array(fcavt)), nlat, nlon)
  gc()
  o1 <- Mean1Dim(ano_obs, posdim = 4, narm = TRUE)
  dim(o1) <- c(1, 1, nyr, 1, nlat, nlon)
  f1 <- Mean1Dim(ano_exp, posdim = 4, narm = TRUE)
  dim(f1) <- c(1, nfc, nyr, 1, nlat, nlon)
  ## Cross-validated PCs. Fabian. This should be extended to
  ## nmod and nlt by simple loops. Virginie
  NAOF.ver <- array(NA, c(1, nfc, nyr))
  NAOO.ver <- array(NA, c(1, 1, nyr))
  for (iy in 1:nyr) {
    ## Observed EOF excluding one forecast start year.
    OEOF <- EOF(o1[1, 1, -iy, 1, , ], lon, lat, neofs = 1)
    ## Correct polarity of pattern.
    sign <- 1
    if (0 < mean(OEOF$EOFs[1, round(nlat/3), ], na.rm = T)) {
      sign <- -1
    }
    OEOF$EOFs <- OEOF$EOFs * sign
    OEOF$PCs <- OEOF$PCs * sign
    if (!obsproj) {
      f2 <- f1[1, , -iy, 1, , ]
      dim(f2) <- c(nfc * (nyr - 1), nlat, nlon)
      FEOF <- EOF(f2, lon, lat, neofs = 1)
      ## Correct polarity of pattern.
      sign <- 1
      if (0 < mean(FEOF$EOFs[1, round(nlat/3), ], na.rm = T)) {
        sign <- -1
      }
      FEOF$EOFs <- FEOF$EOFs * sign
      FEOF$PCs <- FEOF$PCs * sign
      ### Lines below could be simplified further by computing
      ### ProjectField() only on the year of interest... (though this is
      ### not vital). Lauriane
      PCF <- ProjectField(f1, FEOF, mode = 1)
      for (ifc in 1:nfc) {
        NAOF.ver[1, ifc, iy] <- PCF$PC.ver[1, ifc, iy, 
          1]
      }
    } else {
      ## Project forecast anomalies on obs EOF
      PCF <- ProjectField(f1, OEOF, mode = 1)
      NAOF.ver[1, , iy] <- PCF$PC.ver[1, , iy, 1]
    }
    ## Project observed anomalies.
    PCO <- ProjectField(o1, OEOF, mode = 1)
    ## Keep PCs of excluded forecast start year. Fabian.
    NAOO.ver[1, 1, iy] <- PCO$PC.ver[1, 1, iy, 1]
  }
  return(list(NAO_exp = NAOF.ver, NAO_obs = NAOO.ver, EOFs_obs = OEOF))
}
