library(startR)

  repos <- "/esarchive/exp/ecmwf/system5_m1/monthly_mean/$var$_f6h/$var$_$sdate$.nc"
  var <- 'tas'
  sdate <- c('20170101', '20170201')
  lon.min <- 0
  lon.max <- 359.9
  lat.min <- -90
  lat.max <- 90

  data <- Start(dat = repos,
                var = var,
                sdate = sdate,
                ensemble = indices(1:50),  
                time = 'all',
                latitude = values(list(lat.min, lat.max)),
                latitude_reorder = Sort(),
                longitude = values(list(lon.min, lon.max)),
                longitude_reorder = CircularSort(0, 360),
                synonims = list(latitude = c('lat', 'latitude'),
                                longitude = c('lon', 'longitude')),
                return_vars = list(time = 'sdate', 
                                   longitude = NULL, latitude = NULL),
                retrieve = FALSE
               )
  
  func <- function(x, ens_dim, conf, pval) {
    # ensemble mean
    ens_mean <- apply(x, which(names(dim(x)) != ens_dim), mean)
    # temporal trend
    trend <- s2dv:::.Trend(ens_mean, conf = conf, pval = pval)$trend

    return(trend)
  }
  step <- Step(func, target_dims = c('ensemble', 'time'),
               output_dims = list(trend = 'stats'),
               use_libraries = c('s2dv'))
  wf <- AddStep(data, step, ens_dim = 1, conf = FALSE, pval = FALSE)

#-------------------user-defined---------------------
  queue_host <- 'nord1'
  temp_dir <- '/gpfs/scratch/bsc32/bsc32734/startR_hpc/'
  ecflow_suite_dir <- '/home/Earth/aho/startR_local/'
#----------------------------------------------------

  res <- Compute(wf,
                 chunks = list(latitude = 2,
                               longitude = 3),
                 threads_load = 2,
                 threads_compute = 4,
                 cluster = list(queue_host = queue_host,
                                queue_type = 'lsf',
                                temp_dir = temp_dir,
                                cores_per_job = 2,
                                job_wallclock = '05:00',
                                max_jobs = 4,
                                extra_queue_params = list('#BSUB -q bsc_es'),
                                bidirectional = FALSE,
                                polling_period = 10
                 ),
                 ecflow_suite_dir = ecflow_suite_dir,
                 wait = FALSE
                 )  #$output1

# Save the header of res
saveRDS(res, file = '~/nord3_demo_header.Rds')

# You can leave now. When you come back next time, just read the .Rds file
res_collect <- readRDS(save_file)
result <- Collect(res_collect, wait = TRUE)
# Save the result if needed
saveRDS(result, file = '~/nord3_demo_result.Rds')

# Check the result
str(result)
dim(res$trend)

```

