library(startR)

# Path to original cmorfiles:
path <- '/esarchive/exp/ipsl-cm6a-lr/cmip6-dcppA-hindcast_i1p1/original_files/cmorfiles/DCPP/IPSL/IPSL-CM6A-LR/dcppA-hindcast/r1i1p1f1/SImon/siconc/gn/v20200101/$var$_SImon_IPSL-CM6A-LR_dcppA-hindcast_s2016-r1i1p1f1_gn_201701-202612.nc'

# removing the first x, y indices:
data <- Start(dat = path,
              var = 'siconc',
              x = indices(2:362),
              y = indices(2:332),
              time = 'all',
              return_vars = list(nav_lat = NULL, nav_lon = NULL),
              retrieve = TRUE)
image(1:361, 1:331, data[1,1,,,1])

dev.new()

# including all indices
data <- Start(dat = path,
              var = 'siconc',
              x = indices(1:362),
              y = indices(1:332),
              time = 'all',
              return_vars = list(nav_lat = NULL, nav_lon = NULL),
              retrieve = TRUE)
image(1:362, 1:332, data[1,1,,,1])

# This doesn't work Start() doesn't found the relation with nav_lat and y
data <- Start(dat = path,
              var = 'siconc',
              x = indices(2:362),
              y = indices(2:332),
              time = 'all',
              transform = CDORemapper,
              transform_extra_cells = 2,
              transform_params = list(grid = 'r360x181',
                                      method = 'conservative',
                                      crop = TRUE),
              transform_vars = c('nav_lat', 'nav_lon'),
              synonims = list(x = c('x', 'nav_lon'), y = c('y', 'nav_lat')),
              return_vars = list(nav_lat = NULL, nav_lon = NULL, x = NULL, y = NULL),
              retrieve = TRUE)
image(1:361, 1:331, data[1,1,,,1])

# Regrid:
data <- Start(dat = path,
              var = 'siconc',
              x = indices(2:362),
              y = indices(2:332),
              time = 'all',
              return_vars = list(nav_lat = NULL, nav_lon = NULL),
              retrieve = TRUE)
nav_lon <- attributes(data)$Variables$common$nav_lon[2:362, 2:332]
nav_lat <- attributes(data)$Variables$common$nav_lat[2:362, 2:332]

res <- CDORemap(data[1,1, , ,5], 
                nav_lon, 
                nav_lat,
                grid = 'r100x50', method = 'bil', crop = FALSE)
image(res$lons, res$lats, res$data_array)


# Checking files that Marga processed with CDO -selindexbox,2,362,2,331

path <- '/esarchive/exp/CMIP6/dcppA-hindcast/ipsl-cm6a-lr/cmip6-dcppA-hindcast_i1p1/DCPP/IPSL/IPSL-CM6A-LR/dcppA-hindcast/r1i1p1f1/SImon/siconc/gn/v20200101/$var$_SImon_IPSL-CM6A-LR_dcppA-hindcast_s2016-r1i1p1f1_gn_201701-202612.nc'

data <- Start(dat = path,
              var = 'siconc',
              x = 'all',
              y = 'all',
              time = 'all',
              return_vars = list(nav_lat = NULL, nav_lon = NULL),
              retrieve = TRUE)

image(1:362, 1:332, data[1,1,,,1])




