AnimVsLTime <- function(var, lat, lon, toptitle = c('', '', '', '', '', '', '', 
                                                    '', '', '', ''), 
                        units = '', monini = 1, freq = 12, msk95lev = FALSE, 
                        brk = NULL, col = NULL, lonmin = 0, lonmax = 360, 
                        latmin = -90, latmax = 90, center = NULL, equi = TRUE, 
                        fileout = c('output1_animvsltime', 
                                    'output2_animvsltime', 
                                    'output3_animvsltime')) {
  # Create animations showing the anomalies, the climatologies, the mean 
  # InterQuartile Range, Maximum-Mininum, Standard Deviation, Median Absolute 
  # Deviation, the trends, the RMSE or correlation between modelled and 
  # observed data along the forecast time for all input 
  # experiments or input observational datasets.
  # 
  # One plot for each experiment for IQR/Max-Min/SD/MAD/clim/trends.
  # One plot for each experiment/obervational dataset combination for 
  # correlations & RMSE.
  #
  # Args:
  #   var: Matrix of dimensions (nltime, nlat, nlon)
  #                          or (nexp/nmod, nltime, nlat, nlon)
  #                          or (nexp/nmod, 3, nltime, nlat, nlon)
  #                          or (nexp/nmod, nobs, 3, nltime, nlat, nlon)
  #   lat: Vector containing latitudes (°)
  #   lon: Vector containing longtitudes (°)
  #   toptitle: c('','') array of main title for each animation, optional.
  #             If RMS or correlations: first exp with successive obs, then 
  #             second exp with successive obs, etc ...
  #   units: Units, optional
  #   monini: Starting month between 1 and 12. Default = 1
  #   freq: 1 = yearly, 12 = monthly, 4 = seasonal ...
  #   msk95lev: T/F grid points masked if 95% significance level not reached. 
  #             Default = F
  #   brk: Limits of colour levels, optional. For example:
  #        seq(min(var),max(var),(max(var)-min(var))/10)
  #   col: Vector of colours of length(brk)-1, optional.
  #   lonmin: Westward limit of the domain to plot (>0 or <0).
  #           Default : 0°
  #   lonmax: Eastward limit of the domain to plot (>0 or <0).
  #           lonmax > lonmin. Default : 360°
  #   latmin: Southward limit of the domain to plot. Default : -90°
  #   latmax: Northward limit of the domain to plot. Default : 90°
  #   center: (latitude, longitude, angle) for stereographic projection
  #   equi: TRUE/FALSE == cylindrical equidistant/stereographic projection. 
  #         Default : TRUE
  #   fileout: c('','') array of output file name for each animation without 
  #            extension. If RMS or correlations : first exp with successive 
  #            obs, then second exp with successive obs, etc ...
  #
  # Returns:
  #   This function returns nothing under R but produces gif animations
  #   that can be visualized on a html page or in a ppt.
  #
  # History:
  #   1.0  #  2012-04  (V. Guemas, vguemas@ic3.cat)  #  Original code
  #   1.1  #  2014     (N. Manubens, nicolau.manubens@ic3.cat) # Formatting to R CRAN
  #   1.2  #  2015-05  (V. Guemas, virginie.guemas@ic3.cat) Use of PlotEquiMap and PlotStereoMap
  #
  #  Get some arguments
  # ~~~~~~~~~~~~~~~~~~~~
  #
  if (length(dim(var)) == 3) {
    var <- InsertDim(var, posdim = 1, lendim = 1)
  }
  if (length(dim(var)) == 4) {
    var <- InsertDim(var, posdim = 2, lendim = 3)
  }
  if (length(dim(var)) == 5) {
    var <- InsertDim(var, posdim = 2, lendim = 1)
  }
  nleadtime <- dim(var)[4]
  nexp <- dim(var)[1]
  nobs <- dim(var)[2]
  nlat <- dim(var)[5]
  nlon <- dim(var)[6]
  colorbar <- colorRampPalette(c("dodgerblue4", "dodgerblue1",
            "forestgreen", "yellowgreen", "white", "white",
            "yellow", "orange", "red", "saddlebrown"))
  if (is.null(brk) == T) {
    ll <- signif(min(var[,,2,,,], na.rm = T),4)
    ul <- signif(max(var[,,2,,,], na.rm = T),4)
    if (is.null(col) == T) {
      col <- colorbar(10)
    }
    nlev <- length(col)
    brk <- signif(seq(ll, ul, (ul - ll) / nlev),4)
  } else {
    if (is.null(col) == T) {
      nlev <- length(brk) - 1
      col <- colorbar(nlev)
    } else {
      nlev <- length(col)
    }
  }
  lon[which(lon < lonmin)] <- lon[which(lon < lonmin)] + 360.
  lon[which(lon > lonmax)] <- lon[which(lon > lonmax)] - 360.
  latb <- sort(lat[which(lat >= latmin & lat <= latmax)], index.return = TRUE)
  lonb <- sort(lon[which(lon >= lonmin & lon <= lonmax)], index.return = TRUE)

  #
  #  Define some plot parameters
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  #
  labind <- 1:nleadtime
  months <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", 
              "Oct", "Nov", "Dec")
  years <- ((labind - 1) * 12 / freq + monini - 1) %/% 12
  suffixtit <- months[((labind - 1) * 12 / freq + monini - 1) %% 12 + 1]
  for (jx in 1:nleadtime) {
    y2o3dig <- paste("0", as.character(years[jx]), sep = "")
    suffixtit[jx] <- paste(suffixtit[jx], "-", substr(y2o3dig, 
                           nchar(y2o3dig) - 1, nchar(y2o3dig)), sep = "")
  }
  
  #
  #  Loop on experimental & observational data
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  #
  for (jexp in 1:nexp) {
    for (jobs in 1:nobs) {
      postscript(paste(fileout[(jexp - 1) * nobs + jobs], '.png', sep = ""),
                 width = 550, height = 300)
      for (jt in 1:nleadtime) { 
        title <- paste(toptitle[(jexp - 1) * nobs + jobs], " Time=", 
                       suffixtit[jt], sep = "")
        varbis <- var[jexp, jobs, 2, jt, which(lat >= latmin & lat <= latmax),
                      which(lon >= lonmin & lon <= lonmax)]
        varbis <- varbis[latb$ix, lonb$ix]
        if (msk95lev) {
          varbis[which(var[jexp, jobs, 1, jt, latb$ix, lonb$ix] < 0 
                       & var[jexp, jobs, 3, jt, latb$ix, lonb$ix] > 0)] <- NA 
          varbis[which(var[jexp, jobs, 1, jt, latb$ix, lonb$ix] > 0 
                       & var[jexp, jobs, 3, jt, latb$ix, lonb$ix] < 0)] <- NA
        }
        varbis[which(varbis <= min(brk))] <- min(brk) + (max(brk) - min(
                                             brk)) / 1000.0
        varbis[which(varbis >= max(brk))] <- max(brk) - (max(brk) - min(
                                             brk)) / 1000.0
        if (equi) {
          PlotEquiMap(varbis, lonb$x, latb$x, toptitle = title, units = units,
                      brks = brk, cols = col)
        }else{
          PlotStereoMap(varbis, lonb$x, latb$x, latlims = c(latmin, latmax),
                        toptitle = title, units = units, brks = brk, cols = col)
        }
      }
      dev.off()
      system(paste('convert -loop 10 -delay 50 ', 
                   fileout[(jexp - 1) * nobs + jobs], '.png ', 
                   fileout[(jexp - 1) * nobs + jobs], '.gif', sep = ""))
      system(paste('rm -f ', fileout[(jexp - 1) * nobs + jobs])) 
    }
  }
}
