LCOV - code coverage report
Current view: top level - frmts/netcdf - netcdfdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 4992 5898 84.6 %
Date: 2025-09-15 15:34:09 Functions: 156 163 95.7 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  netCDF read/write Driver
       4             :  * Purpose:  GDAL bindings over netCDF library.
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *           Even Rouault <even.rouault at spatialys.com>
       7             :  *
       8             :  ******************************************************************************
       9             :  * Copyright (c) 2004, Frank Warmerdam
      10             :  * Copyright (c) 2007-2016, Even Rouault <even.rouault at spatialys.com>
      11             :  * Copyright (c) 2010, Kyle Shannon <kyle at pobox dot com>
      12             :  * Copyright (c) 2021, CLS
      13             :  *
      14             :  * SPDX-License-Identifier: MIT
      15             :  ****************************************************************************/
      16             : 
      17             : #include "cpl_port.h"
      18             : 
      19             : #include <array>
      20             : #include <cassert>
      21             : #include <cctype>
      22             : #include <cerrno>
      23             : #include <climits>
      24             : #include <cmath>
      25             : #include <cstdio>
      26             : #include <cstdlib>
      27             : #include <cstring>
      28             : #include <ctime>
      29             : #include <algorithm>
      30             : #include <limits>
      31             : #include <map>
      32             : #include <mutex>
      33             : #include <set>
      34             : #include <queue>
      35             : #include <string>
      36             : #include <tuple>
      37             : #include <utility>
      38             : #include <vector>
      39             : 
      40             : // Must be included after standard includes, otherwise VS2015 fails when
      41             : // including <ctime>
      42             : #include "netcdfdataset.h"
      43             : #include "netcdfdrivercore.h"
      44             : #include "netcdfsg.h"
      45             : #include "netcdfuffd.h"
      46             : 
      47             : #include "netcdf_mem.h"
      48             : 
      49             : #include "cpl_conv.h"
      50             : #include "cpl_error.h"
      51             : #include "cpl_float.h"
      52             : #include "cpl_json.h"
      53             : #include "cpl_minixml.h"
      54             : #include "cpl_multiproc.h"
      55             : #include "cpl_progress.h"
      56             : #include "cpl_time.h"
      57             : #include "gdal.h"
      58             : #include "gdal_frmts.h"
      59             : #include "gdal_priv_templates.hpp"
      60             : #include "ogr_core.h"
      61             : #include "ogr_srs_api.h"
      62             : 
      63             : // netCDF 4.8 switched to expecting filenames in UTF-8 on Windows
      64             : // But with netCDF 4.9 and https://github.com/Unidata/netcdf-c/pull/2277/,
      65             : // this is apparently back to expecting filenames in current codepage...
      66             : // Detect netCDF 4.8 with NC_ENCZARR
      67             : // Detect netCDF 4.9 with NC_NOATTCREORD
      68             : #if defined(NC_ENCZARR) && !defined(NC_NOATTCREORD)
      69             : #define NETCDF_USES_UTF8
      70             : #endif
      71             : 
      72             : // Internal function declarations.
      73             : 
      74             : static bool NCDFIsGDALVersionGTE(const char *pszVersion, int nTarget);
      75             : 
      76             : static void
      77             : NCDFAddGDALHistory(int fpImage, const char *pszFilename, bool bWriteGDALVersion,
      78             :                    bool bWriteGDALHistory, const char *pszOldHist,
      79             :                    const char *pszFunctionName,
      80             :                    const char *pszCFVersion = GDAL_DEFAULT_NCDF_CONVENTIONS);
      81             : 
      82             : static void NCDFAddHistory(int fpImage, const char *pszAddHist,
      83             :                            const char *pszOldHist);
      84             : 
      85             : static CPLErr NCDFSafeStrcat(char **ppszDest, const char *pszSrc,
      86             :                              size_t *nDestSize);
      87             : 
      88             : // Var / attribute helper functions.
      89             : static CPLErr NCDFPutAttr(int nCdfId, int nVarId, const char *pszAttrName,
      90             :                           const char *pszValue);
      91             : 
      92             : // Replace this where used.
      93             : static CPLErr NCDFGet1DVar(int nCdfId, int nVarId, char **pszValue);
      94             : static CPLErr NCDFPut1DVar(int nCdfId, int nVarId, const char *pszValue);
      95             : 
      96             : // Replace this where used.
      97             : static char **NCDFTokenizeArray(const char *pszValue);
      98             : static void CopyMetadata(GDALDataset *poSrcDS, GDALRasterBand *poSrcBand,
      99             :                          GDALRasterBand *poDstBand, int fpImage, int CDFVarID,
     100             :                          const char *pszMatchPrefix = nullptr);
     101             : 
     102             : // NetCDF-4 groups helper functions.
     103             : // They all work also for NetCDF-3 files which are considered as
     104             : // NetCDF-4 file with only one group.
     105             : static CPLErr NCDFOpenSubDataset(int nCdfId, const char *pszSubdatasetName,
     106             :                                  int *pnGroupId, int *pnVarId);
     107             : static CPLErr NCDFGetVisibleDims(int nGroupId, int *pnDims, int **ppanDimIds);
     108             : static CPLErr NCDFGetSubGroups(int nGroupId, int *pnSubGroups,
     109             :                                int **ppanSubGroupIds);
     110             : static CPLErr NCDFGetGroupFullName(int nGroupId, char **ppszFullName,
     111             :                                    bool bNC3Compat = true);
     112             : static CPLErr NCDFGetVarFullName(int nGroupId, int nVarId, char **ppszFullName,
     113             :                                  bool bNC3Compat = true);
     114             : static CPLErr NCDFGetRootGroup(int nStartGroupId, int *pnRootGroupId);
     115             : 
     116             : static CPLErr NCDFResolveVarFullName(int nStartGroupId, const char *pszVar,
     117             :                                      char **ppszFullName,
     118             :                                      bool bMandatory = false);
     119             : static CPLErr NCDFResolveAttInt(int nStartGroupId, int nStartVarId,
     120             :                                 const char *pszAtt, int *pnAtt,
     121             :                                 bool bMandatory = false);
     122             : static CPLErr NCDFGetCoordAndBoundVarFullNames(int nCdfId, char ***ppapszVars);
     123             : 
     124             : // Uncomment this for more debug output.
     125             : // #define NCDF_DEBUG 1
     126             : 
     127             : CPLMutex *hNCMutex = nullptr;
     128             : 
     129             : // Workaround https://github.com/OSGeo/gdal/issues/6253
     130             : // Having 2 netCDF handles on the same file doesn't work in a multi-threaded
     131             : // way. Apparently having the same handle works better (this is OK since
     132             : // we have a global mutex on the netCDF library)
     133             : static std::map<std::string, int> goMapNameToNetCDFId;
     134             : static std::map<int, std::pair<std::string, int>> goMapNetCDFIdToKeyAndCount;
     135             : 
     136         674 : int GDAL_nc_open(const char *pszFilename, int nMode, int *pID)
     137             : {
     138        1348 :     std::string osKey(pszFilename);
     139         674 :     osKey += "#####";
     140         674 :     osKey += std::to_string(nMode);
     141         674 :     auto oIter = goMapNameToNetCDFId.find(osKey);
     142         674 :     if (oIter == goMapNameToNetCDFId.end())
     143             :     {
     144         624 :         int ret = nc_open(pszFilename, nMode, pID);
     145         624 :         if (ret != NC_NOERR)
     146           3 :             return ret;
     147         621 :         goMapNameToNetCDFId[osKey] = *pID;
     148         621 :         goMapNetCDFIdToKeyAndCount[*pID] =
     149        1242 :             std::pair<std::string, int>(osKey, 1);
     150         621 :         return ret;
     151             :     }
     152             :     else
     153             :     {
     154          50 :         *pID = oIter->second;
     155          50 :         goMapNetCDFIdToKeyAndCount[oIter->second].second++;
     156          50 :         return NC_NOERR;
     157             :     }
     158             : }
     159             : 
     160         931 : int GDAL_nc_close(int cdfid)
     161             : {
     162         931 :     int ret = NC_NOERR;
     163         931 :     auto oIter = goMapNetCDFIdToKeyAndCount.find(cdfid);
     164         931 :     if (oIter != goMapNetCDFIdToKeyAndCount.end())
     165             :     {
     166         671 :         if (--oIter->second.second == 0)
     167             :         {
     168         621 :             ret = nc_close(cdfid);
     169         621 :             goMapNameToNetCDFId.erase(oIter->second.first);
     170         621 :             goMapNetCDFIdToKeyAndCount.erase(oIter);
     171             :         }
     172             :     }
     173             :     else
     174             :     {
     175             :         // we can go here if file opened with nc_open_mem() or nc_create()
     176         260 :         ret = nc_close(cdfid);
     177             :     }
     178         931 :     return ret;
     179             : }
     180             : 
     181             : /************************************************************************/
     182             : /* ==================================================================== */
     183             : /*                         netCDFRasterBand                             */
     184             : /* ==================================================================== */
     185             : /************************************************************************/
     186             : 
     187             : class netCDFRasterBand final : public GDALPamRasterBand
     188             : {
     189             :     friend class netCDFDataset;
     190             : 
     191             :     nc_type nc_datatype;
     192             :     int cdfid;
     193             :     int nZId;
     194             :     int nZDim;
     195             :     int nLevel;
     196             :     int nBandXPos;
     197             :     int nBandYPos;
     198             :     int *panBandZPos;
     199             :     int *panBandZLev;
     200             :     bool m_bNoDataSet = false;
     201             :     double m_dfNoDataValue = 0;
     202             :     bool m_bNoDataSetAsInt64 = false;
     203             :     int64_t m_nNodataValueInt64 = 0;
     204             :     bool m_bNoDataSetAsUInt64 = false;
     205             :     uint64_t m_nNodataValueUInt64 = 0;
     206             :     bool bValidRangeValid = false;
     207             :     double adfValidRange[2]{0, 0};
     208             :     bool m_bHaveScale = false;
     209             :     bool m_bHaveOffset = false;
     210             :     double m_dfScale = 1;
     211             :     double m_dfOffset = 0;
     212             :     CPLString m_osUnitType{};
     213             :     bool bSignedData;
     214             :     bool bCheckLongitude;
     215             :     bool m_bCreateMetadataFromOtherVarsDone = false;
     216             : 
     217             :     void CreateMetadataFromAttributes();
     218             :     void CreateMetadataFromOtherVars();
     219             : 
     220             :     template <class T>
     221             :     void CheckData(void *pImage, void *pImageNC, size_t nTmpBlockXSize,
     222             :                    size_t nTmpBlockYSize, bool bCheckIsNan = false);
     223             :     template <class T>
     224             :     void CheckDataCpx(void *pImage, void *pImageNC, size_t nTmpBlockXSize,
     225             :                       size_t nTmpBlockYSize, bool bCheckIsNan = false);
     226             :     void SetBlockSize();
     227             : 
     228             :     bool FetchNetcdfChunk(size_t xstart, size_t ystart, void *pImage);
     229             : 
     230             :     void SetNoDataValueNoUpdate(double dfNoData);
     231             :     void SetNoDataValueNoUpdate(int64_t nNoData);
     232             :     void SetNoDataValueNoUpdate(uint64_t nNoData);
     233             : 
     234             :     void SetOffsetNoUpdate(double dfVal);
     235             :     void SetScaleNoUpdate(double dfVal);
     236             :     void SetUnitTypeNoUpdate(const char *pszNewValue);
     237             : 
     238             :   protected:
     239             :     CPLXMLNode *SerializeToXML(const char *pszUnused) override;
     240             : 
     241             :   public:
     242             :     struct CONSTRUCTOR_OPEN
     243             :     {
     244             :     };
     245             : 
     246             :     struct CONSTRUCTOR_CREATE
     247             :     {
     248             :     };
     249             : 
     250             :     netCDFRasterBand(const CONSTRUCTOR_OPEN &, netCDFDataset *poDS,
     251             :                      int nGroupId, int nZId, int nZDim, int nLevel,
     252             :                      const int *panBandZLen, const int *panBandPos, int nBand);
     253             :     netCDFRasterBand(const CONSTRUCTOR_CREATE &, netCDFDataset *poDS,
     254             :                      GDALDataType eType, int nBand, bool bSigned = true,
     255             :                      const char *pszBandName = nullptr,
     256             :                      const char *pszLongName = nullptr, int nZId = -1,
     257             :                      int nZDim = 2, int nLevel = 0,
     258             :                      const int *panBandZLev = nullptr,
     259             :                      const int *panBandZPos = nullptr,
     260             :                      const int *paDimIds = nullptr);
     261             :     ~netCDFRasterBand() override;
     262             : 
     263             :     double GetNoDataValue(int *) override;
     264             :     int64_t GetNoDataValueAsInt64(int *pbSuccess = nullptr) override;
     265             :     uint64_t GetNoDataValueAsUInt64(int *pbSuccess = nullptr) override;
     266             :     CPLErr SetNoDataValue(double) override;
     267             :     CPLErr SetNoDataValueAsInt64(int64_t nNoData) override;
     268             :     CPLErr SetNoDataValueAsUInt64(uint64_t nNoData) override;
     269             :     // virtual CPLErr DeleteNoDataValue();
     270             :     double GetOffset(int *) override;
     271             :     CPLErr SetOffset(double) override;
     272             :     double GetScale(int *) override;
     273             :     CPLErr SetScale(double) override;
     274             :     const char *GetUnitType() override;
     275             :     CPLErr SetUnitType(const char *) override;
     276             :     CPLErr IReadBlock(int, int, void *) override;
     277             :     CPLErr IWriteBlock(int, int, void *) override;
     278             : 
     279             :     char **GetMetadata(const char *pszDomain = "") override;
     280             :     const char *GetMetadataItem(const char *pszName,
     281             :                                 const char *pszDomain = "") override;
     282             : 
     283             :     CPLErr SetMetadataItem(const char *pszName, const char *pszValue,
     284             :                            const char *pszDomain = "") override;
     285             :     CPLErr SetMetadata(char **papszMD, const char *pszDomain = "") override;
     286             : };
     287             : 
     288             : /************************************************************************/
     289             : /*                          netCDFRasterBand()                          */
     290             : /************************************************************************/
     291             : 
     292         481 : netCDFRasterBand::netCDFRasterBand(const netCDFRasterBand::CONSTRUCTOR_OPEN &,
     293             :                                    netCDFDataset *poNCDFDS, int nGroupId,
     294             :                                    int nZIdIn, int nZDimIn, int nLevelIn,
     295             :                                    const int *panBandZLevIn,
     296         481 :                                    const int *panBandZPosIn, int nBandIn)
     297             :     : nc_datatype(NC_NAT), cdfid(nGroupId), nZId(nZIdIn), nZDim(nZDimIn),
     298         481 :       nLevel(nLevelIn), nBandXPos(panBandZPosIn[0]),
     299         481 :       nBandYPos(nZDim == 1 ? -1 : panBandZPosIn[1]), panBandZPos(nullptr),
     300             :       panBandZLev(nullptr),
     301             :       bSignedData(true),  // Default signed, except for Byte.
     302         962 :       bCheckLongitude(false)
     303             : {
     304         481 :     poDS = poNCDFDS;
     305         481 :     nBand = nBandIn;
     306             : 
     307             :     // Take care of all other dimensions.
     308         481 :     if (nZDim > 2)
     309             :     {
     310         176 :         panBandZPos = static_cast<int *>(CPLCalloc(nZDim - 1, sizeof(int)));
     311         176 :         panBandZLev = static_cast<int *>(CPLCalloc(nZDim - 1, sizeof(int)));
     312             : 
     313         478 :         for (int i = 0; i < nZDim - 2; i++)
     314             :         {
     315         302 :             panBandZPos[i] = panBandZPosIn[i + 2];
     316         302 :             panBandZLev[i] = panBandZLevIn[i];
     317             :         }
     318             :     }
     319             : 
     320         481 :     nRasterXSize = poDS->GetRasterXSize();
     321         481 :     nRasterYSize = poDS->GetRasterYSize();
     322         481 :     nBlockXSize = poDS->GetRasterXSize();
     323         481 :     nBlockYSize = 1;
     324             : 
     325             :     // Get the type of the "z" variable, our target raster array.
     326         481 :     if (nc_inq_var(cdfid, nZId, nullptr, &nc_datatype, nullptr, nullptr,
     327         481 :                    nullptr) != NC_NOERR)
     328             :     {
     329           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Error in nc_var_inq() on 'z'.");
     330           0 :         return;
     331             :     }
     332             : 
     333         481 :     if (NCDFIsUserDefinedType(cdfid, nc_datatype))
     334             :     {
     335             :         // First enquire and check that the number of fields is 2
     336             :         size_t nfields, compoundsize;
     337           5 :         if (nc_inq_compound(cdfid, nc_datatype, nullptr, &compoundsize,
     338           5 :                             &nfields) != NC_NOERR)
     339             :         {
     340           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     341             :                      "Error in nc_inq_compound() on 'z'.");
     342           0 :             return;
     343             :         }
     344             : 
     345           5 :         if (nfields != 2)
     346             :         {
     347           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     348             :                      "Unsupported data type encountered in nc_inq_compound() "
     349             :                      "on 'z'.");
     350           0 :             return;
     351             :         }
     352             : 
     353             :         // Now check that that two types are the same in the struct.
     354             :         nc_type field_type1, field_type2;
     355             :         int field_dims1, field_dims2;
     356           5 :         if (nc_inq_compound_field(cdfid, nc_datatype, 0, nullptr, nullptr,
     357             :                                   &field_type1, &field_dims1,
     358           5 :                                   nullptr) != NC_NOERR)
     359             :         {
     360           0 :             CPLError(
     361             :                 CE_Failure, CPLE_AppDefined,
     362             :                 "Error in querying Field 1 in nc_inq_compound_field() on 'z'.");
     363           0 :             return;
     364             :         }
     365             : 
     366           5 :         if (nc_inq_compound_field(cdfid, nc_datatype, 0, nullptr, nullptr,
     367             :                                   &field_type2, &field_dims2,
     368           5 :                                   nullptr) != NC_NOERR)
     369             :         {
     370           0 :             CPLError(
     371             :                 CE_Failure, CPLE_AppDefined,
     372             :                 "Error in querying Field 2 in nc_inq_compound_field() on 'z'.");
     373           0 :             return;
     374             :         }
     375             : 
     376           5 :         if ((field_type1 != field_type2) || (field_dims1 != field_dims2) ||
     377           5 :             (field_dims1 != 0))
     378             :         {
     379           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     380             :                      "Error in interpreting compound data type on 'z'.");
     381           0 :             return;
     382             :         }
     383             : 
     384           5 :         if (field_type1 == NC_SHORT)
     385           0 :             eDataType = GDT_CInt16;
     386           5 :         else if (field_type1 == NC_INT)
     387           0 :             eDataType = GDT_CInt32;
     388           5 :         else if (field_type1 == NC_FLOAT)
     389           4 :             eDataType = GDT_CFloat32;
     390           1 :         else if (field_type1 == NC_DOUBLE)
     391           1 :             eDataType = GDT_CFloat64;
     392             :         else
     393             :         {
     394           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     395             :                      "Unsupported netCDF compound data type encountered.");
     396           0 :             return;
     397             :         }
     398             :     }
     399             :     else
     400             :     {
     401         476 :         if (nc_datatype == NC_BYTE)
     402         146 :             eDataType = GDT_Byte;
     403         330 :         else if (nc_datatype == NC_CHAR)
     404           0 :             eDataType = GDT_Byte;
     405         330 :         else if (nc_datatype == NC_SHORT)
     406          41 :             eDataType = GDT_Int16;
     407         289 :         else if (nc_datatype == NC_INT)
     408          89 :             eDataType = GDT_Int32;
     409         200 :         else if (nc_datatype == NC_FLOAT)
     410         123 :             eDataType = GDT_Float32;
     411          77 :         else if (nc_datatype == NC_DOUBLE)
     412          40 :             eDataType = GDT_Float64;
     413          37 :         else if (nc_datatype == NC_UBYTE)
     414          15 :             eDataType = GDT_Byte;
     415          22 :         else if (nc_datatype == NC_USHORT)
     416           4 :             eDataType = GDT_UInt16;
     417          18 :         else if (nc_datatype == NC_UINT)
     418           3 :             eDataType = GDT_UInt32;
     419          15 :         else if (nc_datatype == NC_INT64)
     420           8 :             eDataType = GDT_Int64;
     421           7 :         else if (nc_datatype == NC_UINT64)
     422           7 :             eDataType = GDT_UInt64;
     423             :         else
     424             :         {
     425           0 :             if (nBand == 1)
     426           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
     427             :                          "Unsupported netCDF datatype (%d), treat as Float32.",
     428           0 :                          static_cast<int>(nc_datatype));
     429           0 :             eDataType = GDT_Float32;
     430           0 :             nc_datatype = NC_FLOAT;
     431             :         }
     432             :     }
     433             : 
     434             :     // Find and set No Data for this variable.
     435         481 :     nc_type atttype = NC_NAT;
     436         481 :     size_t attlen = 0;
     437         481 :     const char *pszNoValueName = nullptr;
     438             : 
     439             :     // Find attribute name, either _FillValue or missing_value.
     440         481 :     int status = nc_inq_att(cdfid, nZId, NCDF_FillValue, &atttype, &attlen);
     441         481 :     if (status == NC_NOERR)
     442             :     {
     443         248 :         pszNoValueName = NCDF_FillValue;
     444             :     }
     445             :     else
     446             :     {
     447         233 :         status = nc_inq_att(cdfid, nZId, "missing_value", &atttype, &attlen);
     448         233 :         if (status == NC_NOERR)
     449             :         {
     450          12 :             pszNoValueName = "missing_value";
     451             :         }
     452             :     }
     453             : 
     454             :     // Fetch missing value.
     455         481 :     double dfNoData = 0.0;
     456         481 :     bool bGotNoData = false;
     457         481 :     int64_t nNoDataAsInt64 = 0;
     458         481 :     bool bGotNoDataAsInt64 = false;
     459         481 :     uint64_t nNoDataAsUInt64 = 0;
     460         481 :     bool bGotNoDataAsUInt64 = false;
     461         481 :     if (status == NC_NOERR)
     462             :     {
     463         260 :         nc_type nAttrType = NC_NAT;
     464         260 :         size_t nAttrLen = 0;
     465         260 :         status = nc_inq_att(cdfid, nZId, pszNoValueName, &nAttrType, &nAttrLen);
     466         260 :         if (status == NC_NOERR && nAttrLen == 1 && nAttrType == NC_INT64)
     467             :         {
     468             :             long long v;
     469           7 :             nc_get_att_longlong(cdfid, nZId, pszNoValueName, &v);
     470           7 :             bGotNoData = true;
     471           7 :             bGotNoDataAsInt64 = true;
     472           7 :             nNoDataAsInt64 = static_cast<int64_t>(v);
     473             :         }
     474         253 :         else if (status == NC_NOERR && nAttrLen == 1 && nAttrType == NC_UINT64)
     475             :         {
     476             :             unsigned long long v;
     477           7 :             nc_get_att_ulonglong(cdfid, nZId, pszNoValueName, &v);
     478           7 :             bGotNoData = true;
     479           7 :             bGotNoDataAsUInt64 = true;
     480           7 :             nNoDataAsUInt64 = static_cast<uint64_t>(v);
     481             :         }
     482         246 :         else if (NCDFGetAttr(cdfid, nZId, pszNoValueName, &dfNoData) == CE_None)
     483             :         {
     484         245 :             bGotNoData = true;
     485             :         }
     486             :     }
     487             : 
     488             :     // If NoData was not found, use the default value, but for non-Byte types
     489             :     // as it is not recommended:
     490             :     // https://www.unidata.ucar.edu/software/netcdf/docs/attribute_conventions.html
     491         481 :     nc_type vartype = NC_NAT;
     492         481 :     if (!bGotNoData)
     493             :     {
     494         222 :         nc_inq_vartype(cdfid, nZId, &vartype);
     495         222 :         if (vartype == NC_INT64)
     496             :         {
     497             :             nNoDataAsInt64 =
     498           1 :                 NCDFGetDefaultNoDataValueAsInt64(cdfid, nZId, bGotNoData);
     499           1 :             bGotNoDataAsInt64 = bGotNoData;
     500             :         }
     501         221 :         else if (vartype == NC_UINT64)
     502             :         {
     503             :             nNoDataAsUInt64 =
     504           0 :                 NCDFGetDefaultNoDataValueAsUInt64(cdfid, nZId, bGotNoData);
     505           0 :             bGotNoDataAsUInt64 = bGotNoData;
     506             :         }
     507         221 :         else if (vartype != NC_CHAR && vartype != NC_BYTE &&
     508          98 :                  vartype != NC_UBYTE)
     509             :         {
     510          89 :             dfNoData =
     511          89 :                 NCDFGetDefaultNoDataValue(cdfid, nZId, vartype, bGotNoData);
     512          89 :             if (bGotNoData)
     513             :             {
     514          78 :                 CPLDebug("GDAL_netCDF",
     515             :                          "did not get nodata value for variable #%d, using "
     516             :                          "default %f",
     517             :                          nZId, dfNoData);
     518             :             }
     519             :         }
     520             :     }
     521             : 
     522         481 :     bool bHasUnderscoreUnsignedAttr = false;
     523         481 :     bool bUnderscoreUnsignedAttrVal = false;
     524             :     {
     525         481 :         char *pszTemp = nullptr;
     526         481 :         if (NCDFGetAttr(cdfid, nZId, "_Unsigned", &pszTemp) == CE_None)
     527             :         {
     528         138 :             if (EQUAL(pszTemp, "true"))
     529             :             {
     530         130 :                 bHasUnderscoreUnsignedAttr = true;
     531         130 :                 bUnderscoreUnsignedAttrVal = true;
     532             :             }
     533           8 :             else if (EQUAL(pszTemp, "false"))
     534             :             {
     535           8 :                 bHasUnderscoreUnsignedAttr = true;
     536           8 :                 bUnderscoreUnsignedAttrVal = false;
     537             :             }
     538         138 :             CPLFree(pszTemp);
     539             :         }
     540             :     }
     541             : 
     542             :     // Look for valid_range or valid_min/valid_max.
     543             : 
     544             :     // First look for valid_range.
     545         481 :     if (CPLFetchBool(poNCDFDS->GetOpenOptions(), "HONOUR_VALID_RANGE", true))
     546             :     {
     547         479 :         char *pszValidRange = nullptr;
     548         479 :         if (NCDFGetAttr(cdfid, nZId, "valid_range", &pszValidRange) ==
     549         131 :                 CE_None &&
     550         610 :             pszValidRange[0] == '{' &&
     551         131 :             pszValidRange[strlen(pszValidRange) - 1] == '}')
     552             :         {
     553             :             const std::string osValidRange =
     554         393 :                 std::string(pszValidRange).substr(1, strlen(pszValidRange) - 2);
     555             :             const CPLStringList aosValidRange(
     556         262 :                 CSLTokenizeString2(osValidRange.c_str(), ",", 0));
     557         131 :             if (aosValidRange.size() == 2 &&
     558         262 :                 CPLGetValueType(aosValidRange[0]) != CPL_VALUE_STRING &&
     559         131 :                 CPLGetValueType(aosValidRange[1]) != CPL_VALUE_STRING)
     560             :             {
     561         131 :                 bValidRangeValid = true;
     562         131 :                 adfValidRange[0] = CPLAtof(aosValidRange[0]);
     563         131 :                 adfValidRange[1] = CPLAtof(aosValidRange[1]);
     564             :             }
     565             :         }
     566         479 :         CPLFree(pszValidRange);
     567             : 
     568             :         // If not found look for valid_min and valid_max.
     569         479 :         if (!bValidRangeValid)
     570             :         {
     571         348 :             double dfMin = 0;
     572         348 :             double dfMax = 0;
     573         363 :             if (NCDFGetAttr(cdfid, nZId, "valid_min", &dfMin) == CE_None &&
     574          15 :                 NCDFGetAttr(cdfid, nZId, "valid_max", &dfMax) == CE_None)
     575             :             {
     576           8 :                 adfValidRange[0] = dfMin;
     577           8 :                 adfValidRange[1] = dfMax;
     578           8 :                 bValidRangeValid = true;
     579             :             }
     580             :         }
     581             : 
     582         479 :         if (bValidRangeValid &&
     583         139 :             (adfValidRange[0] < 0 || adfValidRange[1] < 0) &&
     584          17 :             nc_datatype == NC_SHORT && bHasUnderscoreUnsignedAttr &&
     585             :             bUnderscoreUnsignedAttrVal)
     586             :         {
     587           2 :             if (adfValidRange[0] < 0)
     588           0 :                 adfValidRange[0] += 65536;
     589           2 :             if (adfValidRange[1] < 0)
     590           2 :                 adfValidRange[1] += 65536;
     591           2 :             if (adfValidRange[0] <= adfValidRange[1])
     592             :             {
     593             :                 // Updating metadata item
     594           2 :                 GDALPamRasterBand::SetMetadataItem(
     595             :                     "valid_range",
     596           2 :                     CPLSPrintf("{%d,%d}", static_cast<int>(adfValidRange[0]),
     597           2 :                                static_cast<int>(adfValidRange[1])));
     598             :             }
     599             :         }
     600             : 
     601         479 :         if (bValidRangeValid && adfValidRange[0] > adfValidRange[1])
     602             :         {
     603           0 :             CPLError(CE_Warning, CPLE_AppDefined,
     604             :                      "netCDFDataset::valid_range: min > max:\n"
     605             :                      "  min: %lf\n  max: %lf\n",
     606             :                      adfValidRange[0], adfValidRange[1]);
     607           0 :             bValidRangeValid = false;
     608           0 :             adfValidRange[0] = 0.0;
     609           0 :             adfValidRange[1] = 0.0;
     610             :         }
     611             :     }
     612             : 
     613             :     // Special For Byte Bands: check for signed/unsigned byte.
     614         481 :     if (nc_datatype == NC_BYTE)
     615             :     {
     616             :         // netcdf uses signed byte by default, but GDAL uses unsigned by default
     617             :         // This may cause unexpected results, but is needed for back-compat.
     618         146 :         if (poNCDFDS->bIsGdalFile)
     619         124 :             bSignedData = false;
     620             :         else
     621          22 :             bSignedData = true;
     622             : 
     623             :         // For NC4 format NC_BYTE is (normally) signed, NC_UBYTE is unsigned.
     624             :         // But in case a NC3 file was converted automatically and has hints
     625             :         // that it is unsigned, take them into account
     626         146 :         if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
     627             :         {
     628           3 :             bSignedData = true;
     629             :         }
     630             : 
     631             :         // If we got valid_range, test for signed/unsigned range.
     632             :         // https://docs.unidata.ucar.edu/netcdf-c/current/attribute_conventions.html
     633         146 :         if (bValidRangeValid)
     634             :         {
     635             :             // If we got valid_range={0,255}, treat as unsigned.
     636         127 :             if (adfValidRange[0] == 0 && adfValidRange[1] == 255)
     637             :             {
     638         119 :                 bSignedData = false;
     639             :                 // Reset valid_range.
     640         119 :                 bValidRangeValid = false;
     641             :             }
     642             :             // If we got valid_range={-128,127}, treat as signed.
     643           8 :             else if (adfValidRange[0] == -128 && adfValidRange[1] == 127)
     644             :             {
     645           8 :                 bSignedData = true;
     646             :                 // Reset valid_range.
     647           8 :                 bValidRangeValid = false;
     648             :             }
     649             :         }
     650             :         // Else test for _Unsigned.
     651             :         // https://docs.unidata.ucar.edu/nug/current/best_practices.html
     652             :         else
     653             :         {
     654          19 :             if (bHasUnderscoreUnsignedAttr)
     655           7 :                 bSignedData = !bUnderscoreUnsignedAttrVal;
     656             :         }
     657             : 
     658         146 :         if (bSignedData)
     659             :         {
     660          20 :             eDataType = GDT_Int8;
     661             :         }
     662         126 :         else if (dfNoData < 0)
     663             :         {
     664             :             // Fix nodata value as it was stored signed.
     665           6 :             dfNoData += 256;
     666           6 :             if (pszNoValueName)
     667             :             {
     668             :                 // Updating metadata item
     669           6 :                 GDALPamRasterBand::SetMetadataItem(
     670             :                     pszNoValueName,
     671             :                     CPLSPrintf("%d", static_cast<int>(dfNoData)));
     672             :             }
     673             :         }
     674             :     }
     675         335 :     else if (nc_datatype == NC_SHORT)
     676             :     {
     677          41 :         if (bHasUnderscoreUnsignedAttr)
     678             :         {
     679           4 :             bSignedData = !bUnderscoreUnsignedAttrVal;
     680           4 :             if (!bSignedData)
     681           4 :                 eDataType = GDT_UInt16;
     682             :         }
     683             : 
     684             :         // Fix nodata value as it was stored signed.
     685          41 :         if (!bSignedData && dfNoData < 0)
     686             :         {
     687           4 :             dfNoData += 65536;
     688           4 :             if (pszNoValueName)
     689             :             {
     690             :                 // Updating metadata item
     691           4 :                 GDALPamRasterBand::SetMetadataItem(
     692             :                     pszNoValueName,
     693             :                     CPLSPrintf("%d", static_cast<int>(dfNoData)));
     694             :             }
     695             :         }
     696             :     }
     697             : 
     698         294 :     else if (nc_datatype == NC_UBYTE || nc_datatype == NC_USHORT ||
     699         275 :              nc_datatype == NC_UINT || nc_datatype == NC_UINT64)
     700             :     {
     701          29 :         bSignedData = false;
     702             :     }
     703             : 
     704         481 :     CPLDebug("GDAL_netCDF", "netcdf type=%d gdal type=%d signedByte=%d",
     705         481 :              nc_datatype, eDataType, static_cast<int>(bSignedData));
     706             : 
     707         481 :     if (bGotNoData)
     708             :     {
     709             :         // Set nodata value.
     710         338 :         if (bGotNoDataAsInt64)
     711             :         {
     712           8 :             if (eDataType == GDT_Int64)
     713             :             {
     714           8 :                 SetNoDataValueNoUpdate(nNoDataAsInt64);
     715             :             }
     716           0 :             else if (eDataType == GDT_UInt64 && nNoDataAsInt64 >= 0)
     717             :             {
     718           0 :                 SetNoDataValueNoUpdate(static_cast<uint64_t>(nNoDataAsInt64));
     719             :             }
     720             :             else
     721             :             {
     722           0 :                 SetNoDataValueNoUpdate(static_cast<double>(nNoDataAsInt64));
     723             :             }
     724             :         }
     725         330 :         else if (bGotNoDataAsUInt64)
     726             :         {
     727           7 :             if (eDataType == GDT_UInt64)
     728             :             {
     729           7 :                 SetNoDataValueNoUpdate(nNoDataAsUInt64);
     730             :             }
     731           0 :             else if (eDataType == GDT_Int64 &&
     732             :                      nNoDataAsUInt64 <=
     733           0 :                          static_cast<uint64_t>(
     734           0 :                              std::numeric_limits<int64_t>::max()))
     735             :             {
     736           0 :                 SetNoDataValueNoUpdate(static_cast<int64_t>(nNoDataAsUInt64));
     737             :             }
     738             :             else
     739             :             {
     740           0 :                 SetNoDataValueNoUpdate(static_cast<double>(nNoDataAsUInt64));
     741             :             }
     742             :         }
     743             :         else
     744             :         {
     745             : #ifdef NCDF_DEBUG
     746             :             CPLDebug("GDAL_netCDF", "SetNoDataValue(%f) read", dfNoData);
     747             : #endif
     748         323 :             if (eDataType == GDT_Int64 && GDALIsValueExactAs<int64_t>(dfNoData))
     749             :             {
     750           0 :                 SetNoDataValueNoUpdate(static_cast<int64_t>(dfNoData));
     751             :             }
     752         323 :             else if (eDataType == GDT_UInt64 &&
     753           0 :                      GDALIsValueExactAs<uint64_t>(dfNoData))
     754             :             {
     755           0 :                 SetNoDataValueNoUpdate(static_cast<uint64_t>(dfNoData));
     756             :             }
     757             :             else
     758             :             {
     759         323 :                 SetNoDataValueNoUpdate(dfNoData);
     760             :             }
     761             :         }
     762             :     }
     763             : 
     764         481 :     CreateMetadataFromAttributes();
     765             : 
     766             :     // Attempt to fetch the scale_factor and add_offset attributes for the
     767             :     // variable and set them.  If these values are not available, set
     768             :     // offset to 0 and scale to 1.
     769         481 :     if (nc_inq_attid(cdfid, nZId, CF_ADD_OFFSET, nullptr) == NC_NOERR)
     770             :     {
     771          16 :         double dfOffset = 0;
     772          16 :         status = nc_get_att_double(cdfid, nZId, CF_ADD_OFFSET, &dfOffset);
     773          16 :         CPLDebug("GDAL_netCDF", "got add_offset=%.16g, status=%d", dfOffset,
     774             :                  status);
     775          16 :         SetOffsetNoUpdate(dfOffset);
     776             :     }
     777             : 
     778         481 :     bool bHasScale = false;
     779         481 :     if (nc_inq_attid(cdfid, nZId, CF_SCALE_FACTOR, nullptr) == NC_NOERR)
     780             :     {
     781          20 :         bHasScale = true;
     782          20 :         double dfScale = 1;
     783          20 :         status = nc_get_att_double(cdfid, nZId, CF_SCALE_FACTOR, &dfScale);
     784          20 :         CPLDebug("GDAL_netCDF", "got scale_factor=%.16g, status=%d", dfScale,
     785             :                  status);
     786          20 :         SetScaleNoUpdate(dfScale);
     787             :     }
     788             : 
     789          12 :     if (bValidRangeValid && GDALDataTypeIsInteger(eDataType) &&
     790           4 :         eDataType != GDT_Int64 && eDataType != GDT_UInt64 &&
     791           4 :         (std::fabs(std::round(adfValidRange[0]) - adfValidRange[0]) > 1e-5 ||
     792         493 :          std::fabs(std::round(adfValidRange[1]) - adfValidRange[1]) > 1e-5) &&
     793           1 :         CSLFetchNameValue(poNCDFDS->GetOpenOptions(), "HONOUR_VALID_RANGE") ==
     794             :             nullptr)
     795             :     {
     796           1 :         CPLError(CE_Warning, CPLE_AppDefined,
     797             :                  "validity range = %f, %f contains floating-point values, "
     798             :                  "whereas data type is integer. valid_range is thus likely "
     799             :                  "wrong%s. Ignoring it.",
     800             :                  adfValidRange[0], adfValidRange[1],
     801             :                  bHasScale ? " (likely scaled using scale_factor/add_factor "
     802             :                              "whereas it should be using the packed data type)"
     803             :                            : "");
     804           1 :         bValidRangeValid = false;
     805           1 :         adfValidRange[0] = 0.0;
     806           1 :         adfValidRange[1] = 0.0;
     807             :     }
     808             : 
     809             :     // Should we check for longitude values > 360?
     810         481 :     bCheckLongitude =
     811         962 :         CPLTestBool(CPLGetConfigOption("GDAL_NETCDF_CENTERLONG_180", "YES")) &&
     812         481 :         NCDFIsVarLongitude(cdfid, nZId, nullptr);
     813             : 
     814             :     // Attempt to fetch the units attribute for the variable and set it.
     815         481 :     SetUnitTypeNoUpdate(netCDFRasterBand::GetMetadataItem(CF_UNITS));
     816             : 
     817         481 :     SetBlockSize();
     818             : }
     819             : 
     820         663 : void netCDFRasterBand::SetBlockSize()
     821             : {
     822             :     // Check for variable chunking (netcdf-4 only).
     823             :     // GDAL block size should be set to hdf5 chunk size.
     824         663 :     int nTmpFormat = 0;
     825         663 :     int status = nc_inq_format(cdfid, &nTmpFormat);
     826         663 :     NetCDFFormatEnum eTmpFormat = static_cast<NetCDFFormatEnum>(nTmpFormat);
     827         663 :     if ((status == NC_NOERR) &&
     828         566 :         (eTmpFormat == NCDF_FORMAT_NC4 || eTmpFormat == NCDF_FORMAT_NC4C))
     829             :     {
     830         113 :         size_t chunksize[MAX_NC_DIMS] = {};
     831             :         // Check for chunksize and set it as the blocksize (optimizes read).
     832         113 :         status = nc_inq_var_chunking(cdfid, nZId, &nTmpFormat, chunksize);
     833         113 :         if ((status == NC_NOERR) && (nTmpFormat == NC_CHUNKED))
     834             :         {
     835          13 :             nBlockXSize = (int)chunksize[nZDim - 1];
     836          13 :             if (nZDim >= 2)
     837          13 :                 nBlockYSize = (int)chunksize[nZDim - 2];
     838             :             else
     839           0 :                 nBlockYSize = 1;
     840             :         }
     841             :     }
     842             : 
     843             :     // Deal with bottom-up datasets and nBlockYSize != 1.
     844         663 :     auto poGDS = static_cast<netCDFDataset *>(poDS);
     845         663 :     if (poGDS->bBottomUp && nBlockYSize != 1 && poGDS->poChunkCache == nullptr)
     846             :     {
     847           5 :         if (poGDS->eAccess == GA_ReadOnly)
     848             :         {
     849             :             // Try to cache 1 or 2 'rows' of netCDF chunks along the whole
     850             :             // width of the raster
     851           5 :             size_t nChunks =
     852           5 :                 static_cast<size_t>(DIV_ROUND_UP(nRasterXSize, nBlockXSize));
     853           5 :             if ((nRasterYSize % nBlockYSize) != 0)
     854           1 :                 nChunks *= 2;
     855             :             const size_t nChunkSize =
     856           5 :                 static_cast<size_t>(GDALGetDataTypeSizeBytes(eDataType)) *
     857           5 :                 nBlockXSize * nBlockYSize;
     858           5 :             constexpr size_t MAX_CACHE_SIZE = 100 * 1024 * 1024;
     859           5 :             nChunks = std::min(nChunks, MAX_CACHE_SIZE / nChunkSize);
     860           5 :             if (nChunks)
     861             :             {
     862           5 :                 poGDS->poChunkCache.reset(
     863           5 :                     new netCDFDataset::ChunkCacheType(nChunks));
     864             :             }
     865             :         }
     866             :         else
     867             :         {
     868           0 :             nBlockYSize = 1;
     869             :         }
     870             :     }
     871         663 : }
     872             : 
     873             : // Constructor in create mode.
     874             : // If nZId and following variables are not passed, the band will have 2
     875             : // dimensions.
     876             : // TODO: Get metadata, missing val from band #1 if nZDim > 2.
     877         182 : netCDFRasterBand::netCDFRasterBand(
     878             :     const netCDFRasterBand::CONSTRUCTOR_CREATE &, netCDFDataset *poNCDFDS,
     879             :     const GDALDataType eTypeIn, int nBandIn, bool bSigned,
     880             :     const char *pszBandName, const char *pszLongName, int nZIdIn, int nZDimIn,
     881             :     int nLevelIn, const int *panBandZLevIn, const int *panBandZPosIn,
     882         182 :     const int *paDimIds)
     883         182 :     : nc_datatype(NC_NAT), cdfid(poNCDFDS->GetCDFID()), nZId(nZIdIn),
     884             :       nZDim(nZDimIn), nLevel(nLevelIn), nBandXPos(1), nBandYPos(0),
     885             :       panBandZPos(nullptr), panBandZLev(nullptr), bSignedData(bSigned),
     886         182 :       bCheckLongitude(false), m_bCreateMetadataFromOtherVarsDone(true)
     887             : {
     888         182 :     poDS = poNCDFDS;
     889         182 :     nBand = nBandIn;
     890             : 
     891         182 :     nRasterXSize = poDS->GetRasterXSize();
     892         182 :     nRasterYSize = poDS->GetRasterYSize();
     893         182 :     nBlockXSize = poDS->GetRasterXSize();
     894         182 :     nBlockYSize = 1;
     895             : 
     896         182 :     if (poDS->GetAccess() != GA_Update)
     897             :     {
     898           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     899             :                  "Dataset is not in update mode, "
     900             :                  "wrong netCDFRasterBand constructor");
     901           0 :         return;
     902             :     }
     903             : 
     904             :     // Take care of all other dimensions.
     905         182 :     if (nZDim > 2 && paDimIds != nullptr)
     906             :     {
     907          27 :         nBandXPos = panBandZPosIn[0];
     908          27 :         nBandYPos = panBandZPosIn[1];
     909             : 
     910          27 :         panBandZPos = static_cast<int *>(CPLCalloc(nZDim - 1, sizeof(int)));
     911          27 :         panBandZLev = static_cast<int *>(CPLCalloc(nZDim - 1, sizeof(int)));
     912             : 
     913          76 :         for (int i = 0; i < nZDim - 2; i++)
     914             :         {
     915          49 :             panBandZPos[i] = panBandZPosIn[i + 2];
     916          49 :             panBandZLev[i] = panBandZLevIn[i];
     917             :         }
     918             :     }
     919             : 
     920             :     // Get the type of the "z" variable, our target raster array.
     921         182 :     eDataType = eTypeIn;
     922             : 
     923         182 :     switch (eDataType)
     924             :     {
     925          77 :         case GDT_Byte:
     926          77 :             nc_datatype = NC_BYTE;
     927             :             // NC_UBYTE (unsigned byte) is only available for NC4.
     928          77 :             if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
     929           3 :                 nc_datatype = NC_UBYTE;
     930          77 :             break;
     931           7 :         case GDT_Int8:
     932           7 :             nc_datatype = NC_BYTE;
     933           7 :             break;
     934          11 :         case GDT_Int16:
     935          11 :             nc_datatype = NC_SHORT;
     936          11 :             break;
     937          24 :         case GDT_Int32:
     938          24 :             nc_datatype = NC_INT;
     939          24 :             break;
     940          13 :         case GDT_Float32:
     941          13 :             nc_datatype = NC_FLOAT;
     942          13 :             break;
     943           8 :         case GDT_Float64:
     944           8 :             nc_datatype = NC_DOUBLE;
     945           8 :             break;
     946           7 :         case GDT_Int64:
     947           7 :             if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
     948             :             {
     949           7 :                 nc_datatype = NC_INT64;
     950             :             }
     951             :             else
     952             :             {
     953           0 :                 if (nBand == 1)
     954           0 :                     CPLError(
     955             :                         CE_Warning, CPLE_AppDefined,
     956             :                         "Unsupported GDAL datatype %s, treat as NC_DOUBLE.",
     957             :                         "Int64");
     958           0 :                 nc_datatype = NC_DOUBLE;
     959           0 :                 eDataType = GDT_Float64;
     960             :             }
     961           7 :             break;
     962           7 :         case GDT_UInt64:
     963           7 :             if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
     964             :             {
     965           7 :                 nc_datatype = NC_UINT64;
     966             :             }
     967             :             else
     968             :             {
     969           0 :                 if (nBand == 1)
     970           0 :                     CPLError(
     971             :                         CE_Warning, CPLE_AppDefined,
     972             :                         "Unsupported GDAL datatype %s, treat as NC_DOUBLE.",
     973             :                         "UInt64");
     974           0 :                 nc_datatype = NC_DOUBLE;
     975           0 :                 eDataType = GDT_Float64;
     976             :             }
     977           7 :             break;
     978           6 :         case GDT_UInt16:
     979           6 :             if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
     980             :             {
     981           6 :                 nc_datatype = NC_USHORT;
     982           6 :                 break;
     983             :             }
     984             :             [[fallthrough]];
     985             :         case GDT_UInt32:
     986           6 :             if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
     987             :             {
     988           6 :                 nc_datatype = NC_UINT;
     989           6 :                 break;
     990             :             }
     991             :             [[fallthrough]];
     992             :         default:
     993          16 :             if (nBand == 1)
     994           8 :                 CPLError(CE_Warning, CPLE_AppDefined,
     995             :                          "Unsupported GDAL datatype (%d), treat as NC_FLOAT.",
     996           8 :                          static_cast<int>(eDataType));
     997          16 :             nc_datatype = NC_FLOAT;
     998          16 :             eDataType = GDT_Float32;
     999          16 :             break;
    1000             :     }
    1001             : 
    1002             :     // Define the variable if necessary (if nZId == -1).
    1003         182 :     bool bDefineVar = false;
    1004             : 
    1005         182 :     if (nZId == -1)
    1006             :     {
    1007         160 :         bDefineVar = true;
    1008             : 
    1009             :         // Make sure we are in define mode.
    1010         160 :         static_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
    1011             : 
    1012             :         char szTempPrivate[256 + 1];
    1013         160 :         const char *pszTemp = nullptr;
    1014         160 :         if (!pszBandName || EQUAL(pszBandName, ""))
    1015             :         {
    1016         138 :             snprintf(szTempPrivate, sizeof(szTempPrivate), "Band%d", nBand);
    1017         138 :             pszTemp = szTempPrivate;
    1018             :         }
    1019             :         else
    1020             :         {
    1021          22 :             pszTemp = pszBandName;
    1022             :         }
    1023             : 
    1024             :         int status;
    1025         160 :         if (nZDim > 2 && paDimIds != nullptr)
    1026             :         {
    1027           5 :             status =
    1028           5 :                 nc_def_var(cdfid, pszTemp, nc_datatype, nZDim, paDimIds, &nZId);
    1029             :         }
    1030             :         else
    1031             :         {
    1032         155 :             int anBandDims[2] = {poNCDFDS->nYDimID, poNCDFDS->nXDimID};
    1033             :             status =
    1034         155 :                 nc_def_var(cdfid, pszTemp, nc_datatype, 2, anBandDims, &nZId);
    1035             :         }
    1036         160 :         NCDF_ERR(status);
    1037         160 :         CPLDebug("GDAL_netCDF", "nc_def_var(%d,%s,%d) id=%d", cdfid, pszTemp,
    1038             :                  nc_datatype, nZId);
    1039             : 
    1040         160 :         if (!pszLongName || EQUAL(pszLongName, ""))
    1041             :         {
    1042         153 :             snprintf(szTempPrivate, sizeof(szTempPrivate),
    1043             :                      "GDAL Band Number %d", nBand);
    1044         153 :             pszTemp = szTempPrivate;
    1045             :         }
    1046             :         else
    1047             :         {
    1048           7 :             pszTemp = pszLongName;
    1049             :         }
    1050             :         status =
    1051         160 :             nc_put_att_text(cdfid, nZId, CF_LNG_NAME, strlen(pszTemp), pszTemp);
    1052         160 :         NCDF_ERR(status);
    1053             : 
    1054         160 :         poNCDFDS->DefVarDeflate(nZId, true);
    1055             :     }
    1056             : 
    1057             :     // For Byte data add signed/unsigned info.
    1058         182 :     if (eDataType == GDT_Byte || eDataType == GDT_Int8)
    1059             :     {
    1060          84 :         if (bDefineVar)
    1061             :         {
    1062             :             // Only add attributes if creating variable.
    1063             :             // For unsigned NC_BYTE (except NC4 format),
    1064             :             // add valid_range and _Unsigned ( defined in CF-1 and NUG ).
    1065          76 :             if (nc_datatype == NC_BYTE && poNCDFDS->eFormat != NCDF_FORMAT_NC4)
    1066             :             {
    1067          73 :                 CPLDebug("GDAL_netCDF",
    1068             :                          "adding valid_range attributes for Byte Band");
    1069          73 :                 short l_adfValidRange[2] = {0, 0};
    1070             :                 int status;
    1071          73 :                 if (bSignedData || eDataType == GDT_Int8)
    1072             :                 {
    1073           7 :                     l_adfValidRange[0] = -128;
    1074           7 :                     l_adfValidRange[1] = 127;
    1075           7 :                     status =
    1076           7 :                         nc_put_att_text(cdfid, nZId, "_Unsigned", 5, "false");
    1077             :                 }
    1078             :                 else
    1079             :                 {
    1080          66 :                     l_adfValidRange[0] = 0;
    1081          66 :                     l_adfValidRange[1] = 255;
    1082             :                     status =
    1083          66 :                         nc_put_att_text(cdfid, nZId, "_Unsigned", 4, "true");
    1084             :                 }
    1085          73 :                 NCDF_ERR(status);
    1086          73 :                 status = nc_put_att_short(cdfid, nZId, "valid_range", NC_SHORT,
    1087             :                                           2, l_adfValidRange);
    1088          73 :                 NCDF_ERR(status);
    1089             :             }
    1090             :         }
    1091             :     }
    1092             : 
    1093         182 :     if (nc_datatype != NC_BYTE && nc_datatype != NC_CHAR &&
    1094         101 :         nc_datatype != NC_UBYTE)
    1095             :     {
    1096             :         // Set default nodata.
    1097          98 :         bool bIgnored = false;
    1098             :         double dfNoData =
    1099          98 :             NCDFGetDefaultNoDataValue(cdfid, nZId, nc_datatype, bIgnored);
    1100             : #ifdef NCDF_DEBUG
    1101             :         CPLDebug("GDAL_netCDF", "SetNoDataValue(%f) default", dfNoData);
    1102             : #endif
    1103          98 :         netCDFRasterBand::SetNoDataValue(dfNoData);
    1104             :     }
    1105             : 
    1106         182 :     SetBlockSize();
    1107             : }
    1108             : 
    1109             : /************************************************************************/
    1110             : /*                         ~netCDFRasterBand()                          */
    1111             : /************************************************************************/
    1112             : 
    1113        1326 : netCDFRasterBand::~netCDFRasterBand()
    1114             : {
    1115         663 :     netCDFRasterBand::FlushCache(true);
    1116         663 :     CPLFree(panBandZPos);
    1117         663 :     CPLFree(panBandZLev);
    1118        1326 : }
    1119             : 
    1120             : /************************************************************************/
    1121             : /*                          GetMetadata()                               */
    1122             : /************************************************************************/
    1123             : 
    1124          50 : char **netCDFRasterBand::GetMetadata(const char *pszDomain)
    1125             : {
    1126          50 :     if (!m_bCreateMetadataFromOtherVarsDone)
    1127          48 :         CreateMetadataFromOtherVars();
    1128          50 :     return GDALPamRasterBand::GetMetadata(pszDomain);
    1129             : }
    1130             : 
    1131             : /************************************************************************/
    1132             : /*                        GetMetadataItem()                             */
    1133             : /************************************************************************/
    1134             : 
    1135         555 : const char *netCDFRasterBand::GetMetadataItem(const char *pszName,
    1136             :                                               const char *pszDomain)
    1137             : {
    1138         555 :     if (!m_bCreateMetadataFromOtherVarsDone &&
    1139         539 :         STARTS_WITH(pszName, "NETCDF_DIM_") &&
    1140           1 :         (!pszDomain || pszDomain[0] == 0))
    1141           1 :         CreateMetadataFromOtherVars();
    1142         555 :     return GDALPamRasterBand::GetMetadataItem(pszName, pszDomain);
    1143             : }
    1144             : 
    1145             : /************************************************************************/
    1146             : /*                        SetMetadataItem()                             */
    1147             : /************************************************************************/
    1148             : 
    1149           7 : CPLErr netCDFRasterBand::SetMetadataItem(const char *pszName,
    1150             :                                          const char *pszValue,
    1151             :                                          const char *pszDomain)
    1152             : {
    1153           9 :     if (GetAccess() == GA_Update &&
    1154           9 :         (pszDomain == nullptr || pszDomain[0] == '\0') && pszValue != nullptr)
    1155             :     {
    1156             :         // Same logic as in CopyMetadata()
    1157             : 
    1158           2 :         const char *const papszIgnoreBand[] = {
    1159             :             CF_ADD_OFFSET,  CF_SCALE_FACTOR, "valid_range", "_Unsigned",
    1160             :             NCDF_FillValue, "coordinates",   nullptr};
    1161             :         // Do not copy varname, stats, NETCDF_DIM_*, nodata
    1162             :         // and items in papszIgnoreBand.
    1163           6 :         if (STARTS_WITH(pszName, "NETCDF_VARNAME") ||
    1164           2 :             STARTS_WITH(pszName, "STATISTICS_") ||
    1165           2 :             STARTS_WITH(pszName, "NETCDF_DIM_") ||
    1166           2 :             STARTS_WITH(pszName, "missing_value") ||
    1167           6 :             STARTS_WITH(pszName, "_FillValue") ||
    1168           2 :             CSLFindString(papszIgnoreBand, pszName) != -1)
    1169             :         {
    1170             :             // do nothing
    1171             :         }
    1172             :         else
    1173             :         {
    1174           2 :             cpl::down_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
    1175             : 
    1176           2 :             if (!NCDFPutAttr(cdfid, nZId, pszName, pszValue))
    1177           2 :                 return CE_Failure;
    1178             :         }
    1179             :     }
    1180             : 
    1181           5 :     return GDALPamRasterBand::SetMetadataItem(pszName, pszValue, pszDomain);
    1182             : }
    1183             : 
    1184             : /************************************************************************/
    1185             : /*                          SetMetadata()                               */
    1186             : /************************************************************************/
    1187             : 
    1188           2 : CPLErr netCDFRasterBand::SetMetadata(char **papszMD, const char *pszDomain)
    1189             : {
    1190           4 :     if (GetAccess() == GA_Update &&
    1191           2 :         (pszDomain == nullptr || pszDomain[0] == '\0'))
    1192             :     {
    1193             :         // We don't handle metadata item removal for now
    1194           4 :         for (const char *const *papszIter = papszMD; papszIter && *papszIter;
    1195             :              ++papszIter)
    1196             :         {
    1197           2 :             char *pszName = nullptr;
    1198           2 :             const char *pszValue = CPLParseNameValue(*papszIter, &pszName);
    1199           2 :             if (pszName && pszValue)
    1200           2 :                 SetMetadataItem(pszName, pszValue);
    1201           2 :             CPLFree(pszName);
    1202             :         }
    1203             :     }
    1204           2 :     return GDALPamRasterBand::SetMetadata(papszMD, pszDomain);
    1205             : }
    1206             : 
    1207             : /************************************************************************/
    1208             : /*                             GetOffset()                              */
    1209             : /************************************************************************/
    1210          50 : double netCDFRasterBand::GetOffset(int *pbSuccess)
    1211             : {
    1212          50 :     if (pbSuccess != nullptr)
    1213          45 :         *pbSuccess = static_cast<int>(m_bHaveOffset);
    1214             : 
    1215          50 :     return m_dfOffset;
    1216             : }
    1217             : 
    1218             : /************************************************************************/
    1219             : /*                             SetOffset()                              */
    1220             : /************************************************************************/
    1221           1 : CPLErr netCDFRasterBand::SetOffset(double dfNewOffset)
    1222             : {
    1223           2 :     CPLMutexHolderD(&hNCMutex);
    1224             : 
    1225             :     // Write value if in update mode.
    1226           1 :     if (poDS->GetAccess() == GA_Update)
    1227             :     {
    1228             :         // Make sure we are in define mode.
    1229           1 :         static_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
    1230             : 
    1231           1 :         const int status = nc_put_att_double(cdfid, nZId, CF_ADD_OFFSET,
    1232             :                                              NC_DOUBLE, 1, &dfNewOffset);
    1233             : 
    1234           1 :         NCDF_ERR(status);
    1235           1 :         if (status == NC_NOERR)
    1236             :         {
    1237           1 :             SetOffsetNoUpdate(dfNewOffset);
    1238           1 :             return CE_None;
    1239             :         }
    1240             : 
    1241           0 :         return CE_Failure;
    1242             :     }
    1243             : 
    1244           0 :     SetOffsetNoUpdate(dfNewOffset);
    1245           0 :     return CE_None;
    1246             : }
    1247             : 
    1248             : /************************************************************************/
    1249             : /*                         SetOffsetNoUpdate()                          */
    1250             : /************************************************************************/
    1251          17 : void netCDFRasterBand::SetOffsetNoUpdate(double dfVal)
    1252             : {
    1253          17 :     m_dfOffset = dfVal;
    1254          17 :     m_bHaveOffset = true;
    1255          17 : }
    1256             : 
    1257             : /************************************************************************/
    1258             : /*                              GetScale()                              */
    1259             : /************************************************************************/
    1260          50 : double netCDFRasterBand::GetScale(int *pbSuccess)
    1261             : {
    1262          50 :     if (pbSuccess != nullptr)
    1263          45 :         *pbSuccess = static_cast<int>(m_bHaveScale);
    1264             : 
    1265          50 :     return m_dfScale;
    1266             : }
    1267             : 
    1268             : /************************************************************************/
    1269             : /*                              SetScale()                              */
    1270             : /************************************************************************/
    1271           1 : CPLErr netCDFRasterBand::SetScale(double dfNewScale)
    1272             : {
    1273           2 :     CPLMutexHolderD(&hNCMutex);
    1274             : 
    1275             :     // Write value if in update mode.
    1276           1 :     if (poDS->GetAccess() == GA_Update)
    1277             :     {
    1278             :         // Make sure we are in define mode.
    1279           1 :         static_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
    1280             : 
    1281           1 :         const int status = nc_put_att_double(cdfid, nZId, CF_SCALE_FACTOR,
    1282             :                                              NC_DOUBLE, 1, &dfNewScale);
    1283             : 
    1284           1 :         NCDF_ERR(status);
    1285           1 :         if (status == NC_NOERR)
    1286             :         {
    1287           1 :             SetScaleNoUpdate(dfNewScale);
    1288           1 :             return CE_None;
    1289             :         }
    1290             : 
    1291           0 :         return CE_Failure;
    1292             :     }
    1293             : 
    1294           0 :     SetScaleNoUpdate(dfNewScale);
    1295           0 :     return CE_None;
    1296             : }
    1297             : 
    1298             : /************************************************************************/
    1299             : /*                         SetScaleNoUpdate()                           */
    1300             : /************************************************************************/
    1301          21 : void netCDFRasterBand::SetScaleNoUpdate(double dfVal)
    1302             : {
    1303          21 :     m_dfScale = dfVal;
    1304          21 :     m_bHaveScale = true;
    1305          21 : }
    1306             : 
    1307             : /************************************************************************/
    1308             : /*                            GetUnitType()                             */
    1309             : /************************************************************************/
    1310             : 
    1311          22 : const char *netCDFRasterBand::GetUnitType()
    1312             : 
    1313             : {
    1314          22 :     if (!m_osUnitType.empty())
    1315           6 :         return m_osUnitType;
    1316             : 
    1317          16 :     return GDALRasterBand::GetUnitType();
    1318             : }
    1319             : 
    1320             : /************************************************************************/
    1321             : /*                           SetUnitType()                              */
    1322             : /************************************************************************/
    1323             : 
    1324           1 : CPLErr netCDFRasterBand::SetUnitType(const char *pszNewValue)
    1325             : 
    1326             : {
    1327           2 :     CPLMutexHolderD(&hNCMutex);
    1328             : 
    1329           2 :     const std::string osUnitType = (pszNewValue != nullptr ? pszNewValue : "");
    1330             : 
    1331           1 :     if (!osUnitType.empty())
    1332             :     {
    1333             :         // Write value if in update mode.
    1334           1 :         if (poDS->GetAccess() == GA_Update)
    1335             :         {
    1336             :             // Make sure we are in define mode.
    1337           1 :             static_cast<netCDFDataset *>(poDS)->SetDefineMode(TRUE);
    1338             : 
    1339           1 :             const int status = nc_put_att_text(
    1340             :                 cdfid, nZId, CF_UNITS, osUnitType.size(), osUnitType.c_str());
    1341             : 
    1342           1 :             NCDF_ERR(status);
    1343           1 :             if (status == NC_NOERR)
    1344             :             {
    1345           1 :                 SetUnitTypeNoUpdate(pszNewValue);
    1346           1 :                 return CE_None;
    1347             :             }
    1348             : 
    1349           0 :             return CE_Failure;
    1350             :         }
    1351             :     }
    1352             : 
    1353           0 :     SetUnitTypeNoUpdate(pszNewValue);
    1354             : 
    1355           0 :     return CE_None;
    1356             : }
    1357             : 
    1358             : /************************************************************************/
    1359             : /*                       SetUnitTypeNoUpdate()                          */
    1360             : /************************************************************************/
    1361             : 
    1362         482 : void netCDFRasterBand::SetUnitTypeNoUpdate(const char *pszNewValue)
    1363             : {
    1364         482 :     m_osUnitType = (pszNewValue != nullptr ? pszNewValue : "");
    1365         482 : }
    1366             : 
    1367             : /************************************************************************/
    1368             : /*                           GetNoDataValue()                           */
    1369             : /************************************************************************/
    1370             : 
    1371         162 : double netCDFRasterBand::GetNoDataValue(int *pbSuccess)
    1372             : 
    1373             : {
    1374         162 :     if (m_bNoDataSetAsInt64)
    1375             :     {
    1376           0 :         if (pbSuccess)
    1377           0 :             *pbSuccess = TRUE;
    1378           0 :         return GDALGetNoDataValueCastToDouble(m_nNodataValueInt64);
    1379             :     }
    1380             : 
    1381         162 :     if (m_bNoDataSetAsUInt64)
    1382             :     {
    1383           0 :         if (pbSuccess)
    1384           0 :             *pbSuccess = TRUE;
    1385           0 :         return GDALGetNoDataValueCastToDouble(m_nNodataValueUInt64);
    1386             :     }
    1387             : 
    1388         162 :     if (m_bNoDataSet)
    1389             :     {
    1390         125 :         if (pbSuccess)
    1391         109 :             *pbSuccess = TRUE;
    1392         125 :         return m_dfNoDataValue;
    1393             :     }
    1394             : 
    1395          37 :     return GDALPamRasterBand::GetNoDataValue(pbSuccess);
    1396             : }
    1397             : 
    1398             : /************************************************************************/
    1399             : /*                        GetNoDataValueAsInt64()                       */
    1400             : /************************************************************************/
    1401             : 
    1402           4 : int64_t netCDFRasterBand::GetNoDataValueAsInt64(int *pbSuccess)
    1403             : 
    1404             : {
    1405           4 :     if (m_bNoDataSetAsInt64)
    1406             :     {
    1407           4 :         if (pbSuccess)
    1408           4 :             *pbSuccess = TRUE;
    1409             : 
    1410           4 :         return m_nNodataValueInt64;
    1411             :     }
    1412             : 
    1413           0 :     return GDALPamRasterBand::GetNoDataValueAsInt64(pbSuccess);
    1414             : }
    1415             : 
    1416             : /************************************************************************/
    1417             : /*                        GetNoDataValueAsUInt64()                      */
    1418             : /************************************************************************/
    1419             : 
    1420           4 : uint64_t netCDFRasterBand::GetNoDataValueAsUInt64(int *pbSuccess)
    1421             : 
    1422             : {
    1423           4 :     if (m_bNoDataSetAsUInt64)
    1424             :     {
    1425           4 :         if (pbSuccess)
    1426           4 :             *pbSuccess = TRUE;
    1427             : 
    1428           4 :         return m_nNodataValueUInt64;
    1429             :     }
    1430             : 
    1431           0 :     return GDALPamRasterBand::GetNoDataValueAsUInt64(pbSuccess);
    1432             : }
    1433             : 
    1434             : /************************************************************************/
    1435             : /*                           SetNoDataValue()                           */
    1436             : /************************************************************************/
    1437             : 
    1438         134 : CPLErr netCDFRasterBand::SetNoDataValue(double dfNoData)
    1439             : 
    1440             : {
    1441         268 :     CPLMutexHolderD(&hNCMutex);
    1442             : 
    1443             :     // If already set to new value, don't do anything.
    1444         134 :     if (m_bNoDataSet && CPLIsEqual(dfNoData, m_dfNoDataValue))
    1445          19 :         return CE_None;
    1446             : 
    1447             :     // Write value if in update mode.
    1448         115 :     if (poDS->GetAccess() == GA_Update)
    1449             :     {
    1450             :         // netcdf-4 does not allow to set _FillValue after leaving define mode,
    1451             :         // but it is ok if variable has not been written to, so only print
    1452             :         // debug. See bug #4484.
    1453         125 :         if (m_bNoDataSet &&
    1454          10 :             !cpl::down_cast<netCDFDataset *>(poDS)->GetDefineMode())
    1455             :         {
    1456           0 :             CPLDebug("GDAL_netCDF",
    1457             :                      "Setting NoDataValue to %.17g (previously set to %.17g) "
    1458             :                      "but file is no longer in define mode (id #%d, band #%d)",
    1459             :                      dfNoData, m_dfNoDataValue, cdfid, nBand);
    1460             :         }
    1461             : #ifdef NCDF_DEBUG
    1462             :         else
    1463             :         {
    1464             :             CPLDebug("GDAL_netCDF",
    1465             :                      "Setting NoDataValue to %.17g (id #%d, band #%d)",
    1466             :                      dfNoData, cdfid, nBand);
    1467             :         }
    1468             : #endif
    1469             :         // Make sure we are in define mode.
    1470         115 :         cpl::down_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
    1471             : 
    1472             :         int status;
    1473         115 :         if (eDataType == GDT_Byte)
    1474             :         {
    1475           6 :             if (bSignedData)
    1476             :             {
    1477           0 :                 signed char cNoDataValue = static_cast<signed char>(dfNoData);
    1478           0 :                 status = nc_put_att_schar(cdfid, nZId, NCDF_FillValue,
    1479             :                                           nc_datatype, 1, &cNoDataValue);
    1480             :             }
    1481             :             else
    1482             :             {
    1483           6 :                 const unsigned char ucNoDataValue =
    1484           6 :                     static_cast<unsigned char>(dfNoData);
    1485           6 :                 status = nc_put_att_uchar(cdfid, nZId, NCDF_FillValue,
    1486             :                                           nc_datatype, 1, &ucNoDataValue);
    1487             :             }
    1488             :         }
    1489         109 :         else if (eDataType == GDT_Int16)
    1490             :         {
    1491          14 :             short nsNoDataValue = static_cast<short>(dfNoData);
    1492          14 :             status = nc_put_att_short(cdfid, nZId, NCDF_FillValue, nc_datatype,
    1493             :                                       1, &nsNoDataValue);
    1494             :         }
    1495          95 :         else if (eDataType == GDT_Int32)
    1496             :         {
    1497          27 :             int nNoDataValue = static_cast<int>(dfNoData);
    1498          27 :             status = nc_put_att_int(cdfid, nZId, NCDF_FillValue, nc_datatype, 1,
    1499             :                                     &nNoDataValue);
    1500             :         }
    1501          68 :         else if (eDataType == GDT_Float32)
    1502             :         {
    1503          31 :             float fNoDataValue = static_cast<float>(dfNoData);
    1504          31 :             status = nc_put_att_float(cdfid, nZId, NCDF_FillValue, nc_datatype,
    1505             :                                       1, &fNoDataValue);
    1506             :         }
    1507          43 :         else if (eDataType == GDT_UInt16 &&
    1508           6 :                  cpl::down_cast<netCDFDataset *>(poDS)->eFormat ==
    1509             :                      NCDF_FORMAT_NC4)
    1510             :         {
    1511           6 :             unsigned short usNoDataValue =
    1512           6 :                 static_cast<unsigned short>(dfNoData);
    1513           6 :             status = nc_put_att_ushort(cdfid, nZId, NCDF_FillValue, nc_datatype,
    1514             :                                        1, &usNoDataValue);
    1515             :         }
    1516          38 :         else if (eDataType == GDT_UInt32 &&
    1517           7 :                  cpl::down_cast<netCDFDataset *>(poDS)->eFormat ==
    1518             :                      NCDF_FORMAT_NC4)
    1519             :         {
    1520           7 :             unsigned int unNoDataValue = static_cast<unsigned int>(dfNoData);
    1521           7 :             status = nc_put_att_uint(cdfid, nZId, NCDF_FillValue, nc_datatype,
    1522             :                                      1, &unNoDataValue);
    1523             :         }
    1524             :         else
    1525             :         {
    1526          24 :             status = nc_put_att_double(cdfid, nZId, NCDF_FillValue, nc_datatype,
    1527             :                                        1, &dfNoData);
    1528             :         }
    1529             : 
    1530         115 :         NCDF_ERR(status);
    1531             : 
    1532             :         // Update status if write worked.
    1533         115 :         if (status == NC_NOERR)
    1534             :         {
    1535         115 :             SetNoDataValueNoUpdate(dfNoData);
    1536         115 :             return CE_None;
    1537             :         }
    1538             : 
    1539           0 :         return CE_Failure;
    1540             :     }
    1541             : 
    1542           0 :     SetNoDataValueNoUpdate(dfNoData);
    1543           0 :     return CE_None;
    1544             : }
    1545             : 
    1546             : /************************************************************************/
    1547             : /*                       SetNoDataValueNoUpdate()                       */
    1548             : /************************************************************************/
    1549             : 
    1550         438 : void netCDFRasterBand::SetNoDataValueNoUpdate(double dfNoData)
    1551             : {
    1552         438 :     m_dfNoDataValue = dfNoData;
    1553         438 :     m_bNoDataSet = true;
    1554         438 :     m_bNoDataSetAsInt64 = false;
    1555         438 :     m_bNoDataSetAsUInt64 = false;
    1556         438 : }
    1557             : 
    1558             : /************************************************************************/
    1559             : /*                        SetNoDataValueAsInt64()                       */
    1560             : /************************************************************************/
    1561             : 
    1562           3 : CPLErr netCDFRasterBand::SetNoDataValueAsInt64(int64_t nNoData)
    1563             : 
    1564             : {
    1565           6 :     CPLMutexHolderD(&hNCMutex);
    1566             : 
    1567             :     // If already set to new value, don't do anything.
    1568           3 :     if (m_bNoDataSetAsInt64 && nNoData == m_nNodataValueInt64)
    1569           0 :         return CE_None;
    1570             : 
    1571             :     // Write value if in update mode.
    1572           3 :     if (poDS->GetAccess() == GA_Update)
    1573             :     {
    1574             :         // netcdf-4 does not allow to set NCDF_FillValue after leaving define mode,
    1575             :         // but it is ok if variable has not been written to, so only print
    1576             :         // debug. See bug #4484.
    1577           3 :         if (m_bNoDataSetAsInt64 &&
    1578           0 :             !cpl::down_cast<netCDFDataset *>(poDS)->GetDefineMode())
    1579             :         {
    1580           0 :             CPLDebug("GDAL_netCDF",
    1581             :                      "Setting NoDataValue to " CPL_FRMT_GIB
    1582             :                      " (previously set to " CPL_FRMT_GIB ") "
    1583             :                      "but file is no longer in define mode (id #%d, band #%d)",
    1584             :                      static_cast<GIntBig>(nNoData),
    1585           0 :                      static_cast<GIntBig>(m_nNodataValueInt64), cdfid, nBand);
    1586             :         }
    1587             : #ifdef NCDF_DEBUG
    1588             :         else
    1589             :         {
    1590             :             CPLDebug("GDAL_netCDF",
    1591             :                      "Setting NoDataValue to " CPL_FRMT_GIB
    1592             :                      " (id #%d, band #%d)",
    1593             :                      static_cast<GIntBig>(nNoData), cdfid, nBand);
    1594             :         }
    1595             : #endif
    1596             :         // Make sure we are in define mode.
    1597           3 :         cpl::down_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
    1598             : 
    1599             :         int status;
    1600           6 :         if (eDataType == GDT_Int64 &&
    1601           3 :             cpl::down_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
    1602             :         {
    1603           3 :             long long tmp = static_cast<long long>(nNoData);
    1604           3 :             status = nc_put_att_longlong(cdfid, nZId, NCDF_FillValue,
    1605             :                                          nc_datatype, 1, &tmp);
    1606             :         }
    1607             :         else
    1608             :         {
    1609           0 :             double dfNoData = static_cast<double>(nNoData);
    1610           0 :             status = nc_put_att_double(cdfid, nZId, NCDF_FillValue, nc_datatype,
    1611             :                                        1, &dfNoData);
    1612             :         }
    1613             : 
    1614           3 :         NCDF_ERR(status);
    1615             : 
    1616             :         // Update status if write worked.
    1617           3 :         if (status == NC_NOERR)
    1618             :         {
    1619           3 :             SetNoDataValueNoUpdate(nNoData);
    1620           3 :             return CE_None;
    1621             :         }
    1622             : 
    1623           0 :         return CE_Failure;
    1624             :     }
    1625             : 
    1626           0 :     SetNoDataValueNoUpdate(nNoData);
    1627           0 :     return CE_None;
    1628             : }
    1629             : 
    1630             : /************************************************************************/
    1631             : /*                       SetNoDataValueNoUpdate()                       */
    1632             : /************************************************************************/
    1633             : 
    1634          11 : void netCDFRasterBand::SetNoDataValueNoUpdate(int64_t nNoData)
    1635             : {
    1636          11 :     m_nNodataValueInt64 = nNoData;
    1637          11 :     m_bNoDataSet = false;
    1638          11 :     m_bNoDataSetAsInt64 = true;
    1639          11 :     m_bNoDataSetAsUInt64 = false;
    1640          11 : }
    1641             : 
    1642             : /************************************************************************/
    1643             : /*                        SetNoDataValueAsUInt64()                      */
    1644             : /************************************************************************/
    1645             : 
    1646           3 : CPLErr netCDFRasterBand::SetNoDataValueAsUInt64(uint64_t nNoData)
    1647             : 
    1648             : {
    1649           6 :     CPLMutexHolderD(&hNCMutex);
    1650             : 
    1651             :     // If already set to new value, don't do anything.
    1652           3 :     if (m_bNoDataSetAsUInt64 && nNoData == m_nNodataValueUInt64)
    1653           0 :         return CE_None;
    1654             : 
    1655             :     // Write value if in update mode.
    1656           3 :     if (poDS->GetAccess() == GA_Update)
    1657             :     {
    1658             :         // netcdf-4 does not allow to set _FillValue after leaving define mode,
    1659             :         // but it is ok if variable has not been written to, so only print
    1660             :         // debug. See bug #4484.
    1661           3 :         if (m_bNoDataSetAsUInt64 &&
    1662           0 :             !cpl::down_cast<netCDFDataset *>(poDS)->GetDefineMode())
    1663             :         {
    1664           0 :             CPLDebug("GDAL_netCDF",
    1665             :                      "Setting NoDataValue to " CPL_FRMT_GUIB
    1666             :                      " (previously set to " CPL_FRMT_GUIB ") "
    1667             :                      "but file is no longer in define mode (id #%d, band #%d)",
    1668             :                      static_cast<GUIntBig>(nNoData),
    1669           0 :                      static_cast<GUIntBig>(m_nNodataValueUInt64), cdfid, nBand);
    1670             :         }
    1671             : #ifdef NCDF_DEBUG
    1672             :         else
    1673             :         {
    1674             :             CPLDebug("GDAL_netCDF",
    1675             :                      "Setting NoDataValue to " CPL_FRMT_GUIB
    1676             :                      " (id #%d, band #%d)",
    1677             :                      static_cast<GUIntBig>(nNoData), cdfid, nBand);
    1678             :         }
    1679             : #endif
    1680             :         // Make sure we are in define mode.
    1681           3 :         cpl::down_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
    1682             : 
    1683             :         int status;
    1684           6 :         if (eDataType == GDT_UInt64 &&
    1685           3 :             cpl::down_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
    1686             :         {
    1687           3 :             unsigned long long tmp = static_cast<long long>(nNoData);
    1688           3 :             status = nc_put_att_ulonglong(cdfid, nZId, NCDF_FillValue,
    1689             :                                           nc_datatype, 1, &tmp);
    1690             :         }
    1691             :         else
    1692             :         {
    1693           0 :             double dfNoData = static_cast<double>(nNoData);
    1694           0 :             status = nc_put_att_double(cdfid, nZId, NCDF_FillValue, nc_datatype,
    1695             :                                        1, &dfNoData);
    1696             :         }
    1697             : 
    1698           3 :         NCDF_ERR(status);
    1699             : 
    1700             :         // Update status if write worked.
    1701           3 :         if (status == NC_NOERR)
    1702             :         {
    1703           3 :             SetNoDataValueNoUpdate(nNoData);
    1704           3 :             return CE_None;
    1705             :         }
    1706             : 
    1707           0 :         return CE_Failure;
    1708             :     }
    1709             : 
    1710           0 :     SetNoDataValueNoUpdate(nNoData);
    1711           0 :     return CE_None;
    1712             : }
    1713             : 
    1714             : /************************************************************************/
    1715             : /*                       SetNoDataValueNoUpdate()                       */
    1716             : /************************************************************************/
    1717             : 
    1718          10 : void netCDFRasterBand::SetNoDataValueNoUpdate(uint64_t nNoData)
    1719             : {
    1720          10 :     m_nNodataValueUInt64 = nNoData;
    1721          10 :     m_bNoDataSet = false;
    1722          10 :     m_bNoDataSetAsInt64 = false;
    1723          10 :     m_bNoDataSetAsUInt64 = true;
    1724          10 : }
    1725             : 
    1726             : /************************************************************************/
    1727             : /*                        DeleteNoDataValue()                           */
    1728             : /************************************************************************/
    1729             : 
    1730             : #ifdef notdef
    1731             : CPLErr netCDFRasterBand::DeleteNoDataValue()
    1732             : 
    1733             : {
    1734             :     CPLMutexHolderD(&hNCMutex);
    1735             : 
    1736             :     if (!bNoDataSet)
    1737             :         return CE_None;
    1738             : 
    1739             :     // Write value if in update mode.
    1740             :     if (poDS->GetAccess() == GA_Update)
    1741             :     {
    1742             :         // Make sure we are in define mode.
    1743             :         static_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
    1744             : 
    1745             :         status = nc_del_att(cdfid, nZId, NCDF_FillValue);
    1746             : 
    1747             :         NCDF_ERR(status);
    1748             : 
    1749             :         // Update status if write worked.
    1750             :         if (status == NC_NOERR)
    1751             :         {
    1752             :             dfNoDataValue = 0.0;
    1753             :             bNoDataSet = false;
    1754             :             return CE_None;
    1755             :         }
    1756             : 
    1757             :         return CE_Failure;
    1758             :     }
    1759             : 
    1760             :     dfNoDataValue = 0.0;
    1761             :     bNoDataSet = false;
    1762             :     return CE_None;
    1763             : }
    1764             : #endif
    1765             : 
    1766             : /************************************************************************/
    1767             : /*                           SerializeToXML()                           */
    1768             : /************************************************************************/
    1769             : 
    1770           5 : CPLXMLNode *netCDFRasterBand::SerializeToXML(const char * /* pszUnused */)
    1771             : {
    1772             :     // Overridden from GDALPamDataset to add only band histogram
    1773             :     // and statistics. See bug #4244.
    1774           5 :     if (psPam == nullptr)
    1775           0 :         return nullptr;
    1776             : 
    1777             :     // Setup root node and attributes.
    1778             :     CPLXMLNode *psTree =
    1779           5 :         CPLCreateXMLNode(nullptr, CXT_Element, "PAMRasterBand");
    1780             : 
    1781           5 :     if (GetBand() > 0)
    1782             :     {
    1783          10 :         CPLString oFmt;
    1784           5 :         CPLSetXMLValue(psTree, "#band", oFmt.Printf("%d", GetBand()));
    1785             :     }
    1786             : 
    1787             :     // Histograms.
    1788           5 :     if (psPam->psSavedHistograms != nullptr)
    1789           1 :         CPLAddXMLChild(psTree, CPLCloneXMLTree(psPam->psSavedHistograms));
    1790             : 
    1791             :     // Metadata (statistics only).
    1792           5 :     GDALMultiDomainMetadata oMDMDStats;
    1793           5 :     const char *papszMDStats[] = {"STATISTICS_MINIMUM", "STATISTICS_MAXIMUM",
    1794             :                                   "STATISTICS_MEAN", "STATISTICS_STDDEV",
    1795             :                                   nullptr};
    1796          25 :     for (int i = 0; i < CSLCount(papszMDStats); i++)
    1797             :     {
    1798          20 :         const char *pszMDI = GetMetadataItem(papszMDStats[i]);
    1799          20 :         if (pszMDI)
    1800           4 :             oMDMDStats.SetMetadataItem(papszMDStats[i], pszMDI);
    1801             :     }
    1802           5 :     CPLXMLNode *psMD = oMDMDStats.Serialize();
    1803             : 
    1804           5 :     if (psMD != nullptr)
    1805             :     {
    1806           1 :         if (psMD->psChild == nullptr)
    1807           0 :             CPLDestroyXMLNode(psMD);
    1808             :         else
    1809           1 :             CPLAddXMLChild(psTree, psMD);
    1810             :     }
    1811             : 
    1812             :     // We don't want to return anything if we had no metadata to attach.
    1813           5 :     if (psTree->psChild == nullptr || psTree->psChild->psNext == nullptr)
    1814             :     {
    1815           3 :         CPLDestroyXMLNode(psTree);
    1816           3 :         psTree = nullptr;
    1817             :     }
    1818             : 
    1819           5 :     return psTree;
    1820             : }
    1821             : 
    1822             : /************************************************************************/
    1823             : /*               Get1DVariableIndexedByDimension()                      */
    1824             : /************************************************************************/
    1825             : 
    1826          81 : static int Get1DVariableIndexedByDimension(int cdfid, int nDimId,
    1827             :                                            const char *pszDimName,
    1828             :                                            bool bVerboseError, int *pnGroupID)
    1829             : {
    1830          81 :     *pnGroupID = -1;
    1831          81 :     int nVarID = -1;
    1832             :     // First try to find a variable whose name is identical to the dimension
    1833             :     // name, and check that it is indeed indexed by this dimension
    1834          81 :     if (NCDFResolveVar(cdfid, pszDimName, pnGroupID, &nVarID) == CE_None)
    1835             :     {
    1836          67 :         int nDimCountOfVariable = 0;
    1837          67 :         nc_inq_varndims(*pnGroupID, nVarID, &nDimCountOfVariable);
    1838          67 :         if (nDimCountOfVariable == 1)
    1839             :         {
    1840          67 :             int nDimIdOfVariable = -1;
    1841          67 :             nc_inq_vardimid(*pnGroupID, nVarID, &nDimIdOfVariable);
    1842          67 :             if (nDimIdOfVariable == nDimId)
    1843             :             {
    1844          67 :                 return nVarID;
    1845             :             }
    1846             :         }
    1847             :     }
    1848             : 
    1849             :     // Otherwise iterate over the variables to find potential candidates
    1850             :     // TODO: should be modified to search also in other groups using the same
    1851             :     //       logic than in NCDFResolveVar(), but maybe not needed if it's a
    1852             :     //       very rare case? and I think this is not CF compliant.
    1853          14 :     int nvars = 0;
    1854          14 :     CPL_IGNORE_RET_VAL(nc_inq(cdfid, nullptr, &nvars, nullptr, nullptr));
    1855             : 
    1856          14 :     int nCountCandidateVars = 0;
    1857          14 :     int nCandidateVarID = -1;
    1858          65 :     for (int k = 0; k < nvars; k++)
    1859             :     {
    1860          51 :         int nDimCountOfVariable = 0;
    1861          51 :         nc_inq_varndims(cdfid, k, &nDimCountOfVariable);
    1862          51 :         if (nDimCountOfVariable == 1)
    1863             :         {
    1864          27 :             int nDimIdOfVariable = -1;
    1865          27 :             nc_inq_vardimid(cdfid, k, &nDimIdOfVariable);
    1866          27 :             if (nDimIdOfVariable == nDimId)
    1867             :             {
    1868           7 :                 nCountCandidateVars++;
    1869           7 :                 nCandidateVarID = k;
    1870             :             }
    1871             :         }
    1872             :     }
    1873          14 :     if (nCountCandidateVars > 1)
    1874             :     {
    1875           1 :         if (bVerboseError)
    1876             :         {
    1877           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    1878             :                      "Several 1D variables are indexed by dimension %s",
    1879             :                      pszDimName);
    1880             :         }
    1881           1 :         *pnGroupID = -1;
    1882           1 :         return -1;
    1883             :     }
    1884          13 :     else if (nCandidateVarID < 0)
    1885             :     {
    1886           8 :         if (bVerboseError)
    1887             :         {
    1888           8 :             CPLError(CE_Warning, CPLE_AppDefined,
    1889             :                      "No 1D variable is indexed by dimension %s", pszDimName);
    1890             :         }
    1891             :     }
    1892          13 :     *pnGroupID = cdfid;
    1893          13 :     return nCandidateVarID;
    1894             : }
    1895             : 
    1896             : /************************************************************************/
    1897             : /*                      CreateMetadataFromAttributes()                  */
    1898             : /************************************************************************/
    1899             : 
    1900         481 : void netCDFRasterBand::CreateMetadataFromAttributes()
    1901             : {
    1902         481 :     char szVarName[NC_MAX_NAME + 1] = {};
    1903         481 :     int status = nc_inq_varname(cdfid, nZId, szVarName);
    1904         481 :     NCDF_ERR(status);
    1905             : 
    1906         481 :     GDALPamRasterBand::SetMetadataItem("NETCDF_VARNAME", szVarName);
    1907             : 
    1908             :     // Get attribute metadata.
    1909         481 :     int nAtt = 0;
    1910         481 :     NCDF_ERR(nc_inq_varnatts(cdfid, nZId, &nAtt));
    1911             : 
    1912        2039 :     for (int i = 0; i < nAtt; i++)
    1913             :     {
    1914        1558 :         char szMetaName[NC_MAX_NAME + 1] = {};
    1915        1558 :         status = nc_inq_attname(cdfid, nZId, i, szMetaName);
    1916        1558 :         if (status != NC_NOERR)
    1917          12 :             continue;
    1918             : 
    1919        1558 :         if (GDALPamRasterBand::GetMetadataItem(szMetaName) != nullptr)
    1920             :         {
    1921          12 :             continue;
    1922             :         }
    1923             : 
    1924        1546 :         char *pszMetaValue = nullptr;
    1925        1546 :         if (NCDFGetAttr(cdfid, nZId, szMetaName, &pszMetaValue) == CE_None)
    1926             :         {
    1927        1546 :             GDALPamRasterBand::SetMetadataItem(szMetaName, pszMetaValue);
    1928             :         }
    1929             :         else
    1930             :         {
    1931           0 :             CPLDebug("GDAL_netCDF", "invalid Band metadata %s", szMetaName);
    1932             :         }
    1933             : 
    1934        1546 :         if (pszMetaValue)
    1935             :         {
    1936        1546 :             CPLFree(pszMetaValue);
    1937        1546 :             pszMetaValue = nullptr;
    1938             :         }
    1939             :     }
    1940         481 : }
    1941             : 
    1942             : /************************************************************************/
    1943             : /*                      CreateMetadataFromOtherVars()                   */
    1944             : /************************************************************************/
    1945             : 
    1946          49 : void netCDFRasterBand::CreateMetadataFromOtherVars()
    1947             : 
    1948             : {
    1949          49 :     CPLAssert(!m_bCreateMetadataFromOtherVarsDone);
    1950          49 :     m_bCreateMetadataFromOtherVarsDone = true;
    1951             : 
    1952          49 :     netCDFDataset *l_poDS = cpl::down_cast<netCDFDataset *>(poDS);
    1953          49 :     const int nPamFlagsBackup = l_poDS->nPamFlags;
    1954             : 
    1955             :     // Compute all dimensions from Band number and save in Metadata.
    1956          49 :     int nd = 0;
    1957          49 :     nc_inq_varndims(cdfid, nZId, &nd);
    1958             :     // Compute multidimention band position.
    1959             :     //
    1960             :     // BandPosition = (Total - sum(PastBandLevels) - 1)/sum(remainingLevels)
    1961             :     // if Data[2,3,4,x,y]
    1962             :     //
    1963             :     //  BandPos0 = (nBand) / (3*4)
    1964             :     //  BandPos1 = (nBand - BandPos0*(3*4)) / (4)
    1965             :     //  BandPos2 = (nBand - BandPos0*(3*4)) % (4)
    1966             : 
    1967          49 :     int Sum = 1;
    1968          49 :     if (nd == 3)
    1969             :     {
    1970           5 :         Sum *= panBandZLev[0];
    1971             :     }
    1972             : 
    1973             :     // Loop over non-spatial dimensions.
    1974          49 :     int Taken = 0;
    1975             : 
    1976          89 :     for (int i = 0; i < nd - 2; i++)
    1977             :     {
    1978             :         int result;
    1979          40 :         if (i != nd - 2 - 1)
    1980             :         {
    1981          18 :             Sum = 1;
    1982          37 :             for (int j = i + 1; j < nd - 2; j++)
    1983             :             {
    1984          19 :                 Sum *= panBandZLev[j];
    1985             :             }
    1986          18 :             result = static_cast<int>((nLevel - Taken) / Sum);
    1987             :         }
    1988             :         else
    1989             :         {
    1990          22 :             result = static_cast<int>((nLevel - Taken) % Sum);
    1991             :         }
    1992             : 
    1993          40 :         char szName[NC_MAX_NAME + 1] = {};
    1994          40 :         snprintf(szName, sizeof(szName), "%s",
    1995          40 :                  l_poDS->papszDimName[l_poDS->m_anDimIds[panBandZPos[i]]]);
    1996             : 
    1997             :         char szMetaName[NC_MAX_NAME + 1 + 32];
    1998          40 :         snprintf(szMetaName, sizeof(szMetaName), "NETCDF_DIM_%s", szName);
    1999             : 
    2000          40 :         const int nGroupID = l_poDS->m_anExtraDimGroupIds[i];
    2001          40 :         const int nVarID = l_poDS->m_anExtraDimVarIds[i];
    2002          40 :         if (nVarID < 0)
    2003             :         {
    2004           2 :             GDALPamRasterBand::SetMetadataItem(szMetaName,
    2005             :                                                CPLSPrintf("%d", result + 1));
    2006             :         }
    2007             :         else
    2008             :         {
    2009             :             // TODO: Make sure all the status checks make sense.
    2010             : 
    2011          38 :             nc_type nVarType = NC_NAT;
    2012          38 :             /* status = */ nc_inq_vartype(nGroupID, nVarID, &nVarType);
    2013             : 
    2014          38 :             int nDims = 0;
    2015          38 :             /* status = */ nc_inq_varndims(nGroupID, nVarID, &nDims);
    2016             : 
    2017          38 :             char szMetaTemp[256] = {};
    2018          38 :             if (nDims == 1)
    2019             :             {
    2020          38 :                 size_t count[1] = {1};
    2021          38 :                 size_t start[1] = {static_cast<size_t>(result)};
    2022             : 
    2023          38 :                 switch (nVarType)
    2024             :                 {
    2025           0 :                     case NC_BYTE:
    2026             :                         // TODO: Check for signed/unsigned byte.
    2027             :                         signed char cData;
    2028           0 :                         /* status = */ nc_get_vara_schar(nGroupID, nVarID,
    2029             :                                                          start, count, &cData);
    2030           0 :                         snprintf(szMetaTemp, sizeof(szMetaTemp), "%d", cData);
    2031           0 :                         break;
    2032           0 :                     case NC_SHORT:
    2033             :                         short sData;
    2034           0 :                         /* status = */ nc_get_vara_short(nGroupID, nVarID,
    2035             :                                                          start, count, &sData);
    2036           0 :                         snprintf(szMetaTemp, sizeof(szMetaTemp), "%d", sData);
    2037           0 :                         break;
    2038          19 :                     case NC_INT:
    2039             :                     {
    2040             :                         int nData;
    2041          19 :                         /* status = */ nc_get_vara_int(nGroupID, nVarID, start,
    2042             :                                                        count, &nData);
    2043          19 :                         snprintf(szMetaTemp, sizeof(szMetaTemp), "%d", nData);
    2044          19 :                         break;
    2045             :                     }
    2046           0 :                     case NC_FLOAT:
    2047             :                         float fData;
    2048           0 :                         /* status = */ nc_get_vara_float(nGroupID, nVarID,
    2049             :                                                          start, count, &fData);
    2050           0 :                         CPLsnprintf(szMetaTemp, sizeof(szMetaTemp), "%.8g",
    2051             :                                     fData);
    2052           0 :                         break;
    2053          18 :                     case NC_DOUBLE:
    2054             :                         double dfData;
    2055          18 :                         /* status = */ nc_get_vara_double(
    2056             :                             nGroupID, nVarID, start, count, &dfData);
    2057          18 :                         CPLsnprintf(szMetaTemp, sizeof(szMetaTemp), "%.16g",
    2058             :                                     dfData);
    2059          18 :                         break;
    2060           0 :                     case NC_UBYTE:
    2061             :                         unsigned char ucData;
    2062           0 :                         /* status = */ nc_get_vara_uchar(nGroupID, nVarID,
    2063             :                                                          start, count, &ucData);
    2064           0 :                         snprintf(szMetaTemp, sizeof(szMetaTemp), "%u", ucData);
    2065           0 :                         break;
    2066           0 :                     case NC_USHORT:
    2067             :                         unsigned short usData;
    2068           0 :                         /* status = */ nc_get_vara_ushort(
    2069             :                             nGroupID, nVarID, start, count, &usData);
    2070           0 :                         snprintf(szMetaTemp, sizeof(szMetaTemp), "%u", usData);
    2071           0 :                         break;
    2072           0 :                     case NC_UINT:
    2073             :                     {
    2074             :                         unsigned int unData;
    2075           0 :                         /* status = */ nc_get_vara_uint(nGroupID, nVarID, start,
    2076             :                                                         count, &unData);
    2077           0 :                         snprintf(szMetaTemp, sizeof(szMetaTemp), "%u", unData);
    2078           0 :                         break;
    2079             :                     }
    2080           1 :                     case NC_INT64:
    2081             :                     {
    2082             :                         long long nData;
    2083           1 :                         /* status = */ nc_get_vara_longlong(
    2084             :                             nGroupID, nVarID, start, count, &nData);
    2085           1 :                         snprintf(szMetaTemp, sizeof(szMetaTemp), CPL_FRMT_GIB,
    2086             :                                  nData);
    2087           1 :                         break;
    2088             :                     }
    2089           0 :                     case NC_UINT64:
    2090             :                     {
    2091             :                         unsigned long long unData;
    2092           0 :                         /* status = */ nc_get_vara_ulonglong(
    2093             :                             nGroupID, nVarID, start, count, &unData);
    2094           0 :                         snprintf(szMetaTemp, sizeof(szMetaTemp), CPL_FRMT_GUIB,
    2095             :                                  unData);
    2096           0 :                         break;
    2097             :                     }
    2098           0 :                     default:
    2099           0 :                         CPLDebug("GDAL_netCDF", "invalid dim %s, type=%d",
    2100             :                                  szMetaTemp, nVarType);
    2101           0 :                         break;
    2102             :                 }
    2103             :             }
    2104             :             else
    2105             :             {
    2106           0 :                 snprintf(szMetaTemp, sizeof(szMetaTemp), "%d", result + 1);
    2107             :             }
    2108             : 
    2109             :             // Save dimension value.
    2110             :             // NOTE: removed #original_units as not part of CF-1.
    2111             : 
    2112          38 :             GDALPamRasterBand::SetMetadataItem(szMetaName, szMetaTemp);
    2113             :         }
    2114             : 
    2115             :         // Avoid int32 overflow. Perhaps something more sensible to do here ?
    2116          40 :         if (result > 0 && Sum > INT_MAX / result)
    2117           0 :             break;
    2118          40 :         if (Taken > INT_MAX - result * Sum)
    2119           0 :             break;
    2120             : 
    2121          40 :         Taken += result * Sum;
    2122             :     }  // End loop non-spatial dimensions.
    2123             : 
    2124          49 :     l_poDS->nPamFlags = nPamFlagsBackup;
    2125          49 : }
    2126             : 
    2127             : /************************************************************************/
    2128             : /*                             CheckData()                              */
    2129             : /************************************************************************/
    2130             : template <class T>
    2131        5732 : void netCDFRasterBand::CheckData(void *pImage, void *pImageNC,
    2132             :                                  size_t nTmpBlockXSize, size_t nTmpBlockYSize,
    2133             :                                  bool bCheckIsNan)
    2134             : {
    2135        5732 :     CPLAssert(pImage != nullptr && pImageNC != nullptr);
    2136             : 
    2137             :     // If this block is not a full block (in the x axis), we need to re-arrange
    2138             :     // the data this is because partial blocks are not arranged the same way in
    2139             :     // netcdf and gdal.
    2140        5732 :     if (nTmpBlockXSize != static_cast<size_t>(nBlockXSize))
    2141             :     {
    2142           6 :         T *ptrWrite = static_cast<T *>(pImage);
    2143           6 :         T *ptrRead = static_cast<T *>(pImageNC);
    2144          29 :         for (size_t j = 0; j < nTmpBlockYSize;
    2145          23 :              j++, ptrWrite += nBlockXSize, ptrRead += nTmpBlockXSize)
    2146             :         {
    2147          23 :             memmove(ptrWrite, ptrRead, nTmpBlockXSize * sizeof(T));
    2148             :         }
    2149             :     }
    2150             : 
    2151             :     // Is valid data checking needed or requested?
    2152        5732 :     if (bValidRangeValid || bCheckIsNan)
    2153             :     {
    2154        1265 :         T *ptrImage = static_cast<T *>(pImage);
    2155        2584 :         for (size_t j = 0; j < nTmpBlockYSize; j++)
    2156             :         {
    2157             :             // k moves along the gdal block, skipping the out-of-range pixels.
    2158        1319 :             size_t k = j * nBlockXSize;
    2159       96938 :             for (size_t i = 0; i < nTmpBlockXSize; i++, k++)
    2160             :             {
    2161             :                 // Check for nodata and nan.
    2162       95619 :                 if (CPLIsEqual((double)ptrImage[k], m_dfNoDataValue))
    2163        6301 :                     continue;
    2164       89318 :                 if (bCheckIsNan && std::isnan((double)ptrImage[k]))
    2165             :                 {
    2166        5737 :                     ptrImage[k] = (T)m_dfNoDataValue;
    2167        5737 :                     continue;
    2168             :                 }
    2169             :                 // Check for valid_range.
    2170       83581 :                 if (bValidRangeValid)
    2171             :                 {
    2172       40986 :                     if (((adfValidRange[0] != m_dfNoDataValue) &&
    2173       40986 :                          (ptrImage[k] < (T)adfValidRange[0])) ||
    2174       40983 :                         ((adfValidRange[1] != m_dfNoDataValue) &&
    2175       40983 :                          (ptrImage[k] > (T)adfValidRange[1])))
    2176             :                     {
    2177           4 :                         ptrImage[k] = (T)m_dfNoDataValue;
    2178             :                     }
    2179             :                 }
    2180             :             }
    2181             :         }
    2182             :     }
    2183             : 
    2184             :     // If minimum longitude is > 180, subtract 360 from all.
    2185             :     // If not, disable checking for further calls (check just once).
    2186             :     // Only check first and last block elements since lon must be monotonic.
    2187        5732 :     const bool bIsSigned = std::numeric_limits<T>::is_signed;
    2188        5419 :     if (bCheckLongitude && bIsSigned &&
    2189           9 :         !CPLIsEqual((double)((T *)pImage)[0], m_dfNoDataValue) &&
    2190           8 :         !CPLIsEqual((double)((T *)pImage)[nTmpBlockXSize - 1],
    2191        2714 :                     m_dfNoDataValue) &&
    2192           8 :         std::min(((T *)pImage)[0], ((T *)pImage)[nTmpBlockXSize - 1]) > 180.0)
    2193             :     {
    2194           0 :         T *ptrImage = static_cast<T *>(pImage);
    2195           0 :         for (size_t j = 0; j < nTmpBlockYSize; j++)
    2196             :         {
    2197           0 :             size_t k = j * nBlockXSize;
    2198           0 :             for (size_t i = 0; i < nTmpBlockXSize; i++, k++)
    2199             :             {
    2200           0 :                 if (!CPLIsEqual((double)ptrImage[k], m_dfNoDataValue))
    2201           0 :                     ptrImage[k] = static_cast<T>(ptrImage[k] - 360);
    2202             :             }
    2203             :         }
    2204             :     }
    2205             :     else
    2206             :     {
    2207        5732 :         bCheckLongitude = false;
    2208             :     }
    2209        5732 : }
    2210             : 
    2211             : /************************************************************************/
    2212             : /*                             CheckDataCpx()                              */
    2213             : /************************************************************************/
    2214             : template <class T>
    2215          25 : void netCDFRasterBand::CheckDataCpx(void *pImage, void *pImageNC,
    2216             :                                     size_t nTmpBlockXSize,
    2217             :                                     size_t nTmpBlockYSize, bool bCheckIsNan)
    2218             : {
    2219          25 :     CPLAssert(pImage != nullptr && pImageNC != nullptr);
    2220             : 
    2221             :     // If this block is not a full block (in the x axis), we need to re-arrange
    2222             :     // the data this is because partial blocks are not arranged the same way in
    2223             :     // netcdf and gdal.
    2224          25 :     if (nTmpBlockXSize != static_cast<size_t>(nBlockXSize))
    2225             :     {
    2226           0 :         T *ptrWrite = static_cast<T *>(pImage);
    2227           0 :         T *ptrRead = static_cast<T *>(pImageNC);
    2228           0 :         for (size_t j = 0; j < nTmpBlockYSize; j++,
    2229           0 :                     ptrWrite += (2 * nBlockXSize),
    2230           0 :                     ptrRead += (2 * nTmpBlockXSize))
    2231             :         {
    2232           0 :             memmove(ptrWrite, ptrRead, nTmpBlockXSize * sizeof(T) * 2);
    2233             :         }
    2234             :     }
    2235             : 
    2236             :     // Is valid data checking needed or requested?
    2237          25 :     if (bValidRangeValid || bCheckIsNan)
    2238             :     {
    2239           0 :         T *ptrImage = static_cast<T *>(pImage);
    2240           0 :         for (size_t j = 0; j < nTmpBlockYSize; j++)
    2241             :         {
    2242             :             // k moves along the gdal block, skipping the out-of-range pixels.
    2243           0 :             size_t k = 2 * j * nBlockXSize;
    2244           0 :             for (size_t i = 0; i < (2 * nTmpBlockXSize); i++, k++)
    2245             :             {
    2246             :                 // Check for nodata and nan.
    2247           0 :                 if (CPLIsEqual((double)ptrImage[k], m_dfNoDataValue))
    2248           0 :                     continue;
    2249           0 :                 if (bCheckIsNan && std::isnan((double)ptrImage[k]))
    2250             :                 {
    2251           0 :                     ptrImage[k] = (T)m_dfNoDataValue;
    2252           0 :                     continue;
    2253             :                 }
    2254             :                 // Check for valid_range.
    2255           0 :                 if (bValidRangeValid)
    2256             :                 {
    2257           0 :                     if (((adfValidRange[0] != m_dfNoDataValue) &&
    2258           0 :                          (ptrImage[k] < (T)adfValidRange[0])) ||
    2259           0 :                         ((adfValidRange[1] != m_dfNoDataValue) &&
    2260           0 :                          (ptrImage[k] > (T)adfValidRange[1])))
    2261             :                     {
    2262           0 :                         ptrImage[k] = (T)m_dfNoDataValue;
    2263             :                     }
    2264             :                 }
    2265             :             }
    2266             :         }
    2267             :     }
    2268          25 : }
    2269             : 
    2270             : /************************************************************************/
    2271             : /*                         FetchNetcdfChunk()                           */
    2272             : /************************************************************************/
    2273             : 
    2274        5757 : bool netCDFRasterBand::FetchNetcdfChunk(size_t xstart, size_t ystart,
    2275             :                                         void *pImage)
    2276             : {
    2277        5757 :     size_t start[MAX_NC_DIMS] = {};
    2278        5757 :     size_t edge[MAX_NC_DIMS] = {};
    2279             : 
    2280        5757 :     start[nBandXPos] = xstart;
    2281        5757 :     edge[nBandXPos] = nBlockXSize;
    2282        5757 :     if ((start[nBandXPos] + edge[nBandXPos]) > (size_t)nRasterXSize)
    2283           6 :         edge[nBandXPos] = nRasterXSize - start[nBandXPos];
    2284        5757 :     if (nBandYPos >= 0)
    2285             :     {
    2286        5753 :         start[nBandYPos] = ystart;
    2287        5753 :         edge[nBandYPos] = nBlockYSize;
    2288        5753 :         if ((start[nBandYPos] + edge[nBandYPos]) > (size_t)nRasterYSize)
    2289           4 :             edge[nBandYPos] = nRasterYSize - start[nBandYPos];
    2290             :     }
    2291        5757 :     const size_t nYChunkSize = nBandYPos < 0 ? 1 : edge[nBandYPos];
    2292             : 
    2293             : #ifdef NCDF_DEBUG
    2294             :     CPLDebug("GDAL_netCDF", "start={%ld,%ld} edge={%ld,%ld} bBottomUp=%d",
    2295             :              start[nBandXPos], nBandYPos < 0 ? 0 : start[nBandYPos],
    2296             :              edge[nBandXPos], nYChunkSize, ((netCDFDataset *)poDS)->bBottomUp);
    2297             : #endif
    2298             : 
    2299        5757 :     int nd = 0;
    2300        5757 :     nc_inq_varndims(cdfid, nZId, &nd);
    2301        5757 :     if (nd == 3)
    2302             :     {
    2303        1078 :         start[panBandZPos[0]] = nLevel;  // z
    2304        1078 :         edge[panBandZPos[0]] = 1;
    2305             :     }
    2306             : 
    2307             :     // Compute multidimention band position.
    2308             :     //
    2309             :     // BandPosition = (Total - sum(PastBandLevels) - 1)/sum(remainingLevels)
    2310             :     // if Data[2,3,4,x,y]
    2311             :     //
    2312             :     //  BandPos0 = (nBand) / (3*4)
    2313             :     //  BandPos1 = (nBand - (3*4)) / (4)
    2314             :     //  BandPos2 = (nBand - (3*4)) % (4)
    2315        5757 :     if (nd > 3)
    2316             :     {
    2317         160 :         int Sum = -1;
    2318         160 :         int Taken = 0;
    2319         480 :         for (int i = 0; i < nd - 2; i++)
    2320             :         {
    2321         320 :             if (i != nd - 2 - 1)
    2322             :             {
    2323         160 :                 Sum = 1;
    2324         320 :                 for (int j = i + 1; j < nd - 2; j++)
    2325             :                 {
    2326         160 :                     Sum *= panBandZLev[j];
    2327             :                 }
    2328         160 :                 start[panBandZPos[i]] = (int)((nLevel - Taken) / Sum);
    2329         160 :                 edge[panBandZPos[i]] = 1;
    2330             :             }
    2331             :             else
    2332             :             {
    2333         160 :                 start[panBandZPos[i]] = (int)((nLevel - Taken) % Sum);
    2334         160 :                 edge[panBandZPos[i]] = 1;
    2335             :             }
    2336         320 :             Taken += static_cast<int>(start[panBandZPos[i]]) * Sum;
    2337             :         }
    2338             :     }
    2339             : 
    2340             :     // Make sure we are in data mode.
    2341        5757 :     static_cast<netCDFDataset *>(poDS)->SetDefineMode(false);
    2342             : 
    2343             :     // If this block is not a full block in the x axis, we need to
    2344             :     // re-arrange the data because partial blocks are not arranged the
    2345             :     // same way in netcdf and gdal, so we first we read the netcdf data at
    2346             :     // the end of the gdal block buffer then re-arrange rows in CheckData().
    2347        5757 :     void *pImageNC = pImage;
    2348        5757 :     if (edge[nBandXPos] != static_cast<size_t>(nBlockXSize))
    2349             :     {
    2350           6 :         pImageNC = static_cast<GByte *>(pImage) +
    2351           6 :                    ((static_cast<size_t>(nBlockXSize) * nBlockYSize -
    2352          12 :                      edge[nBandXPos] * nYChunkSize) *
    2353           6 :                     GDALGetDataTypeSizeBytes(eDataType));
    2354             :     }
    2355             : 
    2356             :     // Read data according to type.
    2357             :     int status;
    2358        5757 :     if (eDataType == GDT_Byte)
    2359             :     {
    2360        3005 :         if (bSignedData)
    2361             :         {
    2362           0 :             status = nc_get_vara_schar(cdfid, nZId, start, edge,
    2363             :                                        static_cast<signed char *>(pImageNC));
    2364           0 :             if (status == NC_NOERR)
    2365           0 :                 CheckData<signed char>(pImage, pImageNC, edge[nBandXPos],
    2366             :                                        nYChunkSize, false);
    2367             :         }
    2368             :         else
    2369             :         {
    2370        3005 :             status = nc_get_vara_uchar(cdfid, nZId, start, edge,
    2371             :                                        static_cast<unsigned char *>(pImageNC));
    2372        3005 :             if (status == NC_NOERR)
    2373        3005 :                 CheckData<unsigned char>(pImage, pImageNC, edge[nBandXPos],
    2374             :                                          nYChunkSize, false);
    2375             :         }
    2376             :     }
    2377        2752 :     else if (eDataType == GDT_Int8)
    2378             :     {
    2379          60 :         status = nc_get_vara_schar(cdfid, nZId, start, edge,
    2380             :                                    static_cast<signed char *>(pImageNC));
    2381          60 :         if (status == NC_NOERR)
    2382          60 :             CheckData<signed char>(pImage, pImageNC, edge[nBandXPos],
    2383             :                                    nYChunkSize, false);
    2384             :     }
    2385        2692 :     else if (nc_datatype == NC_SHORT)
    2386             :     {
    2387         465 :         status = nc_get_vara_short(cdfid, nZId, start, edge,
    2388             :                                    static_cast<short *>(pImageNC));
    2389         465 :         if (status == NC_NOERR)
    2390             :         {
    2391         465 :             if (eDataType == GDT_Int16)
    2392             :             {
    2393         462 :                 CheckData<GInt16>(pImage, pImageNC, edge[nBandXPos],
    2394             :                                   nYChunkSize, false);
    2395             :             }
    2396             :             else
    2397             :             {
    2398           3 :                 CheckData<GUInt16>(pImage, pImageNC, edge[nBandXPos],
    2399             :                                    nYChunkSize, false);
    2400             :             }
    2401             :         }
    2402             :     }
    2403        2227 :     else if (eDataType == GDT_Int32)
    2404             :     {
    2405             : #if SIZEOF_UNSIGNED_LONG == 4
    2406             :         status = nc_get_vara_long(cdfid, nZId, start, edge,
    2407             :                                   static_cast<long *>(pImageNC));
    2408             :         if (status == NC_NOERR)
    2409             :             CheckData<long>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
    2410             :                             false);
    2411             : #else
    2412         912 :         status = nc_get_vara_int(cdfid, nZId, start, edge,
    2413             :                                  static_cast<int *>(pImageNC));
    2414         912 :         if (status == NC_NOERR)
    2415         912 :             CheckData<int>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
    2416             :                            false);
    2417             : #endif
    2418             :     }
    2419        1315 :     else if (eDataType == GDT_Float32)
    2420             :     {
    2421        1178 :         status = nc_get_vara_float(cdfid, nZId, start, edge,
    2422             :                                    static_cast<float *>(pImageNC));
    2423        1178 :         if (status == NC_NOERR)
    2424        1178 :             CheckData<float>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
    2425             :                              true);
    2426             :     }
    2427         137 :     else if (eDataType == GDT_Float64)
    2428             :     {
    2429          86 :         status = nc_get_vara_double(cdfid, nZId, start, edge,
    2430             :                                     static_cast<double *>(pImageNC));
    2431          86 :         if (status == NC_NOERR)
    2432          86 :             CheckData<double>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
    2433             :                               true);
    2434             :     }
    2435          51 :     else if (eDataType == GDT_UInt16)
    2436             :     {
    2437           6 :         status = nc_get_vara_ushort(cdfid, nZId, start, edge,
    2438             :                                     static_cast<unsigned short *>(pImageNC));
    2439           6 :         if (status == NC_NOERR)
    2440           6 :             CheckData<unsigned short>(pImage, pImageNC, edge[nBandXPos],
    2441             :                                       nYChunkSize, false);
    2442             :     }
    2443          45 :     else if (eDataType == GDT_UInt32)
    2444             :     {
    2445           6 :         status = nc_get_vara_uint(cdfid, nZId, start, edge,
    2446             :                                   static_cast<unsigned int *>(pImageNC));
    2447           6 :         if (status == NC_NOERR)
    2448           6 :             CheckData<unsigned int>(pImage, pImageNC, edge[nBandXPos],
    2449             :                                     nYChunkSize, false);
    2450             :     }
    2451          39 :     else if (eDataType == GDT_Int64)
    2452             :     {
    2453           7 :         status = nc_get_vara_longlong(cdfid, nZId, start, edge,
    2454             :                                       static_cast<long long *>(pImageNC));
    2455           7 :         if (status == NC_NOERR)
    2456           7 :             CheckData<std::int64_t>(pImage, pImageNC, edge[nBandXPos],
    2457             :                                     nYChunkSize, false);
    2458             :     }
    2459          32 :     else if (eDataType == GDT_UInt64)
    2460             :     {
    2461             :         status =
    2462           7 :             nc_get_vara_ulonglong(cdfid, nZId, start, edge,
    2463             :                                   static_cast<unsigned long long *>(pImageNC));
    2464           7 :         if (status == NC_NOERR)
    2465           7 :             CheckData<std::uint64_t>(pImage, pImageNC, edge[nBandXPos],
    2466             :                                      nYChunkSize, false);
    2467             :     }
    2468          25 :     else if (eDataType == GDT_CInt16)
    2469             :     {
    2470           0 :         status = nc_get_vara(cdfid, nZId, start, edge, pImageNC);
    2471           0 :         if (status == NC_NOERR)
    2472           0 :             CheckDataCpx<short>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
    2473             :                                 false);
    2474             :     }
    2475          25 :     else if (eDataType == GDT_CInt32)
    2476             :     {
    2477           0 :         status = nc_get_vara(cdfid, nZId, start, edge, pImageNC);
    2478           0 :         if (status == NC_NOERR)
    2479           0 :             CheckDataCpx<int>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
    2480             :                               false);
    2481             :     }
    2482          25 :     else if (eDataType == GDT_CFloat32)
    2483             :     {
    2484          20 :         status = nc_get_vara(cdfid, nZId, start, edge, pImageNC);
    2485          20 :         if (status == NC_NOERR)
    2486          20 :             CheckDataCpx<float>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
    2487             :                                 false);
    2488             :     }
    2489           5 :     else if (eDataType == GDT_CFloat64)
    2490             :     {
    2491           5 :         status = nc_get_vara(cdfid, nZId, start, edge, pImageNC);
    2492           5 :         if (status == NC_NOERR)
    2493           5 :             CheckDataCpx<double>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
    2494             :                                  false);
    2495             :     }
    2496             : 
    2497             :     else
    2498           0 :         status = NC_EBADTYPE;
    2499             : 
    2500        5757 :     if (status != NC_NOERR)
    2501             :     {
    2502           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2503             :                  "netCDF chunk fetch failed: #%d (%s)", status,
    2504             :                  nc_strerror(status));
    2505           0 :         return false;
    2506             :     }
    2507        5757 :     return true;
    2508             : }
    2509             : 
    2510             : /************************************************************************/
    2511             : /*                             IReadBlock()                             */
    2512             : /************************************************************************/
    2513             : 
    2514        5757 : CPLErr netCDFRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff,
    2515             :                                     void *pImage)
    2516             : 
    2517             : {
    2518       11514 :     CPLMutexHolderD(&hNCMutex);
    2519             : 
    2520             :     // Locate X, Y and Z position in the array.
    2521             : 
    2522        5757 :     size_t xstart = static_cast<size_t>(nBlockXOff) * nBlockXSize;
    2523        5757 :     size_t ystart = 0;
    2524             : 
    2525             :     // Check y order.
    2526        5757 :     if (nBandYPos >= 0)
    2527             :     {
    2528        5753 :         auto poGDS = static_cast<netCDFDataset *>(poDS);
    2529        5753 :         if (poGDS->bBottomUp)
    2530             :         {
    2531        4838 :             if (nBlockYSize == 1)
    2532             :             {
    2533        4825 :                 ystart = nRasterYSize - 1 - nBlockYOff;
    2534             :             }
    2535             :             else
    2536             :             {
    2537             :                 // in GDAL space
    2538          13 :                 ystart = static_cast<size_t>(nBlockYOff) * nBlockYSize;
    2539             :                 const size_t yend =
    2540          26 :                     std::min(ystart + nBlockYSize - 1,
    2541          13 :                              static_cast<size_t>(nRasterYSize - 1));
    2542             :                 // in netCDF space
    2543          13 :                 const size_t nFirstChunkLine = nRasterYSize - 1 - yend;
    2544          13 :                 const size_t nLastChunkLine = nRasterYSize - 1 - ystart;
    2545          13 :                 const size_t nFirstChunkBlock = nFirstChunkLine / nBlockYSize;
    2546          13 :                 const size_t nLastChunkBlock = nLastChunkLine / nBlockYSize;
    2547             : 
    2548             :                 const auto firstKey = netCDFDataset::ChunkKey(
    2549          13 :                     nBlockXOff, nFirstChunkBlock, nBand);
    2550             :                 const auto secondKey =
    2551          13 :                     netCDFDataset::ChunkKey(nBlockXOff, nLastChunkBlock, nBand);
    2552             : 
    2553             :                 // Retrieve data from the one or 2 needed netCDF chunks
    2554          13 :                 std::shared_ptr<std::vector<GByte>> firstChunk;
    2555          13 :                 std::shared_ptr<std::vector<GByte>> secondChunk;
    2556          13 :                 if (poGDS->poChunkCache)
    2557             :                 {
    2558          13 :                     poGDS->poChunkCache->tryGet(firstKey, firstChunk);
    2559          13 :                     if (firstKey != secondKey)
    2560           6 :                         poGDS->poChunkCache->tryGet(secondKey, secondChunk);
    2561             :                 }
    2562             :                 const size_t nChunkLineSize =
    2563          13 :                     static_cast<size_t>(GDALGetDataTypeSizeBytes(eDataType)) *
    2564          13 :                     nBlockXSize;
    2565          13 :                 const size_t nChunkSize = nChunkLineSize * nBlockYSize;
    2566          13 :                 if (!firstChunk)
    2567             :                 {
    2568          11 :                     firstChunk.reset(new std::vector<GByte>(nChunkSize));
    2569          11 :                     if (!FetchNetcdfChunk(xstart,
    2570          11 :                                           nFirstChunkBlock * nBlockYSize,
    2571          11 :                                           firstChunk.get()->data()))
    2572           0 :                         return CE_Failure;
    2573          11 :                     if (poGDS->poChunkCache)
    2574          11 :                         poGDS->poChunkCache->insert(firstKey, firstChunk);
    2575             :                 }
    2576          13 :                 if (!secondChunk && firstKey != secondKey)
    2577             :                 {
    2578           2 :                     secondChunk.reset(new std::vector<GByte>(nChunkSize));
    2579           2 :                     if (!FetchNetcdfChunk(xstart, nLastChunkBlock * nBlockYSize,
    2580           2 :                                           secondChunk.get()->data()))
    2581           0 :                         return CE_Failure;
    2582           2 :                     if (poGDS->poChunkCache)
    2583           2 :                         poGDS->poChunkCache->insert(secondKey, secondChunk);
    2584             :                 }
    2585             : 
    2586             :                 // Assemble netCDF chunks into GDAL block
    2587          13 :                 GByte *pabyImage = static_cast<GByte *>(pImage);
    2588          13 :                 const size_t nFirstChunkBlockLine =
    2589          13 :                     nFirstChunkBlock * nBlockYSize;
    2590          13 :                 const size_t nLastChunkBlockLine =
    2591          13 :                     nLastChunkBlock * nBlockYSize;
    2592         146 :                 for (size_t iLine = ystart; iLine <= yend; iLine++)
    2593             :                 {
    2594         133 :                     const size_t nLineFromBottom = nRasterYSize - 1 - iLine;
    2595         133 :                     const size_t nChunkY = nLineFromBottom / nBlockYSize;
    2596         133 :                     if (nChunkY == nFirstChunkBlock)
    2597             :                     {
    2598         121 :                         memcpy(pabyImage + nChunkLineSize * (iLine - ystart),
    2599         121 :                                firstChunk.get()->data() +
    2600         121 :                                    (nLineFromBottom - nFirstChunkBlockLine) *
    2601             :                                        nChunkLineSize,
    2602             :                                nChunkLineSize);
    2603             :                     }
    2604             :                     else
    2605             :                     {
    2606          12 :                         CPLAssert(nChunkY == nLastChunkBlock);
    2607          12 :                         assert(secondChunk);
    2608          12 :                         memcpy(pabyImage + nChunkLineSize * (iLine - ystart),
    2609          12 :                                secondChunk.get()->data() +
    2610          12 :                                    (nLineFromBottom - nLastChunkBlockLine) *
    2611             :                                        nChunkLineSize,
    2612             :                                nChunkLineSize);
    2613             :                     }
    2614             :                 }
    2615          13 :                 return CE_None;
    2616             :             }
    2617             :         }
    2618             :         else
    2619             :         {
    2620         915 :             ystart = static_cast<size_t>(nBlockYOff) * nBlockYSize;
    2621             :         }
    2622             :     }
    2623             : 
    2624        5744 :     return FetchNetcdfChunk(xstart, ystart, pImage) ? CE_None : CE_Failure;
    2625             : }
    2626             : 
    2627             : /************************************************************************/
    2628             : /*                             IWriteBlock()                            */
    2629             : /************************************************************************/
    2630             : 
    2631        6401 : CPLErr netCDFRasterBand::IWriteBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff,
    2632             :                                      void *pImage)
    2633             : {
    2634       12802 :     CPLMutexHolderD(&hNCMutex);
    2635             : 
    2636             : #ifdef NCDF_DEBUG
    2637             :     if (nBlockYOff == 0 || (nBlockYOff == nRasterYSize - 1))
    2638             :         CPLDebug("GDAL_netCDF",
    2639             :                  "netCDFRasterBand::IWriteBlock( %d, %d, ...) nBand=%d",
    2640             :                  nBlockXOff, nBlockYOff, nBand);
    2641             : #endif
    2642             : 
    2643        6401 :     int nd = 0;
    2644        6401 :     nc_inq_varndims(cdfid, nZId, &nd);
    2645             : 
    2646             :     // Locate X, Y and Z position in the array.
    2647             : 
    2648             :     size_t start[MAX_NC_DIMS];
    2649        6401 :     memset(start, 0, sizeof(start));
    2650        6401 :     start[nBandXPos] = static_cast<size_t>(nBlockXOff) * nBlockXSize;
    2651             : 
    2652             :     // check y order.
    2653        6401 :     if (static_cast<netCDFDataset *>(poDS)->bBottomUp)
    2654             :     {
    2655        6377 :         if (nBlockYSize == 1)
    2656             :         {
    2657        6377 :             start[nBandYPos] = nRasterYSize - 1 - nBlockYOff;
    2658             :         }
    2659             :         else
    2660             :         {
    2661           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2662             :                      "nBlockYSize = %d, only 1 supported when "
    2663             :                      "writing bottom-up dataset",
    2664             :                      nBlockYSize);
    2665           0 :             return CE_Failure;
    2666             :         }
    2667             :     }
    2668             :     else
    2669             :     {
    2670          24 :         start[nBandYPos] = static_cast<size_t>(nBlockYOff) * nBlockYSize;  // y
    2671             :     }
    2672             : 
    2673        6401 :     size_t edge[MAX_NC_DIMS] = {};
    2674             : 
    2675        6401 :     edge[nBandXPos] = nBlockXSize;
    2676        6401 :     if ((start[nBandXPos] + edge[nBandXPos]) > (size_t)nRasterXSize)
    2677           0 :         edge[nBandXPos] = nRasterXSize - start[nBandXPos];
    2678        6401 :     edge[nBandYPos] = nBlockYSize;
    2679        6401 :     if ((start[nBandYPos] + edge[nBandYPos]) > (size_t)nRasterYSize)
    2680           0 :         edge[nBandYPos] = nRasterYSize - start[nBandYPos];
    2681             : 
    2682        6401 :     if (nd == 3)
    2683             :     {
    2684         610 :         start[panBandZPos[0]] = nLevel;  // z
    2685         610 :         edge[panBandZPos[0]] = 1;
    2686             :     }
    2687             : 
    2688             :     // Compute multidimention band position.
    2689             :     //
    2690             :     // BandPosition = (Total - sum(PastBandLevels) - 1)/sum(remainingLevels)
    2691             :     // if Data[2,3,4,x,y]
    2692             :     //
    2693             :     //  BandPos0 = (nBand) / (3*4)
    2694             :     //  BandPos1 = (nBand - (3*4)) / (4)
    2695             :     //  BandPos2 = (nBand - (3*4)) % (4)
    2696        6401 :     if (nd > 3)
    2697             :     {
    2698         178 :         int Sum = -1;
    2699         178 :         int Taken = 0;
    2700         534 :         for (int i = 0; i < nd - 2; i++)
    2701             :         {
    2702         356 :             if (i != nd - 2 - 1)
    2703             :             {
    2704         178 :                 Sum = 1;
    2705         356 :                 for (int j = i + 1; j < nd - 2; j++)
    2706             :                 {
    2707         178 :                     Sum *= panBandZLev[j];
    2708             :                 }
    2709         178 :                 start[panBandZPos[i]] = (int)((nLevel - Taken) / Sum);
    2710         178 :                 edge[panBandZPos[i]] = 1;
    2711             :             }
    2712             :             else
    2713             :             {
    2714         178 :                 start[panBandZPos[i]] = (int)((nLevel - Taken) % Sum);
    2715         178 :                 edge[panBandZPos[i]] = 1;
    2716             :             }
    2717         356 :             Taken += static_cast<int>(start[panBandZPos[i]]) * Sum;
    2718             :         }
    2719             :     }
    2720             : 
    2721             :     // Make sure we are in data mode.
    2722        6401 :     static_cast<netCDFDataset *>(poDS)->SetDefineMode(false);
    2723             : 
    2724             :     // Copy data according to type.
    2725        6401 :     int status = 0;
    2726        6401 :     if (eDataType == GDT_Byte)
    2727             :     {
    2728        5842 :         if (bSignedData)
    2729           0 :             status = nc_put_vara_schar(cdfid, nZId, start, edge,
    2730             :                                        static_cast<signed char *>(pImage));
    2731             :         else
    2732        5842 :             status = nc_put_vara_uchar(cdfid, nZId, start, edge,
    2733             :                                        static_cast<unsigned char *>(pImage));
    2734             :     }
    2735         559 :     else if (eDataType == GDT_Int8)
    2736             :     {
    2737          40 :         status = nc_put_vara_schar(cdfid, nZId, start, edge,
    2738             :                                    static_cast<signed char *>(pImage));
    2739             :     }
    2740         519 :     else if (nc_datatype == NC_SHORT)
    2741             :     {
    2742         101 :         status = nc_put_vara_short(cdfid, nZId, start, edge,
    2743             :                                    static_cast<short *>(pImage));
    2744             :     }
    2745         418 :     else if (eDataType == GDT_Int32)
    2746             :     {
    2747         210 :         status = nc_put_vara_int(cdfid, nZId, start, edge,
    2748             :                                  static_cast<int *>(pImage));
    2749             :     }
    2750         208 :     else if (eDataType == GDT_Float32)
    2751             :     {
    2752         128 :         status = nc_put_vara_float(cdfid, nZId, start, edge,
    2753             :                                    static_cast<float *>(pImage));
    2754             :     }
    2755          80 :     else if (eDataType == GDT_Float64)
    2756             :     {
    2757          50 :         status = nc_put_vara_double(cdfid, nZId, start, edge,
    2758             :                                     static_cast<double *>(pImage));
    2759             :     }
    2760          30 :     else if (eDataType == GDT_UInt16 &&
    2761          12 :              static_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
    2762             :     {
    2763          12 :         status = nc_put_vara_ushort(cdfid, nZId, start, edge,
    2764             :                                     static_cast<unsigned short *>(pImage));
    2765             :     }
    2766          18 :     else if (eDataType == GDT_UInt32 &&
    2767          12 :              static_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
    2768             :     {
    2769          12 :         status = nc_put_vara_uint(cdfid, nZId, start, edge,
    2770             :                                   static_cast<unsigned int *>(pImage));
    2771             :     }
    2772           6 :     else if (eDataType == GDT_UInt64 &&
    2773           3 :              static_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
    2774             :     {
    2775           3 :         status =
    2776           3 :             nc_put_vara_ulonglong(cdfid, nZId, start, edge,
    2777             :                                   static_cast<unsigned long long *>(pImage));
    2778             :     }
    2779           3 :     else if (eDataType == GDT_Int64 &&
    2780           3 :              static_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
    2781             :     {
    2782           3 :         status = nc_put_vara_longlong(cdfid, nZId, start, edge,
    2783             :                                       static_cast<long long *>(pImage));
    2784             :     }
    2785             :     else
    2786             :     {
    2787           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2788             :                  "The NetCDF driver does not support GDAL data type %d",
    2789           0 :                  eDataType);
    2790           0 :         status = NC_EBADTYPE;
    2791             :     }
    2792        6401 :     NCDF_ERR(status);
    2793             : 
    2794        6401 :     if (status != NC_NOERR)
    2795             :     {
    2796           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2797             :                  "netCDF scanline write failed: %s", nc_strerror(status));
    2798           0 :         return CE_Failure;
    2799             :     }
    2800             : 
    2801        6401 :     return CE_None;
    2802             : }
    2803             : 
    2804             : /************************************************************************/
    2805             : /* ==================================================================== */
    2806             : /*                              netCDFDataset                           */
    2807             : /* ==================================================================== */
    2808             : /************************************************************************/
    2809             : 
    2810             : /************************************************************************/
    2811             : /*                           netCDFDataset()                            */
    2812             : /************************************************************************/
    2813             : 
    2814        1019 : netCDFDataset::netCDFDataset()
    2815             :     :
    2816             : // Basic dataset vars.
    2817             : #ifdef ENABLE_NCDUMP
    2818             :       bFileToDestroyAtClosing(false),
    2819             : #endif
    2820             :       cdfid(-1), nSubDatasets(0), papszSubDatasets(nullptr),
    2821             :       papszMetadata(nullptr), bBottomUp(true), eFormat(NCDF_FORMAT_NONE),
    2822             :       bIsGdalFile(false), bIsGdalCfFile(false), pszCFProjection(nullptr),
    2823             :       pszCFCoordinates(nullptr), nCFVersion(1.6), bSGSupport(false),
    2824        1019 :       eMultipleLayerBehavior(SINGLE_LAYER), logCount(0), vcdf(this, cdfid),
    2825        1019 :       GeometryScribe(vcdf, this->generateLogName()),
    2826        1019 :       FieldScribe(vcdf, this->generateLogName()),
    2827        2038 :       bufManager(CPLGetUsablePhysicalRAM() / 5),
    2828             : 
    2829             :       // projection/GT.
    2830             :       nXDimID(-1), nYDimID(-1), bIsProjected(false),
    2831             :       bIsGeographic(false),  // Can be not projected, and also not geographic
    2832             :       // State vars.
    2833             :       bDefineMode(true), bAddedGridMappingRef(false),
    2834             : 
    2835             :       // Create vars.
    2836             :       papszCreationOptions(nullptr), eCompress(NCDF_COMPRESS_NONE),
    2837             :       nZLevel(NCDF_DEFLATE_LEVEL), bChunking(false), nCreateMode(NC_CLOBBER),
    2838        3057 :       bSignedData(true)
    2839             : {
    2840        1019 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2841             : 
    2842             :     // Set buffers
    2843        1019 :     bufManager.addBuffer(&(GeometryScribe.getMemBuffer()));
    2844        1019 :     bufManager.addBuffer(&(FieldScribe.getMemBuffer()));
    2845        1019 : }
    2846             : 
    2847             : /************************************************************************/
    2848             : /*                           ~netCDFDataset()                           */
    2849             : /************************************************************************/
    2850             : 
    2851        1958 : netCDFDataset::~netCDFDataset()
    2852             : 
    2853             : {
    2854        1019 :     netCDFDataset::Close();
    2855        1958 : }
    2856             : 
    2857             : /************************************************************************/
    2858             : /*                              Close()                                 */
    2859             : /************************************************************************/
    2860             : 
    2861        1773 : CPLErr netCDFDataset::Close()
    2862             : {
    2863        1773 :     CPLErr eErr = CE_None;
    2864        1773 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
    2865             :     {
    2866        2038 :         CPLMutexHolderD(&hNCMutex);
    2867             : 
    2868             : #ifdef NCDF_DEBUG
    2869             :         CPLDebug("GDAL_netCDF",
    2870             :                  "netCDFDataset::~netCDFDataset(), cdfid=%d filename=%s", cdfid,
    2871             :                  osFilename.c_str());
    2872             : #endif
    2873             : 
    2874             :         // Write data related to geotransform
    2875        1252 :         if (GetAccess() == GA_Update && !m_bAddedProjectionVarsData &&
    2876         233 :             (m_bHasProjection || m_bHasGeoTransform))
    2877             :         {
    2878             :             // Ensure projection is written if GeoTransform OR Projection are
    2879             :             // missing.
    2880          37 :             if (!m_bAddedProjectionVarsDefs)
    2881             :             {
    2882           2 :                 AddProjectionVars(true, nullptr, nullptr);
    2883             :             }
    2884          37 :             AddProjectionVars(false, nullptr, nullptr);
    2885             :         }
    2886             : 
    2887        1019 :         if (netCDFDataset::FlushCache(true) != CE_None)
    2888           0 :             eErr = CE_Failure;
    2889             : 
    2890        1019 :         if (GetAccess() == GA_Update && !SGCommitPendingTransaction())
    2891           0 :             eErr = CE_Failure;
    2892             : 
    2893        1021 :         for (size_t i = 0; i < apoVectorDatasets.size(); i++)
    2894           2 :             delete apoVectorDatasets[i];
    2895             : 
    2896             :         // Make sure projection variable is written to band variable.
    2897        1019 :         if (GetAccess() == GA_Update && !bAddedGridMappingRef)
    2898             :         {
    2899         250 :             if (!AddGridMappingRef())
    2900           0 :                 eErr = CE_Failure;
    2901             :         }
    2902             : 
    2903        1019 :         CSLDestroy(papszMetadata);
    2904        1019 :         CSLDestroy(papszSubDatasets);
    2905        1019 :         CSLDestroy(papszCreationOptions);
    2906             : 
    2907        1019 :         CPLFree(pszCFProjection);
    2908             : 
    2909        1019 :         if (cdfid > 0)
    2910             :         {
    2911             : #ifdef NCDF_DEBUG
    2912             :             CPLDebug("GDAL_netCDF", "calling nc_close( %d)", cdfid);
    2913             : #endif
    2914         662 :             int status = GDAL_nc_close(cdfid);
    2915             : #ifdef ENABLE_UFFD
    2916         662 :             NETCDF_UFFD_UNMAP(pCtx);
    2917             : #endif
    2918         662 :             NCDF_ERR(status);
    2919         662 :             if (status != NC_NOERR)
    2920           0 :                 eErr = CE_Failure;
    2921             :         }
    2922             : 
    2923        1019 :         if (fpVSIMEM)
    2924          15 :             VSIFCloseL(fpVSIMEM);
    2925             : 
    2926             : #ifdef ENABLE_NCDUMP
    2927        1019 :         if (bFileToDestroyAtClosing)
    2928           0 :             VSIUnlink(osFilename);
    2929             : #endif
    2930             : 
    2931        1019 :         if (GDALPamDataset::Close() != CE_None)
    2932           0 :             eErr = CE_Failure;
    2933             :     }
    2934        1773 :     return eErr;
    2935             : }
    2936             : 
    2937             : /************************************************************************/
    2938             : /*                            SetDefineMode()                           */
    2939             : /************************************************************************/
    2940       14233 : bool netCDFDataset::SetDefineMode(bool bNewDefineMode)
    2941             : {
    2942             :     // Do nothing if already in new define mode
    2943             :     // or if dataset is in read-only mode or if dataset is true NC4 dataset.
    2944       14792 :     if (bDefineMode == bNewDefineMode || GetAccess() == GA_ReadOnly ||
    2945         559 :         eFormat == NCDF_FORMAT_NC4)
    2946       13821 :         return true;
    2947             : 
    2948         412 :     CPLDebug("GDAL_netCDF", "SetDefineMode(%d) old=%d",
    2949         412 :              static_cast<int>(bNewDefineMode), static_cast<int>(bDefineMode));
    2950             : 
    2951         412 :     bDefineMode = bNewDefineMode;
    2952             : 
    2953             :     int status;
    2954         412 :     if (bDefineMode)
    2955         143 :         status = nc_redef(cdfid);
    2956             :     else
    2957         269 :         status = nc_enddef(cdfid);
    2958             : 
    2959         412 :     NCDF_ERR(status);
    2960         412 :     return status == NC_NOERR;
    2961             : }
    2962             : 
    2963             : /************************************************************************/
    2964             : /*                      GetMetadataDomainList()                         */
    2965             : /************************************************************************/
    2966             : 
    2967          27 : char **netCDFDataset::GetMetadataDomainList()
    2968             : {
    2969          27 :     char **papszDomains = BuildMetadataDomainList(
    2970             :         GDALDataset::GetMetadataDomainList(), TRUE, "SUBDATASETS", nullptr);
    2971          28 :     for (const auto &kv : m_oMapDomainToJSon)
    2972           1 :         papszDomains = CSLAddString(papszDomains, ("json:" + kv.first).c_str());
    2973          27 :     return papszDomains;
    2974             : }
    2975             : 
    2976             : /************************************************************************/
    2977             : /*                            GetMetadata()                             */
    2978             : /************************************************************************/
    2979         369 : char **netCDFDataset::GetMetadata(const char *pszDomain)
    2980             : {
    2981         369 :     if (pszDomain != nullptr && STARTS_WITH_CI(pszDomain, "SUBDATASETS"))
    2982          39 :         return papszSubDatasets;
    2983             : 
    2984         330 :     if (pszDomain != nullptr && STARTS_WITH(pszDomain, "json:"))
    2985             :     {
    2986           1 :         auto iter = m_oMapDomainToJSon.find(pszDomain + strlen("json:"));
    2987           1 :         if (iter != m_oMapDomainToJSon.end())
    2988           1 :             return iter->second.List();
    2989             :     }
    2990             : 
    2991         329 :     return GDALDataset::GetMetadata(pszDomain);
    2992             : }
    2993             : 
    2994             : /************************************************************************/
    2995             : /*                        SetMetadataItem()                             */
    2996             : /************************************************************************/
    2997             : 
    2998          43 : CPLErr netCDFDataset::SetMetadataItem(const char *pszName, const char *pszValue,
    2999             :                                       const char *pszDomain)
    3000             : {
    3001          85 :     if (GetAccess() == GA_Update &&
    3002          85 :         (pszDomain == nullptr || pszDomain[0] == '\0') && pszValue != nullptr)
    3003             :     {
    3004          42 :         std::string osName(pszName);
    3005             : 
    3006             :         // Same logic as in CopyMetadata()
    3007          42 :         if (STARTS_WITH(osName.c_str(), "NC_GLOBAL#"))
    3008           8 :             osName = osName.substr(strlen("NC_GLOBAL#"));
    3009          34 :         else if (strchr(osName.c_str(), '#') == nullptr)
    3010           5 :             osName = "GDAL_" + osName;
    3011             : 
    3012          84 :         if (STARTS_WITH(osName.c_str(), "NETCDF_DIM_") ||
    3013          42 :             strchr(osName.c_str(), '#') != nullptr)
    3014             :         {
    3015             :             // do nothing
    3016          29 :             return CE_None;
    3017             :         }
    3018             :         else
    3019             :         {
    3020          13 :             SetDefineMode(true);
    3021             : 
    3022          13 :             if (!NCDFPutAttr(cdfid, NC_GLOBAL, osName.c_str(), pszValue))
    3023          13 :                 return CE_Failure;
    3024             :         }
    3025             :     }
    3026             : 
    3027           1 :     return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    3028             : }
    3029             : 
    3030             : /************************************************************************/
    3031             : /*                          SetMetadata()                               */
    3032             : /************************************************************************/
    3033             : 
    3034           8 : CPLErr netCDFDataset::SetMetadata(char **papszMD, const char *pszDomain)
    3035             : {
    3036          13 :     if (GetAccess() == GA_Update &&
    3037           5 :         (pszDomain == nullptr || pszDomain[0] == '\0'))
    3038             :     {
    3039             :         // We don't handle metadata item removal for now
    3040          50 :         for (const char *const *papszIter = papszMD; papszIter && *papszIter;
    3041             :              ++papszIter)
    3042             :         {
    3043          42 :             char *pszName = nullptr;
    3044          42 :             const char *pszValue = CPLParseNameValue(*papszIter, &pszName);
    3045          42 :             if (pszName && pszValue)
    3046          42 :                 SetMetadataItem(pszName, pszValue);
    3047          42 :             CPLFree(pszName);
    3048             :         }
    3049           8 :         return CE_None;
    3050             :     }
    3051           0 :     return GDALPamDataset::SetMetadata(papszMD, pszDomain);
    3052             : }
    3053             : 
    3054             : /************************************************************************/
    3055             : /*                          GetSpatialRef()                             */
    3056             : /************************************************************************/
    3057             : 
    3058         190 : const OGRSpatialReference *netCDFDataset::GetSpatialRef() const
    3059             : {
    3060         190 :     if (m_bHasProjection)
    3061          75 :         return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
    3062             : 
    3063         115 :     return GDALPamDataset::GetSpatialRef();
    3064             : }
    3065             : 
    3066             : /************************************************************************/
    3067             : /*                           FetchCopyParam()                            */
    3068             : /************************************************************************/
    3069             : 
    3070         440 : double netCDFDataset::FetchCopyParam(const char *pszGridMappingValue,
    3071             :                                      const char *pszParam, double dfDefault,
    3072             :                                      bool *pbFound)
    3073             : 
    3074             : {
    3075             :     char *pszTemp =
    3076         440 :         CPLStrdup(CPLSPrintf("%s#%s", pszGridMappingValue, pszParam));
    3077         440 :     const char *pszValue = CSLFetchNameValue(papszMetadata, pszTemp);
    3078         440 :     CPLFree(pszTemp);
    3079             : 
    3080         440 :     if (pbFound)
    3081             :     {
    3082         440 :         *pbFound = (pszValue != nullptr);
    3083             :     }
    3084             : 
    3085         440 :     if (pszValue)
    3086             :     {
    3087           0 :         return CPLAtofM(pszValue);
    3088             :     }
    3089             : 
    3090         440 :     return dfDefault;
    3091             : }
    3092             : 
    3093             : /************************************************************************/
    3094             : /*                           FetchStandardParallels()                   */
    3095             : /************************************************************************/
    3096             : 
    3097             : std::vector<std::string>
    3098           0 : netCDFDataset::FetchStandardParallels(const char *pszGridMappingValue)
    3099             : {
    3100             :     // cf-1.0 tags
    3101           0 :     const char *pszValue = FetchAttr(pszGridMappingValue, CF_PP_STD_PARALLEL);
    3102             : 
    3103           0 :     std::vector<std::string> ret;
    3104           0 :     if (pszValue != nullptr)
    3105             :     {
    3106           0 :         CPLStringList aosValues;
    3107           0 :         if (pszValue[0] != '{' &&
    3108           0 :             CPLString(pszValue).Trim().find(' ') != std::string::npos)
    3109             :         {
    3110             :             // Some files like
    3111             :             // ftp://data.knmi.nl/download/KNW-NetCDF-3D/1.0/noversion/2013/11/14/KNW-1.0_H37-ERA_NL_20131114.nc
    3112             :             // do not use standard formatting for arrays, but just space
    3113             :             // separated syntax
    3114           0 :             aosValues = CSLTokenizeString2(pszValue, " ", 0);
    3115             :         }
    3116             :         else
    3117             :         {
    3118           0 :             aosValues = NCDFTokenizeArray(pszValue);
    3119             :         }
    3120           0 :         for (int i = 0; i < aosValues.size(); i++)
    3121             :         {
    3122           0 :             ret.push_back(aosValues[i]);
    3123             :         }
    3124             :     }
    3125             :     // Try gdal tags.
    3126             :     else
    3127             :     {
    3128           0 :         pszValue = FetchAttr(pszGridMappingValue, CF_PP_STD_PARALLEL_1);
    3129             : 
    3130           0 :         if (pszValue != nullptr)
    3131           0 :             ret.push_back(pszValue);
    3132             : 
    3133           0 :         pszValue = FetchAttr(pszGridMappingValue, CF_PP_STD_PARALLEL_2);
    3134             : 
    3135           0 :         if (pszValue != nullptr)
    3136           0 :             ret.push_back(pszValue);
    3137             :     }
    3138             : 
    3139           0 :     return ret;
    3140             : }
    3141             : 
    3142             : /************************************************************************/
    3143             : /*                           FetchAttr()                                */
    3144             : /************************************************************************/
    3145             : 
    3146        3751 : const char *netCDFDataset::FetchAttr(const char *pszVarFullName,
    3147             :                                      const char *pszAttr)
    3148             : 
    3149             : {
    3150        3751 :     char *pszKey = CPLStrdup(CPLSPrintf("%s#%s", pszVarFullName, pszAttr));
    3151        3751 :     const char *pszValue = CSLFetchNameValue(papszMetadata, pszKey);
    3152        3751 :     CPLFree(pszKey);
    3153        3751 :     return pszValue;
    3154             : }
    3155             : 
    3156        2481 : const char *netCDFDataset::FetchAttr(int nGroupId, int nVarId,
    3157             :                                      const char *pszAttr)
    3158             : 
    3159             : {
    3160        2481 :     char *pszVarFullName = nullptr;
    3161        2481 :     NCDFGetVarFullName(nGroupId, nVarId, &pszVarFullName);
    3162        2481 :     const char *pszValue = FetchAttr(pszVarFullName, pszAttr);
    3163        2481 :     CPLFree(pszVarFullName);
    3164        2481 :     return pszValue;
    3165             : }
    3166             : 
    3167             : /************************************************************************/
    3168             : /*                       IsDifferenceBelow()                            */
    3169             : /************************************************************************/
    3170             : 
    3171        1091 : static bool IsDifferenceBelow(double dfA, double dfB, double dfError)
    3172             : {
    3173        1091 :     const double dfAbsDiff = fabs(dfA - dfB);
    3174        1091 :     return dfAbsDiff <= dfError;
    3175             : }
    3176             : 
    3177             : /************************************************************************/
    3178             : /*                      SetProjectionFromVar()                          */
    3179             : /************************************************************************/
    3180         523 : void netCDFDataset::SetProjectionFromVar(
    3181             :     int nGroupId, int nVarId, bool bReadSRSOnly, const char *pszGivenGM,
    3182             :     std::string *returnProjStr, nccfdriver::SGeometry_Reader *sg,
    3183             :     std::vector<std::string> *paosRemovedMDItems)
    3184             : {
    3185         523 :     bool bGotGeogCS = false;
    3186         523 :     bool bGotCfSRS = false;
    3187         523 :     bool bGotCfWktSRS = false;
    3188         523 :     bool bGotGdalSRS = false;
    3189         523 :     bool bGotCfGT = false;
    3190         523 :     bool bGotGdalGT = false;
    3191             : 
    3192             :     // These values from CF metadata.
    3193         523 :     OGRSpatialReference oSRS;
    3194         523 :     oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    3195         523 :     size_t xdim = nRasterXSize;
    3196         523 :     size_t ydim = nRasterYSize;
    3197             : 
    3198             :     // These values from GDAL metadata.
    3199         523 :     const char *pszWKT = nullptr;
    3200         523 :     const char *pszGeoTransform = nullptr;
    3201             : 
    3202         523 :     netCDFDataset *poDS = this;  // Perhaps this should be removed for clarity.
    3203             : 
    3204         523 :     CPLDebug("GDAL_netCDF", "\n=====\nSetProjectionFromVar( %d, %d)", nGroupId,
    3205             :              nVarId);
    3206             : 
    3207             :     // Get x/y range information.
    3208             : 
    3209             :     // Temp variables to use in SetGeoTransform() and SetProjection().
    3210         523 :     GDALGeoTransform tmpGT;
    3211             : 
    3212             :     // Look for grid_mapping metadata.
    3213         523 :     const char *pszValue = pszGivenGM;
    3214         523 :     CPLString osTmpGridMapping;  // let is in this outer scope as pszValue may
    3215             :         // point to it
    3216         523 :     if (pszValue == nullptr)
    3217             :     {
    3218         480 :         pszValue = FetchAttr(nGroupId, nVarId, CF_GRD_MAPPING);
    3219         480 :         if (pszValue && strchr(pszValue, ':') && strchr(pszValue, ' '))
    3220             :         {
    3221             :             // Expanded form of grid_mapping
    3222             :             // e.g. "crsOSGB: x y crsWGS84: lat lon"
    3223             :             // Pickup the grid_mapping whose coordinates are dimensions of the
    3224             :             // variable
    3225           6 :             CPLStringList aosTokens(CSLTokenizeString2(pszValue, " ", 0));
    3226           3 :             if ((aosTokens.size() % 3) == 0)
    3227             :             {
    3228           3 :                 for (int i = 0; i < aosTokens.size() / 3; i++)
    3229             :                 {
    3230           3 :                     if (CSLFindString(poDS->papszDimName,
    3231           9 :                                       aosTokens[3 * i + 1]) >= 0 &&
    3232           3 :                         CSLFindString(poDS->papszDimName,
    3233           3 :                                       aosTokens[3 * i + 2]) >= 0)
    3234             :                     {
    3235           3 :                         osTmpGridMapping = aosTokens[3 * i];
    3236           6 :                         if (!osTmpGridMapping.empty() &&
    3237           3 :                             osTmpGridMapping.back() == ':')
    3238             :                         {
    3239           3 :                             osTmpGridMapping.resize(osTmpGridMapping.size() -
    3240             :                                                     1);
    3241             :                         }
    3242           3 :                         pszValue = osTmpGridMapping.c_str();
    3243           3 :                         break;
    3244             :                     }
    3245             :                 }
    3246             :             }
    3247             :         }
    3248             :     }
    3249         523 :     char *pszGridMappingValue = CPLStrdup(pszValue ? pszValue : "");
    3250             : 
    3251         523 :     if (!EQUAL(pszGridMappingValue, ""))
    3252             :     {
    3253             :         // Read grid_mapping metadata.
    3254         221 :         int nProjGroupID = -1;
    3255         221 :         int nProjVarID = -1;
    3256         221 :         if (NCDFResolveVar(nGroupId, pszGridMappingValue, &nProjGroupID,
    3257         221 :                            &nProjVarID) == CE_None)
    3258             :         {
    3259         220 :             poDS->ReadAttributes(nProjGroupID, nProjVarID);
    3260             : 
    3261             :             // Look for GDAL spatial_ref and GeoTransform within grid_mapping.
    3262         220 :             CPLFree(pszGridMappingValue);
    3263         220 :             pszGridMappingValue = nullptr;
    3264         220 :             NCDFGetVarFullName(nProjGroupID, nProjVarID, &pszGridMappingValue);
    3265         220 :             if (pszGridMappingValue)
    3266             :             {
    3267         220 :                 CPLDebug("GDAL_netCDF", "got grid_mapping %s",
    3268             :                          pszGridMappingValue);
    3269         220 :                 pszWKT = FetchAttr(pszGridMappingValue, NCDF_SPATIAL_REF);
    3270         220 :                 if (!pszWKT)
    3271             :                 {
    3272          35 :                     pszWKT = FetchAttr(pszGridMappingValue, NCDF_CRS_WKT);
    3273             :                 }
    3274             :                 else
    3275             :                 {
    3276         185 :                     bGotGdalSRS = true;
    3277         185 :                     CPLDebug("GDAL_netCDF", "setting WKT from GDAL");
    3278             :                 }
    3279         220 :                 if (pszWKT)
    3280             :                 {
    3281         190 :                     if (!bGotGdalSRS)
    3282             :                     {
    3283           5 :                         bGotCfWktSRS = true;
    3284           5 :                         CPLDebug("GDAL_netCDF", "setting WKT from CF");
    3285             :                     }
    3286         190 :                     if (returnProjStr != nullptr)
    3287             :                     {
    3288          41 :                         (*returnProjStr) = std::string(pszWKT);
    3289             :                     }
    3290             :                     else
    3291             :                     {
    3292         149 :                         m_bAddedProjectionVarsDefs = true;
    3293         149 :                         m_bAddedProjectionVarsData = true;
    3294         298 :                         OGRSpatialReference oSRSTmp;
    3295         149 :                         oSRSTmp.SetAxisMappingStrategy(
    3296             :                             OAMS_TRADITIONAL_GIS_ORDER);
    3297         149 :                         oSRSTmp.importFromWkt(pszWKT);
    3298         149 :                         SetSpatialRefNoUpdate(&oSRSTmp);
    3299             :                     }
    3300             :                     pszGeoTransform =
    3301         190 :                         FetchAttr(pszGridMappingValue, NCDF_GEOTRANSFORM);
    3302             :                 }
    3303             :             }
    3304             :             else
    3305             :             {
    3306           0 :                 pszGridMappingValue = CPLStrdup("");
    3307             :             }
    3308             :         }
    3309             :     }
    3310             : 
    3311             :     // Get information about the file.
    3312             :     //
    3313             :     // Was this file created by the GDAL netcdf driver?
    3314             :     // Was this file created by the newer (CF-conformant) driver?
    3315             :     //
    3316             :     // 1) If GDAL netcdf metadata is set, and version >= 1.9,
    3317             :     //    it was created with the new driver
    3318             :     // 2) Else, if spatial_ref and GeoTransform are present in the
    3319             :     //    grid_mapping variable, it was created by the old driver
    3320         523 :     pszValue = FetchAttr("NC_GLOBAL", "GDAL");
    3321             : 
    3322         523 :     if (pszValue && NCDFIsGDALVersionGTE(pszValue, 1900))
    3323             :     {
    3324         241 :         bIsGdalFile = true;
    3325         241 :         bIsGdalCfFile = true;
    3326             :     }
    3327         282 :     else if (pszWKT != nullptr && pszGeoTransform != nullptr)
    3328             :     {
    3329          18 :         bIsGdalFile = true;
    3330          18 :         bIsGdalCfFile = false;
    3331             :     }
    3332             : 
    3333             :     // Set default bottom-up default value.
    3334             :     // Y axis dimension and absence of GT can modify this value.
    3335             :     // Override with Config option GDAL_NETCDF_BOTTOMUP.
    3336             : 
    3337             :     // New driver is bottom-up by default.
    3338         523 :     if ((bIsGdalFile && !bIsGdalCfFile) || bSwitchedXY)
    3339          20 :         poDS->bBottomUp = false;
    3340             :     else
    3341         503 :         poDS->bBottomUp = true;
    3342             : 
    3343         523 :     CPLDebug("GDAL_netCDF",
    3344             :              "bIsGdalFile=%d bIsGdalCfFile=%d bSwitchedXY=%d bBottomUp=%d",
    3345         523 :              static_cast<int>(bIsGdalFile), static_cast<int>(bIsGdalCfFile),
    3346         523 :              static_cast<int>(bSwitchedXY), static_cast<int>(bBottomUp));
    3347             : 
    3348             :     // Read projection coordinates.
    3349             : 
    3350         523 :     int nGroupDimXID = -1;
    3351         523 :     int nVarDimXID = -1;
    3352         523 :     int nGroupDimYID = -1;
    3353         523 :     int nVarDimYID = -1;
    3354         523 :     if (sg != nullptr)
    3355             :     {
    3356          43 :         nGroupDimXID = sg->get_ncID();
    3357          43 :         nGroupDimYID = sg->get_ncID();
    3358          43 :         nVarDimXID = sg->getNodeCoordVars()[0];
    3359          43 :         nVarDimYID = sg->getNodeCoordVars()[1];
    3360             :     }
    3361             : 
    3362         523 :     if (!bReadSRSOnly)
    3363             :     {
    3364         351 :         NCDFResolveVar(nGroupId, poDS->papszDimName[nXDimID], &nGroupDimXID,
    3365             :                        &nVarDimXID);
    3366         351 :         NCDFResolveVar(nGroupId, poDS->papszDimName[nYDimID], &nGroupDimYID,
    3367             :                        &nVarDimYID);
    3368             :         // TODO: if above resolving fails we should also search for coordinate
    3369             :         // variables without same name than dimension using the same resolving
    3370             :         // logic. This should handle for example NASA Ocean Color L2 products.
    3371             : 
    3372             :         const bool bIgnoreXYAxisNameChecks =
    3373         702 :             CPLTestBool(CSLFetchNameValueDef(
    3374         351 :                 papszOpenOptions, "IGNORE_XY_AXIS_NAME_CHECKS",
    3375             :                 CPLGetConfigOption("GDAL_NETCDF_IGNORE_XY_AXIS_NAME_CHECKS",
    3376         351 :                                    "NO"))) ||
    3377             :             // Dataset from https://github.com/OSGeo/gdal/issues/4075 has a res
    3378             :             // and transform attributes
    3379         351 :             (FetchAttr(nGroupId, nVarId, "res") != nullptr &&
    3380         702 :              FetchAttr(nGroupId, nVarId, "transform") != nullptr) ||
    3381         350 :             FetchAttr(nGroupId, NC_GLOBAL, "GMT_version") != nullptr;
    3382             : 
    3383             :         // Check that they are 1D or 2D variables
    3384         351 :         if (nVarDimXID >= 0)
    3385             :         {
    3386         255 :             int ndims = -1;
    3387         255 :             nc_inq_varndims(nGroupId, nVarDimXID, &ndims);
    3388         255 :             if (ndims == 0 || ndims > 2)
    3389           0 :                 nVarDimXID = -1;
    3390         255 :             else if (!bIgnoreXYAxisNameChecks)
    3391             :             {
    3392         253 :                 if (!NCDFIsVarLongitude(nGroupId, nVarDimXID, nullptr) &&
    3393         163 :                     !NCDFIsVarProjectionX(nGroupId, nVarDimXID, nullptr) &&
    3394             :                     // In case of inversion of X/Y
    3395         448 :                     !NCDFIsVarLatitude(nGroupId, nVarDimXID, nullptr) &&
    3396          32 :                     !NCDFIsVarProjectionY(nGroupId, nVarDimXID, nullptr))
    3397             :                 {
    3398             :                     char szVarNameX[NC_MAX_NAME + 1];
    3399          32 :                     CPL_IGNORE_RET_VAL(
    3400          32 :                         nc_inq_varname(nGroupId, nVarDimXID, szVarNameX));
    3401          32 :                     if (!(ndims == 1 &&
    3402          31 :                           (EQUAL(szVarNameX, CF_LONGITUDE_STD_NAME) ||
    3403          30 :                            EQUAL(szVarNameX, CF_LONGITUDE_VAR_NAME))))
    3404             :                     {
    3405          31 :                         CPLDebug(
    3406             :                             "netCDF",
    3407             :                             "Georeferencing ignored due to non-specific "
    3408             :                             "enough X axis name. "
    3409             :                             "Set GDAL_NETCDF_IGNORE_XY_AXIS_NAME_CHECKS=YES "
    3410             :                             "as configuration option to bypass this check");
    3411          31 :                         nVarDimXID = -1;
    3412             :                     }
    3413             :                 }
    3414             :             }
    3415             :         }
    3416             : 
    3417         351 :         if (nVarDimYID >= 0)
    3418             :         {
    3419         257 :             int ndims = -1;
    3420         257 :             nc_inq_varndims(nGroupId, nVarDimYID, &ndims);
    3421         257 :             if (ndims == 0 || ndims > 2)
    3422           1 :                 nVarDimYID = -1;
    3423         256 :             else if (!bIgnoreXYAxisNameChecks)
    3424             :             {
    3425         254 :                 if (!NCDFIsVarLatitude(nGroupId, nVarDimYID, nullptr) &&
    3426         164 :                     !NCDFIsVarProjectionY(nGroupId, nVarDimYID, nullptr) &&
    3427             :                     // In case of inversion of X/Y
    3428         451 :                     !NCDFIsVarLongitude(nGroupId, nVarDimYID, nullptr) &&
    3429          33 :                     !NCDFIsVarProjectionX(nGroupId, nVarDimYID, nullptr))
    3430             :                 {
    3431             :                     char szVarNameY[NC_MAX_NAME + 1];
    3432          33 :                     CPL_IGNORE_RET_VAL(
    3433          33 :                         nc_inq_varname(nGroupId, nVarDimYID, szVarNameY));
    3434          33 :                     if (!(ndims == 1 &&
    3435          33 :                           (EQUAL(szVarNameY, CF_LATITUDE_STD_NAME) ||
    3436          32 :                            EQUAL(szVarNameY, CF_LATITUDE_VAR_NAME))))
    3437             :                     {
    3438          32 :                         CPLDebug(
    3439             :                             "netCDF",
    3440             :                             "Georeferencing ignored due to non-specific "
    3441             :                             "enough Y axis name. "
    3442             :                             "Set GDAL_NETCDF_IGNORE_XY_AXIS_NAME_CHECKS=YES "
    3443             :                             "as configuration option to bypass this check");
    3444          32 :                         nVarDimYID = -1;
    3445             :                     }
    3446             :                 }
    3447             :             }
    3448             :         }
    3449             : 
    3450         351 :         if ((nVarDimXID >= 0 && xdim == 1) || (nVarDimXID >= 0 && ydim == 1))
    3451             :         {
    3452           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    3453             :                      "1-pixel width/height files not supported, "
    3454             :                      "xdim: %ld ydim: %ld",
    3455             :                      static_cast<long>(xdim), static_cast<long>(ydim));
    3456           0 :             nVarDimXID = -1;
    3457           0 :             nVarDimYID = -1;
    3458             :         }
    3459             :     }
    3460             : 
    3461         523 :     const char *pszUnits = nullptr;
    3462         523 :     if ((nVarDimXID != -1) && (nVarDimYID != -1) && xdim > 0 && ydim > 0)
    3463             :     {
    3464         267 :         const char *pszUnitsX = FetchAttr(nGroupDimXID, nVarDimXID, "units");
    3465         267 :         const char *pszUnitsY = FetchAttr(nGroupDimYID, nVarDimYID, "units");
    3466             :         // Normalize degrees_east/degrees_north to degrees
    3467             :         // Cf https://github.com/OSGeo/gdal/issues/11009
    3468         267 :         if (pszUnitsX && EQUAL(pszUnitsX, "degrees_east"))
    3469          79 :             pszUnitsX = "degrees";
    3470         267 :         if (pszUnitsY && EQUAL(pszUnitsY, "degrees_north"))
    3471          79 :             pszUnitsY = "degrees";
    3472             : 
    3473         267 :         if (pszUnitsX && pszUnitsY)
    3474             :         {
    3475         220 :             if (EQUAL(pszUnitsX, pszUnitsY))
    3476         217 :                 pszUnits = pszUnitsX;
    3477           3 :             else if (!pszWKT && !EQUAL(pszGridMappingValue, ""))
    3478             :             {
    3479           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3480             :                          "X axis unit (%s) is different from Y axis "
    3481             :                          "unit (%s). SRS will ignore axis unit and be "
    3482             :                          "likely wrong.",
    3483             :                          pszUnitsX, pszUnitsY);
    3484             :             }
    3485             :         }
    3486          47 :         else if (pszUnitsX && !pszWKT && !EQUAL(pszGridMappingValue, ""))
    3487             :         {
    3488           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3489             :                      "X axis unit is defined, but not Y one ."
    3490             :                      "SRS will ignore axis unit and be likely wrong.");
    3491             :         }
    3492          47 :         else if (pszUnitsY && !pszWKT && !EQUAL(pszGridMappingValue, ""))
    3493             :         {
    3494           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3495             :                      "Y axis unit is defined, but not X one ."
    3496             :                      "SRS will ignore axis unit and be likely wrong.");
    3497             :         }
    3498             :     }
    3499             : 
    3500         523 :     if (!pszWKT && !EQUAL(pszGridMappingValue, ""))
    3501             :     {
    3502          31 :         CPLStringList aosGridMappingKeyValues;
    3503          31 :         const size_t nLenGridMappingValue = strlen(pszGridMappingValue);
    3504         789 :         for (const char *const *papszIter = papszMetadata;
    3505         789 :              papszIter && *papszIter; ++papszIter)
    3506             :         {
    3507         758 :             if (STARTS_WITH(*papszIter, pszGridMappingValue) &&
    3508         236 :                 (*papszIter)[nLenGridMappingValue] == '#')
    3509             :             {
    3510         236 :                 char *pszKey = nullptr;
    3511         472 :                 pszValue = CPLParseNameValue(
    3512         236 :                     *papszIter + nLenGridMappingValue + 1, &pszKey);
    3513         236 :                 if (pszKey && pszValue)
    3514         236 :                     aosGridMappingKeyValues.SetNameValue(pszKey, pszValue);
    3515         236 :                 CPLFree(pszKey);
    3516             :             }
    3517             :         }
    3518             : 
    3519          31 :         bGotGeogCS = aosGridMappingKeyValues.FetchNameValue(
    3520             :                          CF_PP_SEMI_MAJOR_AXIS) != nullptr;
    3521             : 
    3522          31 :         oSRS.importFromCF1(aosGridMappingKeyValues.List(), pszUnits);
    3523          31 :         bGotCfSRS = oSRS.IsGeographic() || oSRS.IsProjected();
    3524             :     }
    3525             :     else
    3526             :     {
    3527             :         // Dataset from https://github.com/OSGeo/gdal/issues/4075 has a "crs"
    3528             :         // attribute hold on the variable of interest that contains a PROJ.4
    3529             :         // string
    3530         492 :         pszValue = FetchAttr(nGroupId, nVarId, "crs");
    3531         493 :         if (pszValue &&
    3532           1 :             (strstr(pszValue, "+proj=") != nullptr ||
    3533           0 :              strstr(pszValue, "GEOGCS") != nullptr ||
    3534           0 :              strstr(pszValue, "PROJCS") != nullptr ||
    3535         493 :              strstr(pszValue, "EPSG:") != nullptr) &&
    3536           1 :             oSRS.SetFromUserInput(pszValue) == OGRERR_NONE)
    3537             :         {
    3538           1 :             bGotCfSRS = true;
    3539             :         }
    3540             :     }
    3541             : 
    3542             :     // Set Projection from CF.
    3543         523 :     double dfLinearUnitsConvFactor = 1.0;
    3544         523 :     if ((bGotGeogCS || bGotCfSRS))
    3545             :     {
    3546          31 :         if ((nVarDimXID != -1) && (nVarDimYID != -1) && xdim > 0 && ydim > 0)
    3547             :         {
    3548             :             // Set SRS Units.
    3549             : 
    3550             :             // Check units for x and y.
    3551          28 :             if (oSRS.IsProjected())
    3552             :             {
    3553          25 :                 dfLinearUnitsConvFactor = oSRS.GetLinearUnits(nullptr);
    3554             : 
    3555             :                 // If the user doesn't ask to preserve the axis unit,
    3556             :                 // then normalize to metre
    3557          31 :                 if (dfLinearUnitsConvFactor != 1.0 &&
    3558           6 :                     !CPLFetchBool(GetOpenOptions(), "PRESERVE_AXIS_UNIT_IN_CRS",
    3559             :                                   false))
    3560             :                 {
    3561           5 :                     oSRS.SetLinearUnits("metre", 1.0);
    3562           5 :                     oSRS.SetAuthority("PROJCS|UNIT", "EPSG", 9001);
    3563             :                 }
    3564             :                 else
    3565             :                 {
    3566          20 :                     dfLinearUnitsConvFactor = 1.0;
    3567             :                 }
    3568             :             }
    3569             :         }
    3570             : 
    3571             :         // Set projection.
    3572          31 :         char *pszTempProjection = nullptr;
    3573          31 :         oSRS.exportToWkt(&pszTempProjection);
    3574          31 :         if (pszTempProjection)
    3575             :         {
    3576          31 :             CPLDebug("GDAL_netCDF", "setting WKT from CF");
    3577          31 :             if (returnProjStr != nullptr)
    3578             :             {
    3579           2 :                 (*returnProjStr) = std::string(pszTempProjection);
    3580             :             }
    3581             :             else
    3582             :             {
    3583          29 :                 m_bAddedProjectionVarsDefs = true;
    3584          29 :                 m_bAddedProjectionVarsData = true;
    3585          29 :                 SetSpatialRefNoUpdate(&oSRS);
    3586             :             }
    3587             :         }
    3588          31 :         CPLFree(pszTempProjection);
    3589             :     }
    3590             : 
    3591         523 :     if (!bReadSRSOnly && (nVarDimXID != -1) && (nVarDimYID != -1) && xdim > 0 &&
    3592             :         ydim > 0)
    3593             :     {
    3594             :         double *pdfXCoord =
    3595         224 :             static_cast<double *>(CPLCalloc(xdim, sizeof(double)));
    3596             :         double *pdfYCoord =
    3597         224 :             static_cast<double *>(CPLCalloc(ydim, sizeof(double)));
    3598             : 
    3599         224 :         size_t start[2] = {0, 0};
    3600         224 :         size_t edge[2] = {xdim, 0};
    3601         224 :         int status = nc_get_vara_double(nGroupDimXID, nVarDimXID, start, edge,
    3602             :                                         pdfXCoord);
    3603         224 :         NCDF_ERR(status);
    3604             : 
    3605         224 :         edge[0] = ydim;
    3606         224 :         status = nc_get_vara_double(nGroupDimYID, nVarDimYID, start, edge,
    3607             :                                     pdfYCoord);
    3608         224 :         NCDF_ERR(status);
    3609             : 
    3610         224 :         nc_type nc_var_dimx_datatype = NC_NAT;
    3611             :         status =
    3612         224 :             nc_inq_vartype(nGroupDimXID, nVarDimXID, &nc_var_dimx_datatype);
    3613         224 :         NCDF_ERR(status);
    3614             : 
    3615         224 :         nc_type nc_var_dimy_datatype = NC_NAT;
    3616             :         status =
    3617         224 :             nc_inq_vartype(nGroupDimYID, nVarDimYID, &nc_var_dimy_datatype);
    3618         224 :         NCDF_ERR(status);
    3619             : 
    3620         224 :         if (!poDS->bSwitchedXY)
    3621             :         {
    3622             :             // Convert ]180,540] longitude values to ]-180,0].
    3623         312 :             if (NCDFIsVarLongitude(nGroupDimXID, nVarDimXID, nullptr) &&
    3624          90 :                 CPLTestBool(
    3625             :                     CPLGetConfigOption("GDAL_NETCDF_CENTERLONG_180", "YES")))
    3626             :             {
    3627             :                 // If minimum longitude is > 180, subtract 360 from all.
    3628             :                 // Add a check on the maximum X value too, since
    3629             :                 // NCDFIsVarLongitude() is not very specific by default (see
    3630             :                 // https://github.com/OSGeo/gdal/issues/1440)
    3631          97 :                 if (std::min(pdfXCoord[0], pdfXCoord[xdim - 1]) > 180.0 &&
    3632           7 :                     std::max(pdfXCoord[0], pdfXCoord[xdim - 1]) <= 540)
    3633             :                 {
    3634           0 :                     CPLDebug(
    3635             :                         "GDAL_netCDF",
    3636             :                         "Offsetting longitudes from ]180,540] to ]-180,180]. "
    3637             :                         "Can be disabled with GDAL_NETCDF_CENTERLONG_180=NO");
    3638           0 :                     for (size_t i = 0; i < xdim; i++)
    3639           0 :                         pdfXCoord[i] -= 360;
    3640             :                 }
    3641             :             }
    3642             :         }
    3643             : 
    3644             :         // Is pixel spacing uniform across the map?
    3645             : 
    3646             :         // Check Longitude.
    3647             : 
    3648         224 :         bool bLonSpacingOK = false;
    3649         224 :         if (xdim == 2)
    3650             :         {
    3651          28 :             bLonSpacingOK = true;
    3652             :         }
    3653             :         else
    3654             :         {
    3655         196 :             bool bWestIsLeft = (pdfXCoord[0] < pdfXCoord[xdim - 1]);
    3656             : 
    3657             :             // fix longitudes if longitudes should increase from
    3658             :             // west to east, but west > east
    3659         276 :             if (NCDFIsVarLongitude(nGroupDimXID, nVarDimXID, nullptr) &&
    3660          80 :                 !bWestIsLeft)
    3661             :             {
    3662           2 :                 size_t ndecreases = 0;
    3663             : 
    3664             :                 // there is lon wrap if longitudes increase
    3665             :                 // with one single decrease
    3666         107 :                 for (size_t i = 1; i < xdim; i++)
    3667             :                 {
    3668         105 :                     if (pdfXCoord[i] < pdfXCoord[i - 1])
    3669           1 :                         ndecreases++;
    3670             :                 }
    3671             : 
    3672           2 :                 if (ndecreases == 1)
    3673             :                 {
    3674           1 :                     CPLDebug("GDAL_netCDF", "longitude wrap detected");
    3675           4 :                     for (size_t i = 0; i < xdim; i++)
    3676             :                     {
    3677           3 :                         if (pdfXCoord[i] > pdfXCoord[xdim - 1])
    3678           1 :                             pdfXCoord[i] -= 360;
    3679             :                     }
    3680             :                 }
    3681             :             }
    3682             : 
    3683         196 :             const double dfSpacingBegin = pdfXCoord[1] - pdfXCoord[0];
    3684         196 :             const double dfSpacingMiddle =
    3685         196 :                 pdfXCoord[xdim / 2 + 1] - pdfXCoord[xdim / 2];
    3686         196 :             const double dfSpacingLast =
    3687         196 :                 pdfXCoord[xdim - 1] - pdfXCoord[xdim - 2];
    3688             : 
    3689         196 :             CPLDebug("GDAL_netCDF",
    3690             :                      "xdim: %ld dfSpacingBegin: %f dfSpacingMiddle: %f "
    3691             :                      "dfSpacingLast: %f",
    3692             :                      static_cast<long>(xdim), dfSpacingBegin, dfSpacingMiddle,
    3693             :                      dfSpacingLast);
    3694             : #ifdef NCDF_DEBUG
    3695             :             CPLDebug("GDAL_netCDF", "xcoords: %f %f %f %f %f %f", pdfXCoord[0],
    3696             :                      pdfXCoord[1], pdfXCoord[xdim / 2],
    3697             :                      pdfXCoord[(xdim / 2) + 1], pdfXCoord[xdim - 2],
    3698             :                      pdfXCoord[xdim - 1]);
    3699             : #endif
    3700             : 
    3701             :             // ftp://ftp.cdc.noaa.gov/Datasets/NARR/Dailies/monolevel/vwnd.10m.2015.nc
    3702             :             // requires a 0.02% tolerance, so let's settle for 0.05%
    3703             : 
    3704             :             // For float variables, increase to 0.2% (as seen in
    3705             :             // https://github.com/OSGeo/gdal/issues/3663)
    3706         196 :             const double dfEpsRel =
    3707         196 :                 nc_var_dimx_datatype == NC_FLOAT ? 0.002 : 0.0005;
    3708             : 
    3709             :             const double dfEps =
    3710             :                 dfEpsRel *
    3711         392 :                 std::max(fabs(dfSpacingBegin),
    3712         196 :                          std::max(fabs(dfSpacingMiddle), fabs(dfSpacingLast)));
    3713         386 :             if (IsDifferenceBelow(dfSpacingBegin, dfSpacingLast, dfEps) &&
    3714         386 :                 IsDifferenceBelow(dfSpacingBegin, dfSpacingMiddle, dfEps) &&
    3715         190 :                 IsDifferenceBelow(dfSpacingMiddle, dfSpacingLast, dfEps))
    3716             :             {
    3717         190 :                 bLonSpacingOK = true;
    3718             :             }
    3719           6 :             else if (CPLTestBool(CPLGetConfigOption(
    3720             :                          "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK", "NO")))
    3721             :             {
    3722           0 :                 bLonSpacingOK = true;
    3723           0 :                 CPLDebug(
    3724             :                     "GDAL_netCDF",
    3725             :                     "Longitude/X is not equally spaced, but will be considered "
    3726             :                     "as such because of "
    3727             :                     "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK");
    3728             :             }
    3729             :         }
    3730             : 
    3731         224 :         if (bLonSpacingOK == false)
    3732             :         {
    3733           6 :             CPLDebug(
    3734             :                 "GDAL_netCDF", "%s",
    3735             :                 "Longitude/X is not equally spaced (with a 0.05% tolerance). "
    3736             :                 "You may set the "
    3737             :                 "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK configuration "
    3738             :                 "option to YES to ignore this check");
    3739             :         }
    3740             : 
    3741             :         // Check Latitude.
    3742         224 :         bool bLatSpacingOK = false;
    3743             : 
    3744         224 :         if (ydim == 2)
    3745             :         {
    3746          48 :             bLatSpacingOK = true;
    3747             :         }
    3748             :         else
    3749             :         {
    3750         176 :             const double dfSpacingBegin = pdfYCoord[1] - pdfYCoord[0];
    3751         176 :             const double dfSpacingMiddle =
    3752         176 :                 pdfYCoord[ydim / 2 + 1] - pdfYCoord[ydim / 2];
    3753             : 
    3754         176 :             const double dfSpacingLast =
    3755         176 :                 pdfYCoord[ydim - 1] - pdfYCoord[ydim - 2];
    3756             : 
    3757         176 :             CPLDebug("GDAL_netCDF",
    3758             :                      "ydim: %ld dfSpacingBegin: %f dfSpacingMiddle: %f "
    3759             :                      "dfSpacingLast: %f",
    3760             :                      (long)ydim, dfSpacingBegin, dfSpacingMiddle,
    3761             :                      dfSpacingLast);
    3762             : #ifdef NCDF_DEBUG
    3763             :             CPLDebug("GDAL_netCDF", "ycoords: %f %f %f %f %f %f", pdfYCoord[0],
    3764             :                      pdfYCoord[1], pdfYCoord[ydim / 2],
    3765             :                      pdfYCoord[(ydim / 2) + 1], pdfYCoord[ydim - 2],
    3766             :                      pdfYCoord[ydim - 1]);
    3767             : #endif
    3768             : 
    3769         176 :             const double dfEpsRel =
    3770         176 :                 nc_var_dimy_datatype == NC_FLOAT ? 0.002 : 0.0005;
    3771             : 
    3772             :             const double dfEps =
    3773             :                 dfEpsRel *
    3774         352 :                 std::max(fabs(dfSpacingBegin),
    3775         176 :                          std::max(fabs(dfSpacingMiddle), fabs(dfSpacingLast)));
    3776         350 :             if (IsDifferenceBelow(dfSpacingBegin, dfSpacingLast, dfEps) &&
    3777         350 :                 IsDifferenceBelow(dfSpacingBegin, dfSpacingMiddle, dfEps) &&
    3778         165 :                 IsDifferenceBelow(dfSpacingMiddle, dfSpacingLast, dfEps))
    3779             :             {
    3780         165 :                 bLatSpacingOK = true;
    3781             :             }
    3782          11 :             else if (CPLTestBool(CPLGetConfigOption(
    3783             :                          "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK", "NO")))
    3784             :             {
    3785           0 :                 bLatSpacingOK = true;
    3786           0 :                 CPLDebug(
    3787             :                     "GDAL_netCDF",
    3788             :                     "Latitude/Y is not equally spaced, but will be considered "
    3789             :                     "as such because of "
    3790             :                     "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK");
    3791             :             }
    3792          11 :             else if (!oSRS.IsProjected() &&
    3793          11 :                      fabs(dfSpacingBegin - dfSpacingLast) <= 0.1 &&
    3794          30 :                      fabs(dfSpacingBegin - dfSpacingMiddle) <= 0.1 &&
    3795           8 :                      fabs(dfSpacingMiddle - dfSpacingLast) <= 0.1)
    3796             :             {
    3797           8 :                 bLatSpacingOK = true;
    3798           8 :                 CPLError(CE_Warning, CPLE_AppDefined,
    3799             :                          "Latitude grid not spaced evenly.  "
    3800             :                          "Setting projection for grid spacing is "
    3801             :                          "within 0.1 degrees threshold.");
    3802             : 
    3803           8 :                 CPLDebug("GDAL_netCDF",
    3804             :                          "Latitude grid not spaced evenly, but within 0.1 "
    3805             :                          "degree threshold (probably a Gaussian grid).  "
    3806             :                          "Saving original latitude values in Y_VALUES "
    3807             :                          "geolocation metadata");
    3808           8 :                 Set1DGeolocation(nGroupDimYID, nVarDimYID, "Y");
    3809             :             }
    3810             : 
    3811         176 :             if (bLatSpacingOK == false)
    3812             :             {
    3813           3 :                 CPLDebug(
    3814             :                     "GDAL_netCDF", "%s",
    3815             :                     "Latitude/Y is not equally spaced (with a 0.05% "
    3816             :                     "tolerance). "
    3817             :                     "You may set the "
    3818             :                     "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK configuration "
    3819             :                     "option to YES to ignore this check");
    3820             :             }
    3821             :         }
    3822             : 
    3823         224 :         if (bLonSpacingOK && bLatSpacingOK)
    3824             :         {
    3825             :             // We have gridded data so we can set the Georeferencing info.
    3826             : 
    3827             :             // Enable GeoTransform.
    3828             : 
    3829             :             // In the following "actual_range" and "node_offset"
    3830             :             // are attributes used by netCDF files created by GMT.
    3831             :             // If we find them we know how to proceed. Else, use
    3832             :             // the original algorithm.
    3833         217 :             bGotCfGT = true;
    3834             : 
    3835         217 :             int node_offset = 0;
    3836             :             const bool bUseActualRange =
    3837         217 :                 NCDFResolveAttInt(nGroupId, NC_GLOBAL, "node_offset",
    3838         217 :                                   &node_offset) == CE_None;
    3839             : 
    3840         217 :             double adfActualRange[2] = {0.0, 0.0};
    3841         217 :             double xMinMax[2] = {0.0, 0.0};
    3842         217 :             double yMinMax[2] = {0.0, 0.0};
    3843             : 
    3844             :             const auto RoundMinMaxForFloatVals =
    3845          60 :                 [](double &dfMin, double &dfMax, int nIntervals)
    3846             :             {
    3847             :                 // Helps for a case where longitudes range from
    3848             :                 // -179.99 to 180.0 with a 0.01 degree spacing.
    3849             :                 // However as this is encoded in a float array,
    3850             :                 // -179.99 is actually read as -179.99000549316406 as
    3851             :                 // a double. Try to detect that and correct the rounding
    3852             : 
    3853          88 :                 const auto IsAlmostInteger = [](double dfVal)
    3854             :                 {
    3855          88 :                     constexpr double THRESHOLD_INTEGER = 1e-3;
    3856          88 :                     return std::fabs(dfVal - std::round(dfVal)) <=
    3857          88 :                            THRESHOLD_INTEGER;
    3858             :                 };
    3859             : 
    3860          60 :                 const double dfSpacing = (dfMax - dfMin) / nIntervals;
    3861          60 :                 if (dfSpacing > 0)
    3862             :                 {
    3863          48 :                     const double dfInvSpacing = 1.0 / dfSpacing;
    3864          48 :                     if (IsAlmostInteger(dfInvSpacing))
    3865             :                     {
    3866          20 :                         const double dfRoundedSpacing =
    3867          20 :                             1.0 / std::round(dfInvSpacing);
    3868          20 :                         const double dfMinDivRoundedSpacing =
    3869          20 :                             dfMin / dfRoundedSpacing;
    3870          20 :                         const double dfMaxDivRoundedSpacing =
    3871          20 :                             dfMax / dfRoundedSpacing;
    3872          40 :                         if (IsAlmostInteger(dfMinDivRoundedSpacing) &&
    3873          20 :                             IsAlmostInteger(dfMaxDivRoundedSpacing))
    3874             :                         {
    3875          20 :                             const double dfRoundedMin =
    3876          20 :                                 std::round(dfMinDivRoundedSpacing) *
    3877             :                                 dfRoundedSpacing;
    3878          20 :                             const double dfRoundedMax =
    3879          20 :                                 std::round(dfMaxDivRoundedSpacing) *
    3880             :                                 dfRoundedSpacing;
    3881          20 :                             if (static_cast<float>(dfMin) ==
    3882          20 :                                     static_cast<float>(dfRoundedMin) &&
    3883           8 :                                 static_cast<float>(dfMax) ==
    3884           8 :                                     static_cast<float>(dfRoundedMax))
    3885             :                             {
    3886           7 :                                 dfMin = dfRoundedMin;
    3887           7 :                                 dfMax = dfRoundedMax;
    3888             :                             }
    3889             :                         }
    3890             :                     }
    3891             :                 }
    3892          60 :             };
    3893             : 
    3894         220 :             if (bUseActualRange &&
    3895           3 :                 !nc_get_att_double(nGroupDimXID, nVarDimXID, "actual_range",
    3896             :                                    adfActualRange))
    3897             :             {
    3898           1 :                 xMinMax[0] = adfActualRange[0];
    3899           1 :                 xMinMax[1] = adfActualRange[1];
    3900             : 
    3901             :                 // Present xMinMax[] in the same order as padfXCoord
    3902           1 :                 if ((xMinMax[0] - xMinMax[1]) *
    3903           1 :                         (pdfXCoord[0] - pdfXCoord[xdim - 1]) <
    3904             :                     0)
    3905             :                 {
    3906           0 :                     std::swap(xMinMax[0], xMinMax[1]);
    3907             :                 }
    3908             :             }
    3909             :             else
    3910             :             {
    3911         216 :                 xMinMax[0] = pdfXCoord[0];
    3912         216 :                 xMinMax[1] = pdfXCoord[xdim - 1];
    3913         216 :                 node_offset = 0;
    3914             : 
    3915         216 :                 if (nc_var_dimx_datatype == NC_FLOAT)
    3916             :                 {
    3917          30 :                     RoundMinMaxForFloatVals(xMinMax[0], xMinMax[1],
    3918          30 :                                             poDS->nRasterXSize - 1);
    3919             :                 }
    3920             :             }
    3921             : 
    3922         220 :             if (bUseActualRange &&
    3923           3 :                 !nc_get_att_double(nGroupDimYID, nVarDimYID, "actual_range",
    3924             :                                    adfActualRange))
    3925             :             {
    3926           1 :                 yMinMax[0] = adfActualRange[0];
    3927           1 :                 yMinMax[1] = adfActualRange[1];
    3928             : 
    3929             :                 // Present yMinMax[] in the same order as pdfYCoord
    3930           1 :                 if ((yMinMax[0] - yMinMax[1]) *
    3931           1 :                         (pdfYCoord[0] - pdfYCoord[ydim - 1]) <
    3932             :                     0)
    3933             :                 {
    3934           0 :                     std::swap(yMinMax[0], yMinMax[1]);
    3935             :                 }
    3936             :             }
    3937             :             else
    3938             :             {
    3939         216 :                 yMinMax[0] = pdfYCoord[0];
    3940         216 :                 yMinMax[1] = pdfYCoord[ydim - 1];
    3941         216 :                 node_offset = 0;
    3942             : 
    3943         216 :                 if (nc_var_dimy_datatype == NC_FLOAT)
    3944             :                 {
    3945          30 :                     RoundMinMaxForFloatVals(yMinMax[0], yMinMax[1],
    3946          30 :                                             poDS->nRasterYSize - 1);
    3947             :                 }
    3948             :             }
    3949             : 
    3950         217 :             double dfCoordOffset = 0.0;
    3951         217 :             double dfCoordScale = 1.0;
    3952         217 :             if (!nc_get_att_double(nGroupId, nVarDimXID, CF_ADD_OFFSET,
    3953         221 :                                    &dfCoordOffset) &&
    3954           4 :                 !nc_get_att_double(nGroupId, nVarDimXID, CF_SCALE_FACTOR,
    3955             :                                    &dfCoordScale))
    3956             :             {
    3957           4 :                 xMinMax[0] = dfCoordOffset + xMinMax[0] * dfCoordScale;
    3958           4 :                 xMinMax[1] = dfCoordOffset + xMinMax[1] * dfCoordScale;
    3959             :             }
    3960             : 
    3961         217 :             if (!nc_get_att_double(nGroupId, nVarDimYID, CF_ADD_OFFSET,
    3962         221 :                                    &dfCoordOffset) &&
    3963           4 :                 !nc_get_att_double(nGroupId, nVarDimYID, CF_SCALE_FACTOR,
    3964             :                                    &dfCoordScale))
    3965             :             {
    3966           4 :                 yMinMax[0] = dfCoordOffset + yMinMax[0] * dfCoordScale;
    3967           4 :                 yMinMax[1] = dfCoordOffset + yMinMax[1] * dfCoordScale;
    3968             :             }
    3969             : 
    3970             :             // Check for reverse order of y-coordinate.
    3971         217 :             if (!bSwitchedXY)
    3972             :             {
    3973         215 :                 poDS->bBottomUp = (yMinMax[0] <= yMinMax[1]);
    3974         215 :                 CPLDebug("GDAL_netCDF", "set bBottomUp = %d from Y axis",
    3975         215 :                          static_cast<int>(poDS->bBottomUp));
    3976         215 :                 if (!poDS->bBottomUp)
    3977             :                 {
    3978          32 :                     std::swap(yMinMax[0], yMinMax[1]);
    3979             :                 }
    3980             :             }
    3981             : 
    3982             :             // Geostationary satellites can specify units in (micro)radians
    3983             :             // So we check if they do, and if so convert to linear units
    3984             :             // (meters)
    3985         217 :             const char *pszProjName = oSRS.GetAttrValue("PROJECTION");
    3986         217 :             if (pszProjName != nullptr)
    3987             :             {
    3988          24 :                 if (EQUAL(pszProjName, SRS_PT_GEOSTATIONARY_SATELLITE))
    3989             :                 {
    3990             :                     double satelliteHeight =
    3991           3 :                         oSRS.GetProjParm(SRS_PP_SATELLITE_HEIGHT, 1.0);
    3992           3 :                     size_t nAttlen = 0;
    3993             :                     char szUnits[NC_MAX_NAME + 1];
    3994           3 :                     szUnits[0] = '\0';
    3995           3 :                     nc_type nAttype = NC_NAT;
    3996           3 :                     nc_inq_att(nGroupId, nVarDimXID, "units", &nAttype,
    3997             :                                &nAttlen);
    3998           6 :                     if (nAttlen < sizeof(szUnits) &&
    3999           3 :                         nc_get_att_text(nGroupId, nVarDimXID, "units",
    4000             :                                         szUnits) == NC_NOERR)
    4001             :                     {
    4002           3 :                         szUnits[nAttlen] = '\0';
    4003           3 :                         if (EQUAL(szUnits, "microradian"))
    4004             :                         {
    4005           1 :                             xMinMax[0] =
    4006           1 :                                 xMinMax[0] * satelliteHeight * 0.000001;
    4007           1 :                             xMinMax[1] =
    4008           1 :                                 xMinMax[1] * satelliteHeight * 0.000001;
    4009             :                         }
    4010           2 :                         else if (EQUAL(szUnits, "rad") ||
    4011           1 :                                  EQUAL(szUnits, "radian"))
    4012             :                         {
    4013           2 :                             xMinMax[0] = xMinMax[0] * satelliteHeight;
    4014           2 :                             xMinMax[1] = xMinMax[1] * satelliteHeight;
    4015             :                         }
    4016             :                     }
    4017           3 :                     szUnits[0] = '\0';
    4018           3 :                     nc_inq_att(nGroupId, nVarDimYID, "units", &nAttype,
    4019             :                                &nAttlen);
    4020           6 :                     if (nAttlen < sizeof(szUnits) &&
    4021           3 :                         nc_get_att_text(nGroupId, nVarDimYID, "units",
    4022             :                                         szUnits) == NC_NOERR)
    4023             :                     {
    4024           3 :                         szUnits[nAttlen] = '\0';
    4025           3 :                         if (EQUAL(szUnits, "microradian"))
    4026             :                         {
    4027           1 :                             yMinMax[0] =
    4028           1 :                                 yMinMax[0] * satelliteHeight * 0.000001;
    4029           1 :                             yMinMax[1] =
    4030           1 :                                 yMinMax[1] * satelliteHeight * 0.000001;
    4031             :                         }
    4032           2 :                         else if (EQUAL(szUnits, "rad") ||
    4033           1 :                                  EQUAL(szUnits, "radian"))
    4034             :                         {
    4035           2 :                             yMinMax[0] = yMinMax[0] * satelliteHeight;
    4036           2 :                             yMinMax[1] = yMinMax[1] * satelliteHeight;
    4037             :                         }
    4038             :                     }
    4039             :                 }
    4040             :             }
    4041             : 
    4042         217 :             tmpGT[0] = xMinMax[0];
    4043         434 :             tmpGT[1] = (xMinMax[1] - xMinMax[0]) /
    4044         217 :                        (poDS->nRasterXSize + (node_offset - 1));
    4045         217 :             tmpGT[2] = 0;
    4046         217 :             if (bSwitchedXY)
    4047             :             {
    4048           2 :                 tmpGT[3] = yMinMax[0];
    4049           2 :                 tmpGT[4] = 0;
    4050           2 :                 tmpGT[5] = (yMinMax[1] - yMinMax[0]) /
    4051           2 :                            (poDS->nRasterYSize + (node_offset - 1));
    4052             :             }
    4053             :             else
    4054             :             {
    4055         215 :                 tmpGT[3] = yMinMax[1];
    4056         215 :                 tmpGT[4] = 0;
    4057         215 :                 tmpGT[5] = (yMinMax[0] - yMinMax[1]) /
    4058         215 :                            (poDS->nRasterYSize + (node_offset - 1));
    4059             :             }
    4060             : 
    4061             :             // Compute the center of the pixel.
    4062         217 :             if (!node_offset)
    4063             :             {
    4064             :                 // Otherwise its already the pixel center.
    4065         217 :                 tmpGT[0] -= (tmpGT[1] / 2);
    4066         217 :                 tmpGT[3] -= (tmpGT[5] / 2);
    4067             :             }
    4068             :         }
    4069             : 
    4070             :         const auto AreSRSEqualThroughProj4String =
    4071           2 :             [](const OGRSpatialReference &oSRS1,
    4072             :                const OGRSpatialReference &oSRS2)
    4073             :         {
    4074           2 :             char *pszProj4Str1 = nullptr;
    4075           2 :             oSRS1.exportToProj4(&pszProj4Str1);
    4076             : 
    4077           2 :             char *pszProj4Str2 = nullptr;
    4078           2 :             oSRS2.exportToProj4(&pszProj4Str2);
    4079             : 
    4080             :             {
    4081           2 :                 char *pszTmp = strstr(pszProj4Str1, "+datum=");
    4082           2 :                 if (pszTmp)
    4083           0 :                     memcpy(pszTmp, "+ellps=", strlen("+ellps="));
    4084             :             }
    4085             : 
    4086             :             {
    4087           2 :                 char *pszTmp = strstr(pszProj4Str2, "+datum=");
    4088           2 :                 if (pszTmp)
    4089           2 :                     memcpy(pszTmp, "+ellps=", strlen("+ellps="));
    4090             :             }
    4091             : 
    4092           2 :             bool bRet = false;
    4093           2 :             if (pszProj4Str1 && pszProj4Str2 &&
    4094           2 :                 EQUAL(pszProj4Str1, pszProj4Str2))
    4095             :             {
    4096           1 :                 bRet = true;
    4097             :             }
    4098             : 
    4099           2 :             CPLFree(pszProj4Str1);
    4100           2 :             CPLFree(pszProj4Str2);
    4101           2 :             return bRet;
    4102             :         };
    4103             : 
    4104         224 :         if (dfLinearUnitsConvFactor != 1.0)
    4105             :         {
    4106          35 :             for (int i = 0; i < 6; ++i)
    4107          30 :                 tmpGT[i] *= dfLinearUnitsConvFactor;
    4108             : 
    4109           5 :             if (paosRemovedMDItems)
    4110             :             {
    4111             :                 char szVarNameX[NC_MAX_NAME + 1];
    4112           5 :                 CPL_IGNORE_RET_VAL(
    4113           5 :                     nc_inq_varname(nGroupId, nVarDimXID, szVarNameX));
    4114             : 
    4115             :                 char szVarNameY[NC_MAX_NAME + 1];
    4116           5 :                 CPL_IGNORE_RET_VAL(
    4117           5 :                     nc_inq_varname(nGroupId, nVarDimYID, szVarNameY));
    4118             : 
    4119           5 :                 paosRemovedMDItems->push_back(
    4120             :                     CPLSPrintf("%s#units", szVarNameX));
    4121           5 :                 paosRemovedMDItems->push_back(
    4122             :                     CPLSPrintf("%s#units", szVarNameY));
    4123             :             }
    4124             :         }
    4125             : 
    4126             :         // If there is a global "geospatial_bounds_crs" attribute, check that it
    4127             :         // is consistent with the SRS, and if so, use it as the SRS
    4128             :         const char *pszGBCRS =
    4129         224 :             FetchAttr(nGroupId, NC_GLOBAL, "geospatial_bounds_crs");
    4130         224 :         if (pszGBCRS && STARTS_WITH(pszGBCRS, "EPSG:"))
    4131             :         {
    4132           4 :             OGRSpatialReference oSRSFromGBCRS;
    4133           2 :             oSRSFromGBCRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    4134           2 :             if (oSRSFromGBCRS.SetFromUserInput(
    4135             :                     pszGBCRS,
    4136             :                     OGRSpatialReference::
    4137           4 :                         SET_FROM_USER_INPUT_LIMITATIONS_get()) == OGRERR_NONE &&
    4138           2 :                 AreSRSEqualThroughProj4String(oSRS, oSRSFromGBCRS))
    4139             :             {
    4140           1 :                 oSRS = std::move(oSRSFromGBCRS);
    4141           1 :                 SetSpatialRefNoUpdate(&oSRS);
    4142             :             }
    4143             :         }
    4144             : 
    4145         224 :         CPLFree(pdfXCoord);
    4146         224 :         CPLFree(pdfYCoord);
    4147             :     }  // end if(has dims)
    4148             : 
    4149             :     // Process custom GeoTransform GDAL value.
    4150         523 :     if (!EQUAL(pszGridMappingValue, ""))
    4151             :     {
    4152         221 :         if (pszGeoTransform != nullptr)
    4153             :         {
    4154             :             CPLStringList aosGeoTransform(
    4155         222 :                 CSLTokenizeString2(pszGeoTransform, " ", CSLT_HONOURSTRINGS));
    4156         111 :             if (aosGeoTransform.size() == 6)
    4157             :             {
    4158         111 :                 GDALGeoTransform gtFromAttribute;
    4159         777 :                 for (int i = 0; i < 6; i++)
    4160             :                 {
    4161         666 :                     gtFromAttribute[i] = CPLAtof(aosGeoTransform[i]);
    4162             :                 }
    4163             : 
    4164         111 :                 if (bGotCfGT)
    4165             :                 {
    4166          94 :                     constexpr double GT_RELERROR_WARN_THRESHOLD = 1e-6;
    4167          94 :                     double dfMaxAbsoluteError = 0.0;
    4168         658 :                     for (int i = 0; i < 6; i++)
    4169             :                     {
    4170             :                         double dfAbsoluteError =
    4171         564 :                             std::abs(tmpGT[i] - gtFromAttribute[i]);
    4172         564 :                         if (dfAbsoluteError >
    4173         564 :                             std::abs(gtFromAttribute[i] *
    4174             :                                      GT_RELERROR_WARN_THRESHOLD))
    4175             :                         {
    4176           2 :                             dfMaxAbsoluteError =
    4177           2 :                                 std::max(dfMaxAbsoluteError, dfAbsoluteError);
    4178             :                         }
    4179             :                     }
    4180             : 
    4181          94 :                     if (dfMaxAbsoluteError > 0)
    4182             :                     {
    4183           2 :                         CPLError(CE_Warning, CPLE_AppDefined,
    4184             :                                  "GeoTransform read from attribute of %s "
    4185             :                                  "variable differs from value calculated from "
    4186             :                                  "dimension variables (max diff = %g). Using "
    4187             :                                  "value from attribute.",
    4188             :                                  pszGridMappingValue, dfMaxAbsoluteError);
    4189             :                     }
    4190             :                 }
    4191             : 
    4192         111 :                 tmpGT = std::move(gtFromAttribute);
    4193         111 :                 bGotGdalGT = true;
    4194             :             }
    4195             :         }
    4196             :         else
    4197             :         {
    4198             :             // Look for corner array values.
    4199             :             // CPLDebug("GDAL_netCDF",
    4200             :             //           "looking for geotransform corners");
    4201         110 :             bool bGotNN = false;
    4202         110 :             double dfNN = FetchCopyParam(pszGridMappingValue,
    4203             :                                          "Northernmost_Northing", 0, &bGotNN);
    4204             : 
    4205         110 :             bool bGotSN = false;
    4206         110 :             double dfSN = FetchCopyParam(pszGridMappingValue,
    4207             :                                          "Southernmost_Northing", 0, &bGotSN);
    4208             : 
    4209         110 :             bool bGotEE = false;
    4210         110 :             double dfEE = FetchCopyParam(pszGridMappingValue,
    4211             :                                          "Easternmost_Easting", 0, &bGotEE);
    4212             : 
    4213         110 :             bool bGotWE = false;
    4214         110 :             double dfWE = FetchCopyParam(pszGridMappingValue,
    4215             :                                          "Westernmost_Easting", 0, &bGotWE);
    4216             : 
    4217             :             // Only set the GeoTransform if we got all the values.
    4218         110 :             if (bGotNN && bGotSN && bGotEE && bGotWE)
    4219             :             {
    4220           0 :                 bGotGdalGT = true;
    4221             : 
    4222           0 :                 tmpGT[0] = dfWE;
    4223           0 :                 tmpGT[1] = (dfEE - dfWE) / (poDS->GetRasterXSize() - 1);
    4224           0 :                 tmpGT[2] = 0.0;
    4225           0 :                 tmpGT[3] = dfNN;
    4226           0 :                 tmpGT[4] = 0.0;
    4227           0 :                 tmpGT[5] = (dfSN - dfNN) / (poDS->GetRasterYSize() - 1);
    4228             :                 // Compute the center of the pixel.
    4229           0 :                 tmpGT[0] = dfWE - (tmpGT[1] / 2);
    4230           0 :                 tmpGT[3] = dfNN - (tmpGT[5] / 2);
    4231             :             }
    4232             :         }  // (pszGeoTransform != NULL)
    4233             : 
    4234         221 :         if (bGotGdalSRS && !bGotGdalGT)
    4235          74 :             CPLDebug("GDAL_netCDF", "Got SRS but no geotransform from GDAL!");
    4236             :     }
    4237             : 
    4238         523 :     if (!pszWKT && !bGotCfSRS)
    4239             :     {
    4240             :         // Some netCDF files have a srid attribute (#6613) like
    4241             :         // urn:ogc:def:crs:EPSG::6931
    4242         302 :         const char *pszSRID = FetchAttr(pszGridMappingValue, "srid");
    4243         302 :         if (pszSRID != nullptr)
    4244             :         {
    4245           0 :             oSRS.Clear();
    4246           0 :             if (oSRS.SetFromUserInput(
    4247             :                     pszSRID,
    4248             :                     OGRSpatialReference::
    4249           0 :                         SET_FROM_USER_INPUT_LIMITATIONS_get()) == OGRERR_NONE)
    4250             :             {
    4251           0 :                 char *pszWKTExport = nullptr;
    4252           0 :                 CPLDebug("GDAL_netCDF", "Got SRS from %s", pszSRID);
    4253           0 :                 oSRS.exportToWkt(&pszWKTExport);
    4254           0 :                 if (returnProjStr != nullptr)
    4255             :                 {
    4256           0 :                     (*returnProjStr) = std::string(pszWKTExport);
    4257             :                 }
    4258             :                 else
    4259             :                 {
    4260           0 :                     m_bAddedProjectionVarsDefs = true;
    4261           0 :                     m_bAddedProjectionVarsData = true;
    4262           0 :                     SetSpatialRefNoUpdate(&oSRS);
    4263             :                 }
    4264           0 :                 CPLFree(pszWKTExport);
    4265             :             }
    4266             :         }
    4267             :     }
    4268             : 
    4269         523 :     CPLFree(pszGridMappingValue);
    4270             : 
    4271         523 :     if (bReadSRSOnly)
    4272         172 :         return;
    4273             : 
    4274             :     // Determines the SRS to be used by the geolocation array, if any
    4275         702 :     std::string osGeolocWKT = SRS_WKT_WGS84_LAT_LONG;
    4276         351 :     if (!m_oSRS.IsEmpty())
    4277             :     {
    4278         264 :         OGRSpatialReference oGeogCRS;
    4279         132 :         oGeogCRS.CopyGeogCSFrom(&m_oSRS);
    4280         132 :         char *pszWKTTmp = nullptr;
    4281         132 :         const char *const apszOptions[] = {"FORMAT=WKT2_2019", nullptr};
    4282         132 :         if (oGeogCRS.exportToWkt(&pszWKTTmp, apszOptions) == OGRERR_NONE)
    4283             :         {
    4284         132 :             osGeolocWKT = pszWKTTmp;
    4285             :         }
    4286         132 :         CPLFree(pszWKTTmp);
    4287             :     }
    4288             : 
    4289             :     // Process geolocation arrays from CF "coordinates" attribute.
    4290         702 :     std::string osGeolocXName, osGeolocYName;
    4291         351 :     if (ProcessCFGeolocation(nGroupId, nVarId, osGeolocWKT, osGeolocXName,
    4292         351 :                              osGeolocYName))
    4293             :     {
    4294          53 :         bool bCanCancelGT = true;
    4295          53 :         if ((nVarDimXID != -1) && (nVarDimYID != -1))
    4296             :         {
    4297             :             char szVarNameX[NC_MAX_NAME + 1];
    4298          44 :             CPL_IGNORE_RET_VAL(
    4299          44 :                 nc_inq_varname(nGroupId, nVarDimXID, szVarNameX));
    4300             :             char szVarNameY[NC_MAX_NAME + 1];
    4301          44 :             CPL_IGNORE_RET_VAL(
    4302          44 :                 nc_inq_varname(nGroupId, nVarDimYID, szVarNameY));
    4303          44 :             bCanCancelGT =
    4304          44 :                 !(osGeolocXName == szVarNameX && osGeolocYName == szVarNameY);
    4305             :         }
    4306          88 :         if (bCanCancelGT && !m_oSRS.IsGeographic() && !m_oSRS.IsProjected() &&
    4307          35 :             !bSwitchedXY)
    4308             :         {
    4309          33 :             bGotCfGT = false;
    4310             :         }
    4311             :     }
    4312         121 :     else if (!bGotCfGT && !bReadSRSOnly && (nVarDimXID != -1) &&
    4313         422 :              (nVarDimYID != -1) && xdim > 0 && ydim > 0 &&
    4314           3 :              ((!bSwitchedXY &&
    4315           3 :                NCDFIsVarLongitude(nGroupId, nVarDimXID, nullptr) &&
    4316           1 :                NCDFIsVarLatitude(nGroupId, nVarDimYID, nullptr)) ||
    4317           2 :               (bSwitchedXY &&
    4318           0 :                NCDFIsVarLongitude(nGroupId, nVarDimYID, nullptr) &&
    4319           0 :                NCDFIsVarLatitude(nGroupId, nVarDimXID, nullptr))))
    4320             :     {
    4321             :         // Case of autotest/gdrivers/data/netcdf/GLMELT_4X5.OCN.nc
    4322             :         // which is indexed by lat, lon variables, but lat has irregular
    4323             :         // spacing.
    4324           1 :         const char *pszGeolocXFullName = poDS->papszDimName[poDS->nXDimID];
    4325           1 :         const char *pszGeolocYFullName = poDS->papszDimName[poDS->nYDimID];
    4326           1 :         if (bSwitchedXY)
    4327             :         {
    4328           0 :             std::swap(pszGeolocXFullName, pszGeolocYFullName);
    4329           0 :             GDALPamDataset::SetMetadataItem("SWAP_XY", "YES", "GEOLOCATION");
    4330             :         }
    4331             : 
    4332           1 :         CPLDebug("GDAL_netCDF", "using variables %s and %s for GEOLOCATION",
    4333             :                  pszGeolocXFullName, pszGeolocYFullName);
    4334             : 
    4335           1 :         GDALPamDataset::SetMetadataItem("SRS", osGeolocWKT.c_str(),
    4336             :                                         "GEOLOCATION");
    4337             : 
    4338           2 :         CPLString osTMP;
    4339           1 :         osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(),
    4340           1 :                      pszGeolocXFullName);
    4341             : 
    4342           1 :         GDALPamDataset::SetMetadataItem("X_DATASET", osTMP, "GEOLOCATION");
    4343           1 :         GDALPamDataset::SetMetadataItem("X_BAND", "1", "GEOLOCATION");
    4344           1 :         osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(),
    4345           1 :                      pszGeolocYFullName);
    4346             : 
    4347           1 :         GDALPamDataset::SetMetadataItem("Y_DATASET", osTMP, "GEOLOCATION");
    4348           1 :         GDALPamDataset::SetMetadataItem("Y_BAND", "1", "GEOLOCATION");
    4349             : 
    4350           1 :         GDALPamDataset::SetMetadataItem("PIXEL_OFFSET", "0", "GEOLOCATION");
    4351           1 :         GDALPamDataset::SetMetadataItem("PIXEL_STEP", "1", "GEOLOCATION");
    4352             : 
    4353           1 :         GDALPamDataset::SetMetadataItem("LINE_OFFSET", "0", "GEOLOCATION");
    4354           1 :         GDALPamDataset::SetMetadataItem("LINE_STEP", "1", "GEOLOCATION");
    4355             : 
    4356           1 :         GDALPamDataset::SetMetadataItem("GEOREFERENCING_CONVENTION",
    4357             :                                         "PIXEL_CENTER", "GEOLOCATION");
    4358             :     }
    4359             : 
    4360             :     // Set GeoTransform if we got a complete one - after projection has been set
    4361         351 :     if (bGotCfGT || bGotGdalGT)
    4362             :     {
    4363         199 :         m_bAddedProjectionVarsDefs = true;
    4364         199 :         m_bAddedProjectionVarsData = true;
    4365         199 :         SetGeoTransformNoUpdate(tmpGT);
    4366             :     }
    4367             : 
    4368             :     // Debugging reports.
    4369         351 :     CPLDebug("GDAL_netCDF",
    4370             :              "bGotGeogCS=%d bGotCfSRS=%d bGotCfGT=%d bGotCfWktSRS=%d "
    4371             :              "bGotGdalSRS=%d bGotGdalGT=%d",
    4372             :              static_cast<int>(bGotGeogCS), static_cast<int>(bGotCfSRS),
    4373             :              static_cast<int>(bGotCfGT), static_cast<int>(bGotCfWktSRS),
    4374             :              static_cast<int>(bGotGdalSRS), static_cast<int>(bGotGdalGT));
    4375             : 
    4376         351 :     if (!bGotCfGT && !bGotGdalGT)
    4377         152 :         CPLDebug("GDAL_netCDF", "did not get geotransform from CF nor GDAL!");
    4378             : 
    4379         351 :     if (!bGotGeogCS && !bGotCfSRS && !bGotGdalSRS && !bGotCfGT && !bGotCfWktSRS)
    4380         152 :         CPLDebug("GDAL_netCDF", "did not get projection from CF nor GDAL!");
    4381             : 
    4382             :     // wish of 6195
    4383             :     // we don't have CS/SRS, but we do have GT, and we live in -180,360 -90,90
    4384         351 :     if (!bGotGeogCS && !bGotCfSRS && !bGotGdalSRS && !bGotCfWktSRS)
    4385             :     {
    4386         219 :         if (bGotCfGT || bGotGdalGT)
    4387             :         {
    4388         134 :             bool bAssumedLongLat = CPLTestBool(CSLFetchNameValueDef(
    4389          67 :                 papszOpenOptions, "ASSUME_LONGLAT",
    4390             :                 CPLGetConfigOption("GDAL_NETCDF_ASSUME_LONGLAT", "NO")));
    4391             : 
    4392           2 :             if (bAssumedLongLat && tmpGT[0] >= -180 && tmpGT[0] < 360 &&
    4393           2 :                 (tmpGT[0] + tmpGT[1] * poDS->GetRasterXSize()) <= 360 &&
    4394          71 :                 tmpGT[3] <= 90 && tmpGT[3] > -90 &&
    4395           2 :                 (tmpGT[3] + tmpGT[5] * poDS->GetRasterYSize()) >= -90)
    4396             :             {
    4397             : 
    4398           2 :                 poDS->bIsGeographic = true;
    4399           2 :                 char *pszTempProjection = nullptr;
    4400             :                 // seems odd to use 4326 so OGC:CRS84
    4401           2 :                 oSRS.SetFromUserInput("OGC:CRS84");
    4402           2 :                 oSRS.exportToWkt(&pszTempProjection);
    4403           2 :                 if (returnProjStr != nullptr)
    4404             :                 {
    4405           0 :                     (*returnProjStr) = std::string(pszTempProjection);
    4406             :                 }
    4407             :                 else
    4408             :                 {
    4409           2 :                     m_bAddedProjectionVarsDefs = true;
    4410           2 :                     m_bAddedProjectionVarsData = true;
    4411           2 :                     SetSpatialRefNoUpdate(&oSRS);
    4412             :                 }
    4413           2 :                 CPLFree(pszTempProjection);
    4414             : 
    4415           2 :                 CPLDebug("netCDF",
    4416             :                          "Assumed Longitude Latitude CRS 'OGC:CRS84' because "
    4417             :                          "none otherwise available and geotransform within "
    4418             :                          "suitable bounds. "
    4419             :                          "Set GDAL_NETCDF_ASSUME_LONGLAT=NO as configuration "
    4420             :                          "option or "
    4421             :                          "    ASSUME_LONGLAT=NO as open option to bypass this "
    4422             :                          "assumption.");
    4423             :             }
    4424             :         }
    4425             :     }
    4426             : 
    4427             : // Search for Well-known GeogCS if got only CF WKT
    4428             : // Disabled for now, as a named datum also include control points
    4429             : // (see mailing list and bug#4281
    4430             : // For example, WGS84 vs. GDA94 (EPSG:3577) - AEA in netcdf_cf.py
    4431             : 
    4432             : // Disabled for now, but could be set in a config option.
    4433             : #if 0
    4434             :     bool bLookForWellKnownGCS = false;  // This could be a Config Option.
    4435             : 
    4436             :     if( bLookForWellKnownGCS && bGotCfSRS && !bGotGdalSRS )
    4437             :     {
    4438             :         // ET - Could use a more exhaustive method by scanning all EPSG codes in
    4439             :         // data/gcs.csv as proposed by Even in the gdal-dev mailing list "help
    4440             :         // for comparing two WKT".
    4441             :         // This code could be contributed to a new function.
    4442             :         // OGRSpatialReference * OGRSpatialReference::FindMatchingGeogCS(
    4443             :         //     const OGRSpatialReference *poOther) */
    4444             :         CPLDebug("GDAL_netCDF", "Searching for Well-known GeogCS");
    4445             :         const char *pszWKGCSList[] = { "WGS84", "WGS72", "NAD27", "NAD83" };
    4446             :         char *pszWKGCS = NULL;
    4447             :         oSRS.exportToPrettyWkt(&pszWKGCS);
    4448             :         for( size_t i = 0; i < sizeof(pszWKGCSList) / 8; i++ )
    4449             :         {
    4450             :             pszWKGCS = CPLStrdup(pszWKGCSList[i]);
    4451             :             OGRSpatialReference oSRSTmp;
    4452             :             oSRSTmp.SetWellKnownGeogCS(pszWKGCSList[i]);
    4453             :             // Set datum to unknown, bug #4281.
    4454             :             if( oSRSTmp.GetAttrNode("DATUM" ) )
    4455             :                 oSRSTmp.GetAttrNode("DATUM")->GetChild(0)->SetValue("unknown");
    4456             :             // Could use OGRSpatialReference::StripCTParms(), but let's keep
    4457             :             // TOWGS84.
    4458             :             oSRSTmp.GetRoot()->StripNodes("AXIS");
    4459             :             oSRSTmp.GetRoot()->StripNodes("AUTHORITY");
    4460             :             oSRSTmp.GetRoot()->StripNodes("EXTENSION");
    4461             : 
    4462             :             oSRSTmp.exportToPrettyWkt(&pszWKGCS);
    4463             :             if( oSRS.IsSameGeogCS(&oSRSTmp) )
    4464             :             {
    4465             :                 oSRS.SetWellKnownGeogCS(pszWKGCSList[i]);
    4466             :                 oSRS.exportToWkt(&(pszTempProjection));
    4467             :                 SetProjection(pszTempProjection);
    4468             :                 CPLFree(pszTempProjection);
    4469             :             }
    4470             :         }
    4471             :     }
    4472             : #endif
    4473             : }
    4474             : 
    4475         129 : void netCDFDataset::SetProjectionFromVar(int nGroupId, int nVarId,
    4476             :                                          bool bReadSRSOnly)
    4477             : {
    4478         129 :     SetProjectionFromVar(nGroupId, nVarId, bReadSRSOnly, nullptr, nullptr,
    4479             :                          nullptr, nullptr);
    4480         129 : }
    4481             : 
    4482         287 : bool netCDFDataset::ProcessNASAL2OceanGeoLocation(int nGroupId, int nVarId)
    4483             : {
    4484             :     // Cf https://oceancolor.gsfc.nasa.gov/docs/format/l2nc/
    4485             :     // and https://github.com/OSGeo/gdal/issues/7605
    4486             : 
    4487             :     // Check for a structure like:
    4488             :     /* netcdf SNPP_VIIRS.20230406T024200.L2.OC.NRT {
    4489             :         dimensions:
    4490             :             number_of_lines = 3248 ;
    4491             :             pixels_per_line = 3200 ;
    4492             :             [...]
    4493             :             pixel_control_points = 3200 ;
    4494             :         [...]
    4495             :         group: geophysical_data {
    4496             :           variables:
    4497             :             short aot_862(number_of_lines, pixels_per_line) ;  <-- nVarId
    4498             :                 [...]
    4499             :         }
    4500             :         group: navigation_data {
    4501             :           variables:
    4502             :             float longitude(number_of_lines, pixel_control_points) ;
    4503             :                 [...]
    4504             :             float latitude(number_of_lines, pixel_control_points) ;
    4505             :                 [...]
    4506             :         }
    4507             :     }
    4508             :     */
    4509             :     // Note that the longitude and latitude arrays are not indexed by the
    4510             :     // same dimensions. Handle only the case where
    4511             :     // pixel_control_points == pixels_per_line
    4512             :     // If there was a subsampling of the geolocation arrays, we'd need to
    4513             :     // add more logic.
    4514             : 
    4515         574 :     std::string osGroupName;
    4516         287 :     osGroupName.resize(NC_MAX_NAME);
    4517         287 :     NCDF_ERR(nc_inq_grpname(nGroupId, &osGroupName[0]));
    4518         287 :     osGroupName.resize(strlen(osGroupName.data()));
    4519         287 :     if (osGroupName != "geophysical_data")
    4520         286 :         return false;
    4521             : 
    4522           1 :     int nVarDims = 0;
    4523           1 :     NCDF_ERR(nc_inq_varndims(nGroupId, nVarId, &nVarDims));
    4524           1 :     if (nVarDims != 2)
    4525           0 :         return false;
    4526             : 
    4527           1 :     int nNavigationDataGrpId = 0;
    4528           1 :     if (nc_inq_grp_ncid(cdfid, "navigation_data", &nNavigationDataGrpId) !=
    4529             :         NC_NOERR)
    4530           0 :         return false;
    4531             : 
    4532             :     std::array<int, 2> anVarDimIds;
    4533           1 :     NCDF_ERR(nc_inq_vardimid(nGroupId, nVarId, anVarDimIds.data()));
    4534             : 
    4535           1 :     int nLongitudeId = 0;
    4536           1 :     int nLatitudeId = 0;
    4537           1 :     if (nc_inq_varid(nNavigationDataGrpId, "longitude", &nLongitudeId) !=
    4538           2 :             NC_NOERR ||
    4539           1 :         nc_inq_varid(nNavigationDataGrpId, "latitude", &nLatitudeId) !=
    4540             :             NC_NOERR)
    4541             :     {
    4542           0 :         return false;
    4543             :     }
    4544             : 
    4545           1 :     int nDimsLongitude = 0;
    4546           1 :     NCDF_ERR(
    4547             :         nc_inq_varndims(nNavigationDataGrpId, nLongitudeId, &nDimsLongitude));
    4548           1 :     int nDimsLatitude = 0;
    4549           1 :     NCDF_ERR(
    4550             :         nc_inq_varndims(nNavigationDataGrpId, nLatitudeId, &nDimsLatitude));
    4551           1 :     if (!(nDimsLongitude == 2 && nDimsLatitude == 2))
    4552             :     {
    4553           0 :         return false;
    4554             :     }
    4555             : 
    4556             :     std::array<int, 2> anDimLongitudeIds;
    4557           1 :     NCDF_ERR(nc_inq_vardimid(nNavigationDataGrpId, nLongitudeId,
    4558             :                              anDimLongitudeIds.data()));
    4559             :     std::array<int, 2> anDimLatitudeIds;
    4560           1 :     NCDF_ERR(nc_inq_vardimid(nNavigationDataGrpId, nLatitudeId,
    4561             :                              anDimLatitudeIds.data()));
    4562           1 :     if (anDimLongitudeIds != anDimLatitudeIds)
    4563             :     {
    4564           0 :         return false;
    4565             :     }
    4566             : 
    4567             :     std::array<size_t, 2> anSizeVarDimIds;
    4568             :     std::array<size_t, 2> anSizeLongLatIds;
    4569           2 :     if (!(nc_inq_dimlen(cdfid, anVarDimIds[0], &anSizeVarDimIds[0]) ==
    4570           1 :               NC_NOERR &&
    4571           1 :           nc_inq_dimlen(cdfid, anVarDimIds[1], &anSizeVarDimIds[1]) ==
    4572           1 :               NC_NOERR &&
    4573           1 :           nc_inq_dimlen(cdfid, anDimLongitudeIds[0], &anSizeLongLatIds[0]) ==
    4574           1 :               NC_NOERR &&
    4575           1 :           nc_inq_dimlen(cdfid, anDimLongitudeIds[1], &anSizeLongLatIds[1]) ==
    4576             :               NC_NOERR &&
    4577           1 :           anSizeVarDimIds == anSizeLongLatIds))
    4578             :     {
    4579           0 :         return false;
    4580             :     }
    4581             : 
    4582           1 :     const char *pszGeolocXFullName = "/navigation_data/longitude";
    4583           1 :     const char *pszGeolocYFullName = "/navigation_data/latitude";
    4584             : 
    4585           1 :     if (bSwitchedXY)
    4586             :     {
    4587           0 :         std::swap(pszGeolocXFullName, pszGeolocYFullName);
    4588           0 :         GDALPamDataset::SetMetadataItem("SWAP_XY", "YES", "GEOLOCATION");
    4589             :     }
    4590             : 
    4591           1 :     CPLDebug("GDAL_netCDF", "using variables %s and %s for GEOLOCATION",
    4592             :              pszGeolocXFullName, pszGeolocYFullName);
    4593             : 
    4594           1 :     GDALPamDataset::SetMetadataItem("SRS", SRS_WKT_WGS84_LAT_LONG,
    4595             :                                     "GEOLOCATION");
    4596             : 
    4597           1 :     CPLString osTMP;
    4598           1 :     osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(), pszGeolocXFullName);
    4599             : 
    4600           1 :     GDALPamDataset::SetMetadataItem("X_DATASET", osTMP, "GEOLOCATION");
    4601           1 :     GDALPamDataset::SetMetadataItem("X_BAND", "1", "GEOLOCATION");
    4602           1 :     osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(), pszGeolocYFullName);
    4603             : 
    4604           1 :     GDALPamDataset::SetMetadataItem("Y_DATASET", osTMP, "GEOLOCATION");
    4605           1 :     GDALPamDataset::SetMetadataItem("Y_BAND", "1", "GEOLOCATION");
    4606             : 
    4607           1 :     GDALPamDataset::SetMetadataItem("PIXEL_OFFSET", "0", "GEOLOCATION");
    4608           1 :     GDALPamDataset::SetMetadataItem("PIXEL_STEP", "1", "GEOLOCATION");
    4609             : 
    4610           1 :     GDALPamDataset::SetMetadataItem("LINE_OFFSET", "0", "GEOLOCATION");
    4611           1 :     GDALPamDataset::SetMetadataItem("LINE_STEP", "1", "GEOLOCATION");
    4612             : 
    4613           1 :     GDALPamDataset::SetMetadataItem("GEOREFERENCING_CONVENTION", "PIXEL_CENTER",
    4614             :                                     "GEOLOCATION");
    4615           1 :     return true;
    4616             : }
    4617             : 
    4618         286 : bool netCDFDataset::ProcessNASAEMITGeoLocation(int nGroupId, int nVarId)
    4619             : {
    4620             :     // Cf https://earth.jpl.nasa.gov/emit/data/data-portal/coverage-and-forecasts/
    4621             : 
    4622             :     // Check for a structure like:
    4623             :     /* netcdf EMIT_L2A_RFL_001_20220903T163129_2224611_012 {
    4624             :         dimensions:
    4625             :             downtrack = 1280 ;
    4626             :             crosstrack = 1242 ;
    4627             :             bands = 285 ;
    4628             :             [...]
    4629             : 
    4630             :         variables:
    4631             :             float reflectance(downtrack, crosstrack, bands) ;
    4632             : 
    4633             :         group: location {
    4634             :           variables:
    4635             :                 double lon(downtrack, crosstrack) ;
    4636             :                         lon:_FillValue = -9999. ;
    4637             :                         lon:long_name = "Longitude (WGS-84)" ;
    4638             :                         lon:units = "degrees east" ;
    4639             :                 double lat(downtrack, crosstrack) ;
    4640             :                         lat:_FillValue = -9999. ;
    4641             :                         lat:long_name = "Latitude (WGS-84)" ;
    4642             :                         lat:units = "degrees north" ;
    4643             :           } // group location
    4644             : 
    4645             :     }
    4646             :     or
    4647             :     netcdf EMIT_L2B_MIN_001_20231024T055538_2329704_040 {
    4648             :         dimensions:
    4649             :                 downtrack = 1664 ;
    4650             :                 crosstrack = 1242 ;
    4651             :                 [...]
    4652             :         variables:
    4653             :                 float group_1_band_depth(downtrack, crosstrack) ;
    4654             :                         group_1_band_depth:_FillValue = -9999.f ;
    4655             :                         group_1_band_depth:long_name = "Group 1 Band Depth" ;
    4656             :                         group_1_band_depth:units = "unitless" ;
    4657             :                 [...]
    4658             :         group: location {
    4659             :           variables:
    4660             :                 double lon(downtrack, crosstrack) ;
    4661             :                         lon:_FillValue = -9999. ;
    4662             :                         lon:long_name = "Longitude (WGS-84)" ;
    4663             :                         lon:units = "degrees east" ;
    4664             :                 double lat(downtrack, crosstrack) ;
    4665             :                         lat:_FillValue = -9999. ;
    4666             :                         lat:long_name = "Latitude (WGS-84)" ;
    4667             :                         lat:units = "degrees north" ;
    4668             :         }
    4669             :     */
    4670             : 
    4671         286 :     int nVarDims = 0;
    4672         286 :     NCDF_ERR(nc_inq_varndims(nGroupId, nVarId, &nVarDims));
    4673         286 :     if (nVarDims != 2 && nVarDims != 3)
    4674          14 :         return false;
    4675             : 
    4676         272 :     int nLocationGrpId = 0;
    4677         272 :     if (nc_inq_grp_ncid(cdfid, "location", &nLocationGrpId) != NC_NOERR)
    4678          58 :         return false;
    4679             : 
    4680             :     std::array<int, 3> anVarDimIds;
    4681         214 :     NCDF_ERR(nc_inq_vardimid(nGroupId, nVarId, anVarDimIds.data()));
    4682         214 :     if (nYDimID != anVarDimIds[0] || nXDimID != anVarDimIds[1])
    4683          21 :         return false;
    4684             : 
    4685         193 :     int nLongitudeId = 0;
    4686         193 :     int nLatitudeId = 0;
    4687         231 :     if (nc_inq_varid(nLocationGrpId, "lon", &nLongitudeId) != NC_NOERR ||
    4688          38 :         nc_inq_varid(nLocationGrpId, "lat", &nLatitudeId) != NC_NOERR)
    4689             :     {
    4690         155 :         return false;
    4691             :     }
    4692             : 
    4693          38 :     int nDimsLongitude = 0;
    4694          38 :     NCDF_ERR(nc_inq_varndims(nLocationGrpId, nLongitudeId, &nDimsLongitude));
    4695          38 :     int nDimsLatitude = 0;
    4696          38 :     NCDF_ERR(nc_inq_varndims(nLocationGrpId, nLatitudeId, &nDimsLatitude));
    4697          38 :     if (!(nDimsLongitude == 2 && nDimsLatitude == 2))
    4698             :     {
    4699          34 :         return false;
    4700             :     }
    4701             : 
    4702             :     std::array<int, 2> anDimLongitudeIds;
    4703           4 :     NCDF_ERR(nc_inq_vardimid(nLocationGrpId, nLongitudeId,
    4704             :                              anDimLongitudeIds.data()));
    4705             :     std::array<int, 2> anDimLatitudeIds;
    4706           4 :     NCDF_ERR(
    4707             :         nc_inq_vardimid(nLocationGrpId, nLatitudeId, anDimLatitudeIds.data()));
    4708           4 :     if (anDimLongitudeIds != anDimLatitudeIds)
    4709             :     {
    4710           0 :         return false;
    4711             :     }
    4712             : 
    4713           8 :     if (anDimLongitudeIds[0] != anVarDimIds[0] ||
    4714           4 :         anDimLongitudeIds[1] != anVarDimIds[1])
    4715             :     {
    4716           0 :         return false;
    4717             :     }
    4718             : 
    4719           4 :     const char *pszGeolocXFullName = "/location/lon";
    4720           4 :     const char *pszGeolocYFullName = "/location/lat";
    4721             : 
    4722           4 :     CPLDebug("GDAL_netCDF", "using variables %s and %s for GEOLOCATION",
    4723             :              pszGeolocXFullName, pszGeolocYFullName);
    4724             : 
    4725           4 :     GDALPamDataset::SetMetadataItem("SRS", SRS_WKT_WGS84_LAT_LONG,
    4726             :                                     "GEOLOCATION");
    4727             : 
    4728           4 :     CPLString osTMP;
    4729           4 :     osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(), pszGeolocXFullName);
    4730             : 
    4731           4 :     GDALPamDataset::SetMetadataItem("X_DATASET", osTMP, "GEOLOCATION");
    4732           4 :     GDALPamDataset::SetMetadataItem("X_BAND", "1", "GEOLOCATION");
    4733           4 :     osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(), pszGeolocYFullName);
    4734             : 
    4735           4 :     GDALPamDataset::SetMetadataItem("Y_DATASET", osTMP, "GEOLOCATION");
    4736           4 :     GDALPamDataset::SetMetadataItem("Y_BAND", "1", "GEOLOCATION");
    4737             : 
    4738           4 :     GDALPamDataset::SetMetadataItem("PIXEL_OFFSET", "0", "GEOLOCATION");
    4739           4 :     GDALPamDataset::SetMetadataItem("PIXEL_STEP", "1", "GEOLOCATION");
    4740             : 
    4741           4 :     GDALPamDataset::SetMetadataItem("LINE_OFFSET", "0", "GEOLOCATION");
    4742           4 :     GDALPamDataset::SetMetadataItem("LINE_STEP", "1", "GEOLOCATION");
    4743             : 
    4744           4 :     GDALPamDataset::SetMetadataItem("GEOREFERENCING_CONVENTION", "PIXEL_CENTER",
    4745             :                                     "GEOLOCATION");
    4746           4 :     return true;
    4747             : }
    4748             : 
    4749         351 : int netCDFDataset::ProcessCFGeolocation(int nGroupId, int nVarId,
    4750             :                                         const std::string &osGeolocWKT,
    4751             :                                         std::string &osGeolocXNameOut,
    4752             :                                         std::string &osGeolocYNameOut)
    4753             : {
    4754         351 :     bool bAddGeoloc = false;
    4755         351 :     char *pszCoordinates = nullptr;
    4756             : 
    4757             :     // If there is no explicit "coordinates" attribute, check if there are
    4758             :     // "lon" and "lat" 2D variables whose dimensions are the last
    4759             :     // 2 ones of the variable of interest.
    4760         351 :     if (NCDFGetAttr(nGroupId, nVarId, "coordinates", &pszCoordinates) !=
    4761             :         CE_None)
    4762             :     {
    4763         304 :         CPLFree(pszCoordinates);
    4764         304 :         pszCoordinates = nullptr;
    4765             : 
    4766         304 :         int nVarDims = 0;
    4767         304 :         NCDF_ERR(nc_inq_varndims(nGroupId, nVarId, &nVarDims));
    4768         304 :         if (nVarDims >= 2)
    4769             :         {
    4770         608 :             std::vector<int> anVarDimIds(nVarDims);
    4771         304 :             NCDF_ERR(nc_inq_vardimid(nGroupId, nVarId, anVarDimIds.data()));
    4772             : 
    4773         304 :             int nLongitudeId = 0;
    4774         304 :             int nLatitudeId = 0;
    4775         372 :             if (nc_inq_varid(nGroupId, "lon", &nLongitudeId) == NC_NOERR &&
    4776          68 :                 nc_inq_varid(nGroupId, "lat", &nLatitudeId) == NC_NOERR)
    4777             :             {
    4778          68 :                 int nDimsLongitude = 0;
    4779          68 :                 NCDF_ERR(
    4780             :                     nc_inq_varndims(nGroupId, nLongitudeId, &nDimsLongitude));
    4781          68 :                 int nDimsLatitude = 0;
    4782          68 :                 NCDF_ERR(
    4783             :                     nc_inq_varndims(nGroupId, nLatitudeId, &nDimsLatitude));
    4784          68 :                 if (nDimsLongitude == 2 && nDimsLatitude == 2)
    4785             :                 {
    4786          34 :                     std::vector<int> anDimLongitudeIds(2);
    4787          17 :                     NCDF_ERR(nc_inq_vardimid(nGroupId, nLongitudeId,
    4788             :                                              anDimLongitudeIds.data()));
    4789          34 :                     std::vector<int> anDimLatitudeIds(2);
    4790          17 :                     NCDF_ERR(nc_inq_vardimid(nGroupId, nLatitudeId,
    4791             :                                              anDimLatitudeIds.data()));
    4792          17 :                     if (anDimLongitudeIds == anDimLatitudeIds &&
    4793          34 :                         anVarDimIds[anVarDimIds.size() - 2] ==
    4794          51 :                             anDimLongitudeIds[0] &&
    4795          34 :                         anVarDimIds[anVarDimIds.size() - 1] ==
    4796          17 :                             anDimLongitudeIds[1])
    4797             :                     {
    4798          17 :                         pszCoordinates = CPLStrdup("lon lat");
    4799             :                     }
    4800             :                 }
    4801             :             }
    4802             :         }
    4803             :     }
    4804             : 
    4805         351 :     if (pszCoordinates)
    4806             :     {
    4807             :         // Get X and Y geolocation names from coordinates attribute.
    4808             :         const CPLStringList aosCoordinates(
    4809         128 :             NCDFTokenizeCoordinatesAttribute(pszCoordinates));
    4810          64 :         if (aosCoordinates.size() >= 2)
    4811             :         {
    4812             :             char szGeolocXName[NC_MAX_NAME + 1];
    4813             :             char szGeolocYName[NC_MAX_NAME + 1];
    4814          61 :             szGeolocXName[0] = '\0';
    4815          61 :             szGeolocYName[0] = '\0';
    4816             : 
    4817             :             // Test that each variable is longitude/latitude.
    4818         196 :             for (int i = 0; i < aosCoordinates.size(); i++)
    4819             :             {
    4820         135 :                 if (NCDFIsVarLongitude(nGroupId, -1, aosCoordinates[i]))
    4821             :                 {
    4822          50 :                     int nOtherGroupId = -1;
    4823          50 :                     int nOtherVarId = -1;
    4824             :                     // Check that the variable actually exists
    4825             :                     // Needed on Sentinel-3 products
    4826          50 :                     if (NCDFResolveVar(nGroupId, aosCoordinates[i],
    4827          50 :                                        &nOtherGroupId, &nOtherVarId) == CE_None)
    4828             :                     {
    4829          48 :                         snprintf(szGeolocXName, sizeof(szGeolocXName), "%s",
    4830             :                                  aosCoordinates[i]);
    4831             :                     }
    4832             :                 }
    4833          85 :                 else if (NCDFIsVarLatitude(nGroupId, -1, aosCoordinates[i]))
    4834             :                 {
    4835          50 :                     int nOtherGroupId = -1;
    4836          50 :                     int nOtherVarId = -1;
    4837             :                     // Check that the variable actually exists
    4838             :                     // Needed on Sentinel-3 products
    4839          50 :                     if (NCDFResolveVar(nGroupId, aosCoordinates[i],
    4840          50 :                                        &nOtherGroupId, &nOtherVarId) == CE_None)
    4841             :                     {
    4842          48 :                         snprintf(szGeolocYName, sizeof(szGeolocYName), "%s",
    4843             :                                  aosCoordinates[i]);
    4844             :                     }
    4845             :                 }
    4846             :             }
    4847             :             // Add GEOLOCATION metadata.
    4848          61 :             if (!EQUAL(szGeolocXName, "") && !EQUAL(szGeolocYName, ""))
    4849             :             {
    4850          48 :                 osGeolocXNameOut = szGeolocXName;
    4851          48 :                 osGeolocYNameOut = szGeolocYName;
    4852             : 
    4853          48 :                 char *pszGeolocXFullName = nullptr;
    4854          48 :                 char *pszGeolocYFullName = nullptr;
    4855          48 :                 if (NCDFResolveVarFullName(nGroupId, szGeolocXName,
    4856          96 :                                            &pszGeolocXFullName) == CE_None &&
    4857          48 :                     NCDFResolveVarFullName(nGroupId, szGeolocYName,
    4858             :                                            &pszGeolocYFullName) == CE_None)
    4859             :                 {
    4860          48 :                     if (bSwitchedXY)
    4861             :                     {
    4862           2 :                         std::swap(pszGeolocXFullName, pszGeolocYFullName);
    4863           2 :                         GDALPamDataset::SetMetadataItem("SWAP_XY", "YES",
    4864             :                                                         "GEOLOCATION");
    4865             :                     }
    4866             : 
    4867          48 :                     bAddGeoloc = true;
    4868          48 :                     CPLDebug("GDAL_netCDF",
    4869             :                              "using variables %s and %s for GEOLOCATION",
    4870             :                              pszGeolocXFullName, pszGeolocYFullName);
    4871             : 
    4872          48 :                     GDALPamDataset::SetMetadataItem("SRS", osGeolocWKT.c_str(),
    4873             :                                                     "GEOLOCATION");
    4874             : 
    4875          96 :                     CPLString osTMP;
    4876          48 :                     osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(),
    4877          48 :                                  pszGeolocXFullName);
    4878             : 
    4879          48 :                     GDALPamDataset::SetMetadataItem("X_DATASET", osTMP,
    4880             :                                                     "GEOLOCATION");
    4881          48 :                     GDALPamDataset::SetMetadataItem("X_BAND", "1",
    4882             :                                                     "GEOLOCATION");
    4883          48 :                     osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(),
    4884          48 :                                  pszGeolocYFullName);
    4885             : 
    4886          48 :                     GDALPamDataset::SetMetadataItem("Y_DATASET", osTMP,
    4887             :                                                     "GEOLOCATION");
    4888          48 :                     GDALPamDataset::SetMetadataItem("Y_BAND", "1",
    4889             :                                                     "GEOLOCATION");
    4890             : 
    4891          48 :                     GDALPamDataset::SetMetadataItem("PIXEL_OFFSET", "0",
    4892             :                                                     "GEOLOCATION");
    4893          48 :                     GDALPamDataset::SetMetadataItem("PIXEL_STEP", "1",
    4894             :                                                     "GEOLOCATION");
    4895             : 
    4896          48 :                     GDALPamDataset::SetMetadataItem("LINE_OFFSET", "0",
    4897             :                                                     "GEOLOCATION");
    4898          48 :                     GDALPamDataset::SetMetadataItem("LINE_STEP", "1",
    4899             :                                                     "GEOLOCATION");
    4900             : 
    4901          48 :                     GDALPamDataset::SetMetadataItem("GEOREFERENCING_CONVENTION",
    4902             :                                                     "PIXEL_CENTER",
    4903             :                                                     "GEOLOCATION");
    4904             :                 }
    4905             :                 else
    4906             :                 {
    4907           0 :                     CPLDebug("GDAL_netCDF",
    4908             :                              "cannot resolve location of "
    4909             :                              "lat/lon variables specified by the coordinates "
    4910             :                              "attribute [%s]",
    4911             :                              pszCoordinates);
    4912             :                 }
    4913          48 :                 CPLFree(pszGeolocXFullName);
    4914          48 :                 CPLFree(pszGeolocYFullName);
    4915             :             }
    4916             :             else
    4917             :             {
    4918          13 :                 CPLDebug("GDAL_netCDF",
    4919             :                          "coordinates attribute [%s] is unsupported",
    4920             :                          pszCoordinates);
    4921             :             }
    4922             :         }
    4923             :         else
    4924             :         {
    4925           3 :             CPLDebug("GDAL_netCDF",
    4926             :                      "coordinates attribute [%s] with %d element(s) is "
    4927             :                      "unsupported",
    4928             :                      pszCoordinates, aosCoordinates.size());
    4929             :         }
    4930             :     }
    4931             : 
    4932             :     else
    4933             :     {
    4934         287 :         bAddGeoloc = ProcessNASAL2OceanGeoLocation(nGroupId, nVarId);
    4935             : 
    4936         287 :         if (!bAddGeoloc)
    4937         286 :             bAddGeoloc = ProcessNASAEMITGeoLocation(nGroupId, nVarId);
    4938             :     }
    4939             : 
    4940         351 :     CPLFree(pszCoordinates);
    4941             : 
    4942         351 :     return bAddGeoloc;
    4943             : }
    4944             : 
    4945           8 : CPLErr netCDFDataset::Set1DGeolocation(int nGroupId, int nVarId,
    4946             :                                        const char *szDimName)
    4947             : {
    4948             :     // Get values.
    4949           8 :     char *pszVarValues = nullptr;
    4950           8 :     CPLErr eErr = NCDFGet1DVar(nGroupId, nVarId, &pszVarValues);
    4951           8 :     if (eErr != CE_None)
    4952           0 :         return eErr;
    4953             : 
    4954             :     // Write metadata.
    4955           8 :     char szTemp[NC_MAX_NAME + 1 + 32] = {};
    4956           8 :     snprintf(szTemp, sizeof(szTemp), "%s_VALUES", szDimName);
    4957           8 :     GDALPamDataset::SetMetadataItem(szTemp, pszVarValues, "GEOLOCATION2");
    4958             : 
    4959           8 :     CPLFree(pszVarValues);
    4960             : 
    4961           8 :     return CE_None;
    4962             : }
    4963             : 
    4964           0 : double *netCDFDataset::Get1DGeolocation(CPL_UNUSED const char *szDimName,
    4965             :                                         int &nVarLen)
    4966             : {
    4967           0 :     nVarLen = 0;
    4968             : 
    4969             :     // Get Y_VALUES as tokens.
    4970             :     char **papszValues =
    4971           0 :         NCDFTokenizeArray(GetMetadataItem("Y_VALUES", "GEOLOCATION2"));
    4972           0 :     if (papszValues == nullptr)
    4973           0 :         return nullptr;
    4974             : 
    4975             :     // Initialize and fill array.
    4976           0 :     nVarLen = CSLCount(papszValues);
    4977             :     double *pdfVarValues =
    4978           0 :         static_cast<double *>(CPLCalloc(nVarLen, sizeof(double)));
    4979             : 
    4980           0 :     for (int i = 0, j = 0; i < nVarLen; i++)
    4981             :     {
    4982           0 :         if (!bBottomUp)
    4983           0 :             j = nVarLen - 1 - i;
    4984             :         else
    4985           0 :             j = i;  // Invert latitude values.
    4986           0 :         char *pszTemp = nullptr;
    4987           0 :         pdfVarValues[j] = CPLStrtod(papszValues[i], &pszTemp);
    4988             :     }
    4989           0 :     CSLDestroy(papszValues);
    4990             : 
    4991           0 :     return pdfVarValues;
    4992             : }
    4993             : 
    4994             : /************************************************************************/
    4995             : /*                        SetSpatialRefNoUpdate()                       */
    4996             : /************************************************************************/
    4997             : 
    4998         257 : void netCDFDataset::SetSpatialRefNoUpdate(const OGRSpatialReference *poSRS)
    4999             : {
    5000         257 :     m_oSRS.Clear();
    5001         257 :     if (poSRS)
    5002         250 :         m_oSRS = *poSRS;
    5003         257 :     m_bHasProjection = true;
    5004         257 : }
    5005             : 
    5006             : /************************************************************************/
    5007             : /*                          SetSpatialRef()                             */
    5008             : /************************************************************************/
    5009             : 
    5010          76 : CPLErr netCDFDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    5011             : {
    5012         152 :     CPLMutexHolderD(&hNCMutex);
    5013             : 
    5014          76 :     if (GetAccess() != GA_Update || m_bHasProjection)
    5015             :     {
    5016           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5017             :                  "netCDFDataset::_SetProjection() should only be called once "
    5018             :                  "in update mode!");
    5019           0 :         return CE_Failure;
    5020             :     }
    5021             : 
    5022          76 :     if (m_bHasGeoTransform)
    5023             :     {
    5024          32 :         SetSpatialRefNoUpdate(poSRS);
    5025             : 
    5026             :         // For NC4/NC4C, writing both projection variables and data,
    5027             :         // followed by redefining nodata value, cancels the projection
    5028             :         // info from the Band variable, so for now only write the
    5029             :         // variable definitions, and write data at the end.
    5030             :         // See https://trac.osgeo.org/gdal/ticket/7245
    5031          32 :         return AddProjectionVars(true, nullptr, nullptr);
    5032             :     }
    5033             : 
    5034          44 :     SetSpatialRefNoUpdate(poSRS);
    5035             : 
    5036          44 :     return CE_None;
    5037             : }
    5038             : 
    5039             : /************************************************************************/
    5040             : /*                     SetGeoTransformNoUpdate()                        */
    5041             : /************************************************************************/
    5042             : 
    5043         276 : void netCDFDataset::SetGeoTransformNoUpdate(const GDALGeoTransform &gt)
    5044             : {
    5045         276 :     m_gt = gt;
    5046         276 :     m_bHasGeoTransform = true;
    5047         276 : }
    5048             : 
    5049             : /************************************************************************/
    5050             : /*                          SetGeoTransform()                           */
    5051             : /************************************************************************/
    5052             : 
    5053          77 : CPLErr netCDFDataset::SetGeoTransform(const GDALGeoTransform &gt)
    5054             : {
    5055         154 :     CPLMutexHolderD(&hNCMutex);
    5056             : 
    5057          77 :     if (GetAccess() != GA_Update || m_bHasGeoTransform)
    5058             :     {
    5059           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5060             :                  "netCDFDataset::SetGeoTransform() should only be called once "
    5061             :                  "in update mode!");
    5062           0 :         return CE_Failure;
    5063             :     }
    5064             : 
    5065          77 :     CPLDebug("GDAL_netCDF", "SetGeoTransform(%f,%f,%f,%f,%f,%f)", gt[0], gt[1],
    5066             :              gt[2], gt[3], gt[4], gt[5]);
    5067             : 
    5068          77 :     SetGeoTransformNoUpdate(gt);
    5069             : 
    5070          77 :     if (m_bHasProjection)
    5071             :     {
    5072             : 
    5073             :         // For NC4/NC4C, writing both projection variables and data,
    5074             :         // followed by redefining nodata value, cancels the projection
    5075             :         // info from the Band variable, so for now only write the
    5076             :         // variable definitions, and write data at the end.
    5077             :         // See https://trac.osgeo.org/gdal/ticket/7245
    5078           3 :         return AddProjectionVars(true, nullptr, nullptr);
    5079             :     }
    5080             : 
    5081          74 :     return CE_None;
    5082             : }
    5083             : 
    5084             : /************************************************************************/
    5085             : /*                         NCDFWriteSRSVariable()                       */
    5086             : /************************************************************************/
    5087             : 
    5088         128 : int NCDFWriteSRSVariable(int cdfid, const OGRSpatialReference *poSRS,
    5089             :                          char **ppszCFProjection, bool bWriteGDALTags,
    5090             :                          const std::string &srsVarName)
    5091             : {
    5092         128 :     char *pszCFProjection = nullptr;
    5093         128 :     char **papszKeyValues = nullptr;
    5094         128 :     poSRS->exportToCF1(&pszCFProjection, &papszKeyValues, nullptr, nullptr);
    5095             : 
    5096         128 :     if (bWriteGDALTags)
    5097             :     {
    5098         127 :         const char *pszWKT = CSLFetchNameValue(papszKeyValues, NCDF_CRS_WKT);
    5099         127 :         if (pszWKT)
    5100             :         {
    5101             :             // SPATIAL_REF is deprecated. Will be removed in GDAL 4.
    5102         127 :             papszKeyValues =
    5103         127 :                 CSLSetNameValue(papszKeyValues, NCDF_SPATIAL_REF, pszWKT);
    5104             :         }
    5105             :     }
    5106             : 
    5107         128 :     const int nValues = CSLCount(papszKeyValues);
    5108             : 
    5109             :     int NCDFVarID;
    5110         256 :     std::string varNameRadix(pszCFProjection);
    5111         128 :     int nCounter = 2;
    5112             :     while (true)
    5113             :     {
    5114         130 :         NCDFVarID = -1;
    5115         130 :         nc_inq_varid(cdfid, pszCFProjection, &NCDFVarID);
    5116         130 :         if (NCDFVarID < 0)
    5117         125 :             break;
    5118             : 
    5119           5 :         int nbAttr = 0;
    5120           5 :         NCDF_ERR(nc_inq_varnatts(cdfid, NCDFVarID, &nbAttr));
    5121           5 :         bool bSame = nbAttr == nValues;
    5122          41 :         for (int i = 0; bSame && (i < nbAttr); i++)
    5123             :         {
    5124             :             char szAttrName[NC_MAX_NAME + 1];
    5125          38 :             szAttrName[0] = 0;
    5126          38 :             NCDF_ERR(nc_inq_attname(cdfid, NCDFVarID, i, szAttrName));
    5127             : 
    5128             :             const char *pszValue =
    5129          38 :                 CSLFetchNameValue(papszKeyValues, szAttrName);
    5130          38 :             if (!pszValue)
    5131             :             {
    5132           0 :                 bSame = false;
    5133           2 :                 break;
    5134             :             }
    5135             : 
    5136          38 :             nc_type atttype = NC_NAT;
    5137          38 :             size_t attlen = 0;
    5138          38 :             NCDF_ERR(
    5139             :                 nc_inq_att(cdfid, NCDFVarID, szAttrName, &atttype, &attlen));
    5140          38 :             if (atttype != NC_CHAR && atttype != NC_DOUBLE)
    5141             :             {
    5142           0 :                 bSame = false;
    5143           0 :                 break;
    5144             :             }
    5145          38 :             if (atttype == NC_CHAR)
    5146             :             {
    5147          15 :                 if (CPLGetValueType(pszValue) != CPL_VALUE_STRING)
    5148             :                 {
    5149           0 :                     bSame = false;
    5150           0 :                     break;
    5151             :                 }
    5152          15 :                 std::string val;
    5153          15 :                 val.resize(attlen);
    5154          15 :                 nc_get_att_text(cdfid, NCDFVarID, szAttrName, &val[0]);
    5155          15 :                 if (val != pszValue)
    5156             :                 {
    5157           0 :                     bSame = false;
    5158           0 :                     break;
    5159             :                 }
    5160             :             }
    5161             :             else
    5162             :             {
    5163             :                 const CPLStringList aosTokens(
    5164          23 :                     CSLTokenizeString2(pszValue, ",", 0));
    5165          23 :                 if (static_cast<size_t>(aosTokens.size()) != attlen)
    5166             :                 {
    5167           0 :                     bSame = false;
    5168           0 :                     break;
    5169             :                 }
    5170             :                 double vals[2];
    5171          23 :                 nc_get_att_double(cdfid, NCDFVarID, szAttrName, vals);
    5172          44 :                 if (vals[0] != CPLAtof(aosTokens[0]) ||
    5173          21 :                     (attlen == 2 && vals[1] != CPLAtof(aosTokens[1])))
    5174             :                 {
    5175           2 :                     bSame = false;
    5176           2 :                     break;
    5177             :                 }
    5178             :             }
    5179             :         }
    5180           5 :         if (bSame)
    5181             :         {
    5182           3 :             *ppszCFProjection = pszCFProjection;
    5183           3 :             CSLDestroy(papszKeyValues);
    5184           3 :             return NCDFVarID;
    5185             :         }
    5186           2 :         CPLFree(pszCFProjection);
    5187           2 :         pszCFProjection =
    5188           2 :             CPLStrdup(CPLSPrintf("%s_%d", varNameRadix.c_str(), nCounter));
    5189           2 :         nCounter++;
    5190           2 :     }
    5191             : 
    5192         125 :     *ppszCFProjection = pszCFProjection;
    5193             : 
    5194             :     const char *pszVarName;
    5195             : 
    5196         125 :     if (srsVarName != "")
    5197             :     {
    5198          38 :         pszVarName = srsVarName.c_str();
    5199             :     }
    5200             :     else
    5201             :     {
    5202          87 :         pszVarName = pszCFProjection;
    5203             :     }
    5204             : 
    5205         125 :     int status = nc_def_var(cdfid, pszVarName, NC_CHAR, 0, nullptr, &NCDFVarID);
    5206         125 :     NCDF_ERR(status);
    5207        1199 :     for (int i = 0; i < nValues; ++i)
    5208             :     {
    5209        1074 :         char *pszKey = nullptr;
    5210        1074 :         const char *pszValue = CPLParseNameValue(papszKeyValues[i], &pszKey);
    5211        1074 :         if (pszKey && pszValue)
    5212             :         {
    5213        2148 :             const CPLStringList aosTokens(CSLTokenizeString2(pszValue, ",", 0));
    5214        1074 :             double adfValues[2] = {0, 0};
    5215        1074 :             const int nDoubleCount = std::min(2, aosTokens.size());
    5216        1074 :             if (!(aosTokens.size() == 2 &&
    5217        2147 :                   CPLGetValueType(aosTokens[0]) != CPL_VALUE_STRING) &&
    5218        1073 :                 CPLGetValueType(pszValue) == CPL_VALUE_STRING)
    5219             :             {
    5220         499 :                 status = nc_put_att_text(cdfid, NCDFVarID, pszKey,
    5221             :                                          strlen(pszValue), pszValue);
    5222             :             }
    5223             :             else
    5224             :             {
    5225        1151 :                 for (int j = 0; j < nDoubleCount; ++j)
    5226         576 :                     adfValues[j] = CPLAtof(aosTokens[j]);
    5227         575 :                 status = nc_put_att_double(cdfid, NCDFVarID, pszKey, NC_DOUBLE,
    5228             :                                            nDoubleCount, adfValues);
    5229             :             }
    5230        1074 :             NCDF_ERR(status);
    5231             :         }
    5232        1074 :         CPLFree(pszKey);
    5233             :     }
    5234             : 
    5235         125 :     CSLDestroy(papszKeyValues);
    5236         125 :     return NCDFVarID;
    5237             : }
    5238             : 
    5239             : /************************************************************************/
    5240             : /*                   NCDFWriteLonLatVarsAttributes()                    */
    5241             : /************************************************************************/
    5242             : 
    5243         101 : void NCDFWriteLonLatVarsAttributes(nccfdriver::netCDFVID &vcdf, int nVarLonID,
    5244             :                                    int nVarLatID)
    5245             : {
    5246             : 
    5247             :     try
    5248             :     {
    5249         101 :         vcdf.nc_put_vatt_text(nVarLatID, CF_STD_NAME, CF_LATITUDE_STD_NAME);
    5250         101 :         vcdf.nc_put_vatt_text(nVarLatID, CF_LNG_NAME, CF_LATITUDE_LNG_NAME);
    5251         101 :         vcdf.nc_put_vatt_text(nVarLatID, CF_UNITS, CF_DEGREES_NORTH);
    5252         101 :         vcdf.nc_put_vatt_text(nVarLonID, CF_STD_NAME, CF_LONGITUDE_STD_NAME);
    5253         101 :         vcdf.nc_put_vatt_text(nVarLonID, CF_LNG_NAME, CF_LONGITUDE_LNG_NAME);
    5254         101 :         vcdf.nc_put_vatt_text(nVarLonID, CF_UNITS, CF_DEGREES_EAST);
    5255             :     }
    5256           0 :     catch (nccfdriver::SG_Exception &e)
    5257             :     {
    5258           0 :         CPLError(CE_Failure, CPLE_FileIO, "%s", e.get_err_msg());
    5259             :     }
    5260         101 : }
    5261             : 
    5262             : /************************************************************************/
    5263             : /*                   NCDFWriteRLonRLatVarsAttributes()                    */
    5264             : /************************************************************************/
    5265             : 
    5266           0 : void NCDFWriteRLonRLatVarsAttributes(nccfdriver::netCDFVID &vcdf,
    5267             :                                      int nVarRLonID, int nVarRLatID)
    5268             : {
    5269             :     try
    5270             :     {
    5271           0 :         vcdf.nc_put_vatt_text(nVarRLatID, CF_STD_NAME, "grid_latitude");
    5272           0 :         vcdf.nc_put_vatt_text(nVarRLatID, CF_LNG_NAME,
    5273             :                               "latitude in rotated pole grid");
    5274           0 :         vcdf.nc_put_vatt_text(nVarRLatID, CF_UNITS, "degrees");
    5275           0 :         vcdf.nc_put_vatt_text(nVarRLatID, CF_AXIS, "Y");
    5276             : 
    5277           0 :         vcdf.nc_put_vatt_text(nVarRLonID, CF_STD_NAME, "grid_longitude");
    5278           0 :         vcdf.nc_put_vatt_text(nVarRLonID, CF_LNG_NAME,
    5279             :                               "longitude in rotated pole grid");
    5280           0 :         vcdf.nc_put_vatt_text(nVarRLonID, CF_UNITS, "degrees");
    5281           0 :         vcdf.nc_put_vatt_text(nVarRLonID, CF_AXIS, "X");
    5282             :     }
    5283           0 :     catch (nccfdriver::SG_Exception &e)
    5284             :     {
    5285           0 :         CPLError(CE_Failure, CPLE_FileIO, "%s", e.get_err_msg());
    5286             :     }
    5287           0 : }
    5288             : 
    5289             : /************************************************************************/
    5290             : /*                        NCDFGetProjectedCFUnit()                      */
    5291             : /************************************************************************/
    5292             : 
    5293          40 : std::string NCDFGetProjectedCFUnit(const OGRSpatialReference *poSRS)
    5294             : {
    5295          40 :     char *pszUnitsToWrite = nullptr;
    5296          40 :     poSRS->exportToCF1(nullptr, nullptr, &pszUnitsToWrite, nullptr);
    5297          40 :     std::string osRet = pszUnitsToWrite ? pszUnitsToWrite : std::string();
    5298          40 :     CPLFree(pszUnitsToWrite);
    5299          80 :     return osRet;
    5300             : }
    5301             : 
    5302             : /************************************************************************/
    5303             : /*                     NCDFWriteXYVarsAttributes()                      */
    5304             : /************************************************************************/
    5305             : 
    5306          29 : void NCDFWriteXYVarsAttributes(nccfdriver::netCDFVID &vcdf, int nVarXID,
    5307             :                                int nVarYID, const OGRSpatialReference *poSRS)
    5308             : {
    5309          58 :     const std::string osUnitsToWrite = NCDFGetProjectedCFUnit(poSRS);
    5310             : 
    5311             :     try
    5312             :     {
    5313          29 :         vcdf.nc_put_vatt_text(nVarXID, CF_STD_NAME, CF_PROJ_X_COORD);
    5314          29 :         vcdf.nc_put_vatt_text(nVarXID, CF_LNG_NAME, CF_PROJ_X_COORD_LONG_NAME);
    5315          29 :         if (!osUnitsToWrite.empty())
    5316          29 :             vcdf.nc_put_vatt_text(nVarXID, CF_UNITS, osUnitsToWrite.c_str());
    5317          29 :         vcdf.nc_put_vatt_text(nVarYID, CF_STD_NAME, CF_PROJ_Y_COORD);
    5318          29 :         vcdf.nc_put_vatt_text(nVarYID, CF_LNG_NAME, CF_PROJ_Y_COORD_LONG_NAME);
    5319          29 :         if (!osUnitsToWrite.empty())
    5320          29 :             vcdf.nc_put_vatt_text(nVarYID, CF_UNITS, osUnitsToWrite.c_str());
    5321             :     }
    5322           0 :     catch (nccfdriver::SG_Exception &e)
    5323             :     {
    5324           0 :         CPLError(CE_Failure, CPLE_FileIO, "%s", e.get_err_msg());
    5325             :     }
    5326          29 : }
    5327             : 
    5328             : /************************************************************************/
    5329             : /*                          AddProjectionVars()                         */
    5330             : /************************************************************************/
    5331             : 
    5332         164 : CPLErr netCDFDataset::AddProjectionVars(bool bDefsOnly,
    5333             :                                         GDALProgressFunc pfnProgress,
    5334             :                                         void *pProgressData)
    5335             : {
    5336         164 :     if (nCFVersion >= 1.8)
    5337           0 :         return CE_None;  // do nothing
    5338             : 
    5339         164 :     bool bWriteGridMapping = false;
    5340         164 :     bool bWriteLonLat = false;
    5341         164 :     bool bHasGeoloc = false;
    5342         164 :     bool bWriteGDALTags = false;
    5343         164 :     bool bWriteGeoTransform = false;
    5344             : 
    5345             :     // For GEOLOCATION information.
    5346         164 :     GDALDatasetH hDS_X = nullptr;
    5347         164 :     GDALRasterBandH hBand_X = nullptr;
    5348         164 :     GDALDatasetH hDS_Y = nullptr;
    5349         164 :     GDALRasterBandH hBand_Y = nullptr;
    5350             : 
    5351         328 :     OGRSpatialReference oSRS(m_oSRS);
    5352         164 :     if (!m_oSRS.IsEmpty())
    5353             :     {
    5354         138 :         if (oSRS.IsProjected())
    5355          50 :             bIsProjected = true;
    5356          88 :         else if (oSRS.IsGeographic())
    5357          88 :             bIsGeographic = true;
    5358             :     }
    5359             : 
    5360         164 :     if (bDefsOnly)
    5361             :     {
    5362          82 :         char *pszProjection = nullptr;
    5363          82 :         m_oSRS.exportToWkt(&pszProjection);
    5364          82 :         CPLDebug("GDAL_netCDF",
    5365             :                  "SetProjection, WKT now = [%s]\nprojected: %d geographic: %d",
    5366          82 :                  pszProjection ? pszProjection : "(null)",
    5367          82 :                  static_cast<int>(bIsProjected),
    5368          82 :                  static_cast<int>(bIsGeographic));
    5369          82 :         CPLFree(pszProjection);
    5370             : 
    5371          82 :         if (!m_bHasGeoTransform)
    5372           5 :             CPLDebug("GDAL_netCDF",
    5373             :                      "netCDFDataset::AddProjectionVars() called, "
    5374             :                      "but GeoTransform has not yet been defined!");
    5375             : 
    5376          82 :         if (!m_bHasProjection)
    5377           6 :             CPLDebug("GDAL_netCDF",
    5378             :                      "netCDFDataset::AddProjectionVars() called, "
    5379             :                      "but Projection has not yet been defined!");
    5380             :     }
    5381             : 
    5382             :     // Check GEOLOCATION information.
    5383         164 :     char **papszGeolocationInfo = netCDFDataset::GetMetadata("GEOLOCATION");
    5384         164 :     if (papszGeolocationInfo != nullptr)
    5385             :     {
    5386             :         // Look for geolocation datasets.
    5387             :         const char *pszDSName =
    5388          10 :             CSLFetchNameValue(papszGeolocationInfo, "X_DATASET");
    5389          10 :         if (pszDSName != nullptr)
    5390          10 :             hDS_X = GDALOpenShared(pszDSName, GA_ReadOnly);
    5391          10 :         pszDSName = CSLFetchNameValue(papszGeolocationInfo, "Y_DATASET");
    5392          10 :         if (pszDSName != nullptr)
    5393          10 :             hDS_Y = GDALOpenShared(pszDSName, GA_ReadOnly);
    5394             : 
    5395          10 :         if (hDS_X != nullptr && hDS_Y != nullptr)
    5396             :         {
    5397          10 :             int nBand = std::max(1, atoi(CSLFetchNameValueDef(
    5398          10 :                                         papszGeolocationInfo, "X_BAND", "0")));
    5399          10 :             hBand_X = GDALGetRasterBand(hDS_X, nBand);
    5400          10 :             nBand = std::max(1, atoi(CSLFetchNameValueDef(papszGeolocationInfo,
    5401          10 :                                                           "Y_BAND", "0")));
    5402          10 :             hBand_Y = GDALGetRasterBand(hDS_Y, nBand);
    5403             : 
    5404             :             // If geoloc bands are found, do basic validation based on their
    5405             :             // dimensions.
    5406          10 :             if (hBand_X != nullptr && hBand_Y != nullptr)
    5407             :             {
    5408          10 :                 int nXSize_XBand = GDALGetRasterXSize(hDS_X);
    5409          10 :                 int nYSize_XBand = GDALGetRasterYSize(hDS_X);
    5410          10 :                 int nXSize_YBand = GDALGetRasterXSize(hDS_Y);
    5411          10 :                 int nYSize_YBand = GDALGetRasterYSize(hDS_Y);
    5412             : 
    5413             :                 // TODO 1D geolocation arrays not implemented.
    5414          10 :                 if (nYSize_XBand == 1 && nYSize_YBand == 1)
    5415             :                 {
    5416           0 :                     bHasGeoloc = false;
    5417           0 :                     CPLDebug("GDAL_netCDF",
    5418             :                              "1D GEOLOCATION arrays not supported yet");
    5419             :                 }
    5420             :                 // 2D bands must have same sizes as the raster bands.
    5421          10 :                 else if (nXSize_XBand != nRasterXSize ||
    5422          10 :                          nYSize_XBand != nRasterYSize ||
    5423          10 :                          nXSize_YBand != nRasterXSize ||
    5424          10 :                          nYSize_YBand != nRasterYSize)
    5425             :                 {
    5426           0 :                     bHasGeoloc = false;
    5427           0 :                     CPLDebug("GDAL_netCDF",
    5428             :                              "GEOLOCATION array sizes (%dx%d %dx%d) differ "
    5429             :                              "from raster (%dx%d), not supported",
    5430             :                              nXSize_XBand, nYSize_XBand, nXSize_YBand,
    5431             :                              nYSize_YBand, nRasterXSize, nRasterYSize);
    5432             :                 }
    5433             :                 else
    5434             :                 {
    5435          10 :                     bHasGeoloc = true;
    5436          10 :                     CPLDebug("GDAL_netCDF",
    5437             :                              "dataset has GEOLOCATION information, will try to "
    5438             :                              "write it");
    5439             :                 }
    5440             :             }
    5441             :         }
    5442             :     }
    5443             : 
    5444             :     // Process projection options.
    5445         164 :     if (bIsProjected)
    5446             :     {
    5447             :         bool bIsCfProjection =
    5448          50 :             oSRS.exportToCF1(nullptr, nullptr, nullptr, nullptr) == OGRERR_NONE;
    5449          50 :         bWriteGridMapping = true;
    5450          50 :         bWriteGDALTags = CPL_TO_BOOL(
    5451          50 :             CSLFetchBoolean(papszCreationOptions, "WRITE_GDAL_TAGS", TRUE));
    5452             :         // Force WRITE_GDAL_TAGS if is not a CF projection.
    5453          50 :         if (!bWriteGDALTags && !bIsCfProjection)
    5454           0 :             bWriteGDALTags = true;
    5455          50 :         if (bWriteGDALTags)
    5456          50 :             bWriteGeoTransform = true;
    5457             : 
    5458             :         // Write lon/lat: default is NO, except if has geolocation.
    5459             :         // With IF_NEEDED: write if has geoloc or is not CF projection.
    5460             :         const char *pszValue =
    5461          50 :             CSLFetchNameValue(papszCreationOptions, "WRITE_LONLAT");
    5462          50 :         if (pszValue)
    5463             :         {
    5464           2 :             if (EQUAL(pszValue, "IF_NEEDED"))
    5465             :             {
    5466           0 :                 bWriteLonLat = bHasGeoloc || !bIsCfProjection;
    5467             :             }
    5468             :             else
    5469             :             {
    5470           2 :                 bWriteLonLat = CPLTestBool(pszValue);
    5471             :             }
    5472             :         }
    5473             :         else
    5474             :         {
    5475          48 :             bWriteLonLat = bHasGeoloc;
    5476             :         }
    5477             : 
    5478             :         // Save value of pszCFCoordinates for later.
    5479          50 :         if (bWriteLonLat)
    5480             :         {
    5481           4 :             pszCFCoordinates = NCDF_LONLAT;
    5482             :         }
    5483             :     }
    5484             :     else
    5485             :     {
    5486             :         // Files without a Datum will not have a grid_mapping variable and
    5487             :         // geographic information.
    5488         114 :         bWriteGridMapping = bIsGeographic;
    5489             : 
    5490         114 :         if (bHasGeoloc)
    5491             :         {
    5492           8 :             bWriteLonLat = true;
    5493             :         }
    5494             :         else
    5495             :         {
    5496         106 :             bWriteGDALTags = CPL_TO_BOOL(CSLFetchBoolean(
    5497         106 :                 papszCreationOptions, "WRITE_GDAL_TAGS", bWriteGridMapping));
    5498         106 :             if (bWriteGDALTags)
    5499          88 :                 bWriteGeoTransform = true;
    5500             : 
    5501         106 :             const char *pszValue = CSLFetchNameValueDef(papszCreationOptions,
    5502             :                                                         "WRITE_LONLAT", "YES");
    5503         106 :             if (EQUAL(pszValue, "IF_NEEDED"))
    5504           0 :                 bWriteLonLat = true;
    5505             :             else
    5506         106 :                 bWriteLonLat = CPLTestBool(pszValue);
    5507             :             //  Don't write lon/lat if no source geotransform.
    5508         106 :             if (!m_bHasGeoTransform)
    5509           0 :                 bWriteLonLat = false;
    5510             :             // If we don't write lon/lat, set dimnames to X/Y and write gdal
    5511             :             // tags.
    5512         106 :             if (!bWriteLonLat)
    5513             :             {
    5514           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    5515             :                          "creating geographic file without lon/lat values!");
    5516           0 :                 if (m_bHasGeoTransform)
    5517             :                 {
    5518           0 :                     bWriteGDALTags = true;  // Not desirable if no geotransform.
    5519           0 :                     bWriteGeoTransform = true;
    5520             :                 }
    5521             :             }
    5522             :         }
    5523             :     }
    5524             : 
    5525             :     // Make sure we write grid_mapping if we need to write GDAL tags.
    5526         164 :     if (bWriteGDALTags)
    5527         138 :         bWriteGridMapping = true;
    5528             : 
    5529             :     // bottom-up value: new driver is bottom-up by default.
    5530             :     // Override with WRITE_BOTTOMUP.
    5531         164 :     bBottomUp = CPL_TO_BOOL(
    5532         164 :         CSLFetchBoolean(papszCreationOptions, "WRITE_BOTTOMUP", TRUE));
    5533             : 
    5534         164 :     if (bDefsOnly)
    5535             :     {
    5536          82 :         CPLDebug(
    5537             :             "GDAL_netCDF",
    5538             :             "bIsProjected=%d bIsGeographic=%d bWriteGridMapping=%d "
    5539             :             "bWriteGDALTags=%d bWriteLonLat=%d bBottomUp=%d bHasGeoloc=%d",
    5540          82 :             static_cast<int>(bIsProjected), static_cast<int>(bIsGeographic),
    5541             :             static_cast<int>(bWriteGridMapping),
    5542             :             static_cast<int>(bWriteGDALTags), static_cast<int>(bWriteLonLat),
    5543          82 :             static_cast<int>(bBottomUp), static_cast<int>(bHasGeoloc));
    5544             :     }
    5545             : 
    5546             :     // Exit if nothing to do.
    5547         164 :     if (!bIsProjected && !bWriteLonLat)
    5548           0 :         return CE_None;
    5549             : 
    5550             :     // Define dimension names.
    5551             : 
    5552         164 :     constexpr const char *ROTATED_POLE_VAR_NAME = "rotated_pole";
    5553             : 
    5554         164 :     if (bDefsOnly)
    5555             :     {
    5556          82 :         int nVarLonID = -1;
    5557          82 :         int nVarLatID = -1;
    5558          82 :         int nVarXID = -1;
    5559          82 :         int nVarYID = -1;
    5560             : 
    5561          82 :         m_bAddedProjectionVarsDefs = true;
    5562             : 
    5563             :         // Make sure we are in define mode.
    5564          82 :         SetDefineMode(true);
    5565             : 
    5566             :         // Write projection attributes.
    5567          82 :         if (bWriteGridMapping)
    5568             :         {
    5569          69 :             const int NCDFVarID = NCDFWriteSRSVariable(
    5570             :                 cdfid, &oSRS, &pszCFProjection, bWriteGDALTags);
    5571          69 :             if (NCDFVarID < 0)
    5572           0 :                 return CE_Failure;
    5573             : 
    5574             :             // Optional GDAL custom projection tags.
    5575          69 :             if (bWriteGDALTags)
    5576             :             {
    5577         138 :                 CPLString osGeoTransform;
    5578         483 :                 for (int i = 0; i < 6; i++)
    5579             :                 {
    5580         414 :                     osGeoTransform += CPLSPrintf("%.17g ", m_gt[i]);
    5581             :                 }
    5582          69 :                 CPLDebug("GDAL_netCDF", "szGeoTransform = %s",
    5583             :                          osGeoTransform.c_str());
    5584             : 
    5585             :                 // if( strlen(pszProj4Defn) > 0 ) {
    5586             :                 //     nc_put_att_text(cdfid, NCDFVarID, "proj4",
    5587             :                 //                      strlen(pszProj4Defn), pszProj4Defn);
    5588             :                 // }
    5589             : 
    5590             :                 // For now, write the geotransform for back-compat or else
    5591             :                 // the old (1.8.1) driver overrides the CF geotransform with
    5592             :                 // empty values from dfNN, dfSN, dfEE, dfWE;
    5593             : 
    5594             :                 // TODO: fix this in 1.8 branch, and then remove this here.
    5595          69 :                 if (bWriteGeoTransform && m_bHasGeoTransform)
    5596             :                 {
    5597             :                     {
    5598          68 :                         const int status = nc_put_att_text(
    5599             :                             cdfid, NCDFVarID, NCDF_GEOTRANSFORM,
    5600             :                             osGeoTransform.size(), osGeoTransform.c_str());
    5601          68 :                         NCDF_ERR(status);
    5602             :                     }
    5603             :                 }
    5604             :             }
    5605             : 
    5606             :             // Write projection variable to band variable.
    5607             :             // Need to call later if there are no bands.
    5608          69 :             AddGridMappingRef();
    5609             :         }  // end if( bWriteGridMapping )
    5610             : 
    5611             :         // Write CF Projection vars.
    5612             : 
    5613          82 :         const bool bIsRotatedPole =
    5614         151 :             pszCFProjection != nullptr &&
    5615          69 :             EQUAL(pszCFProjection, ROTATED_POLE_VAR_NAME);
    5616          82 :         if (bIsRotatedPole)
    5617             :         {
    5618             :             // Rename dims to rlat/rlon.
    5619             :             papszDimName
    5620           0 :                 .Clear();  // If we add other dims one day, this has to change
    5621           0 :             papszDimName.AddString(NCDF_DIMNAME_RLAT);
    5622           0 :             papszDimName.AddString(NCDF_DIMNAME_RLON);
    5623             : 
    5624           0 :             int status = nc_rename_dim(cdfid, nYDimID, NCDF_DIMNAME_RLAT);
    5625           0 :             NCDF_ERR(status);
    5626           0 :             status = nc_rename_dim(cdfid, nXDimID, NCDF_DIMNAME_RLON);
    5627           0 :             NCDF_ERR(status);
    5628             :         }
    5629             :         // Rename dimensions if lon/lat.
    5630          82 :         else if (!bIsProjected && !bHasGeoloc)
    5631             :         {
    5632             :             // Rename dims to lat/lon.
    5633             :             papszDimName
    5634          53 :                 .Clear();  // If we add other dims one day, this has to change
    5635          53 :             papszDimName.AddString(NCDF_DIMNAME_LAT);
    5636          53 :             papszDimName.AddString(NCDF_DIMNAME_LON);
    5637             : 
    5638          53 :             int status = nc_rename_dim(cdfid, nYDimID, NCDF_DIMNAME_LAT);
    5639          53 :             NCDF_ERR(status);
    5640          53 :             status = nc_rename_dim(cdfid, nXDimID, NCDF_DIMNAME_LON);
    5641          53 :             NCDF_ERR(status);
    5642             :         }
    5643             : 
    5644             :         // Write X/Y attributes.
    5645             :         else /* if( bIsProjected || bHasGeoloc ) */
    5646             :         {
    5647             :             // X
    5648             :             int anXDims[1];
    5649          29 :             anXDims[0] = nXDimID;
    5650          29 :             CPLDebug("GDAL_netCDF", "nc_def_var(%d,%s,%d)", cdfid,
    5651             :                      CF_PROJ_X_VAR_NAME, NC_DOUBLE);
    5652          29 :             int status = nc_def_var(cdfid, CF_PROJ_X_VAR_NAME, NC_DOUBLE, 1,
    5653             :                                     anXDims, &nVarXID);
    5654          29 :             NCDF_ERR(status);
    5655             : 
    5656             :             // Y
    5657             :             int anYDims[1];
    5658          29 :             anYDims[0] = nYDimID;
    5659          29 :             CPLDebug("GDAL_netCDF", "nc_def_var(%d,%s,%d)", cdfid,
    5660             :                      CF_PROJ_Y_VAR_NAME, NC_DOUBLE);
    5661          29 :             status = nc_def_var(cdfid, CF_PROJ_Y_VAR_NAME, NC_DOUBLE, 1,
    5662             :                                 anYDims, &nVarYID);
    5663          29 :             NCDF_ERR(status);
    5664             : 
    5665          29 :             if (bIsProjected)
    5666             :             {
    5667          25 :                 NCDFWriteXYVarsAttributes(this->vcdf, nVarXID, nVarYID, &oSRS);
    5668             :             }
    5669             :             else
    5670             :             {
    5671           4 :                 CPLAssert(bHasGeoloc);
    5672             :                 try
    5673             :                 {
    5674           4 :                     vcdf.nc_put_vatt_text(nVarXID, CF_AXIS, CF_SG_X_AXIS);
    5675           4 :                     vcdf.nc_put_vatt_text(nVarXID, CF_LNG_NAME,
    5676             :                                           "x-coordinate in Cartesian system");
    5677           4 :                     vcdf.nc_put_vatt_text(nVarXID, CF_UNITS, "m");
    5678           4 :                     vcdf.nc_put_vatt_text(nVarYID, CF_AXIS, CF_SG_Y_AXIS);
    5679           4 :                     vcdf.nc_put_vatt_text(nVarYID, CF_LNG_NAME,
    5680             :                                           "y-coordinate in Cartesian system");
    5681           4 :                     vcdf.nc_put_vatt_text(nVarYID, CF_UNITS, "m");
    5682             : 
    5683           4 :                     pszCFCoordinates = NCDF_LONLAT;
    5684             :                 }
    5685           0 :                 catch (nccfdriver::SG_Exception &e)
    5686             :                 {
    5687           0 :                     CPLError(CE_Failure, CPLE_FileIO, "%s", e.get_err_msg());
    5688           0 :                     return CE_Failure;
    5689             :                 }
    5690             :             }
    5691             :         }
    5692             : 
    5693             :         // Write lat/lon attributes if needed.
    5694          82 :         if (bWriteLonLat)
    5695             :         {
    5696          59 :             int *panLatDims = nullptr;
    5697          59 :             int *panLonDims = nullptr;
    5698          59 :             int nLatDims = -1;
    5699          59 :             int nLonDims = -1;
    5700             : 
    5701             :             // Get information.
    5702          59 :             if (bHasGeoloc)
    5703             :             {
    5704             :                 // Geoloc
    5705           5 :                 nLatDims = 2;
    5706             :                 panLatDims =
    5707           5 :                     static_cast<int *>(CPLCalloc(nLatDims, sizeof(int)));
    5708           5 :                 panLatDims[0] = nYDimID;
    5709           5 :                 panLatDims[1] = nXDimID;
    5710           5 :                 nLonDims = 2;
    5711             :                 panLonDims =
    5712           5 :                     static_cast<int *>(CPLCalloc(nLonDims, sizeof(int)));
    5713           5 :                 panLonDims[0] = nYDimID;
    5714           5 :                 panLonDims[1] = nXDimID;
    5715             :             }
    5716          54 :             else if (bIsProjected)
    5717             :             {
    5718             :                 // Projected
    5719           1 :                 nLatDims = 2;
    5720             :                 panLatDims =
    5721           1 :                     static_cast<int *>(CPLCalloc(nLatDims, sizeof(int)));
    5722           1 :                 panLatDims[0] = nYDimID;
    5723           1 :                 panLatDims[1] = nXDimID;
    5724           1 :                 nLonDims = 2;
    5725             :                 panLonDims =
    5726           1 :                     static_cast<int *>(CPLCalloc(nLonDims, sizeof(int)));
    5727           1 :                 panLonDims[0] = nYDimID;
    5728           1 :                 panLonDims[1] = nXDimID;
    5729             :             }
    5730             :             else
    5731             :             {
    5732             :                 // Geographic
    5733          53 :                 nLatDims = 1;
    5734             :                 panLatDims =
    5735          53 :                     static_cast<int *>(CPLCalloc(nLatDims, sizeof(int)));
    5736          53 :                 panLatDims[0] = nYDimID;
    5737          53 :                 nLonDims = 1;
    5738             :                 panLonDims =
    5739          53 :                     static_cast<int *>(CPLCalloc(nLonDims, sizeof(int)));
    5740          53 :                 panLonDims[0] = nXDimID;
    5741             :             }
    5742             : 
    5743          59 :             nc_type eLonLatType = NC_NAT;
    5744          59 :             if (bIsProjected)
    5745             :             {
    5746           2 :                 eLonLatType = NC_FLOAT;
    5747           4 :                 const char *pszValue = CSLFetchNameValueDef(
    5748           2 :                     papszCreationOptions, "TYPE_LONLAT", "FLOAT");
    5749           2 :                 if (EQUAL(pszValue, "DOUBLE"))
    5750           0 :                     eLonLatType = NC_DOUBLE;
    5751             :             }
    5752             :             else
    5753             :             {
    5754          57 :                 eLonLatType = NC_DOUBLE;
    5755         114 :                 const char *pszValue = CSLFetchNameValueDef(
    5756          57 :                     papszCreationOptions, "TYPE_LONLAT", "DOUBLE");
    5757          57 :                 if (EQUAL(pszValue, "FLOAT"))
    5758           0 :                     eLonLatType = NC_FLOAT;
    5759             :             }
    5760             : 
    5761             :             // Def vars and attributes.
    5762             :             {
    5763          59 :                 const char *pszVarName =
    5764          59 :                     bIsRotatedPole ? NCDF_DIMNAME_RLAT : CF_LATITUDE_VAR_NAME;
    5765          59 :                 int status = nc_def_var(cdfid, pszVarName, eLonLatType,
    5766             :                                         nLatDims, panLatDims, &nVarLatID);
    5767          59 :                 CPLDebug("GDAL_netCDF", "nc_def_var(%d,%s,%d,%d,-,-) got id %d",
    5768             :                          cdfid, pszVarName, eLonLatType, nLatDims, nVarLatID);
    5769          59 :                 NCDF_ERR(status);
    5770          59 :                 DefVarDeflate(nVarLatID, false);  // Don't set chunking.
    5771             :             }
    5772             : 
    5773             :             {
    5774          59 :                 const char *pszVarName =
    5775          59 :                     bIsRotatedPole ? NCDF_DIMNAME_RLON : CF_LONGITUDE_VAR_NAME;
    5776          59 :                 int status = nc_def_var(cdfid, pszVarName, eLonLatType,
    5777             :                                         nLonDims, panLonDims, &nVarLonID);
    5778          59 :                 CPLDebug("GDAL_netCDF", "nc_def_var(%d,%s,%d,%d,-,-) got id %d",
    5779             :                          cdfid, pszVarName, eLonLatType, nLatDims, nVarLonID);
    5780          59 :                 NCDF_ERR(status);
    5781          59 :                 DefVarDeflate(nVarLonID, false);  // Don't set chunking.
    5782             :             }
    5783             : 
    5784          59 :             if (bIsRotatedPole)
    5785           0 :                 NCDFWriteRLonRLatVarsAttributes(this->vcdf, nVarLonID,
    5786             :                                                 nVarLatID);
    5787             :             else
    5788          59 :                 NCDFWriteLonLatVarsAttributes(this->vcdf, nVarLonID, nVarLatID);
    5789             : 
    5790          59 :             CPLFree(panLatDims);
    5791          59 :             CPLFree(panLonDims);
    5792             :         }
    5793             :     }
    5794             : 
    5795         164 :     if (!bDefsOnly)
    5796             :     {
    5797          82 :         m_bAddedProjectionVarsData = true;
    5798             : 
    5799          82 :         int nVarXID = -1;
    5800          82 :         int nVarYID = -1;
    5801             : 
    5802          82 :         nc_inq_varid(cdfid, CF_PROJ_X_VAR_NAME, &nVarXID);
    5803          82 :         nc_inq_varid(cdfid, CF_PROJ_Y_VAR_NAME, &nVarYID);
    5804             : 
    5805          82 :         int nVarLonID = -1;
    5806          82 :         int nVarLatID = -1;
    5807             : 
    5808          82 :         const bool bIsRotatedPole =
    5809         151 :             pszCFProjection != nullptr &&
    5810          69 :             EQUAL(pszCFProjection, ROTATED_POLE_VAR_NAME);
    5811          82 :         nc_inq_varid(cdfid,
    5812             :                      bIsRotatedPole ? NCDF_DIMNAME_RLON : CF_LONGITUDE_VAR_NAME,
    5813             :                      &nVarLonID);
    5814          82 :         nc_inq_varid(cdfid,
    5815             :                      bIsRotatedPole ? NCDF_DIMNAME_RLAT : CF_LATITUDE_VAR_NAME,
    5816             :                      &nVarLatID);
    5817             : 
    5818             :         // Get projection values.
    5819             : 
    5820          82 :         double *padLonVal = nullptr;
    5821          82 :         double *padLatVal = nullptr;
    5822             : 
    5823          82 :         if (bIsProjected)
    5824             :         {
    5825          25 :             OGRSpatialReference *poLatLonSRS = nullptr;
    5826          25 :             OGRCoordinateTransformation *poTransform = nullptr;
    5827             : 
    5828             :             size_t startX[1];
    5829             :             size_t countX[1];
    5830             :             size_t startY[1];
    5831             :             size_t countY[1];
    5832             : 
    5833          25 :             CPLDebug("GDAL_netCDF", "Getting (X,Y) values");
    5834             : 
    5835             :             double *padXVal =
    5836          25 :                 static_cast<double *>(CPLMalloc(nRasterXSize * sizeof(double)));
    5837             :             double *padYVal =
    5838          25 :                 static_cast<double *>(CPLMalloc(nRasterYSize * sizeof(double)));
    5839             : 
    5840             :             // Get Y values.
    5841          25 :             const double dfY0 = (!bBottomUp) ? m_gt[3] :
    5842             :                                              // Invert latitude values.
    5843          25 :                                     m_gt[3] + (m_gt[5] * nRasterYSize);
    5844          25 :             const double dfDY = m_gt[5];
    5845             : 
    5846        1456 :             for (int j = 0; j < nRasterYSize; j++)
    5847             :             {
    5848             :                 // The data point is centered inside the pixel.
    5849        1431 :                 if (!bBottomUp)
    5850           0 :                     padYVal[j] = dfY0 + (j + 0.5) * dfDY;
    5851             :                 else  // Invert latitude values.
    5852        1431 :                     padYVal[j] = dfY0 - (j + 0.5) * dfDY;
    5853             :             }
    5854          25 :             startX[0] = 0;
    5855          25 :             countX[0] = nRasterXSize;
    5856             : 
    5857             :             // Get X values.
    5858          25 :             const double dfX0 = m_gt[0];
    5859          25 :             const double dfDX = m_gt[1];
    5860             : 
    5861        1477 :             for (int i = 0; i < nRasterXSize; i++)
    5862             :             {
    5863             :                 // The data point is centered inside the pixel.
    5864        1452 :                 padXVal[i] = dfX0 + (i + 0.5) * dfDX;
    5865             :             }
    5866          25 :             startY[0] = 0;
    5867          25 :             countY[0] = nRasterYSize;
    5868             : 
    5869             :             // Write X/Y values.
    5870             : 
    5871             :             // Make sure we are in data mode.
    5872          25 :             SetDefineMode(false);
    5873             : 
    5874          25 :             CPLDebug("GDAL_netCDF", "Writing X values");
    5875             :             int status =
    5876          25 :                 nc_put_vara_double(cdfid, nVarXID, startX, countX, padXVal);
    5877          25 :             NCDF_ERR(status);
    5878             : 
    5879          25 :             CPLDebug("GDAL_netCDF", "Writing Y values");
    5880             :             status =
    5881          25 :                 nc_put_vara_double(cdfid, nVarYID, startY, countY, padYVal);
    5882          25 :             NCDF_ERR(status);
    5883             : 
    5884          25 :             if (pfnProgress)
    5885          21 :                 pfnProgress(0.20, nullptr, pProgressData);
    5886             : 
    5887             :             // Write lon/lat arrays (CF coordinates) if requested.
    5888             : 
    5889             :             // Get OGR transform if GEOLOCATION is not available.
    5890          25 :             if (bWriteLonLat && !bHasGeoloc)
    5891             :             {
    5892           1 :                 poLatLonSRS = m_oSRS.CloneGeogCS();
    5893           1 :                 if (poLatLonSRS != nullptr)
    5894             :                 {
    5895           1 :                     poLatLonSRS->SetAxisMappingStrategy(
    5896             :                         OAMS_TRADITIONAL_GIS_ORDER);
    5897             :                     poTransform =
    5898           1 :                         OGRCreateCoordinateTransformation(&m_oSRS, poLatLonSRS);
    5899             :                 }
    5900             :                 // If no OGR transform, then don't write CF lon/lat.
    5901           1 :                 if (poTransform == nullptr)
    5902             :                 {
    5903           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    5904             :                              "Unable to get Coordinate Transform");
    5905           0 :                     bWriteLonLat = false;
    5906             :                 }
    5907             :             }
    5908             : 
    5909          25 :             if (bWriteLonLat)
    5910             :             {
    5911           2 :                 if (!bHasGeoloc)
    5912           1 :                     CPLDebug("GDAL_netCDF", "Transforming (X,Y)->(lon,lat)");
    5913             :                 else
    5914           1 :                     CPLDebug("GDAL_netCDF",
    5915             :                              "Writing (lon,lat) from GEOLOCATION arrays");
    5916             : 
    5917           2 :                 bool bOK = true;
    5918           2 :                 double dfProgress = 0.2;
    5919             : 
    5920           2 :                 size_t start[] = {0, 0};
    5921           2 :                 size_t count[] = {1, (size_t)nRasterXSize};
    5922             :                 padLatVal = static_cast<double *>(
    5923           2 :                     CPLMalloc(nRasterXSize * sizeof(double)));
    5924             :                 padLonVal = static_cast<double *>(
    5925           2 :                     CPLMalloc(nRasterXSize * sizeof(double)));
    5926             : 
    5927          61 :                 for (int j = 0; j < nRasterYSize && bOK && status == NC_NOERR;
    5928             :                      j++)
    5929             :                 {
    5930          59 :                     start[0] = j;
    5931             : 
    5932             :                     // Get values from geotransform.
    5933          59 :                     if (!bHasGeoloc)
    5934             :                     {
    5935             :                         // Fill values to transform.
    5936         420 :                         for (int i = 0; i < nRasterXSize; i++)
    5937             :                         {
    5938         400 :                             padLatVal[i] = padYVal[j];
    5939         400 :                             padLonVal[i] = padXVal[i];
    5940             :                         }
    5941             : 
    5942             :                         // Do the transform.
    5943          20 :                         bOK = CPL_TO_BOOL(poTransform->Transform(
    5944          20 :                             nRasterXSize, padLonVal, padLatVal, nullptr));
    5945          20 :                         if (!bOK)
    5946             :                         {
    5947           0 :                             CPLError(CE_Failure, CPLE_AppDefined,
    5948             :                                      "Unable to Transform (X,Y) to (lon,lat).");
    5949             :                         }
    5950             :                     }
    5951             :                     // Get values from geoloc arrays.
    5952             :                     else
    5953             :                     {
    5954          39 :                         CPLErr eErr = GDALRasterIO(
    5955             :                             hBand_Y, GF_Read, 0, j, nRasterXSize, 1, padLatVal,
    5956             :                             nRasterXSize, 1, GDT_Float64, 0, 0);
    5957          39 :                         if (eErr == CE_None)
    5958             :                         {
    5959          39 :                             eErr = GDALRasterIO(
    5960             :                                 hBand_X, GF_Read, 0, j, nRasterXSize, 1,
    5961             :                                 padLonVal, nRasterXSize, 1, GDT_Float64, 0, 0);
    5962             :                         }
    5963             : 
    5964          39 :                         if (eErr == CE_None)
    5965             :                         {
    5966          39 :                             bOK = true;
    5967             :                         }
    5968             :                         else
    5969             :                         {
    5970           0 :                             bOK = false;
    5971           0 :                             CPLError(CE_Failure, CPLE_AppDefined,
    5972             :                                      "Unable to get scanline %d", j);
    5973             :                         }
    5974             :                     }
    5975             : 
    5976             :                     // Write data.
    5977          59 :                     if (bOK)
    5978             :                     {
    5979          59 :                         status = nc_put_vara_double(cdfid, nVarLatID, start,
    5980             :                                                     count, padLatVal);
    5981          59 :                         NCDF_ERR(status);
    5982          59 :                         status = nc_put_vara_double(cdfid, nVarLonID, start,
    5983             :                                                     count, padLonVal);
    5984          59 :                         NCDF_ERR(status);
    5985             :                     }
    5986             : 
    5987          59 :                     if (pfnProgress && (nRasterYSize / 10) > 0 &&
    5988          59 :                         (j % (nRasterYSize / 10) == 0))
    5989             :                     {
    5990          23 :                         dfProgress += 0.08;
    5991          23 :                         pfnProgress(dfProgress, nullptr, pProgressData);
    5992             :                     }
    5993             :                 }
    5994             :             }
    5995             : 
    5996          25 :             if (poLatLonSRS != nullptr)
    5997           1 :                 delete poLatLonSRS;
    5998          25 :             if (poTransform != nullptr)
    5999           1 :                 delete poTransform;
    6000             : 
    6001          25 :             CPLFree(padXVal);
    6002          25 :             CPLFree(padYVal);
    6003             :         }  // Projected
    6004             : 
    6005             :         // If not projected/geographic and has geoloc
    6006          57 :         else if (!bIsGeographic && bHasGeoloc)
    6007             :         {
    6008             :             // Use
    6009             :             // https://cfconventions.org/Data/cf-conventions/cf-conventions-1.9/cf-conventions.html#_two_dimensional_latitude_longitude_coordinate_variables
    6010             : 
    6011           4 :             bool bOK = true;
    6012           4 :             double dfProgress = 0.2;
    6013             : 
    6014             :             // Make sure we are in data mode.
    6015           4 :             SetDefineMode(false);
    6016             : 
    6017             :             size_t startX[1];
    6018             :             size_t countX[1];
    6019             :             size_t startY[1];
    6020             :             size_t countY[1];
    6021           4 :             startX[0] = 0;
    6022           4 :             countX[0] = nRasterXSize;
    6023             : 
    6024           4 :             startY[0] = 0;
    6025           4 :             countY[0] = nRasterYSize;
    6026             : 
    6027           8 :             std::vector<double> adfXVal(nRasterXSize);
    6028          16 :             for (int i = 0; i < nRasterXSize; i++)
    6029          12 :                 adfXVal[i] = i;
    6030             : 
    6031           8 :             std::vector<double> adfYVal(nRasterYSize);
    6032          12 :             for (int i = 0; i < nRasterYSize; i++)
    6033           8 :                 adfYVal[i] = bBottomUp ? nRasterYSize - 1 - i : i;
    6034             : 
    6035           4 :             CPLDebug("GDAL_netCDF", "Writing X values");
    6036           4 :             int status = nc_put_vara_double(cdfid, nVarXID, startX, countX,
    6037           4 :                                             adfXVal.data());
    6038           4 :             NCDF_ERR(status);
    6039             : 
    6040           4 :             CPLDebug("GDAL_netCDF", "Writing Y values");
    6041           4 :             status = nc_put_vara_double(cdfid, nVarYID, startY, countY,
    6042           4 :                                         adfYVal.data());
    6043           4 :             NCDF_ERR(status);
    6044             : 
    6045           4 :             if (pfnProgress)
    6046           0 :                 pfnProgress(0.20, nullptr, pProgressData);
    6047             : 
    6048           4 :             size_t start[] = {0, 0};
    6049           4 :             size_t count[] = {1, (size_t)nRasterXSize};
    6050             :             padLatVal =
    6051           4 :                 static_cast<double *>(CPLMalloc(nRasterXSize * sizeof(double)));
    6052             :             padLonVal =
    6053           4 :                 static_cast<double *>(CPLMalloc(nRasterXSize * sizeof(double)));
    6054             : 
    6055          12 :             for (int j = 0; j < nRasterYSize && bOK && status == NC_NOERR; j++)
    6056             :             {
    6057           8 :                 start[0] = j;
    6058             : 
    6059           8 :                 CPLErr eErr = GDALRasterIO(hBand_Y, GF_Read, 0,
    6060           8 :                                            bBottomUp ? nRasterYSize - 1 - j : j,
    6061             :                                            nRasterXSize, 1, padLatVal,
    6062             :                                            nRasterXSize, 1, GDT_Float64, 0, 0);
    6063           8 :                 if (eErr == CE_None)
    6064             :                 {
    6065           8 :                     eErr = GDALRasterIO(hBand_X, GF_Read, 0,
    6066           8 :                                         bBottomUp ? nRasterYSize - 1 - j : j,
    6067             :                                         nRasterXSize, 1, padLonVal,
    6068             :                                         nRasterXSize, 1, GDT_Float64, 0, 0);
    6069             :                 }
    6070             : 
    6071           8 :                 if (eErr == CE_None)
    6072             :                 {
    6073           8 :                     bOK = true;
    6074             :                 }
    6075             :                 else
    6076             :                 {
    6077           0 :                     bOK = false;
    6078           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    6079             :                              "Unable to get scanline %d", j);
    6080             :                 }
    6081             : 
    6082             :                 // Write data.
    6083           8 :                 if (bOK)
    6084             :                 {
    6085           8 :                     status = nc_put_vara_double(cdfid, nVarLatID, start, count,
    6086             :                                                 padLatVal);
    6087           8 :                     NCDF_ERR(status);
    6088           8 :                     status = nc_put_vara_double(cdfid, nVarLonID, start, count,
    6089             :                                                 padLonVal);
    6090           8 :                     NCDF_ERR(status);
    6091             :                 }
    6092             : 
    6093           8 :                 if (pfnProgress && (nRasterYSize / 10) > 0 &&
    6094           0 :                     (j % (nRasterYSize / 10) == 0))
    6095             :                 {
    6096           0 :                     dfProgress += 0.08;
    6097           0 :                     pfnProgress(dfProgress, nullptr, pProgressData);
    6098             :                 }
    6099           4 :             }
    6100             :         }
    6101             : 
    6102             :         // If not projected, assume geographic to catch grids without Datum.
    6103          53 :         else if (bWriteLonLat)
    6104             :         {
    6105             :             // Get latitude values.
    6106          53 :             const double dfY0 = (!bBottomUp) ? m_gt[3] :
    6107             :                                              // Invert latitude values.
    6108          53 :                                     m_gt[3] + (m_gt[5] * nRasterYSize);
    6109          53 :             const double dfDY = m_gt[5];
    6110             : 
    6111             :             // Override lat values with the ones in GEOLOCATION/Y_VALUES.
    6112          53 :             if (netCDFDataset::GetMetadataItem("Y_VALUES", "GEOLOCATION") !=
    6113             :                 nullptr)
    6114             :             {
    6115           0 :                 int nTemp = 0;
    6116           0 :                 padLatVal = Get1DGeolocation("Y_VALUES", nTemp);
    6117             :                 // Make sure we got the correct amount, if not fallback to GT */
    6118             :                 // could add test fabs(fabs(padLatVal[0]) - fabs(dfY0)) <= 0.1))
    6119           0 :                 if (nTemp == nRasterYSize)
    6120             :                 {
    6121           0 :                     CPLDebug(
    6122             :                         "GDAL_netCDF",
    6123             :                         "Using Y_VALUES geolocation metadata for lat values");
    6124             :                 }
    6125             :                 else
    6126             :                 {
    6127           0 :                     CPLDebug("GDAL_netCDF",
    6128             :                              "Got %d elements from Y_VALUES geolocation "
    6129             :                              "metadata, need %d",
    6130             :                              nTemp, nRasterYSize);
    6131           0 :                     if (padLatVal)
    6132             :                     {
    6133           0 :                         CPLFree(padLatVal);
    6134           0 :                         padLatVal = nullptr;
    6135             :                     }
    6136             :                 }
    6137             :             }
    6138             : 
    6139          53 :             if (padLatVal == nullptr)
    6140             :             {
    6141             :                 padLatVal = static_cast<double *>(
    6142          53 :                     CPLMalloc(nRasterYSize * sizeof(double)));
    6143        7105 :                 for (int i = 0; i < nRasterYSize; i++)
    6144             :                 {
    6145             :                     // The data point is centered inside the pixel.
    6146        7052 :                     if (!bBottomUp)
    6147           0 :                         padLatVal[i] = dfY0 + (i + 0.5) * dfDY;
    6148             :                     else  // Invert latitude values.
    6149        7052 :                         padLatVal[i] = dfY0 - (i + 0.5) * dfDY;
    6150             :                 }
    6151             :             }
    6152             : 
    6153          53 :             size_t startLat[1] = {0};
    6154          53 :             size_t countLat[1] = {static_cast<size_t>(nRasterYSize)};
    6155             : 
    6156             :             // Get longitude values.
    6157          53 :             const double dfX0 = m_gt[0];
    6158          53 :             const double dfDX = m_gt[1];
    6159             : 
    6160             :             padLonVal =
    6161          53 :                 static_cast<double *>(CPLMalloc(nRasterXSize * sizeof(double)));
    6162        7157 :             for (int i = 0; i < nRasterXSize; i++)
    6163             :             {
    6164             :                 // The data point is centered inside the pixel.
    6165        7104 :                 padLonVal[i] = dfX0 + (i + 0.5) * dfDX;
    6166             :             }
    6167             : 
    6168          53 :             size_t startLon[1] = {0};
    6169          53 :             size_t countLon[1] = {static_cast<size_t>(nRasterXSize)};
    6170             : 
    6171             :             // Write latitude and longitude values.
    6172             : 
    6173             :             // Make sure we are in data mode.
    6174          53 :             SetDefineMode(false);
    6175             : 
    6176             :             // Write values.
    6177          53 :             CPLDebug("GDAL_netCDF", "Writing lat values");
    6178             : 
    6179          53 :             int status = nc_put_vara_double(cdfid, nVarLatID, startLat,
    6180             :                                             countLat, padLatVal);
    6181          53 :             NCDF_ERR(status);
    6182             : 
    6183          53 :             CPLDebug("GDAL_netCDF", "Writing lon values");
    6184          53 :             status = nc_put_vara_double(cdfid, nVarLonID, startLon, countLon,
    6185             :                                         padLonVal);
    6186          53 :             NCDF_ERR(status);
    6187             : 
    6188             :         }  // Not projected.
    6189             : 
    6190          82 :         CPLFree(padLatVal);
    6191          82 :         CPLFree(padLonVal);
    6192             : 
    6193          82 :         if (pfnProgress)
    6194          41 :             pfnProgress(1.00, nullptr, pProgressData);
    6195             :     }
    6196             : 
    6197         164 :     if (hDS_X != nullptr)
    6198             :     {
    6199          10 :         GDALClose(hDS_X);
    6200             :     }
    6201         164 :     if (hDS_Y != nullptr)
    6202             :     {
    6203          10 :         GDALClose(hDS_Y);
    6204             :     }
    6205             : 
    6206         164 :     return CE_None;
    6207             : }
    6208             : 
    6209             : // Write Projection variable to band variable.
    6210             : // Moved from AddProjectionVars() for cases when bands are added after
    6211             : // projection.
    6212         377 : bool netCDFDataset::AddGridMappingRef()
    6213             : {
    6214         377 :     bool bRet = true;
    6215         377 :     bool bOldDefineMode = bDefineMode;
    6216             : 
    6217         568 :     if ((GetAccess() == GA_Update) && (nBands >= 1) && (GetRasterBand(1)) &&
    6218         191 :         ((pszCFCoordinates != nullptr && !EQUAL(pszCFCoordinates, "")) ||
    6219         185 :          (pszCFProjection != nullptr && !EQUAL(pszCFProjection, ""))))
    6220             :     {
    6221          73 :         bAddedGridMappingRef = true;
    6222             : 
    6223             :         // Make sure we are in define mode.
    6224          73 :         SetDefineMode(true);
    6225             : 
    6226         192 :         for (int i = 1; i <= nBands; i++)
    6227             :         {
    6228             :             const int nVarId =
    6229         119 :                 static_cast<netCDFRasterBand *>(GetRasterBand(i))->nZId;
    6230             : 
    6231         119 :             if (pszCFProjection != nullptr && !EQUAL(pszCFProjection, ""))
    6232             :             {
    6233             :                 int status =
    6234         230 :                     nc_put_att_text(cdfid, nVarId, CF_GRD_MAPPING,
    6235         115 :                                     strlen(pszCFProjection), pszCFProjection);
    6236         115 :                 NCDF_ERR(status);
    6237         115 :                 if (status != NC_NOERR)
    6238           0 :                     bRet = false;
    6239             :             }
    6240         119 :             if (pszCFCoordinates != nullptr && !EQUAL(pszCFCoordinates, ""))
    6241             :             {
    6242             :                 int status =
    6243           6 :                     nc_put_att_text(cdfid, nVarId, CF_COORDINATES,
    6244             :                                     strlen(pszCFCoordinates), pszCFCoordinates);
    6245           6 :                 NCDF_ERR(status);
    6246           6 :                 if (status != NC_NOERR)
    6247           0 :                     bRet = false;
    6248             :             }
    6249             :         }
    6250             : 
    6251             :         // Go back to previous define mode.
    6252          73 :         SetDefineMode(bOldDefineMode);
    6253             :     }
    6254         377 :     return bRet;
    6255             : }
    6256             : 
    6257             : /************************************************************************/
    6258             : /*                          GetGeoTransform()                           */
    6259             : /************************************************************************/
    6260             : 
    6261         118 : CPLErr netCDFDataset::GetGeoTransform(GDALGeoTransform &gt) const
    6262             : 
    6263             : {
    6264         118 :     gt = m_gt;
    6265         118 :     if (m_bHasGeoTransform)
    6266          87 :         return CE_None;
    6267             : 
    6268          31 :     return GDALPamDataset::GetGeoTransform(gt);
    6269             : }
    6270             : 
    6271             : /************************************************************************/
    6272             : /*                                rint()                                */
    6273             : /************************************************************************/
    6274             : 
    6275           0 : double netCDFDataset::rint(double dfX)
    6276             : {
    6277           0 :     return std::round(dfX);
    6278             : }
    6279             : 
    6280             : /************************************************************************/
    6281             : /*                          NCDFReadIsoMetadata()                       */
    6282             : /************************************************************************/
    6283             : 
    6284          16 : static void NCDFReadMetadataAsJson(int cdfid, CPLJSONObject &obj)
    6285             : {
    6286          16 :     int nbAttr = 0;
    6287          16 :     NCDF_ERR(nc_inq_varnatts(cdfid, NC_GLOBAL, &nbAttr));
    6288             : 
    6289          32 :     std::map<std::string, CPLJSONArray> oMapNameToArray;
    6290          40 :     for (int l = 0; l < nbAttr; l++)
    6291             :     {
    6292             :         char szAttrName[NC_MAX_NAME + 1];
    6293          24 :         szAttrName[0] = 0;
    6294          24 :         NCDF_ERR(nc_inq_attname(cdfid, NC_GLOBAL, l, szAttrName));
    6295             : 
    6296          24 :         char *pszMetaValue = nullptr;
    6297          24 :         if (NCDFGetAttr(cdfid, NC_GLOBAL, szAttrName, &pszMetaValue) == CE_None)
    6298             :         {
    6299          24 :             nc_type nAttrType = NC_NAT;
    6300          24 :             size_t nAttrLen = 0;
    6301             : 
    6302          24 :             NCDF_ERR(nc_inq_att(cdfid, NC_GLOBAL, szAttrName, &nAttrType,
    6303             :                                 &nAttrLen));
    6304             : 
    6305          24 :             std::string osAttrName(szAttrName);
    6306          24 :             const auto sharpPos = osAttrName.find('#');
    6307          24 :             if (sharpPos == std::string::npos)
    6308             :             {
    6309          16 :                 if (nAttrType == NC_DOUBLE || nAttrType == NC_FLOAT)
    6310           4 :                     obj.Add(osAttrName, CPLAtof(pszMetaValue));
    6311             :                 else
    6312          12 :                     obj.Add(osAttrName, pszMetaValue);
    6313             :             }
    6314             :             else
    6315             :             {
    6316           8 :                 osAttrName.resize(sharpPos);
    6317           8 :                 auto iter = oMapNameToArray.find(osAttrName);
    6318           8 :                 if (iter == oMapNameToArray.end())
    6319             :                 {
    6320           8 :                     CPLJSONArray array;
    6321           4 :                     obj.Add(osAttrName, array);
    6322           4 :                     oMapNameToArray[osAttrName] = array;
    6323           4 :                     array.Add(pszMetaValue);
    6324             :                 }
    6325             :                 else
    6326             :                 {
    6327           4 :                     iter->second.Add(pszMetaValue);
    6328             :                 }
    6329             :             }
    6330          24 :             CPLFree(pszMetaValue);
    6331          24 :             pszMetaValue = nullptr;
    6332             :         }
    6333             :     }
    6334             : 
    6335          16 :     int nSubGroups = 0;
    6336          16 :     int *panSubGroupIds = nullptr;
    6337          16 :     NCDFGetSubGroups(cdfid, &nSubGroups, &panSubGroupIds);
    6338          16 :     oMapNameToArray.clear();
    6339          28 :     for (int i = 0; i < nSubGroups; i++)
    6340             :     {
    6341          24 :         CPLJSONObject subObj;
    6342          12 :         NCDFReadMetadataAsJson(panSubGroupIds[i], subObj);
    6343             : 
    6344          24 :         std::string osGroupName;
    6345          12 :         osGroupName.resize(NC_MAX_NAME);
    6346          12 :         NCDF_ERR(nc_inq_grpname(panSubGroupIds[i], &osGroupName[0]));
    6347          12 :         osGroupName.resize(strlen(osGroupName.data()));
    6348          12 :         const auto sharpPos = osGroupName.find('#');
    6349          12 :         if (sharpPos == std::string::npos)
    6350             :         {
    6351           4 :             obj.Add(osGroupName, subObj);
    6352             :         }
    6353             :         else
    6354             :         {
    6355           8 :             osGroupName.resize(sharpPos);
    6356           8 :             auto iter = oMapNameToArray.find(osGroupName);
    6357           8 :             if (iter == oMapNameToArray.end())
    6358             :             {
    6359           8 :                 CPLJSONArray array;
    6360           4 :                 obj.Add(osGroupName, array);
    6361           4 :                 oMapNameToArray[osGroupName] = array;
    6362           4 :                 array.Add(subObj);
    6363             :             }
    6364             :             else
    6365             :             {
    6366           4 :                 iter->second.Add(subObj);
    6367             :             }
    6368             :         }
    6369             :     }
    6370          16 :     CPLFree(panSubGroupIds);
    6371          16 : }
    6372             : 
    6373           4 : std::string NCDFReadMetadataAsJson(int cdfid)
    6374             : {
    6375           8 :     CPLJSONDocument oDoc;
    6376           8 :     CPLJSONObject oRoot = oDoc.GetRoot();
    6377           4 :     NCDFReadMetadataAsJson(cdfid, oRoot);
    6378           8 :     return oDoc.SaveAsString();
    6379             : }
    6380             : 
    6381             : /************************************************************************/
    6382             : /*                        ReadAttributes()                              */
    6383             : /************************************************************************/
    6384        1816 : CPLErr netCDFDataset::ReadAttributes(int cdfidIn, int var)
    6385             : 
    6386             : {
    6387        1816 :     char *pszVarFullName = nullptr;
    6388        1816 :     ERR_RET(NCDFGetVarFullName(cdfidIn, var, &pszVarFullName));
    6389             : 
    6390             :     // For metadata in Sentinel 5
    6391        1816 :     if (STARTS_WITH(pszVarFullName, "/METADATA/"))
    6392             :     {
    6393           6 :         for (const char *key :
    6394             :              {"ISO_METADATA", "ESA_METADATA", "EOP_METADATA", "QA_STATISTICS",
    6395           8 :               "GRANULE_DESCRIPTION", "ALGORITHM_SETTINGS"})
    6396             :         {
    6397          14 :             if (var == NC_GLOBAL &&
    6398           7 :                 strcmp(pszVarFullName,
    6399             :                        CPLSPrintf("/METADATA/%s/NC_GLOBAL", key)) == 0)
    6400             :             {
    6401           1 :                 CPLFree(pszVarFullName);
    6402           1 :                 CPLStringList aosList;
    6403           2 :                 aosList.AddString(CPLString(NCDFReadMetadataAsJson(cdfidIn))
    6404           1 :                                       .replaceAll("\\/", '/'));
    6405           1 :                 m_oMapDomainToJSon[key] = std::move(aosList);
    6406           1 :                 return CE_None;
    6407             :             }
    6408             :         }
    6409             :     }
    6410        1815 :     if (STARTS_WITH(pszVarFullName, "/PRODUCT/SUPPORT_DATA/"))
    6411             :     {
    6412           0 :         CPLFree(pszVarFullName);
    6413           0 :         CPLStringList aosList;
    6414             :         aosList.AddString(
    6415           0 :             CPLString(NCDFReadMetadataAsJson(cdfidIn)).replaceAll("\\/", '/'));
    6416           0 :         m_oMapDomainToJSon["SUPPORT_DATA"] = std::move(aosList);
    6417           0 :         return CE_None;
    6418             :     }
    6419             : 
    6420        1815 :     size_t nMetaNameSize =
    6421        1815 :         sizeof(char) * (strlen(pszVarFullName) + 1 + NC_MAX_NAME + 1);
    6422        1815 :     char *pszMetaName = static_cast<char *>(CPLMalloc(nMetaNameSize));
    6423             : 
    6424        1815 :     int nbAttr = 0;
    6425        1815 :     NCDF_ERR(nc_inq_varnatts(cdfidIn, var, &nbAttr));
    6426             : 
    6427        9113 :     for (int l = 0; l < nbAttr; l++)
    6428             :     {
    6429             :         char szAttrName[NC_MAX_NAME + 1];
    6430        7298 :         szAttrName[0] = 0;
    6431        7298 :         NCDF_ERR(nc_inq_attname(cdfidIn, var, l, szAttrName));
    6432        7298 :         snprintf(pszMetaName, nMetaNameSize, "%s#%s", pszVarFullName,
    6433             :                  szAttrName);
    6434             : 
    6435        7298 :         char *pszMetaTemp = nullptr;
    6436        7298 :         if (NCDFGetAttr(cdfidIn, var, szAttrName, &pszMetaTemp) == CE_None)
    6437             :         {
    6438        7297 :             papszMetadata =
    6439        7297 :                 CSLSetNameValue(papszMetadata, pszMetaName, pszMetaTemp);
    6440        7297 :             CPLFree(pszMetaTemp);
    6441        7297 :             pszMetaTemp = nullptr;
    6442             :         }
    6443             :         else
    6444             :         {
    6445           1 :             CPLDebug("GDAL_netCDF", "invalid metadata %s", pszMetaName);
    6446             :         }
    6447             :     }
    6448             : 
    6449        1815 :     CPLFree(pszVarFullName);
    6450        1815 :     CPLFree(pszMetaName);
    6451             : 
    6452        1815 :     if (var == NC_GLOBAL)
    6453             :     {
    6454             :         // Recurse on sub-groups.
    6455         528 :         int nSubGroups = 0;
    6456         528 :         int *panSubGroupIds = nullptr;
    6457         528 :         NCDFGetSubGroups(cdfidIn, &nSubGroups, &panSubGroupIds);
    6458         560 :         for (int i = 0; i < nSubGroups; i++)
    6459             :         {
    6460          32 :             ReadAttributes(panSubGroupIds[i], var);
    6461             :         }
    6462         528 :         CPLFree(panSubGroupIds);
    6463             :     }
    6464             : 
    6465        1815 :     return CE_None;
    6466             : }
    6467             : 
    6468             : /************************************************************************/
    6469             : /*                netCDFDataset::CreateSubDatasetList()                 */
    6470             : /************************************************************************/
    6471          55 : void netCDFDataset::CreateSubDatasetList(int nGroupId)
    6472             : {
    6473             :     char szVarStdName[NC_MAX_NAME + 1];
    6474          55 :     int *ponDimIds = nullptr;
    6475             :     nc_type nAttype;
    6476             :     size_t nAttlen;
    6477             : 
    6478          55 :     netCDFDataset *poDS = this;
    6479             : 
    6480             :     int nVarCount;
    6481          55 :     nc_inq_nvars(nGroupId, &nVarCount);
    6482             : 
    6483          55 :     const bool bListAllArrays = CPLTestBool(
    6484          55 :         CSLFetchNameValueDef(papszOpenOptions, "LIST_ALL_ARRAYS", "NO"));
    6485             : 
    6486         338 :     for (int nVar = 0; nVar < nVarCount; nVar++)
    6487             :     {
    6488             : 
    6489             :         int nDims;
    6490         283 :         nc_inq_varndims(nGroupId, nVar, &nDims);
    6491             : 
    6492         283 :         if ((bListAllArrays && nDims > 0) || nDims >= 2)
    6493             :         {
    6494         162 :             ponDimIds = static_cast<int *>(CPLCalloc(nDims, sizeof(int)));
    6495         162 :             nc_inq_vardimid(nGroupId, nVar, ponDimIds);
    6496             : 
    6497             :             // Create Sub dataset list.
    6498         162 :             CPLString osDim;
    6499         499 :             for (int i = 0; i < nDims; i++)
    6500             :             {
    6501             :                 size_t nDimLen;
    6502         337 :                 nc_inq_dimlen(nGroupId, ponDimIds[i], &nDimLen);
    6503         337 :                 if (!osDim.empty())
    6504         175 :                     osDim += 'x';
    6505         337 :                 osDim += CPLSPrintf("%d", (int)nDimLen);
    6506             :             }
    6507         162 :             CPLFree(ponDimIds);
    6508             : 
    6509             :             nc_type nVarType;
    6510         162 :             nc_inq_vartype(nGroupId, nVar, &nVarType);
    6511         162 :             const char *pszType = "";
    6512         162 :             switch (nVarType)
    6513             :             {
    6514          38 :                 case NC_BYTE:
    6515          38 :                     pszType = "8-bit integer";
    6516          38 :                     break;
    6517           2 :                 case NC_CHAR:
    6518           2 :                     pszType = "8-bit character";
    6519           2 :                     break;
    6520           6 :                 case NC_SHORT:
    6521           6 :                     pszType = "16-bit integer";
    6522           6 :                     break;
    6523          10 :                 case NC_INT:
    6524          10 :                     pszType = "32-bit integer";
    6525          10 :                     break;
    6526          54 :                 case NC_FLOAT:
    6527          54 :                     pszType = "32-bit floating-point";
    6528          54 :                     break;
    6529          34 :                 case NC_DOUBLE:
    6530          34 :                     pszType = "64-bit floating-point";
    6531          34 :                     break;
    6532           4 :                 case NC_UBYTE:
    6533           4 :                     pszType = "8-bit unsigned integer";
    6534           4 :                     break;
    6535           1 :                 case NC_USHORT:
    6536           1 :                     pszType = "16-bit unsigned integer";
    6537           1 :                     break;
    6538           1 :                 case NC_UINT:
    6539           1 :                     pszType = "32-bit unsigned integer";
    6540           1 :                     break;
    6541           1 :                 case NC_INT64:
    6542           1 :                     pszType = "64-bit integer";
    6543           1 :                     break;
    6544           1 :                 case NC_UINT64:
    6545           1 :                     pszType = "64-bit unsigned integer";
    6546           1 :                     break;
    6547          10 :                 default:
    6548          10 :                     break;
    6549             :             }
    6550             : 
    6551         162 :             char *pszName = nullptr;
    6552         162 :             if (NCDFGetVarFullName(nGroupId, nVar, &pszName) != CE_None)
    6553           0 :                 continue;
    6554             : 
    6555         162 :             nSubDatasets++;
    6556             : 
    6557         162 :             nAttlen = 0;
    6558         162 :             nc_inq_att(nGroupId, nVar, CF_STD_NAME, &nAttype, &nAttlen);
    6559         324 :             if (nAttlen < sizeof(szVarStdName) &&
    6560         162 :                 nc_get_att_text(nGroupId, nVar, CF_STD_NAME, szVarStdName) ==
    6561             :                     NC_NOERR)
    6562             :             {
    6563          56 :                 szVarStdName[nAttlen] = '\0';
    6564             :             }
    6565             :             else
    6566             :             {
    6567         106 :                 snprintf(szVarStdName, sizeof(szVarStdName), "%s", pszName);
    6568             :             }
    6569             : 
    6570             :             char szTemp[NC_MAX_NAME + 1];
    6571         162 :             snprintf(szTemp, sizeof(szTemp), "SUBDATASET_%d_NAME",
    6572             :                      nSubDatasets);
    6573             : 
    6574         162 :             if (strchr(pszName, ' ') || strchr(pszName, ':'))
    6575             :             {
    6576           1 :                 poDS->papszSubDatasets = CSLSetNameValue(
    6577             :                     poDS->papszSubDatasets, szTemp,
    6578             :                     CPLSPrintf("NETCDF:\"%s\":\"%s\"", poDS->osFilename.c_str(),
    6579             :                                pszName));
    6580             :             }
    6581             :             else
    6582             :             {
    6583         161 :                 poDS->papszSubDatasets = CSLSetNameValue(
    6584             :                     poDS->papszSubDatasets, szTemp,
    6585             :                     CPLSPrintf("NETCDF:\"%s\":%s", poDS->osFilename.c_str(),
    6586             :                                pszName));
    6587             :             }
    6588             : 
    6589         162 :             CPLFree(pszName);
    6590             : 
    6591         162 :             snprintf(szTemp, sizeof(szTemp), "SUBDATASET_%d_DESC",
    6592             :                      nSubDatasets);
    6593             : 
    6594         162 :             poDS->papszSubDatasets =
    6595         162 :                 CSLSetNameValue(poDS->papszSubDatasets, szTemp,
    6596             :                                 CPLSPrintf("[%s] %s (%s)", osDim.c_str(),
    6597             :                                            szVarStdName, pszType));
    6598             :         }
    6599             :     }
    6600             : 
    6601             :     // Recurse on sub groups.
    6602          55 :     int nSubGroups = 0;
    6603          55 :     int *panSubGroupIds = nullptr;
    6604          55 :     NCDFGetSubGroups(nGroupId, &nSubGroups, &panSubGroupIds);
    6605          62 :     for (int i = 0; i < nSubGroups; i++)
    6606             :     {
    6607           7 :         CreateSubDatasetList(panSubGroupIds[i]);
    6608             :     }
    6609          55 :     CPLFree(panSubGroupIds);
    6610          55 : }
    6611             : 
    6612             : /************************************************************************/
    6613             : /*                            TestCapability()                          */
    6614             : /************************************************************************/
    6615             : 
    6616         249 : int netCDFDataset::TestCapability(const char *pszCap) const
    6617             : {
    6618         249 :     if (EQUAL(pszCap, ODsCCreateLayer))
    6619             :     {
    6620         225 :         return eAccess == GA_Update && nBands == 0 &&
    6621         219 :                (eMultipleLayerBehavior != SINGLE_LAYER ||
    6622         230 :                 this->GetLayerCount() == 0 || bSGSupport);
    6623             :     }
    6624         136 :     else if (EQUAL(pszCap, ODsCZGeometries))
    6625           2 :         return true;
    6626             : 
    6627         134 :     return false;
    6628             : }
    6629             : 
    6630             : /************************************************************************/
    6631             : /*                            GetLayer()                                */
    6632             : /************************************************************************/
    6633             : 
    6634         385 : const OGRLayer *netCDFDataset::GetLayer(int nIdx) const
    6635             : {
    6636         385 :     if (nIdx < 0 || nIdx >= this->GetLayerCount())
    6637           2 :         return nullptr;
    6638         383 :     return papoLayers[nIdx].get();
    6639             : }
    6640             : 
    6641             : /************************************************************************/
    6642             : /*                            ICreateLayer()                            */
    6643             : /************************************************************************/
    6644             : 
    6645          60 : OGRLayer *netCDFDataset::ICreateLayer(const char *pszName,
    6646             :                                       const OGRGeomFieldDefn *poGeomFieldDefn,
    6647             :                                       CSLConstList papszOptions)
    6648             : {
    6649          60 :     int nLayerCDFId = cdfid;
    6650          60 :     if (!TestCapability(ODsCCreateLayer))
    6651           0 :         return nullptr;
    6652             : 
    6653          60 :     const auto eGType = poGeomFieldDefn ? poGeomFieldDefn->GetType() : wkbNone;
    6654             :     const auto poSpatialRef =
    6655          60 :         poGeomFieldDefn ? poGeomFieldDefn->GetSpatialRef() : nullptr;
    6656             : 
    6657         120 :     CPLString osNetCDFLayerName(pszName);
    6658          60 :     const netCDFWriterConfigLayer *poLayerConfig = nullptr;
    6659          60 :     if (oWriterConfig.m_bIsValid)
    6660             :     {
    6661             :         std::map<CPLString, netCDFWriterConfigLayer>::const_iterator
    6662           2 :             oLayerIter = oWriterConfig.m_oLayers.find(pszName);
    6663           2 :         if (oLayerIter != oWriterConfig.m_oLayers.end())
    6664             :         {
    6665           1 :             poLayerConfig = &(oLayerIter->second);
    6666           1 :             osNetCDFLayerName = poLayerConfig->m_osNetCDFName;
    6667             :         }
    6668             :     }
    6669             : 
    6670          60 :     netCDFDataset *poLayerDataset = nullptr;
    6671          60 :     if (eMultipleLayerBehavior == SEPARATE_FILES)
    6672             :     {
    6673           3 :         if (CPLLaunderForFilenameSafe(osNetCDFLayerName.c_str(), nullptr) !=
    6674             :             osNetCDFLayerName)
    6675             :         {
    6676           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6677             :                      "Illegal characters in '%s' to form a valid filename",
    6678             :                      osNetCDFLayerName.c_str());
    6679           1 :             return nullptr;
    6680             :         }
    6681           2 :         char **papszDatasetOptions = nullptr;
    6682           2 :         papszDatasetOptions = CSLSetNameValue(
    6683             :             papszDatasetOptions, "CONFIG_FILE",
    6684           2 :             CSLFetchNameValue(papszCreationOptions, "CONFIG_FILE"));
    6685             :         papszDatasetOptions =
    6686           2 :             CSLSetNameValue(papszDatasetOptions, "FORMAT",
    6687           2 :                             CSLFetchNameValue(papszCreationOptions, "FORMAT"));
    6688           2 :         papszDatasetOptions = CSLSetNameValue(
    6689             :             papszDatasetOptions, "WRITE_GDAL_TAGS",
    6690           2 :             CSLFetchNameValue(papszCreationOptions, "WRITE_GDAL_TAGS"));
    6691             :         const CPLString osLayerFilename(
    6692           2 :             CPLFormFilenameSafe(osFilename, osNetCDFLayerName, "nc"));
    6693           2 :         CPLAcquireMutex(hNCMutex, 1000.0);
    6694           2 :         poLayerDataset =
    6695           2 :             CreateLL(osLayerFilename, 0, 0, 0, papszDatasetOptions);
    6696           2 :         CPLReleaseMutex(hNCMutex);
    6697           2 :         CSLDestroy(papszDatasetOptions);
    6698           2 :         if (poLayerDataset == nullptr)
    6699           0 :             return nullptr;
    6700             : 
    6701           2 :         nLayerCDFId = poLayerDataset->cdfid;
    6702           2 :         NCDFAddGDALHistory(nLayerCDFId, osLayerFilename, bWriteGDALVersion,
    6703           2 :                            bWriteGDALHistory, "", "Create",
    6704             :                            NCDF_CONVENTIONS_CF_V1_6);
    6705             :     }
    6706          57 :     else if (eMultipleLayerBehavior == SEPARATE_GROUPS)
    6707             :     {
    6708           2 :         SetDefineMode(true);
    6709             : 
    6710           2 :         nLayerCDFId = -1;
    6711           2 :         int status = nc_def_grp(cdfid, osNetCDFLayerName, &nLayerCDFId);
    6712           2 :         NCDF_ERR(status);
    6713           2 :         if (status != NC_NOERR)
    6714           0 :             return nullptr;
    6715             : 
    6716           2 :         NCDFAddGDALHistory(nLayerCDFId, osFilename, bWriteGDALVersion,
    6717           2 :                            bWriteGDALHistory, "", "Create",
    6718             :                            NCDF_CONVENTIONS_CF_V1_6);
    6719             :     }
    6720             : 
    6721             :     // Make a clone to workaround a bug in released MapServer versions
    6722             :     // that destroys the passed SRS instead of releasing it .
    6723          59 :     OGRSpatialReference *poSRS = nullptr;
    6724          59 :     if (poSpatialRef)
    6725             :     {
    6726          43 :         poSRS = poSpatialRef->Clone();
    6727          43 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    6728             :     }
    6729             :     std::shared_ptr<netCDFLayer> poLayer(
    6730          59 :         new netCDFLayer(poLayerDataset ? poLayerDataset : this, nLayerCDFId,
    6731         118 :                         osNetCDFLayerName, eGType, poSRS));
    6732          59 :     if (poSRS != nullptr)
    6733          43 :         poSRS->Release();
    6734             : 
    6735             :     // Fetch layer creation options coming from config file
    6736          59 :     char **papszNewOptions = CSLDuplicate(papszOptions);
    6737          59 :     if (oWriterConfig.m_bIsValid)
    6738             :     {
    6739           2 :         std::map<CPLString, CPLString>::const_iterator oIter;
    6740           3 :         for (oIter = oWriterConfig.m_oLayerCreationOptions.begin();
    6741           3 :              oIter != oWriterConfig.m_oLayerCreationOptions.end(); ++oIter)
    6742             :         {
    6743             :             papszNewOptions =
    6744           1 :                 CSLSetNameValue(papszNewOptions, oIter->first, oIter->second);
    6745             :         }
    6746           2 :         if (poLayerConfig != nullptr)
    6747             :         {
    6748           3 :             for (oIter = poLayerConfig->m_oLayerCreationOptions.begin();
    6749           3 :                  oIter != poLayerConfig->m_oLayerCreationOptions.end(); ++oIter)
    6750             :             {
    6751           2 :                 papszNewOptions = CSLSetNameValue(papszNewOptions, oIter->first,
    6752           2 :                                                   oIter->second);
    6753             :             }
    6754             :         }
    6755             :     }
    6756             : 
    6757          59 :     const bool bRet = poLayer->Create(papszNewOptions, poLayerConfig);
    6758          59 :     CSLDestroy(papszNewOptions);
    6759             : 
    6760          59 :     if (!bRet)
    6761             :     {
    6762           0 :         return nullptr;
    6763             :     }
    6764             : 
    6765          59 :     if (poLayerDataset != nullptr)
    6766           2 :         apoVectorDatasets.push_back(poLayerDataset);
    6767             : 
    6768          59 :     papoLayers.push_back(poLayer);
    6769          59 :     return poLayer.get();
    6770             : }
    6771             : 
    6772             : /************************************************************************/
    6773             : /*                           CloneAttributes()                          */
    6774             : /************************************************************************/
    6775             : 
    6776         137 : bool netCDFDataset::CloneAttributes(int old_cdfid, int new_cdfid, int nSrcVarId,
    6777             :                                     int nDstVarId)
    6778             : {
    6779         137 :     int nAttCount = -1;
    6780         137 :     int status = nc_inq_varnatts(old_cdfid, nSrcVarId, &nAttCount);
    6781         137 :     NCDF_ERR(status);
    6782             : 
    6783         693 :     for (int i = 0; i < nAttCount; i++)
    6784             :     {
    6785             :         char szName[NC_MAX_NAME + 1];
    6786         556 :         szName[0] = 0;
    6787         556 :         status = nc_inq_attname(old_cdfid, nSrcVarId, i, szName);
    6788         556 :         NCDF_ERR(status);
    6789             : 
    6790             :         status =
    6791         556 :             nc_copy_att(old_cdfid, nSrcVarId, szName, new_cdfid, nDstVarId);
    6792         556 :         NCDF_ERR(status);
    6793         556 :         if (status != NC_NOERR)
    6794           0 :             return false;
    6795             :     }
    6796             : 
    6797         137 :     return true;
    6798             : }
    6799             : 
    6800             : /************************************************************************/
    6801             : /*                          CloneVariableContent()                      */
    6802             : /************************************************************************/
    6803             : 
    6804         121 : bool netCDFDataset::CloneVariableContent(int old_cdfid, int new_cdfid,
    6805             :                                          int nSrcVarId, int nDstVarId)
    6806             : {
    6807         121 :     int nVarDimCount = -1;
    6808         121 :     int status = nc_inq_varndims(old_cdfid, nSrcVarId, &nVarDimCount);
    6809         121 :     NCDF_ERR(status);
    6810         121 :     int anDimIds[] = {-1, 1};
    6811         121 :     status = nc_inq_vardimid(old_cdfid, nSrcVarId, anDimIds);
    6812         121 :     NCDF_ERR(status);
    6813         121 :     nc_type nc_datatype = NC_NAT;
    6814         121 :     status = nc_inq_vartype(old_cdfid, nSrcVarId, &nc_datatype);
    6815         121 :     NCDF_ERR(status);
    6816         121 :     size_t nTypeSize = 0;
    6817         121 :     switch (nc_datatype)
    6818             :     {
    6819          35 :         case NC_BYTE:
    6820             :         case NC_CHAR:
    6821          35 :             nTypeSize = 1;
    6822          35 :             break;
    6823           4 :         case NC_SHORT:
    6824           4 :             nTypeSize = 2;
    6825           4 :             break;
    6826          24 :         case NC_INT:
    6827          24 :             nTypeSize = 4;
    6828          24 :             break;
    6829           4 :         case NC_FLOAT:
    6830           4 :             nTypeSize = 4;
    6831           4 :             break;
    6832          43 :         case NC_DOUBLE:
    6833          43 :             nTypeSize = 8;
    6834          43 :             break;
    6835           2 :         case NC_UBYTE:
    6836           2 :             nTypeSize = 1;
    6837           2 :             break;
    6838           2 :         case NC_USHORT:
    6839           2 :             nTypeSize = 2;
    6840           2 :             break;
    6841           2 :         case NC_UINT:
    6842           2 :             nTypeSize = 4;
    6843           2 :             break;
    6844           4 :         case NC_INT64:
    6845             :         case NC_UINT64:
    6846           4 :             nTypeSize = 8;
    6847           4 :             break;
    6848           1 :         case NC_STRING:
    6849           1 :             nTypeSize = sizeof(char *);
    6850           1 :             break;
    6851           0 :         default:
    6852             :         {
    6853           0 :             CPLError(CE_Failure, CPLE_NotSupported, "Unsupported data type: %d",
    6854             :                      nc_datatype);
    6855           0 :             return false;
    6856             :         }
    6857             :     }
    6858             : 
    6859         121 :     size_t nElems = 1;
    6860             :     size_t anStart[NC_MAX_DIMS];
    6861             :     size_t anCount[NC_MAX_DIMS];
    6862         121 :     size_t nRecords = 1;
    6863         261 :     for (int i = 0; i < nVarDimCount; i++)
    6864             :     {
    6865         140 :         anStart[i] = 0;
    6866         140 :         if (i == 0)
    6867             :         {
    6868         116 :             anCount[i] = 1;
    6869         116 :             status = nc_inq_dimlen(old_cdfid, anDimIds[i], &nRecords);
    6870         116 :             NCDF_ERR(status);
    6871             :         }
    6872             :         else
    6873             :         {
    6874          24 :             anCount[i] = 0;
    6875          24 :             status = nc_inq_dimlen(old_cdfid, anDimIds[i], &anCount[i]);
    6876          24 :             NCDF_ERR(status);
    6877          24 :             nElems *= anCount[i];
    6878             :         }
    6879             :     }
    6880             : 
    6881             :     /* Workaround in some cases a netCDF bug:
    6882             :      * https://github.com/Unidata/netcdf-c/pull/1442 */
    6883         121 :     if (nRecords > 0 && nRecords < 10 * 1000 * 1000 / (nElems * nTypeSize))
    6884             :     {
    6885         119 :         nElems *= nRecords;
    6886         119 :         anCount[0] = nRecords;
    6887         119 :         nRecords = 1;
    6888             :     }
    6889             : 
    6890         121 :     void *pBuffer = VSI_MALLOC2_VERBOSE(nElems, nTypeSize);
    6891         121 :     if (pBuffer == nullptr)
    6892           0 :         return false;
    6893             : 
    6894         240 :     for (size_t iRecord = 0; iRecord < nRecords; iRecord++)
    6895             :     {
    6896         119 :         anStart[0] = iRecord;
    6897             : 
    6898         119 :         switch (nc_datatype)
    6899             :         {
    6900           5 :             case NC_BYTE:
    6901             :                 status =
    6902           5 :                     nc_get_vara_schar(old_cdfid, nSrcVarId, anStart, anCount,
    6903             :                                       static_cast<signed char *>(pBuffer));
    6904           5 :                 if (!status)
    6905           5 :                     status = nc_put_vara_schar(
    6906             :                         new_cdfid, nDstVarId, anStart, anCount,
    6907             :                         static_cast<signed char *>(pBuffer));
    6908           5 :                 break;
    6909          28 :             case NC_CHAR:
    6910             :                 status =
    6911          28 :                     nc_get_vara_text(old_cdfid, nSrcVarId, anStart, anCount,
    6912             :                                      static_cast<char *>(pBuffer));
    6913          28 :                 if (!status)
    6914             :                     status =
    6915          28 :                         nc_put_vara_text(new_cdfid, nDstVarId, anStart, anCount,
    6916             :                                          static_cast<char *>(pBuffer));
    6917          28 :                 break;
    6918           4 :             case NC_SHORT:
    6919             :                 status =
    6920           4 :                     nc_get_vara_short(old_cdfid, nSrcVarId, anStart, anCount,
    6921             :                                       static_cast<short *>(pBuffer));
    6922           4 :                 if (!status)
    6923           4 :                     status = nc_put_vara_short(new_cdfid, nDstVarId, anStart,
    6924             :                                                anCount,
    6925             :                                                static_cast<short *>(pBuffer));
    6926           4 :                 break;
    6927          24 :             case NC_INT:
    6928          24 :                 status = nc_get_vara_int(old_cdfid, nSrcVarId, anStart, anCount,
    6929             :                                          static_cast<int *>(pBuffer));
    6930          24 :                 if (!status)
    6931             :                     status =
    6932          24 :                         nc_put_vara_int(new_cdfid, nDstVarId, anStart, anCount,
    6933             :                                         static_cast<int *>(pBuffer));
    6934          24 :                 break;
    6935           4 :             case NC_FLOAT:
    6936             :                 status =
    6937           4 :                     nc_get_vara_float(old_cdfid, nSrcVarId, anStart, anCount,
    6938             :                                       static_cast<float *>(pBuffer));
    6939           4 :                 if (!status)
    6940           4 :                     status = nc_put_vara_float(new_cdfid, nDstVarId, anStart,
    6941             :                                                anCount,
    6942             :                                                static_cast<float *>(pBuffer));
    6943           4 :                 break;
    6944          43 :             case NC_DOUBLE:
    6945             :                 status =
    6946          43 :                     nc_get_vara_double(old_cdfid, nSrcVarId, anStart, anCount,
    6947             :                                        static_cast<double *>(pBuffer));
    6948          43 :                 if (!status)
    6949          43 :                     status = nc_put_vara_double(new_cdfid, nDstVarId, anStart,
    6950             :                                                 anCount,
    6951             :                                                 static_cast<double *>(pBuffer));
    6952          43 :                 break;
    6953           1 :             case NC_STRING:
    6954             :                 status =
    6955           1 :                     nc_get_vara_string(old_cdfid, nSrcVarId, anStart, anCount,
    6956             :                                        static_cast<char **>(pBuffer));
    6957           1 :                 if (!status)
    6958             :                 {
    6959           1 :                     status = nc_put_vara_string(
    6960             :                         new_cdfid, nDstVarId, anStart, anCount,
    6961             :                         static_cast<const char **>(pBuffer));
    6962           1 :                     nc_free_string(nElems, static_cast<char **>(pBuffer));
    6963             :                 }
    6964           1 :                 break;
    6965             : 
    6966           2 :             case NC_UBYTE:
    6967             :                 status =
    6968           2 :                     nc_get_vara_uchar(old_cdfid, nSrcVarId, anStart, anCount,
    6969             :                                       static_cast<unsigned char *>(pBuffer));
    6970           2 :                 if (!status)
    6971           2 :                     status = nc_put_vara_uchar(
    6972             :                         new_cdfid, nDstVarId, anStart, anCount,
    6973             :                         static_cast<unsigned char *>(pBuffer));
    6974           2 :                 break;
    6975           2 :             case NC_USHORT:
    6976             :                 status =
    6977           2 :                     nc_get_vara_ushort(old_cdfid, nSrcVarId, anStart, anCount,
    6978             :                                        static_cast<unsigned short *>(pBuffer));
    6979           2 :                 if (!status)
    6980           2 :                     status = nc_put_vara_ushort(
    6981             :                         new_cdfid, nDstVarId, anStart, anCount,
    6982             :                         static_cast<unsigned short *>(pBuffer));
    6983           2 :                 break;
    6984           2 :             case NC_UINT:
    6985             :                 status =
    6986           2 :                     nc_get_vara_uint(old_cdfid, nSrcVarId, anStart, anCount,
    6987             :                                      static_cast<unsigned int *>(pBuffer));
    6988           2 :                 if (!status)
    6989             :                     status =
    6990           2 :                         nc_put_vara_uint(new_cdfid, nDstVarId, anStart, anCount,
    6991             :                                          static_cast<unsigned int *>(pBuffer));
    6992           2 :                 break;
    6993           2 :             case NC_INT64:
    6994             :                 status =
    6995           2 :                     nc_get_vara_longlong(old_cdfid, nSrcVarId, anStart, anCount,
    6996             :                                          static_cast<long long *>(pBuffer));
    6997           2 :                 if (!status)
    6998           2 :                     status = nc_put_vara_longlong(
    6999             :                         new_cdfid, nDstVarId, anStart, anCount,
    7000             :                         static_cast<long long *>(pBuffer));
    7001           2 :                 break;
    7002           2 :             case NC_UINT64:
    7003           2 :                 status = nc_get_vara_ulonglong(
    7004             :                     old_cdfid, nSrcVarId, anStart, anCount,
    7005             :                     static_cast<unsigned long long *>(pBuffer));
    7006           2 :                 if (!status)
    7007           2 :                     status = nc_put_vara_ulonglong(
    7008             :                         new_cdfid, nDstVarId, anStart, anCount,
    7009             :                         static_cast<unsigned long long *>(pBuffer));
    7010           2 :                 break;
    7011           0 :             default:
    7012           0 :                 status = NC_EBADTYPE;
    7013             :         }
    7014             : 
    7015         119 :         NCDF_ERR(status);
    7016         119 :         if (status != NC_NOERR)
    7017             :         {
    7018           0 :             VSIFree(pBuffer);
    7019           0 :             return false;
    7020             :         }
    7021             :     }
    7022             : 
    7023         121 :     VSIFree(pBuffer);
    7024         121 :     return true;
    7025             : }
    7026             : 
    7027             : /************************************************************************/
    7028             : /*                         NCDFIsUnlimitedDim()                         */
    7029             : /************************************************************************/
    7030             : 
    7031          58 : bool NCDFIsUnlimitedDim(bool bIsNC4, int cdfid, int nDimId)
    7032             : {
    7033          58 :     if (bIsNC4)
    7034             :     {
    7035          16 :         int nUnlimitedDims = 0;
    7036          16 :         nc_inq_unlimdims(cdfid, &nUnlimitedDims, nullptr);
    7037          16 :         bool bFound = false;
    7038          16 :         if (nUnlimitedDims)
    7039             :         {
    7040             :             int *panUnlimitedDimIds =
    7041          16 :                 static_cast<int *>(CPLMalloc(sizeof(int) * nUnlimitedDims));
    7042          16 :             nc_inq_unlimdims(cdfid, nullptr, panUnlimitedDimIds);
    7043          30 :             for (int i = 0; i < nUnlimitedDims; i++)
    7044             :             {
    7045          22 :                 if (panUnlimitedDimIds[i] == nDimId)
    7046             :                 {
    7047           8 :                     bFound = true;
    7048           8 :                     break;
    7049             :                 }
    7050             :             }
    7051          16 :             CPLFree(panUnlimitedDimIds);
    7052             :         }
    7053          16 :         return bFound;
    7054             :     }
    7055             :     else
    7056             :     {
    7057          42 :         int nUnlimitedDimId = -1;
    7058          42 :         nc_inq(cdfid, nullptr, nullptr, nullptr, &nUnlimitedDimId);
    7059          42 :         return nDimId == nUnlimitedDimId;
    7060             :     }
    7061             : }
    7062             : 
    7063             : /************************************************************************/
    7064             : /*                              CloneGrp()                              */
    7065             : /************************************************************************/
    7066             : 
    7067          16 : bool netCDFDataset::CloneGrp(int nOldGrpId, int nNewGrpId, bool bIsNC4,
    7068             :                              int nLayerId, int nDimIdToGrow, size_t nNewSize)
    7069             : {
    7070             :     // Clone dimensions
    7071          16 :     int nDimCount = -1;
    7072          16 :     int status = nc_inq_ndims(nOldGrpId, &nDimCount);
    7073          16 :     NCDF_ERR(status);
    7074          16 :     if (nDimCount < 0 || nDimCount > NC_MAX_DIMS)
    7075           0 :         return false;
    7076             :     int anDimIds[NC_MAX_DIMS];
    7077          16 :     int nUnlimiDimID = -1;
    7078          16 :     status = nc_inq_unlimdim(nOldGrpId, &nUnlimiDimID);
    7079          16 :     NCDF_ERR(status);
    7080          16 :     if (bIsNC4)
    7081             :     {
    7082             :         // In NC4, the dimension ids of a group are not necessarily in
    7083             :         // [0,nDimCount-1] range
    7084           8 :         int nDimCount2 = -1;
    7085           8 :         status = nc_inq_dimids(nOldGrpId, &nDimCount2, anDimIds, FALSE);
    7086           8 :         NCDF_ERR(status);
    7087           8 :         CPLAssert(nDimCount == nDimCount2);
    7088             :     }
    7089             :     else
    7090             :     {
    7091          36 :         for (int i = 0; i < nDimCount; i++)
    7092          28 :             anDimIds[i] = i;
    7093             :     }
    7094          60 :     for (int i = 0; i < nDimCount; i++)
    7095             :     {
    7096             :         char szDimName[NC_MAX_NAME + 1];
    7097          44 :         szDimName[0] = 0;
    7098          44 :         size_t nLen = 0;
    7099          44 :         const int nDimId = anDimIds[i];
    7100          44 :         status = nc_inq_dim(nOldGrpId, nDimId, szDimName, &nLen);
    7101          44 :         NCDF_ERR(status);
    7102          44 :         if (NCDFIsUnlimitedDim(bIsNC4, nOldGrpId, nDimId))
    7103          16 :             nLen = NC_UNLIMITED;
    7104          28 :         else if (nDimId == nDimIdToGrow && nOldGrpId == nLayerId)
    7105          13 :             nLen = nNewSize;
    7106          44 :         int nNewDimId = -1;
    7107          44 :         status = nc_def_dim(nNewGrpId, szDimName, nLen, &nNewDimId);
    7108          44 :         NCDF_ERR(status);
    7109          44 :         CPLAssert(nDimId == nNewDimId);
    7110          44 :         if (status != NC_NOERR)
    7111             :         {
    7112           0 :             return false;
    7113             :         }
    7114             :     }
    7115             : 
    7116             :     // Clone main attributes
    7117          16 :     if (!CloneAttributes(nOldGrpId, nNewGrpId, NC_GLOBAL, NC_GLOBAL))
    7118             :     {
    7119           0 :         return false;
    7120             :     }
    7121             : 
    7122             :     // Clone variable definitions
    7123          16 :     int nVarCount = -1;
    7124          16 :     status = nc_inq_nvars(nOldGrpId, &nVarCount);
    7125          16 :     NCDF_ERR(status);
    7126             : 
    7127         137 :     for (int i = 0; i < nVarCount; i++)
    7128             :     {
    7129             :         char szVarName[NC_MAX_NAME + 1];
    7130         121 :         szVarName[0] = 0;
    7131         121 :         status = nc_inq_varname(nOldGrpId, i, szVarName);
    7132         121 :         NCDF_ERR(status);
    7133         121 :         nc_type nc_datatype = NC_NAT;
    7134         121 :         status = nc_inq_vartype(nOldGrpId, i, &nc_datatype);
    7135         121 :         NCDF_ERR(status);
    7136         121 :         int nVarDimCount = -1;
    7137         121 :         status = nc_inq_varndims(nOldGrpId, i, &nVarDimCount);
    7138         121 :         NCDF_ERR(status);
    7139         121 :         status = nc_inq_vardimid(nOldGrpId, i, anDimIds);
    7140         121 :         NCDF_ERR(status);
    7141         121 :         int nNewVarId = -1;
    7142         121 :         status = nc_def_var(nNewGrpId, szVarName, nc_datatype, nVarDimCount,
    7143             :                             anDimIds, &nNewVarId);
    7144         121 :         NCDF_ERR(status);
    7145         121 :         CPLAssert(i == nNewVarId);
    7146         121 :         if (status != NC_NOERR)
    7147             :         {
    7148           0 :             return false;
    7149             :         }
    7150             : 
    7151         121 :         if (!CloneAttributes(nOldGrpId, nNewGrpId, i, i))
    7152             :         {
    7153           0 :             return false;
    7154             :         }
    7155             :     }
    7156             : 
    7157          16 :     status = nc_enddef(nNewGrpId);
    7158          16 :     NCDF_ERR(status);
    7159          16 :     if (status != NC_NOERR)
    7160             :     {
    7161           0 :         return false;
    7162             :     }
    7163             : 
    7164             :     // Clone variable content
    7165         137 :     for (int i = 0; i < nVarCount; i++)
    7166             :     {
    7167         121 :         if (!CloneVariableContent(nOldGrpId, nNewGrpId, i, i))
    7168             :         {
    7169           0 :             return false;
    7170             :         }
    7171             :     }
    7172             : 
    7173          16 :     return true;
    7174             : }
    7175             : 
    7176             : /************************************************************************/
    7177             : /*                              GrowDim()                               */
    7178             : /************************************************************************/
    7179             : 
    7180          13 : bool netCDFDataset::GrowDim(int nLayerId, int nDimIdToGrow, size_t nNewSize)
    7181             : {
    7182             :     int nCreationMode;
    7183             :     // Set nCreationMode based on eFormat.
    7184          13 :     switch (eFormat)
    7185             :     {
    7186             : #ifdef NETCDF_HAS_NC2
    7187           0 :         case NCDF_FORMAT_NC2:
    7188           0 :             nCreationMode = NC_CLOBBER | NC_64BIT_OFFSET;
    7189           0 :             break;
    7190             : #endif
    7191           5 :         case NCDF_FORMAT_NC4:
    7192           5 :             nCreationMode = NC_CLOBBER | NC_NETCDF4;
    7193           5 :             break;
    7194           0 :         case NCDF_FORMAT_NC4C:
    7195           0 :             nCreationMode = NC_CLOBBER | NC_NETCDF4 | NC_CLASSIC_MODEL;
    7196           0 :             break;
    7197           8 :         case NCDF_FORMAT_NC:
    7198             :         default:
    7199           8 :             nCreationMode = NC_CLOBBER;
    7200           8 :             break;
    7201             :     }
    7202             : 
    7203          13 :     int new_cdfid = -1;
    7204          26 :     CPLString osTmpFilename(osFilename + ".tmp");
    7205          26 :     CPLString osFilenameForNCCreate(osTmpFilename);
    7206             : #if defined(_WIN32) && !defined(NETCDF_USES_UTF8)
    7207             :     if (CPLTestBool(CPLGetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")))
    7208             :     {
    7209             :         char *pszTemp =
    7210             :             CPLRecode(osFilenameForNCCreate, CPL_ENC_UTF8, "CP_ACP");
    7211             :         osFilenameForNCCreate = pszTemp;
    7212             :         CPLFree(pszTemp);
    7213             :     }
    7214             : #endif
    7215          13 :     int status = nc_create(osFilenameForNCCreate, nCreationMode, &new_cdfid);
    7216          13 :     NCDF_ERR(status);
    7217          13 :     if (status != NC_NOERR)
    7218           0 :         return false;
    7219             : 
    7220          13 :     if (!CloneGrp(cdfid, new_cdfid, eFormat == NCDF_FORMAT_NC4, nLayerId,
    7221             :                   nDimIdToGrow, nNewSize))
    7222             :     {
    7223           0 :         GDAL_nc_close(new_cdfid);
    7224           0 :         return false;
    7225             :     }
    7226             : 
    7227          13 :     int nGroupCount = 0;
    7228          26 :     std::vector<CPLString> oListGrpName;
    7229          31 :     if (eFormat == NCDF_FORMAT_NC4 &&
    7230          18 :         nc_inq_grps(cdfid, &nGroupCount, nullptr) == NC_NOERR &&
    7231           5 :         nGroupCount > 0)
    7232             :     {
    7233             :         int *panGroupIds =
    7234           2 :             static_cast<int *>(CPLMalloc(sizeof(int) * nGroupCount));
    7235           2 :         status = nc_inq_grps(cdfid, nullptr, panGroupIds);
    7236           2 :         NCDF_ERR(status);
    7237           5 :         for (int i = 0; i < nGroupCount; i++)
    7238             :         {
    7239             :             char szGroupName[NC_MAX_NAME + 1];
    7240           3 :             szGroupName[0] = 0;
    7241           3 :             NCDF_ERR(nc_inq_grpname(panGroupIds[i], szGroupName));
    7242           3 :             int nNewGrpId = -1;
    7243           3 :             status = nc_def_grp(new_cdfid, szGroupName, &nNewGrpId);
    7244           3 :             NCDF_ERR(status);
    7245           3 :             if (status != NC_NOERR)
    7246             :             {
    7247           0 :                 CPLFree(panGroupIds);
    7248           0 :                 GDAL_nc_close(new_cdfid);
    7249           0 :                 return false;
    7250             :             }
    7251           3 :             if (!CloneGrp(panGroupIds[i], nNewGrpId, /*bIsNC4=*/true, nLayerId,
    7252             :                           nDimIdToGrow, nNewSize))
    7253             :             {
    7254           0 :                 CPLFree(panGroupIds);
    7255           0 :                 GDAL_nc_close(new_cdfid);
    7256           0 :                 return false;
    7257             :             }
    7258             :         }
    7259           2 :         CPLFree(panGroupIds);
    7260             : 
    7261           5 :         for (int i = 0; i < this->GetLayerCount(); i++)
    7262             :         {
    7263           3 :             auto poLayer = dynamic_cast<netCDFLayer *>(papoLayers[i].get());
    7264           3 :             if (poLayer)
    7265             :             {
    7266             :                 char szGroupName[NC_MAX_NAME + 1];
    7267           3 :                 szGroupName[0] = 0;
    7268           3 :                 status = nc_inq_grpname(poLayer->GetCDFID(), szGroupName);
    7269           3 :                 NCDF_ERR(status);
    7270           3 :                 oListGrpName.push_back(szGroupName);
    7271             :             }
    7272             :         }
    7273             :     }
    7274             : 
    7275          13 :     GDAL_nc_close(cdfid);
    7276          13 :     cdfid = -1;
    7277          13 :     GDAL_nc_close(new_cdfid);
    7278             : 
    7279          26 :     CPLString osOriFilename(osFilename + ".ori");
    7280          26 :     if (VSIRename(osFilename, osOriFilename) != 0 ||
    7281          13 :         VSIRename(osTmpFilename, osFilename) != 0)
    7282             :     {
    7283           0 :         CPLError(CE_Failure, CPLE_FileIO, "Renaming of files failed");
    7284           0 :         return false;
    7285             :     }
    7286          13 :     VSIUnlink(osOriFilename);
    7287             : 
    7288          26 :     CPLString osFilenameForNCOpen(osFilename);
    7289             : #if defined(_WIN32) && !defined(NETCDF_USES_UTF8)
    7290             :     if (CPLTestBool(CPLGetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")))
    7291             :     {
    7292             :         char *pszTemp = CPLRecode(osFilenameForNCOpen, CPL_ENC_UTF8, "CP_ACP");
    7293             :         osFilenameForNCOpen = pszTemp;
    7294             :         CPLFree(pszTemp);
    7295             :     }
    7296             : #endif
    7297          13 :     status = GDAL_nc_open(osFilenameForNCOpen, NC_WRITE, &cdfid);
    7298          13 :     NCDF_ERR(status);
    7299          13 :     if (status != NC_NOERR)
    7300           0 :         return false;
    7301          13 :     bDefineMode = false;
    7302             : 
    7303          13 :     if (!oListGrpName.empty())
    7304             :     {
    7305           5 :         for (int i = 0; i < this->GetLayerCount(); i++)
    7306             :         {
    7307           3 :             auto poLayer = dynamic_cast<netCDFLayer *>(papoLayers[i].get());
    7308           3 :             if (poLayer)
    7309             :             {
    7310           3 :                 int nNewLayerCDFID = -1;
    7311           3 :                 status = nc_inq_ncid(cdfid, oListGrpName[i].c_str(),
    7312             :                                      &nNewLayerCDFID);
    7313           3 :                 NCDF_ERR(status);
    7314           3 :                 poLayer->SetCDFID(nNewLayerCDFID);
    7315             :             }
    7316             :         }
    7317             :     }
    7318             :     else
    7319             :     {
    7320          22 :         for (int i = 0; i < this->GetLayerCount(); i++)
    7321             :         {
    7322          11 :             auto poLayer = dynamic_cast<netCDFLayer *>(papoLayers[i].get());
    7323          11 :             if (poLayer)
    7324          11 :                 poLayer->SetCDFID(cdfid);
    7325             :         }
    7326             :     }
    7327             : 
    7328          13 :     return true;
    7329             : }
    7330             : 
    7331             : #ifdef ENABLE_NCDUMP
    7332             : 
    7333             : /************************************************************************/
    7334             : /*                      netCDFDatasetCreateTempFile()                   */
    7335             : /************************************************************************/
    7336             : 
    7337             : /* Create a netCDF file from a text dump (format of ncdump) */
    7338             : /* Mostly to easy fuzzing of the driver, while still generating valid */
    7339             : /* netCDF files. */
    7340             : /* Note: not all data types are supported ! */
    7341           4 : bool netCDFDatasetCreateTempFile(NetCDFFormatEnum eFormat,
    7342             :                                  const char *pszTmpFilename, VSILFILE *fpSrc)
    7343             : {
    7344           4 :     CPL_IGNORE_RET_VAL(eFormat);
    7345           4 :     int nCreateMode = NC_CLOBBER;
    7346           4 :     if (eFormat == NCDF_FORMAT_NC4)
    7347           1 :         nCreateMode |= NC_NETCDF4;
    7348           3 :     else if (eFormat == NCDF_FORMAT_NC4C)
    7349           0 :         nCreateMode |= NC_NETCDF4 | NC_CLASSIC_MODEL;
    7350           4 :     int nCdfId = -1;
    7351           4 :     int status = nc_create(pszTmpFilename, nCreateMode, &nCdfId);
    7352           4 :     if (status != NC_NOERR)
    7353             :     {
    7354           0 :         return false;
    7355             :     }
    7356           4 :     VSIFSeekL(fpSrc, 0, SEEK_SET);
    7357             :     const char *pszLine;
    7358           4 :     constexpr int SECTION_NONE = 0;
    7359           4 :     constexpr int SECTION_DIMENSIONS = 1;
    7360           4 :     constexpr int SECTION_VARIABLES = 2;
    7361           4 :     constexpr int SECTION_DATA = 3;
    7362           4 :     int nActiveSection = SECTION_NONE;
    7363           8 :     std::map<CPLString, int> oMapDimToId;
    7364           8 :     std::map<int, int> oMapDimIdToDimLen;
    7365           8 :     std::map<CPLString, int> oMapVarToId;
    7366           8 :     std::map<int, std::vector<int>> oMapVarIdToVectorOfDimId;
    7367           8 :     std::map<int, int> oMapVarIdToType;
    7368           4 :     std::set<CPLString> oSetAttrDefined;
    7369           4 :     oMapVarToId[""] = -1;
    7370           4 :     size_t nTotalVarSize = 0;
    7371         208 :     while ((pszLine = CPLReadLineL(fpSrc)) != nullptr)
    7372             :     {
    7373         204 :         if (STARTS_WITH(pszLine, "dimensions:") &&
    7374             :             nActiveSection == SECTION_NONE)
    7375             :         {
    7376           4 :             nActiveSection = SECTION_DIMENSIONS;
    7377             :         }
    7378         200 :         else if (STARTS_WITH(pszLine, "variables:") &&
    7379             :                  nActiveSection == SECTION_DIMENSIONS)
    7380             :         {
    7381           4 :             nActiveSection = SECTION_VARIABLES;
    7382             :         }
    7383         196 :         else if (STARTS_WITH(pszLine, "data:") &&
    7384             :                  nActiveSection == SECTION_VARIABLES)
    7385             :         {
    7386           4 :             nActiveSection = SECTION_DATA;
    7387           4 :             status = nc_enddef(nCdfId);
    7388           4 :             if (status != NC_NOERR)
    7389             :             {
    7390           0 :                 CPLDebug("netCDF", "nc_enddef() failed: %s",
    7391             :                          nc_strerror(status));
    7392             :             }
    7393             :         }
    7394         192 :         else if (nActiveSection == SECTION_DIMENSIONS)
    7395             :         {
    7396           9 :             char **papszTokens = CSLTokenizeString2(pszLine, " \t=;", 0);
    7397           9 :             if (CSLCount(papszTokens) == 2)
    7398             :             {
    7399           9 :                 const char *pszDimName = papszTokens[0];
    7400           9 :                 bool bValidName = true;
    7401           9 :                 if (STARTS_WITH(pszDimName, "_nc4_non_coord_"))
    7402             :                 {
    7403             :                     // This is an internal netcdf prefix. Using it may
    7404             :                     // cause memory leaks.
    7405           0 :                     bValidName = false;
    7406             :                 }
    7407           9 :                 if (!bValidName)
    7408             :                 {
    7409           0 :                     CPLDebug("netCDF",
    7410             :                              "nc_def_dim(%s) failed: invalid name found",
    7411             :                              pszDimName);
    7412           0 :                     CSLDestroy(papszTokens);
    7413           0 :                     continue;
    7414             :                 }
    7415             : 
    7416             :                 const bool bIsASCII =
    7417           9 :                     CPLIsASCII(pszDimName, static_cast<size_t>(-1));
    7418           9 :                 if (!bIsASCII)
    7419             :                 {
    7420             :                     // Workaround https://github.com/Unidata/netcdf-c/pull/450
    7421           0 :                     CPLDebug("netCDF",
    7422             :                              "nc_def_dim(%s) failed: rejected because "
    7423             :                              "of non-ASCII characters",
    7424             :                              pszDimName);
    7425           0 :                     CSLDestroy(papszTokens);
    7426           0 :                     continue;
    7427             :                 }
    7428           9 :                 int nDimSize = EQUAL(papszTokens[1], "UNLIMITED")
    7429             :                                    ? NC_UNLIMITED
    7430           9 :                                    : atoi(papszTokens[1]);
    7431           9 :                 if (nDimSize >= 1000)
    7432           1 :                     nDimSize = 1000;  // to avoid very long processing
    7433           9 :                 if (nDimSize >= 0)
    7434             :                 {
    7435           9 :                     int nDimId = -1;
    7436           9 :                     status = nc_def_dim(nCdfId, pszDimName, nDimSize, &nDimId);
    7437           9 :                     if (status != NC_NOERR)
    7438             :                     {
    7439           0 :                         CPLDebug("netCDF", "nc_def_dim(%s, %d) failed: %s",
    7440             :                                  pszDimName, nDimSize, nc_strerror(status));
    7441             :                     }
    7442             :                     else
    7443             :                     {
    7444             : #ifdef DEBUG_VERBOSE
    7445             :                         CPLDebug("netCDF", "nc_def_dim(%s, %d) (%s) succeeded",
    7446             :                                  pszDimName, nDimSize, pszLine);
    7447             : #endif
    7448           9 :                         oMapDimToId[pszDimName] = nDimId;
    7449           9 :                         oMapDimIdToDimLen[nDimId] = nDimSize;
    7450             :                     }
    7451             :                 }
    7452             :             }
    7453           9 :             CSLDestroy(papszTokens);
    7454             :         }
    7455         183 :         else if (nActiveSection == SECTION_VARIABLES)
    7456             :         {
    7457         390 :             while (*pszLine == ' ' || *pszLine == '\t')
    7458         249 :                 pszLine++;
    7459         141 :             const char *pszColumn = strchr(pszLine, ':');
    7460         141 :             const char *pszEqual = strchr(pszLine, '=');
    7461         141 :             if (pszColumn == nullptr)
    7462             :             {
    7463          21 :                 char **papszTokens = CSLTokenizeString2(pszLine, " \t=(),;", 0);
    7464          21 :                 if (CSLCount(papszTokens) >= 2)
    7465             :                 {
    7466          17 :                     const char *pszVarName = papszTokens[1];
    7467          17 :                     bool bValidName = true;
    7468          17 :                     if (STARTS_WITH(pszVarName, "_nc4_non_coord_"))
    7469             :                     {
    7470             :                         // This is an internal netcdf prefix. Using it may
    7471             :                         // cause memory leaks.
    7472           0 :                         bValidName = false;
    7473             :                     }
    7474         138 :                     for (int i = 0; pszVarName[i]; i++)
    7475             :                     {
    7476         121 :                         if (!((pszVarName[i] >= 'a' && pszVarName[i] <= 'z') ||
    7477          28 :                               (pszVarName[i] >= 'A' && pszVarName[i] <= 'Z') ||
    7478           9 :                               (pszVarName[i] >= '0' && pszVarName[i] <= '9') ||
    7479           6 :                               pszVarName[i] == '_'))
    7480             :                         {
    7481           0 :                             bValidName = false;
    7482             :                         }
    7483             :                     }
    7484          17 :                     if (!bValidName)
    7485             :                     {
    7486           0 :                         CPLDebug(
    7487             :                             "netCDF",
    7488             :                             "nc_def_var(%s) failed: illegal character found",
    7489             :                             pszVarName);
    7490           0 :                         CSLDestroy(papszTokens);
    7491           0 :                         continue;
    7492             :                     }
    7493          17 :                     if (oMapVarToId.find(pszVarName) != oMapVarToId.end())
    7494             :                     {
    7495           0 :                         CPLDebug("netCDF",
    7496             :                                  "nc_def_var(%s) failed: already defined",
    7497             :                                  pszVarName);
    7498           0 :                         CSLDestroy(papszTokens);
    7499           0 :                         continue;
    7500             :                     }
    7501          17 :                     const char *pszVarType = papszTokens[0];
    7502          17 :                     int nc_datatype = NC_BYTE;
    7503          17 :                     size_t nDataTypeSize = 1;
    7504          17 :                     if (EQUAL(pszVarType, "char"))
    7505             :                     {
    7506           6 :                         nc_datatype = NC_CHAR;
    7507           6 :                         nDataTypeSize = 1;
    7508             :                     }
    7509          11 :                     else if (EQUAL(pszVarType, "byte"))
    7510             :                     {
    7511           3 :                         nc_datatype = NC_BYTE;
    7512           3 :                         nDataTypeSize = 1;
    7513             :                     }
    7514           8 :                     else if (EQUAL(pszVarType, "short"))
    7515             :                     {
    7516           0 :                         nc_datatype = NC_SHORT;
    7517           0 :                         nDataTypeSize = 2;
    7518             :                     }
    7519           8 :                     else if (EQUAL(pszVarType, "int"))
    7520             :                     {
    7521           0 :                         nc_datatype = NC_INT;
    7522           0 :                         nDataTypeSize = 4;
    7523             :                     }
    7524           8 :                     else if (EQUAL(pszVarType, "float"))
    7525             :                     {
    7526           0 :                         nc_datatype = NC_FLOAT;
    7527           0 :                         nDataTypeSize = 4;
    7528             :                     }
    7529           8 :                     else if (EQUAL(pszVarType, "double"))
    7530             :                     {
    7531           8 :                         nc_datatype = NC_DOUBLE;
    7532           8 :                         nDataTypeSize = 8;
    7533             :                     }
    7534           0 :                     else if (EQUAL(pszVarType, "ubyte"))
    7535             :                     {
    7536           0 :                         nc_datatype = NC_UBYTE;
    7537           0 :                         nDataTypeSize = 1;
    7538             :                     }
    7539           0 :                     else if (EQUAL(pszVarType, "ushort"))
    7540             :                     {
    7541           0 :                         nc_datatype = NC_USHORT;
    7542           0 :                         nDataTypeSize = 2;
    7543             :                     }
    7544           0 :                     else if (EQUAL(pszVarType, "uint"))
    7545             :                     {
    7546           0 :                         nc_datatype = NC_UINT;
    7547           0 :                         nDataTypeSize = 4;
    7548             :                     }
    7549           0 :                     else if (EQUAL(pszVarType, "int64"))
    7550             :                     {
    7551           0 :                         nc_datatype = NC_INT64;
    7552           0 :                         nDataTypeSize = 8;
    7553             :                     }
    7554           0 :                     else if (EQUAL(pszVarType, "uint64"))
    7555             :                     {
    7556           0 :                         nc_datatype = NC_UINT64;
    7557           0 :                         nDataTypeSize = 8;
    7558             :                     }
    7559             : 
    7560          17 :                     int nDims = CSLCount(papszTokens) - 2;
    7561          17 :                     if (nDims >= 32)
    7562             :                     {
    7563             :                         // The number of dimensions in a netCDFv4 file is
    7564             :                         // limited by #define H5S_MAX_RANK    32
    7565             :                         // but libnetcdf doesn't check that...
    7566           0 :                         CPLDebug("netCDF",
    7567             :                                  "nc_def_var(%s) failed: too many dimensions",
    7568             :                                  pszVarName);
    7569           0 :                         CSLDestroy(papszTokens);
    7570           0 :                         continue;
    7571             :                     }
    7572          17 :                     std::vector<int> aoDimIds;
    7573          17 :                     bool bFailed = false;
    7574          17 :                     size_t nSize = 1;
    7575          35 :                     for (int i = 0; i < nDims; i++)
    7576             :                     {
    7577          18 :                         const char *pszDimName = papszTokens[2 + i];
    7578          18 :                         if (oMapDimToId.find(pszDimName) == oMapDimToId.end())
    7579             :                         {
    7580           0 :                             bFailed = true;
    7581           0 :                             break;
    7582             :                         }
    7583          18 :                         const int nDimId = oMapDimToId[pszDimName];
    7584          18 :                         aoDimIds.push_back(nDimId);
    7585             : 
    7586          18 :                         const size_t nDimSize = oMapDimIdToDimLen[nDimId];
    7587          18 :                         if (nDimSize != 0)
    7588             :                         {
    7589          18 :                             if (nSize >
    7590          18 :                                 std::numeric_limits<size_t>::max() / nDimSize)
    7591             :                             {
    7592           0 :                                 bFailed = true;
    7593           0 :                                 break;
    7594             :                             }
    7595             :                             else
    7596             :                             {
    7597          18 :                                 nSize *= nDimSize;
    7598             :                             }
    7599             :                         }
    7600             :                     }
    7601          17 :                     if (bFailed)
    7602             :                     {
    7603           0 :                         CPLDebug("netCDF",
    7604             :                                  "nc_def_var(%s) failed: unknown dimension(s)",
    7605             :                                  pszVarName);
    7606           0 :                         CSLDestroy(papszTokens);
    7607           0 :                         continue;
    7608             :                     }
    7609          17 :                     if (nSize > 100U * 1024 * 1024 / nDataTypeSize)
    7610             :                     {
    7611           0 :                         CPLDebug("netCDF",
    7612             :                                  "nc_def_var(%s) failed: too large data",
    7613             :                                  pszVarName);
    7614           0 :                         CSLDestroy(papszTokens);
    7615           0 :                         continue;
    7616             :                     }
    7617          17 :                     if (nTotalVarSize >
    7618          34 :                             std::numeric_limits<size_t>::max() - nSize ||
    7619          17 :                         nTotalVarSize + nSize > 100 * 1024 * 1024)
    7620             :                     {
    7621           0 :                         CPLDebug("netCDF",
    7622             :                                  "nc_def_var(%s) failed: too large data",
    7623             :                                  pszVarName);
    7624           0 :                         CSLDestroy(papszTokens);
    7625           0 :                         continue;
    7626             :                     }
    7627          17 :                     nTotalVarSize += nSize;
    7628             : 
    7629          17 :                     int nVarId = -1;
    7630             :                     status =
    7631          30 :                         nc_def_var(nCdfId, pszVarName, nc_datatype, nDims,
    7632          13 :                                    (nDims) ? &aoDimIds[0] : nullptr, &nVarId);
    7633          17 :                     if (status != NC_NOERR)
    7634             :                     {
    7635           0 :                         CPLDebug("netCDF", "nc_def_var(%s) failed: %s",
    7636             :                                  pszVarName, nc_strerror(status));
    7637             :                     }
    7638             :                     else
    7639             :                     {
    7640             : #ifdef DEBUG_VERBOSE
    7641             :                         CPLDebug("netCDF", "nc_def_var(%s) (%s) succeeded",
    7642             :                                  pszVarName, pszLine);
    7643             : #endif
    7644          17 :                         oMapVarToId[pszVarName] = nVarId;
    7645          17 :                         oMapVarIdToType[nVarId] = nc_datatype;
    7646          17 :                         oMapVarIdToVectorOfDimId[nVarId] = std::move(aoDimIds);
    7647             :                     }
    7648             :                 }
    7649          21 :                 CSLDestroy(papszTokens);
    7650             :             }
    7651         120 :             else if (pszEqual != nullptr && pszEqual - pszColumn > 0)
    7652             :             {
    7653         116 :                 CPLString osVarName(pszLine, pszColumn - pszLine);
    7654         116 :                 CPLString osAttrName(pszColumn + 1, pszEqual - pszColumn - 1);
    7655         116 :                 osAttrName.Trim();
    7656         116 :                 if (oMapVarToId.find(osVarName) == oMapVarToId.end())
    7657             :                 {
    7658           0 :                     CPLDebug("netCDF",
    7659             :                              "nc_put_att(%s:%s) failed: "
    7660             :                              "no corresponding variable",
    7661             :                              osVarName.c_str(), osAttrName.c_str());
    7662           0 :                     continue;
    7663             :                 }
    7664         116 :                 bool bValidName = true;
    7665        1743 :                 for (size_t i = 0; i < osAttrName.size(); i++)
    7666             :                 {
    7667        1865 :                     if (!((osAttrName[i] >= 'a' && osAttrName[i] <= 'z') ||
    7668         238 :                           (osAttrName[i] >= 'A' && osAttrName[i] <= 'Z') ||
    7669         158 :                           (osAttrName[i] >= '0' && osAttrName[i] <= '9') ||
    7670         158 :                           osAttrName[i] == '_'))
    7671             :                     {
    7672           0 :                         bValidName = false;
    7673             :                     }
    7674             :                 }
    7675         116 :                 if (!bValidName)
    7676             :                 {
    7677           0 :                     CPLDebug(
    7678             :                         "netCDF",
    7679             :                         "nc_put_att(%s:%s) failed: illegal character found",
    7680             :                         osVarName.c_str(), osAttrName.c_str());
    7681           0 :                     continue;
    7682             :                 }
    7683         116 :                 if (oSetAttrDefined.find(osVarName + ":" + osAttrName) !=
    7684         232 :                     oSetAttrDefined.end())
    7685             :                 {
    7686           0 :                     CPLDebug("netCDF",
    7687             :                              "nc_put_att(%s:%s) failed: already defined",
    7688             :                              osVarName.c_str(), osAttrName.c_str());
    7689           0 :                     continue;
    7690             :                 }
    7691             : 
    7692         116 :                 const int nVarId = oMapVarToId[osVarName];
    7693         116 :                 const char *pszValue = pszEqual + 1;
    7694         232 :                 while (*pszValue == ' ')
    7695         116 :                     pszValue++;
    7696             : 
    7697         116 :                 status = NC_EBADTYPE;
    7698         116 :                 if (*pszValue == '"')
    7699             :                 {
    7700             :                     // For _FillValue, the attribute type should match
    7701             :                     // the variable type. Leaks memory with NC4 otherwise
    7702          74 :                     if (osAttrName == "_FillValue")
    7703             :                     {
    7704           0 :                         CPLDebug("netCDF", "nc_put_att_(%s:%s) failed: %s",
    7705             :                                  osVarName.c_str(), osAttrName.c_str(),
    7706             :                                  nc_strerror(status));
    7707           0 :                         continue;
    7708             :                     }
    7709             : 
    7710             :                     // Unquote and unescape string value
    7711          74 :                     CPLString osVal(pszValue + 1);
    7712         222 :                     while (!osVal.empty())
    7713             :                     {
    7714         222 :                         if (osVal.back() == ';' || osVal.back() == ' ')
    7715             :                         {
    7716         148 :                             osVal.pop_back();
    7717             :                         }
    7718          74 :                         else if (osVal.back() == '"')
    7719             :                         {
    7720          74 :                             osVal.pop_back();
    7721          74 :                             break;
    7722             :                         }
    7723             :                         else
    7724             :                         {
    7725           0 :                             break;
    7726             :                         }
    7727             :                     }
    7728          74 :                     osVal.replaceAll("\\\"", '"');
    7729          74 :                     status = nc_put_att_text(nCdfId, nVarId, osAttrName,
    7730             :                                              osVal.size(), osVal.c_str());
    7731             :                 }
    7732             :                 else
    7733             :                 {
    7734          84 :                     CPLString osVal(pszValue);
    7735         126 :                     while (!osVal.empty())
    7736             :                     {
    7737         126 :                         if (osVal.back() == ';' || osVal.back() == ' ')
    7738             :                         {
    7739          84 :                             osVal.pop_back();
    7740             :                         }
    7741             :                         else
    7742             :                         {
    7743          42 :                             break;
    7744             :                         }
    7745             :                     }
    7746          42 :                     int nc_datatype = -1;
    7747          42 :                     if (!osVal.empty() && osVal.back() == 'b')
    7748             :                     {
    7749           3 :                         nc_datatype = NC_BYTE;
    7750           3 :                         osVal.pop_back();
    7751             :                     }
    7752          39 :                     else if (!osVal.empty() && osVal.back() == 's')
    7753             :                     {
    7754           3 :                         nc_datatype = NC_SHORT;
    7755           3 :                         osVal.pop_back();
    7756             :                     }
    7757          42 :                     if (CPLGetValueType(osVal) == CPL_VALUE_INTEGER)
    7758             :                     {
    7759           7 :                         if (nc_datatype < 0)
    7760           4 :                             nc_datatype = NC_INT;
    7761             :                     }
    7762          35 :                     else if (CPLGetValueType(osVal) == CPL_VALUE_REAL)
    7763             :                     {
    7764          32 :                         nc_datatype = NC_DOUBLE;
    7765             :                     }
    7766             :                     else
    7767             :                     {
    7768           3 :                         nc_datatype = -1;
    7769             :                     }
    7770             : 
    7771             :                     // For _FillValue, check that the attribute type matches
    7772             :                     // the variable type. Leaks memory with NC4 otherwise
    7773          42 :                     if (osAttrName == "_FillValue")
    7774             :                     {
    7775           6 :                         if (nVarId < 0 ||
    7776           3 :                             nc_datatype != oMapVarIdToType[nVarId])
    7777             :                         {
    7778           0 :                             nc_datatype = -1;
    7779             :                         }
    7780             :                     }
    7781             : 
    7782          42 :                     if (nc_datatype == NC_BYTE)
    7783             :                     {
    7784             :                         signed char chVal =
    7785           3 :                             static_cast<signed char>(atoi(osVal));
    7786           3 :                         status = nc_put_att_schar(nCdfId, nVarId, osAttrName,
    7787             :                                                   NC_BYTE, 1, &chVal);
    7788             :                     }
    7789          39 :                     else if (nc_datatype == NC_SHORT)
    7790             :                     {
    7791           0 :                         short nVal = static_cast<short>(atoi(osVal));
    7792           0 :                         status = nc_put_att_short(nCdfId, nVarId, osAttrName,
    7793             :                                                   NC_SHORT, 1, &nVal);
    7794             :                     }
    7795          39 :                     else if (nc_datatype == NC_INT)
    7796             :                     {
    7797           4 :                         int nVal = static_cast<int>(atoi(osVal));
    7798           4 :                         status = nc_put_att_int(nCdfId, nVarId, osAttrName,
    7799             :                                                 NC_INT, 1, &nVal);
    7800             :                     }
    7801          35 :                     else if (nc_datatype == NC_DOUBLE)
    7802             :                     {
    7803          32 :                         double dfVal = CPLAtof(osVal);
    7804          32 :                         status = nc_put_att_double(nCdfId, nVarId, osAttrName,
    7805             :                                                    NC_DOUBLE, 1, &dfVal);
    7806             :                     }
    7807             :                 }
    7808         116 :                 if (status != NC_NOERR)
    7809             :                 {
    7810           3 :                     CPLDebug("netCDF", "nc_put_att_(%s:%s) failed: %s",
    7811             :                              osVarName.c_str(), osAttrName.c_str(),
    7812             :                              nc_strerror(status));
    7813             :                 }
    7814             :                 else
    7815             :                 {
    7816         113 :                     oSetAttrDefined.insert(osVarName + ":" + osAttrName);
    7817             : #ifdef DEBUG_VERBOSE
    7818             :                     CPLDebug("netCDF", "nc_put_att_(%s:%s) (%s) succeeded",
    7819             :                              osVarName.c_str(), osAttrName.c_str(), pszLine);
    7820             : #endif
    7821             :                 }
    7822             :             }
    7823             :         }
    7824          42 :         else if (nActiveSection == SECTION_DATA)
    7825             :         {
    7826          55 :             while (*pszLine == ' ' || *pszLine == '\t')
    7827          17 :                 pszLine++;
    7828          38 :             const char *pszEqual = strchr(pszLine, '=');
    7829          38 :             if (pszEqual)
    7830             :             {
    7831          17 :                 CPLString osVarName(pszLine, pszEqual - pszLine);
    7832          17 :                 osVarName.Trim();
    7833          17 :                 if (oMapVarToId.find(osVarName) == oMapVarToId.end())
    7834           0 :                     continue;
    7835          17 :                 const int nVarId = oMapVarToId[osVarName];
    7836          17 :                 CPLString osAccVal(pszEqual + 1);
    7837          17 :                 osAccVal.Trim();
    7838         153 :                 while (osAccVal.empty() || osAccVal.back() != ';')
    7839             :                 {
    7840         136 :                     pszLine = CPLReadLineL(fpSrc);
    7841         136 :                     if (pszLine == nullptr)
    7842           0 :                         break;
    7843         272 :                     CPLString osVal(pszLine);
    7844         136 :                     osVal.Trim();
    7845         136 :                     osAccVal += osVal;
    7846             :                 }
    7847          17 :                 if (pszLine == nullptr)
    7848           0 :                     break;
    7849          17 :                 osAccVal.pop_back();
    7850             : 
    7851             :                 const std::vector<int> aoDimIds =
    7852          34 :                     oMapVarIdToVectorOfDimId[nVarId];
    7853          17 :                 size_t nSize = 1;
    7854          34 :                 std::vector<size_t> aoStart, aoEdge;
    7855          17 :                 aoStart.resize(aoDimIds.size());
    7856          17 :                 aoEdge.resize(aoDimIds.size());
    7857          35 :                 for (size_t i = 0; i < aoDimIds.size(); ++i)
    7858             :                 {
    7859          18 :                     const size_t nDimSize = oMapDimIdToDimLen[aoDimIds[i]];
    7860          36 :                     if (nDimSize != 0 &&
    7861          18 :                         nSize > std::numeric_limits<size_t>::max() / nDimSize)
    7862             :                     {
    7863           0 :                         nSize = 0;
    7864             :                     }
    7865             :                     else
    7866             :                     {
    7867          18 :                         nSize *= nDimSize;
    7868             :                     }
    7869          18 :                     aoStart[i] = 0;
    7870          18 :                     aoEdge[i] = nDimSize;
    7871             :                 }
    7872             : 
    7873          17 :                 status = NC_EBADTYPE;
    7874          17 :                 if (nSize == 0)
    7875             :                 {
    7876             :                     // Might happen with a unlimited dimension
    7877             :                 }
    7878          17 :                 else if (oMapVarIdToType[nVarId] == NC_DOUBLE)
    7879             :                 {
    7880           8 :                     if (!aoStart.empty())
    7881             :                     {
    7882             :                         char **papszTokens =
    7883           8 :                             CSLTokenizeString2(osAccVal, " ,;", 0);
    7884           8 :                         size_t nTokens = CSLCount(papszTokens);
    7885           8 :                         if (nTokens >= nSize)
    7886             :                         {
    7887             :                             double *padfVals = static_cast<double *>(
    7888           8 :                                 VSI_CALLOC_VERBOSE(nSize, sizeof(double)));
    7889           8 :                             if (padfVals)
    7890             :                             {
    7891         132 :                                 for (size_t i = 0; i < nSize; i++)
    7892             :                                 {
    7893         124 :                                     padfVals[i] = CPLAtof(papszTokens[i]);
    7894             :                                 }
    7895           8 :                                 status = nc_put_vara_double(
    7896           8 :                                     nCdfId, nVarId, &aoStart[0], &aoEdge[0],
    7897             :                                     padfVals);
    7898           8 :                                 VSIFree(padfVals);
    7899             :                             }
    7900             :                         }
    7901           8 :                         CSLDestroy(papszTokens);
    7902             :                     }
    7903             :                 }
    7904           9 :                 else if (oMapVarIdToType[nVarId] == NC_BYTE)
    7905             :                 {
    7906           3 :                     if (!aoStart.empty())
    7907             :                     {
    7908             :                         char **papszTokens =
    7909           3 :                             CSLTokenizeString2(osAccVal, " ,;", 0);
    7910           3 :                         size_t nTokens = CSLCount(papszTokens);
    7911           3 :                         if (nTokens >= nSize)
    7912             :                         {
    7913             :                             signed char *panVals = static_cast<signed char *>(
    7914           3 :                                 VSI_CALLOC_VERBOSE(nSize, sizeof(signed char)));
    7915           3 :                             if (panVals)
    7916             :                             {
    7917        1203 :                                 for (size_t i = 0; i < nSize; i++)
    7918             :                                 {
    7919        1200 :                                     panVals[i] = static_cast<signed char>(
    7920        1200 :                                         atoi(papszTokens[i]));
    7921             :                                 }
    7922           3 :                                 status = nc_put_vara_schar(nCdfId, nVarId,
    7923           3 :                                                            &aoStart[0],
    7924           3 :                                                            &aoEdge[0], panVals);
    7925           3 :                                 VSIFree(panVals);
    7926             :                             }
    7927             :                         }
    7928           3 :                         CSLDestroy(papszTokens);
    7929             :                     }
    7930             :                 }
    7931           6 :                 else if (oMapVarIdToType[nVarId] == NC_CHAR)
    7932             :                 {
    7933           6 :                     if (aoStart.size() == 2)
    7934             :                     {
    7935           4 :                         std::vector<CPLString> aoStrings;
    7936           2 :                         bool bInString = false;
    7937           4 :                         CPLString osCurString;
    7938         935 :                         for (size_t i = 0; i < osAccVal.size();)
    7939             :                         {
    7940         933 :                             if (!bInString)
    7941             :                             {
    7942           8 :                                 if (osAccVal[i] == '"')
    7943             :                                 {
    7944           4 :                                     bInString = true;
    7945           4 :                                     osCurString.clear();
    7946             :                                 }
    7947           8 :                                 i++;
    7948             :                             }
    7949         926 :                             else if (osAccVal[i] == '\\' &&
    7950         926 :                                      i + 1 < osAccVal.size() &&
    7951           1 :                                      osAccVal[i + 1] == '"')
    7952             :                             {
    7953           1 :                                 osCurString += '"';
    7954           1 :                                 i += 2;
    7955             :                             }
    7956         924 :                             else if (osAccVal[i] == '"')
    7957             :                             {
    7958           4 :                                 aoStrings.push_back(osCurString);
    7959           4 :                                 osCurString.clear();
    7960           4 :                                 bInString = false;
    7961           4 :                                 i++;
    7962             :                             }
    7963             :                             else
    7964             :                             {
    7965         920 :                                 osCurString += osAccVal[i];
    7966         920 :                                 i++;
    7967             :                             }
    7968             :                         }
    7969           2 :                         const size_t nRecords = oMapDimIdToDimLen[aoDimIds[0]];
    7970           2 :                         const size_t nWidth = oMapDimIdToDimLen[aoDimIds[1]];
    7971           2 :                         size_t nIters = aoStrings.size();
    7972           2 :                         if (nIters > nRecords)
    7973           0 :                             nIters = nRecords;
    7974           6 :                         for (size_t i = 0; i < nIters; i++)
    7975             :                         {
    7976             :                             size_t anIndex[2];
    7977           4 :                             anIndex[0] = i;
    7978           4 :                             anIndex[1] = 0;
    7979             :                             size_t anCount[2];
    7980           4 :                             anCount[0] = 1;
    7981           4 :                             anCount[1] = aoStrings[i].size();
    7982           4 :                             if (anCount[1] > nWidth)
    7983           0 :                                 anCount[1] = nWidth;
    7984             :                             status =
    7985           4 :                                 nc_put_vara_text(nCdfId, nVarId, anIndex,
    7986           4 :                                                  anCount, aoStrings[i].c_str());
    7987           4 :                             if (status != NC_NOERR)
    7988           0 :                                 break;
    7989             :                         }
    7990             :                     }
    7991             :                 }
    7992          17 :                 if (status != NC_NOERR)
    7993             :                 {
    7994           4 :                     CPLDebug("netCDF", "nc_put_var_(%s) failed: %s",
    7995             :                              osVarName.c_str(), nc_strerror(status));
    7996             :                 }
    7997             :             }
    7998             :         }
    7999             :     }
    8000             : 
    8001           4 :     GDAL_nc_close(nCdfId);
    8002           4 :     return true;
    8003             : }
    8004             : 
    8005             : #endif  // ENABLE_NCDUMP
    8006             : 
    8007             : /************************************************************************/
    8008             : /*                                Open()                                */
    8009             : /************************************************************************/
    8010             : 
    8011         685 : GDALDataset *netCDFDataset::Open(GDALOpenInfo *poOpenInfo)
    8012             : 
    8013             : {
    8014             : #ifdef NCDF_DEBUG
    8015             :     CPLDebug("GDAL_netCDF", "\n=====\nOpen(), filename=[%s]",
    8016             :              poOpenInfo->pszFilename);
    8017             : #endif
    8018             : 
    8019             :     // Does this appear to be a netcdf file?
    8020         685 :     NetCDFFormatEnum eTmpFormat = NCDF_FORMAT_NONE;
    8021         685 :     if (!STARTS_WITH_CI(poOpenInfo->pszFilename, "NETCDF:"))
    8022             :     {
    8023         625 :         eTmpFormat = netCDFIdentifyFormat(poOpenInfo, /* bCheckExt = */ true);
    8024             : #ifdef NCDF_DEBUG
    8025             :         CPLDebug("GDAL_netCDF", "identified format %d", eTmpFormat);
    8026             : #endif
    8027             :         // Note: not calling Identify() directly, because we want the file type.
    8028             :         // Only support NCDF_FORMAT* formats.
    8029         625 :         if (NCDF_FORMAT_NC == eTmpFormat || NCDF_FORMAT_NC2 == eTmpFormat ||
    8030           2 :             NCDF_FORMAT_NC4 == eTmpFormat || NCDF_FORMAT_NC4C == eTmpFormat)
    8031             :         {
    8032             :             // ok
    8033             :         }
    8034           2 :         else if (eTmpFormat == NCDF_FORMAT_HDF4 &&
    8035           0 :                  poOpenInfo->IsSingleAllowedDriver("netCDF"))
    8036             :         {
    8037             :             // ok
    8038             :         }
    8039             :         else
    8040             :         {
    8041           2 :             return nullptr;
    8042             :         }
    8043             :     }
    8044             :     else
    8045             :     {
    8046             : #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    8047             :         // We don't necessarily want to catch bugs in libnetcdf ...
    8048             :         if (CPLGetConfigOption("DISABLE_OPEN_REAL_NETCDF_FILES", nullptr))
    8049             :         {
    8050             :             return nullptr;
    8051             :         }
    8052             : #endif
    8053             :     }
    8054             : 
    8055         683 :     if (poOpenInfo->nOpenFlags & GDAL_OF_MULTIDIM_RASTER)
    8056             :     {
    8057         186 :         return OpenMultiDim(poOpenInfo);
    8058             :     }
    8059             : 
    8060         994 :     CPLMutexHolderD(&hNCMutex);
    8061             : 
    8062         497 :     CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock with
    8063             :         // GDALDataset own mutex.
    8064         497 :     netCDFDataset *poDS = new netCDFDataset();
    8065         497 :     poDS->papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
    8066         497 :     CPLAcquireMutex(hNCMutex, 1000.0);
    8067             : 
    8068         497 :     poDS->SetDescription(poOpenInfo->pszFilename);
    8069             : 
    8070             :     // Check if filename start with NETCDF: tag.
    8071         497 :     bool bTreatAsSubdataset = false;
    8072         994 :     CPLString osSubdatasetName;
    8073             : 
    8074             : #ifdef ENABLE_NCDUMP
    8075         497 :     const char *pszHeader =
    8076             :         reinterpret_cast<const char *>(poOpenInfo->pabyHeader);
    8077         497 :     if (poOpenInfo->fpL != nullptr && STARTS_WITH(pszHeader, "netcdf ") &&
    8078           3 :         strstr(pszHeader, "dimensions:") && strstr(pszHeader, "variables:"))
    8079             :     {
    8080             :         // By default create a temporary file that will be destroyed,
    8081             :         // unless NETCDF_TMP_FILE is defined. Can be useful to see which
    8082             :         // netCDF file has been generated from a potential fuzzed input.
    8083           3 :         poDS->osFilename = CPLGetConfigOption("NETCDF_TMP_FILE", "");
    8084           3 :         if (poDS->osFilename.empty())
    8085             :         {
    8086           3 :             poDS->bFileToDestroyAtClosing = true;
    8087           3 :             poDS->osFilename = CPLGenerateTempFilenameSafe("netcdf_tmp");
    8088             :         }
    8089           3 :         if (!netCDFDatasetCreateTempFile(eTmpFormat, poDS->osFilename,
    8090             :                                          poOpenInfo->fpL))
    8091             :         {
    8092           0 :             CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    8093             :                 // deadlock with GDALDataset own mutex.
    8094           0 :             delete poDS;
    8095           0 :             CPLAcquireMutex(hNCMutex, 1000.0);
    8096           0 :             return nullptr;
    8097             :         }
    8098           3 :         bTreatAsSubdataset = false;
    8099           3 :         poDS->eFormat = eTmpFormat;
    8100             :     }
    8101             :     else
    8102             : #endif
    8103             : 
    8104         494 :         if (STARTS_WITH_CI(poOpenInfo->pszFilename, "NETCDF:"))
    8105             :     {
    8106             :         char **papszName =
    8107          60 :             CSLTokenizeString2(poOpenInfo->pszFilename, ":",
    8108             :                                CSLT_HONOURSTRINGS | CSLT_PRESERVEESCAPES);
    8109             : 
    8110         120 :         if (CSLCount(papszName) >= 3 &&
    8111          60 :             ((strlen(papszName[1]) == 1 && /* D:\\bla */
    8112           0 :               (papszName[2][0] == '/' || papszName[2][0] == '\\')) ||
    8113          60 :              EQUAL(papszName[1], "http") || EQUAL(papszName[1], "https") ||
    8114          60 :              EQUAL(papszName[1], "/vsicurl/http") ||
    8115          60 :              EQUAL(papszName[1], "/vsicurl/https") ||
    8116          60 :              EQUAL(papszName[1], "/vsicurl_streaming/http") ||
    8117          60 :              EQUAL(papszName[1], "/vsicurl_streaming/https")))
    8118             :         {
    8119           0 :             const int nCountBefore = CSLCount(papszName);
    8120           0 :             CPLString osTmp = papszName[1];
    8121           0 :             osTmp += ':';
    8122           0 :             osTmp += papszName[2];
    8123           0 :             CPLFree(papszName[1]);
    8124           0 :             CPLFree(papszName[2]);
    8125           0 :             papszName[1] = CPLStrdup(osTmp);
    8126           0 :             memmove(papszName + 2, papszName + 3,
    8127           0 :                     (nCountBefore - 2) * sizeof(char *));
    8128             :         }
    8129             : 
    8130          60 :         if (CSLCount(papszName) == 3)
    8131             :         {
    8132          60 :             poDS->osFilename = papszName[1];
    8133          60 :             osSubdatasetName = papszName[2];
    8134          60 :             bTreatAsSubdataset = true;
    8135          60 :             CSLDestroy(papszName);
    8136             :         }
    8137           0 :         else if (CSLCount(papszName) == 2)
    8138             :         {
    8139           0 :             poDS->osFilename = papszName[1];
    8140           0 :             osSubdatasetName = "";
    8141           0 :             bTreatAsSubdataset = false;
    8142           0 :             CSLDestroy(papszName);
    8143             :         }
    8144             :         else
    8145             :         {
    8146           0 :             CSLDestroy(papszName);
    8147           0 :             CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    8148             :                 // deadlock with GDALDataset own mutex.
    8149           0 :             delete poDS;
    8150           0 :             CPLAcquireMutex(hNCMutex, 1000.0);
    8151           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    8152             :                      "Failed to parse NETCDF: prefix string into expected 2, 3 "
    8153             :                      "or 4 fields.");
    8154           0 :             return nullptr;
    8155             :         }
    8156             : 
    8157         120 :         if (!STARTS_WITH(poDS->osFilename, "http://") &&
    8158          60 :             !STARTS_WITH(poDS->osFilename, "https://"))
    8159             :         {
    8160             :             // Identify Format from real file, with bCheckExt=FALSE.
    8161             :             GDALOpenInfo *poOpenInfo2 =
    8162          60 :                 new GDALOpenInfo(poDS->osFilename.c_str(), GA_ReadOnly);
    8163          60 :             poDS->eFormat =
    8164          60 :                 netCDFIdentifyFormat(poOpenInfo2, /* bCheckExt = */ false);
    8165          60 :             delete poOpenInfo2;
    8166          60 :             if (NCDF_FORMAT_NONE == poDS->eFormat ||
    8167          60 :                 NCDF_FORMAT_UNKNOWN == poDS->eFormat)
    8168             :             {
    8169           0 :                 CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    8170             :                     // deadlock with GDALDataset own mutex.
    8171           0 :                 delete poDS;
    8172           0 :                 CPLAcquireMutex(hNCMutex, 1000.0);
    8173           0 :                 return nullptr;
    8174             :             }
    8175             :         }
    8176             :     }
    8177             :     else
    8178             :     {
    8179         434 :         poDS->osFilename = poOpenInfo->pszFilename;
    8180         434 :         bTreatAsSubdataset = false;
    8181         434 :         poDS->eFormat = eTmpFormat;
    8182             :     }
    8183             : 
    8184             : // Try opening the dataset.
    8185             : #if defined(NCDF_DEBUG) && defined(ENABLE_UFFD)
    8186             :     CPLDebug("GDAL_netCDF", "calling nc_open_mem(%s)",
    8187             :              poDS->osFilename.c_str());
    8188             : #elif defined(NCDF_DEBUG) && !defined(ENABLE_UFFD)
    8189             :     CPLDebug("GDAL_netCDF", "calling nc_open(%s)", poDS->osFilename.c_str());
    8190             : #endif
    8191         497 :     int cdfid = -1;
    8192         497 :     const int nMode = ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE) != 0)
    8193             :                           ? NC_WRITE
    8194             :                           : NC_NOWRITE;
    8195         994 :     CPLString osFilenameForNCOpen(poDS->osFilename);
    8196             : #if defined(_WIN32) && !defined(NETCDF_USES_UTF8)
    8197             :     if (CPLTestBool(CPLGetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")))
    8198             :     {
    8199             :         char *pszTemp = CPLRecode(osFilenameForNCOpen, CPL_ENC_UTF8, "CP_ACP");
    8200             :         osFilenameForNCOpen = pszTemp;
    8201             :         CPLFree(pszTemp);
    8202             :     }
    8203             : #endif
    8204         497 :     int status2 = -1;
    8205             : 
    8206             : #ifdef ENABLE_UFFD
    8207         497 :     cpl_uffd_context *pCtx = nullptr;
    8208             : #endif
    8209             : 
    8210         512 :     if (STARTS_WITH(osFilenameForNCOpen, "/vsimem/") &&
    8211          15 :         poOpenInfo->eAccess == GA_ReadOnly)
    8212             :     {
    8213          15 :         vsi_l_offset nLength = 0;
    8214          15 :         poDS->fpVSIMEM = VSIFOpenL(osFilenameForNCOpen, "rb");
    8215          15 :         if (poDS->fpVSIMEM)
    8216             :         {
    8217             :             // We assume that the file will not be modified. If it is, then
    8218             :             // pabyBuffer might become invalid.
    8219             :             GByte *pabyBuffer =
    8220          15 :                 VSIGetMemFileBuffer(osFilenameForNCOpen, &nLength, false);
    8221          15 :             if (pabyBuffer)
    8222             :             {
    8223          15 :                 status2 = nc_open_mem(CPLGetFilename(osFilenameForNCOpen),
    8224             :                                       nMode, static_cast<size_t>(nLength),
    8225             :                                       pabyBuffer, &cdfid);
    8226             :             }
    8227             :         }
    8228             :     }
    8229             :     else
    8230             :     {
    8231             :         const bool bVsiFile =
    8232         482 :             !strncmp(osFilenameForNCOpen, "/vsi", strlen("/vsi"));
    8233             : #ifdef ENABLE_UFFD
    8234         482 :         bool bReadOnly = (poOpenInfo->eAccess == GA_ReadOnly);
    8235         482 :         void *pVma = nullptr;
    8236         482 :         uint64_t nVmaSize = 0;
    8237             : 
    8238         482 :         if (bVsiFile)
    8239             :         {
    8240           2 :             if (bReadOnly)
    8241             :             {
    8242           2 :                 if (CPLIsUserFaultMappingSupported())
    8243             :                 {
    8244           2 :                     pCtx = CPLCreateUserFaultMapping(osFilenameForNCOpen, &pVma,
    8245             :                                                      &nVmaSize);
    8246             :                 }
    8247             :                 else
    8248             :                 {
    8249           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    8250             :                              "Opening a /vsi file with the netCDF driver "
    8251             :                              "requires Linux userfaultfd to be available. "
    8252             :                              "If running from Docker, "
    8253             :                              "--security-opt seccomp=unconfined might be "
    8254             :                              "needed.%s",
    8255           0 :                              ((poDS->eFormat == NCDF_FORMAT_NC4 ||
    8256           0 :                                poDS->eFormat == NCDF_FORMAT_HDF5) &&
    8257           0 :                               GDALGetDriverByName("HDF5"))
    8258             :                                  ? " Or you may set the GDAL_SKIP=netCDF "
    8259             :                                    "configuration option to force the use of "
    8260             :                                    "the HDF5 driver."
    8261             :                                  : "");
    8262             :                 }
    8263             :             }
    8264             :             else
    8265             :             {
    8266           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    8267             :                          "Opening a /vsi file with the netCDF driver is only "
    8268             :                          "supported in read-only mode");
    8269             :             }
    8270             :         }
    8271         482 :         if (pCtx != nullptr && pVma != nullptr && nVmaSize > 0)
    8272             :         {
    8273             :             // netCDF code, at least for netCDF 4.7.0, is confused by filenames
    8274             :             // like /vsicurl/http[s]://example.com/foo.nc, so just pass the
    8275             :             // final part
    8276           2 :             status2 = nc_open_mem(CPLGetFilename(osFilenameForNCOpen), nMode,
    8277             :                                   static_cast<size_t>(nVmaSize), pVma, &cdfid);
    8278             :         }
    8279             :         else
    8280         480 :             status2 = GDAL_nc_open(osFilenameForNCOpen, nMode, &cdfid);
    8281             : #else
    8282             :         if (bVsiFile)
    8283             :         {
    8284             :             CPLError(
    8285             :                 CE_Failure, CPLE_AppDefined,
    8286             :                 "Opening a /vsi file with the netCDF driver requires Linux "
    8287             :                 "userfaultfd to be available.%s",
    8288             :                 ((poDS->eFormat == NCDF_FORMAT_NC4 ||
    8289             :                   poDS->eFormat == NCDF_FORMAT_HDF5) &&
    8290             :                  GDALGetDriverByName("HDF5"))
    8291             :                     ? " Or you may set the GDAL_SKIP=netCDF "
    8292             :                       "configuration option to force the use of the HDF5 "
    8293             :                       "driver."
    8294             :                     : "");
    8295             :             status2 = NC_EIO;
    8296             :         }
    8297             :         else
    8298             :         {
    8299             :             status2 = GDAL_nc_open(osFilenameForNCOpen, nMode, &cdfid);
    8300             :         }
    8301             : #endif
    8302             :     }
    8303         497 :     if (status2 != NC_NOERR)
    8304             :     {
    8305             : #ifdef NCDF_DEBUG
    8306             :         CPLDebug("GDAL_netCDF", "error opening");
    8307             : #endif
    8308           0 :         CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock
    8309             :             // with GDALDataset own mutex.
    8310           0 :         delete poDS;
    8311           0 :         CPLAcquireMutex(hNCMutex, 1000.0);
    8312           0 :         return nullptr;
    8313             :     }
    8314             : #ifdef NCDF_DEBUG
    8315             :     CPLDebug("GDAL_netCDF", "got cdfid=%d", cdfid);
    8316             : #endif
    8317             : 
    8318             : #if defined(ENABLE_NCDUMP) && !defined(_WIN32)
    8319             :     // Try to destroy the temporary file right now on Unix
    8320         497 :     if (poDS->bFileToDestroyAtClosing)
    8321             :     {
    8322           3 :         if (VSIUnlink(poDS->osFilename) == 0)
    8323             :         {
    8324           3 :             poDS->bFileToDestroyAtClosing = false;
    8325             :         }
    8326             :     }
    8327             : #endif
    8328             : 
    8329             :     // Is this a real netCDF file?
    8330             :     int ndims;
    8331             :     int ngatts;
    8332             :     int nvars;
    8333             :     int unlimdimid;
    8334         497 :     int status = nc_inq(cdfid, &ndims, &nvars, &ngatts, &unlimdimid);
    8335         497 :     if (status != NC_NOERR)
    8336             :     {
    8337           0 :         CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock
    8338             :             // with GDALDataset own mutex.
    8339           0 :         delete poDS;
    8340           0 :         CPLAcquireMutex(hNCMutex, 1000.0);
    8341           0 :         return nullptr;
    8342             :     }
    8343             : 
    8344             :     // Get file type from netcdf.
    8345         497 :     int nTmpFormat = NCDF_FORMAT_NONE;
    8346         497 :     status = nc_inq_format(cdfid, &nTmpFormat);
    8347         497 :     if (status != NC_NOERR)
    8348             :     {
    8349           0 :         NCDF_ERR(status);
    8350             :     }
    8351             :     else
    8352             :     {
    8353         497 :         CPLDebug("GDAL_netCDF",
    8354             :                  "driver detected file type=%d, libnetcdf detected type=%d",
    8355         497 :                  poDS->eFormat, nTmpFormat);
    8356         497 :         if (static_cast<NetCDFFormatEnum>(nTmpFormat) != poDS->eFormat)
    8357             :         {
    8358             :             // Warn if file detection conflicts with that from libnetcdf
    8359             :             // except for NC4C, which we have no way of detecting initially.
    8360          26 :             if (nTmpFormat != NCDF_FORMAT_NC4C &&
    8361          13 :                 !STARTS_WITH(poDS->osFilename, "http://") &&
    8362           0 :                 !STARTS_WITH(poDS->osFilename, "https://"))
    8363             :             {
    8364           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    8365             :                          "NetCDF driver detected file type=%d, but libnetcdf "
    8366             :                          "detected type=%d",
    8367           0 :                          poDS->eFormat, nTmpFormat);
    8368             :             }
    8369          13 :             CPLDebug("GDAL_netCDF", "setting file type to %d, was %d",
    8370          13 :                      nTmpFormat, poDS->eFormat);
    8371          13 :             poDS->eFormat = static_cast<NetCDFFormatEnum>(nTmpFormat);
    8372             :         }
    8373             :     }
    8374             : 
    8375             :     // Does the request variable exist?
    8376         497 :     if (bTreatAsSubdataset)
    8377             :     {
    8378             :         int dummy;
    8379          60 :         if (NCDFOpenSubDataset(cdfid, osSubdatasetName.c_str(), &dummy,
    8380          60 :                                &dummy) != CE_None)
    8381             :         {
    8382           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    8383             :                      "%s is a netCDF file, but %s is not a variable.",
    8384             :                      poOpenInfo->pszFilename, osSubdatasetName.c_str());
    8385             : 
    8386           0 :             GDAL_nc_close(cdfid);
    8387             : #ifdef ENABLE_UFFD
    8388           0 :             NETCDF_UFFD_UNMAP(pCtx);
    8389             : #endif
    8390           0 :             CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    8391             :                 // deadlock with GDALDataset own mutex.
    8392           0 :             delete poDS;
    8393           0 :             CPLAcquireMutex(hNCMutex, 1000.0);
    8394           0 :             return nullptr;
    8395             :         }
    8396             :     }
    8397             : 
    8398             :     // Figure out whether or not the listed dataset has support for simple
    8399             :     // geometries (CF-1.8)
    8400         497 :     poDS->nCFVersion = nccfdriver::getCFVersion(cdfid);
    8401         497 :     bool bHasSimpleGeometries = false;  // but not necessarily valid
    8402         497 :     if (poDS->nCFVersion >= 1.8)
    8403             :     {
    8404          75 :         bHasSimpleGeometries = poDS->DetectAndFillSGLayers(cdfid);
    8405          75 :         if (bHasSimpleGeometries)
    8406             :         {
    8407          67 :             poDS->bSGSupport = true;
    8408          67 :             poDS->vcdf.enableFullVirtualMode();
    8409             :         }
    8410             :     }
    8411             : 
    8412             :     char szConventions[NC_MAX_NAME + 1];
    8413         497 :     szConventions[0] = '\0';
    8414         497 :     nc_type nAttype = NC_NAT;
    8415         497 :     size_t nAttlen = 0;
    8416         497 :     nc_inq_att(cdfid, NC_GLOBAL, "Conventions", &nAttype, &nAttlen);
    8417         994 :     if (nAttlen >= sizeof(szConventions) ||
    8418         497 :         nc_get_att_text(cdfid, NC_GLOBAL, "Conventions", szConventions) !=
    8419             :             NC_NOERR)
    8420             :     {
    8421          59 :         CPLDebug("GDAL_netCDF", "No UNIDATA NC_GLOBAL:Conventions attribute");
    8422             :         // Note that 'Conventions' is always capital 'C' in CF spec.
    8423             :     }
    8424             :     else
    8425             :     {
    8426         438 :         szConventions[nAttlen] = '\0';
    8427             :     }
    8428             : 
    8429             :     // Create band information objects.
    8430         497 :     CPLDebug("GDAL_netCDF", "var_count = %d", nvars);
    8431             : 
    8432             :     // Create a corresponding GDALDataset.
    8433             :     // Create Netcdf Subdataset if filename as NETCDF tag.
    8434         497 :     poDS->cdfid = cdfid;
    8435             : #ifdef ENABLE_UFFD
    8436         497 :     poDS->pCtx = pCtx;
    8437             : #endif
    8438         497 :     poDS->eAccess = poOpenInfo->eAccess;
    8439         497 :     poDS->bDefineMode = false;
    8440             : 
    8441         497 :     poDS->ReadAttributes(cdfid, NC_GLOBAL);
    8442             : 
    8443             :     // Identify coordinate and boundary variables that we should
    8444             :     // ignore as Raster Bands.
    8445         497 :     char **papszIgnoreVars = nullptr;
    8446         497 :     NCDFGetCoordAndBoundVarFullNames(cdfid, &papszIgnoreVars);
    8447             :     // Filter variables to keep only valid 2+D raster bands and vector fields.
    8448         497 :     int nRasterVars = 0;
    8449         497 :     int nIgnoredVars = 0;
    8450         497 :     int nGroupID = -1;
    8451         497 :     int nVarID = -1;
    8452             : 
    8453             :     std::map<std::array<int, 3>, std::vector<std::pair<int, int>>>
    8454         994 :         oMap2DDimsToGroupAndVar;
    8455        1147 :     if ((poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
    8456         153 :         STARTS_WITH(CSLFetchNameValueDef(poDS->papszMetadata,
    8457             :                                          "NC_GLOBAL#mission_name", ""),
    8458           1 :                     "Sentinel 3") &&
    8459           1 :         EQUAL(CSLFetchNameValueDef(poDS->papszMetadata,
    8460             :                                    "NC_GLOBAL#altimeter_sensor_name", ""),
    8461         650 :               "SRAL") &&
    8462           1 :         EQUAL(CSLFetchNameValueDef(poDS->papszMetadata,
    8463             :                                    "NC_GLOBAL#radiometer_sensor_name", ""),
    8464             :               "MWR"))
    8465             :     {
    8466           1 :         if (poDS->eAccess == GA_Update)
    8467             :         {
    8468           0 :             CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    8469             :                 // deadlock with GDALDataset own mutex.
    8470           0 :             delete poDS;
    8471           0 :             return nullptr;
    8472             :         }
    8473           1 :         poDS->ProcessSentinel3_SRAL_MWR();
    8474             :     }
    8475             :     else
    8476             :     {
    8477         496 :         poDS->FilterVars(cdfid, (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) != 0,
    8478         648 :                          (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
    8479         152 :                              !bHasSimpleGeometries,
    8480             :                          papszIgnoreVars, &nRasterVars, &nGroupID, &nVarID,
    8481             :                          &nIgnoredVars, oMap2DDimsToGroupAndVar);
    8482             :     }
    8483         497 :     CSLDestroy(papszIgnoreVars);
    8484             : 
    8485         497 :     const bool bListAllArrays = CPLTestBool(
    8486         497 :         CSLFetchNameValueDef(poDS->papszOpenOptions, "LIST_ALL_ARRAYS", "NO"));
    8487             : 
    8488             :     // Case where there is no raster variable
    8489         497 :     if (!bListAllArrays && nRasterVars == 0 && !bTreatAsSubdataset)
    8490             :     {
    8491         119 :         poDS->GDALPamDataset::SetMetadata(poDS->papszMetadata);
    8492         119 :         CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock
    8493             :             // with GDALDataset own mutex.
    8494         119 :         poDS->TryLoadXML();
    8495             :         // If the dataset has been opened in raster mode only, exit
    8496         119 :         if ((poOpenInfo->nOpenFlags & GDAL_OF_RASTER) != 0 &&
    8497           9 :             (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) == 0)
    8498             :         {
    8499           4 :             delete poDS;
    8500           4 :             poDS = nullptr;
    8501             :         }
    8502             :         // Otherwise if the dataset is opened in vector mode, that there is
    8503             :         // no vector layer and we are in read-only, exit too.
    8504         115 :         else if (poDS->GetLayerCount() == 0 &&
    8505         123 :                  (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
    8506           8 :                  poOpenInfo->eAccess == GA_ReadOnly)
    8507             :         {
    8508           8 :             delete poDS;
    8509           8 :             poDS = nullptr;
    8510             :         }
    8511         119 :         CPLAcquireMutex(hNCMutex, 1000.0);
    8512         119 :         return poDS;
    8513             :     }
    8514             : 
    8515             :     // We have more than one variable with 2 dimensions in the
    8516             :     // file, then treat this as a subdataset container dataset.
    8517         378 :     bool bSeveralVariablesAsBands = false;
    8518         378 :     if (bListAllArrays || ((nRasterVars > 1) && !bTreatAsSubdataset))
    8519             :     {
    8520          29 :         if (CPLFetchBool(poOpenInfo->papszOpenOptions, "VARIABLES_AS_BANDS",
    8521          35 :                          false) &&
    8522           6 :             oMap2DDimsToGroupAndVar.size() == 1)
    8523             :         {
    8524           6 :             std::tie(nGroupID, nVarID) =
    8525          12 :                 oMap2DDimsToGroupAndVar.begin()->second.front();
    8526           6 :             bSeveralVariablesAsBands = true;
    8527             :         }
    8528             :         else
    8529             :         {
    8530          23 :             poDS->CreateSubDatasetList(cdfid);
    8531          23 :             poDS->GDALPamDataset::SetMetadata(poDS->papszMetadata);
    8532          23 :             CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    8533             :                 // deadlock with GDALDataset own mutex.
    8534          23 :             poDS->TryLoadXML();
    8535          23 :             CPLAcquireMutex(hNCMutex, 1000.0);
    8536          23 :             return poDS;
    8537             :         }
    8538             :     }
    8539             : 
    8540             :     // If we are not treating things as a subdataset, then capture
    8541             :     // the name of the single available variable as the subdataset.
    8542         355 :     if (!bTreatAsSubdataset)
    8543             :     {
    8544         295 :         char *pszVarName = nullptr;
    8545         295 :         NCDF_ERR(NCDFGetVarFullName(nGroupID, nVarID, &pszVarName));
    8546         295 :         osSubdatasetName = (pszVarName != nullptr ? pszVarName : "");
    8547         295 :         CPLFree(pszVarName);
    8548             :     }
    8549             : 
    8550             :     // We have ignored at least one variable, so we should report them
    8551             :     // as subdatasets for reference.
    8552         355 :     if (nIgnoredVars > 0 && !bTreatAsSubdataset)
    8553             :     {
    8554          25 :         CPLDebug("GDAL_netCDF",
    8555             :                  "As %d variables were ignored, creating subdataset list "
    8556             :                  "for reference. Variable #%d [%s] is the main variable",
    8557             :                  nIgnoredVars, nVarID, osSubdatasetName.c_str());
    8558          25 :         poDS->CreateSubDatasetList(cdfid);
    8559             :     }
    8560             : 
    8561             :     // Open the NETCDF subdataset NETCDF:"filename":subdataset.
    8562         355 :     int var = -1;
    8563         355 :     NCDFOpenSubDataset(cdfid, osSubdatasetName.c_str(), &nGroupID, &var);
    8564             :     // Now we can forget the root cdfid and only use the selected group.
    8565         355 :     cdfid = nGroupID;
    8566         355 :     int nd = 0;
    8567         355 :     nc_inq_varndims(cdfid, var, &nd);
    8568             : 
    8569         355 :     poDS->m_anDimIds.resize(nd);
    8570             : 
    8571             :     // X, Y, Z position in array
    8572         710 :     std::vector<int> anBandDimPos(nd);
    8573             : 
    8574         355 :     nc_inq_vardimid(cdfid, var, poDS->m_anDimIds.data());
    8575             : 
    8576             :     // Check if somebody tried to pass a variable with less than 1D.
    8577         355 :     if (nd < 1)
    8578             :     {
    8579           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    8580             :                  "Variable has %d dimension(s) - not supported.", nd);
    8581           0 :         CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock
    8582             :             // with GDALDataset own mutex.
    8583           0 :         delete poDS;
    8584           0 :         CPLAcquireMutex(hNCMutex, 1000.0);
    8585           0 :         return nullptr;
    8586             :     }
    8587             : 
    8588             :     // CF-1 Convention
    8589             :     //
    8590             :     // Dimensions to appear in the relative order T, then Z, then Y,
    8591             :     // then X  to the file. All other dimensions should, whenever
    8592             :     // possible, be placed to the left of the spatiotemporal
    8593             :     // dimensions.
    8594             : 
    8595             :     // Verify that dimensions are in the {T,Z,Y,X} or {T,Z,Y,X} order
    8596             :     // Ideally we should detect for other ordering and act accordingly
    8597             :     // Only done if file has Conventions=CF-* and only prints warning
    8598             :     // To disable set GDAL_NETCDF_VERIFY_DIMS=NO and to use only
    8599             :     // attributes (not varnames) set GDAL_NETCDF_VERIFY_DIMS=STRICT
    8600             :     const bool bCheckDims =
    8601         710 :         CPLTestBool(CPLGetConfigOption("GDAL_NETCDF_VERIFY_DIMS", "YES")) &&
    8602         355 :         STARTS_WITH_CI(szConventions, "CF");
    8603             : 
    8604         355 :     bool bYXBandOrder = false;
    8605         355 :     if (nd == 3)
    8606             :     {
    8607             :         // If there's a coordinates attributes, and the variable it points to
    8608             :         // are 2D variables indexed by the same first and second dimension than
    8609             :         // our variable of interest, then it is Y,X,Band order.
    8610          46 :         char *pszCoordinates = nullptr;
    8611          46 :         if (NCDFGetAttr(cdfid, var, "coordinates", &pszCoordinates) ==
    8612          63 :                 CE_None &&
    8613          17 :             pszCoordinates)
    8614             :         {
    8615             :             const CPLStringList aosCoordinates(
    8616          34 :                 NCDFTokenizeCoordinatesAttribute(pszCoordinates));
    8617          17 :             if (aosCoordinates.size() == 2)
    8618             :             {
    8619             :                 // Test that each variable is longitude/latitude.
    8620          13 :                 for (int i = 0; i < aosCoordinates.size(); i++)
    8621             :                 {
    8622          13 :                     if (NCDFIsVarLongitude(cdfid, -1, aosCoordinates[i]) ||
    8623           4 :                         NCDFIsVarLatitude(cdfid, -1, aosCoordinates[i]))
    8624             :                     {
    8625           9 :                         int nOtherGroupId = -1;
    8626           9 :                         int nOtherVarId = -1;
    8627           9 :                         if (NCDFResolveVar(cdfid, aosCoordinates[i],
    8628             :                                            &nOtherGroupId,
    8629           9 :                                            &nOtherVarId) == CE_None)
    8630             :                         {
    8631           9 :                             int coordDimCount = 0;
    8632           9 :                             nc_inq_varndims(nOtherGroupId, nOtherVarId,
    8633             :                                             &coordDimCount);
    8634           9 :                             if (coordDimCount == 2)
    8635             :                             {
    8636           3 :                                 int coordDimIds[2] = {0, 0};
    8637           3 :                                 nc_inq_vardimid(nOtherGroupId, nOtherVarId,
    8638             :                                                 coordDimIds);
    8639           4 :                                 if (coordDimIds[0] == poDS->m_anDimIds[0] &&
    8640           1 :                                     coordDimIds[1] == poDS->m_anDimIds[1])
    8641             :                                 {
    8642           1 :                                     bYXBandOrder = true;
    8643           1 :                                     break;
    8644             :                                 }
    8645             :                             }
    8646             :                         }
    8647             :                     }
    8648             :                 }
    8649             :             }
    8650             :         }
    8651          46 :         CPLFree(pszCoordinates);
    8652             : 
    8653          46 :         if (!bYXBandOrder)
    8654             :         {
    8655          45 :             char szDim0Name[NC_MAX_NAME + 1] = {};
    8656          45 :             char szDim1Name[NC_MAX_NAME + 1] = {};
    8657          45 :             status = nc_inq_dimname(cdfid, poDS->m_anDimIds[0], szDim0Name);
    8658          45 :             NCDF_ERR(status);
    8659          45 :             status = nc_inq_dimname(cdfid, poDS->m_anDimIds[1], szDim1Name);
    8660          45 :             NCDF_ERR(status);
    8661             : 
    8662          45 :             if (strcmp(szDim0Name, "number_of_lines") == 0 &&
    8663           1 :                 strcmp(szDim1Name, "pixels_per_line") == 0)
    8664             :             {
    8665             :                 // Like in PACE OCI products
    8666           1 :                 bYXBandOrder = true;
    8667             :             }
    8668             :             else
    8669             :             {
    8670             :                 // For example for EMIT data (https://earth.jpl.nasa.gov/emit/data/data-portal/coverage-and-forecasts/),
    8671             :                 // dimension order is downtrack, crosstrack, bands
    8672          44 :                 char szDim2Name[NC_MAX_NAME + 1] = {};
    8673          44 :                 status = nc_inq_dimname(cdfid, poDS->m_anDimIds[2], szDim2Name);
    8674          44 :                 NCDF_ERR(status);
    8675          86 :                 bYXBandOrder = strcmp(szDim2Name, "bands") == 0 ||
    8676          42 :                                strcmp(szDim2Name, "band") == 0;
    8677             :             }
    8678             :         }
    8679             :     }
    8680             : 
    8681         355 :     if (nd >= 2 && bCheckDims && !bYXBandOrder)
    8682             :     {
    8683         268 :         char szDimName1[NC_MAX_NAME + 1] = {};
    8684         268 :         char szDimName2[NC_MAX_NAME + 1] = {};
    8685         268 :         status = nc_inq_dimname(cdfid, poDS->m_anDimIds[nd - 1], szDimName1);
    8686         268 :         NCDF_ERR(status);
    8687         268 :         status = nc_inq_dimname(cdfid, poDS->m_anDimIds[nd - 2], szDimName2);
    8688         268 :         NCDF_ERR(status);
    8689         427 :         if (NCDFIsVarLongitude(cdfid, -1, szDimName1) == false &&
    8690         159 :             NCDFIsVarProjectionX(cdfid, -1, szDimName1) == false)
    8691             :         {
    8692           4 :             CPLError(CE_Warning, CPLE_AppDefined,
    8693             :                      "dimension #%d (%s) is not a Longitude/X dimension.",
    8694             :                      nd - 1, szDimName1);
    8695             :         }
    8696         427 :         if (NCDFIsVarLatitude(cdfid, -1, szDimName2) == false &&
    8697         159 :             NCDFIsVarProjectionY(cdfid, -1, szDimName2) == false)
    8698             :         {
    8699           4 :             CPLError(CE_Warning, CPLE_AppDefined,
    8700             :                      "dimension #%d (%s) is not a Latitude/Y dimension.",
    8701             :                      nd - 2, szDimName2);
    8702             :         }
    8703         268 :         if ((NCDFIsVarLongitude(cdfid, -1, szDimName2) ||
    8704         270 :              NCDFIsVarProjectionX(cdfid, -1, szDimName2)) &&
    8705           2 :             (NCDFIsVarLatitude(cdfid, -1, szDimName1) ||
    8706           0 :              NCDFIsVarProjectionY(cdfid, -1, szDimName1)))
    8707             :         {
    8708           2 :             poDS->bSwitchedXY = true;
    8709             :         }
    8710         268 :         if (nd >= 3)
    8711             :         {
    8712          52 :             char szDimName3[NC_MAX_NAME + 1] = {};
    8713             :             status =
    8714          52 :                 nc_inq_dimname(cdfid, poDS->m_anDimIds[nd - 3], szDimName3);
    8715          52 :             NCDF_ERR(status);
    8716          52 :             if (nd >= 4)
    8717             :             {
    8718          13 :                 char szDimName4[NC_MAX_NAME + 1] = {};
    8719             :                 status =
    8720          13 :                     nc_inq_dimname(cdfid, poDS->m_anDimIds[nd - 4], szDimName4);
    8721          13 :                 NCDF_ERR(status);
    8722          13 :                 if (NCDFIsVarVerticalCoord(cdfid, -1, szDimName3) == false)
    8723             :                 {
    8724           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    8725             :                              "dimension #%d (%s) is not a Vertical dimension.",
    8726             :                              nd - 3, szDimName3);
    8727             :                 }
    8728          13 :                 if (NCDFIsVarTimeCoord(cdfid, -1, szDimName4) == false)
    8729             :                 {
    8730           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    8731             :                              "dimension #%d (%s) is not a Time dimension.",
    8732             :                              nd - 4, szDimName4);
    8733             :                 }
    8734             :             }
    8735             :             else
    8736             :             {
    8737          75 :                 if (NCDFIsVarVerticalCoord(cdfid, -1, szDimName3) == false &&
    8738          36 :                     NCDFIsVarTimeCoord(cdfid, -1, szDimName3) == false)
    8739             :                 {
    8740           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    8741             :                              "dimension #%d (%s) is not a "
    8742             :                              "Time or Vertical dimension.",
    8743             :                              nd - 3, szDimName3);
    8744             :                 }
    8745             :             }
    8746             :         }
    8747             :     }
    8748             : 
    8749             :     // Get X dimensions information.
    8750             :     size_t xdim;
    8751         355 :     poDS->nXDimID = poDS->m_anDimIds[bYXBandOrder ? 1 : nd - 1];
    8752         355 :     nc_inq_dimlen(cdfid, poDS->nXDimID, &xdim);
    8753             : 
    8754             :     // Get Y dimension information.
    8755             :     size_t ydim;
    8756         355 :     if (nd >= 2)
    8757             :     {
    8758         351 :         poDS->nYDimID = poDS->m_anDimIds[bYXBandOrder ? 0 : nd - 2];
    8759         351 :         nc_inq_dimlen(cdfid, poDS->nYDimID, &ydim);
    8760             :     }
    8761             :     else
    8762             :     {
    8763           4 :         poDS->nYDimID = -1;
    8764           4 :         ydim = 1;
    8765             :     }
    8766             : 
    8767         355 :     if (xdim > INT_MAX || ydim > INT_MAX)
    8768             :     {
    8769           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    8770             :                  "Invalid raster dimensions: " CPL_FRMT_GUIB "x" CPL_FRMT_GUIB,
    8771             :                  static_cast<GUIntBig>(xdim), static_cast<GUIntBig>(ydim));
    8772           0 :         CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock
    8773             :             // with GDALDataset own mutex.
    8774           0 :         delete poDS;
    8775           0 :         CPLAcquireMutex(hNCMutex, 1000.0);
    8776           0 :         return nullptr;
    8777             :     }
    8778             : 
    8779         355 :     poDS->nRasterXSize = static_cast<int>(xdim);
    8780         355 :     poDS->nRasterYSize = static_cast<int>(ydim);
    8781             : 
    8782         355 :     unsigned int k = 0;
    8783        1142 :     for (int j = 0; j < nd; j++)
    8784             :     {
    8785         787 :         if (poDS->m_anDimIds[j] == poDS->nXDimID)
    8786             :         {
    8787         355 :             anBandDimPos[0] = j;  // Save Position of XDim
    8788         355 :             k++;
    8789             :         }
    8790         787 :         if (poDS->m_anDimIds[j] == poDS->nYDimID)
    8791             :         {
    8792         351 :             anBandDimPos[1] = j;  // Save Position of YDim
    8793         351 :             k++;
    8794             :         }
    8795             :     }
    8796             :     // X and Y Dimension Ids were not found!
    8797         355 :     if ((nd >= 2 && k != 2) || (nd == 1 && k != 1))
    8798             :     {
    8799           0 :         CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock
    8800             :             // with GDALDataset own mutex.
    8801           0 :         delete poDS;
    8802           0 :         CPLAcquireMutex(hNCMutex, 1000.0);
    8803           0 :         return nullptr;
    8804             :     }
    8805             : 
    8806             :     // Read Metadata for this variable.
    8807             : 
    8808             :     // Should disable as is also done at band level, except driver needs the
    8809             :     // variables as metadata (e.g. projection).
    8810         355 :     poDS->ReadAttributes(cdfid, var);
    8811             : 
    8812             :     // Read Metadata for each dimension.
    8813         355 :     int *panDimIds = nullptr;
    8814         355 :     NCDFGetVisibleDims(cdfid, &ndims, &panDimIds);
    8815             :     // With NetCDF-4 groups panDimIds is not always [0..dim_count-1] like
    8816             :     // in NetCDF-3 because we see only the dimensions of the selected group
    8817             :     // and its parents.
    8818             :     // poDS->papszDimName is indexed by dim IDs, so it must contains all IDs
    8819             :     // [0..max(panDimIds)], but they are not all useful so we fill names
    8820             :     // of useless dims with empty string.
    8821         355 :     if (panDimIds)
    8822             :     {
    8823         355 :         const int nMaxDimId = *std::max_element(panDimIds, panDimIds + ndims);
    8824         355 :         std::set<int> oSetExistingDimIds;
    8825        1182 :         for (int i = 0; i < ndims; i++)
    8826             :         {
    8827         827 :             oSetExistingDimIds.insert(panDimIds[i]);
    8828             :         }
    8829         355 :         std::set<int> oSetDimIdsUsedByVar;
    8830        1142 :         for (int i = 0; i < nd; i++)
    8831             :         {
    8832         787 :             oSetDimIdsUsedByVar.insert(poDS->m_anDimIds[i]);
    8833             :         }
    8834        1184 :         for (int j = 0; j <= nMaxDimId; j++)
    8835             :         {
    8836             :             // Is j dim used?
    8837         829 :             if (oSetExistingDimIds.find(j) != oSetExistingDimIds.end())
    8838             :             {
    8839             :                 // Useful dim.
    8840         827 :                 char szTemp[NC_MAX_NAME + 1] = {};
    8841         827 :                 status = nc_inq_dimname(cdfid, j, szTemp);
    8842         827 :                 if (status != NC_NOERR)
    8843             :                 {
    8844           0 :                     CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    8845             :                         // deadlock with GDALDataset own
    8846             :                         // mutex.
    8847           0 :                     delete poDS;
    8848           0 :                     CPLAcquireMutex(hNCMutex, 1000.0);
    8849           0 :                     return nullptr;
    8850             :                 }
    8851         827 :                 poDS->papszDimName.AddString(szTemp);
    8852             : 
    8853         827 :                 if (oSetDimIdsUsedByVar.find(j) != oSetDimIdsUsedByVar.end())
    8854             :                 {
    8855         787 :                     int nDimGroupId = -1;
    8856         787 :                     int nDimVarId = -1;
    8857         787 :                     if (NCDFResolveVar(cdfid, poDS->papszDimName[j],
    8858         787 :                                        &nDimGroupId, &nDimVarId) == CE_None)
    8859             :                     {
    8860         583 :                         poDS->ReadAttributes(nDimGroupId, nDimVarId);
    8861             :                     }
    8862             :                 }
    8863             :             }
    8864             :             else
    8865             :             {
    8866             :                 // Useless dim.
    8867           2 :                 poDS->papszDimName.AddString("");
    8868             :             }
    8869             :         }
    8870         355 :         CPLFree(panDimIds);
    8871             :     }
    8872             : 
    8873             :     // Set projection info.
    8874         710 :     std::vector<std::string> aosRemovedMDItems;
    8875         355 :     if (nd > 1)
    8876             :     {
    8877         351 :         poDS->SetProjectionFromVar(cdfid, var,
    8878             :                                    /*bReadSRSOnly=*/false,
    8879             :                                    /* pszGivenGM = */ nullptr,
    8880             :                                    /* returnProjStr = */ nullptr,
    8881             :                                    /* sg = */ nullptr, &aosRemovedMDItems);
    8882             :     }
    8883             : 
    8884             :     // Override bottom-up with GDAL_NETCDF_BOTTOMUP config option.
    8885         355 :     const char *pszValue = CPLGetConfigOption("GDAL_NETCDF_BOTTOMUP", nullptr);
    8886         355 :     if (pszValue)
    8887             :     {
    8888          24 :         poDS->bBottomUp = CPLTestBool(pszValue);
    8889          24 :         CPLDebug("GDAL_netCDF",
    8890             :                  "set bBottomUp=%d because GDAL_NETCDF_BOTTOMUP=%s",
    8891          24 :                  static_cast<int>(poDS->bBottomUp), pszValue);
    8892             :     }
    8893             : 
    8894             :     // Save non-spatial dimension info.
    8895             : 
    8896         355 :     int *panBandZLev = nullptr;
    8897         355 :     int nDim = (nd >= 2) ? 2 : 1;
    8898             :     size_t lev_count;
    8899         355 :     size_t nTotLevCount = 1;
    8900         355 :     nc_type nType = NC_NAT;
    8901             : 
    8902         710 :     CPLString osExtraDimNames;
    8903             : 
    8904         355 :     if (nd > 2)
    8905             :     {
    8906          62 :         nDim = 2;
    8907          62 :         panBandZLev = static_cast<int *>(CPLCalloc(nd - 2, sizeof(int)));
    8908             : 
    8909          62 :         osExtraDimNames = "{";
    8910             : 
    8911          62 :         char szDimName[NC_MAX_NAME + 1] = {};
    8912             : 
    8913          62 :         bool bREPORT_EXTRA_DIM_VALUESWarningEmitted = false;
    8914         267 :         for (int j = 0; j < nd; j++)
    8915             :         {
    8916         348 :             if ((poDS->m_anDimIds[j] != poDS->nXDimID) &&
    8917         143 :                 (poDS->m_anDimIds[j] != poDS->nYDimID))
    8918             :             {
    8919          81 :                 nc_inq_dimlen(cdfid, poDS->m_anDimIds[j], &lev_count);
    8920          81 :                 nTotLevCount *= lev_count;
    8921          81 :                 panBandZLev[nDim - 2] = static_cast<int>(lev_count);
    8922          81 :                 anBandDimPos[nDim] = j;  // Save Position of ZDim
    8923             :                 // Save non-spatial dimension names.
    8924          81 :                 if (nc_inq_dimname(cdfid, poDS->m_anDimIds[j], szDimName) ==
    8925             :                     NC_NOERR)
    8926             :                 {
    8927          81 :                     osExtraDimNames += szDimName;
    8928          81 :                     if (j < nd - 3)
    8929             :                     {
    8930          19 :                         osExtraDimNames += ",";
    8931             :                     }
    8932             : 
    8933          81 :                     int nIdxGroupID = -1;
    8934          81 :                     int nIdxVarID = Get1DVariableIndexedByDimension(
    8935          81 :                         cdfid, poDS->m_anDimIds[j], szDimName, true,
    8936          81 :                         &nIdxGroupID);
    8937          81 :                     poDS->m_anExtraDimGroupIds.push_back(nIdxGroupID);
    8938          81 :                     poDS->m_anExtraDimVarIds.push_back(nIdxVarID);
    8939             : 
    8940          81 :                     if (nIdxVarID >= 0)
    8941             :                     {
    8942          72 :                         nc_inq_vartype(nIdxGroupID, nIdxVarID, &nType);
    8943             :                         char szExtraDimDef[NC_MAX_NAME + 1];
    8944          72 :                         snprintf(szExtraDimDef, sizeof(szExtraDimDef),
    8945             :                                  "{%ld,%d}", (long)lev_count, nType);
    8946             :                         char szTemp[NC_MAX_NAME + 32 + 1];
    8947          72 :                         snprintf(szTemp, sizeof(szTemp), "NETCDF_DIM_%s_DEF",
    8948             :                                  szDimName);
    8949          72 :                         poDS->papszMetadata = CSLSetNameValue(
    8950             :                             poDS->papszMetadata, szTemp, szExtraDimDef);
    8951             : 
    8952             :                         // Retrieving data for unlimited dimensions might be
    8953             :                         // costly on network storage, so don't do it.
    8954             :                         // Each band will capture the value along the extra
    8955             :                         // dimension in its NETCDF_DIM_xxxx band metadata item
    8956             :                         // Addresses use case of
    8957             :                         // https://lists.osgeo.org/pipermail/gdal-dev/2023-May/057209.html
    8958             :                         const bool bIsLocal =
    8959          72 :                             VSIIsLocal(osFilenameForNCOpen.c_str());
    8960             :                         bool bListDimValues =
    8961          73 :                             bIsLocal || lev_count == 1 ||
    8962           1 :                             !NCDFIsUnlimitedDim(poDS->eFormat ==
    8963             :                                                     NCDF_FORMAT_NC4,
    8964           1 :                                                 cdfid, poDS->m_anDimIds[j]);
    8965             :                         const char *pszGDAL_NETCDF_REPORT_EXTRA_DIM_VALUES =
    8966          72 :                             CPLGetConfigOption(
    8967             :                                 "GDAL_NETCDF_REPORT_EXTRA_DIM_VALUES", nullptr);
    8968          72 :                         if (pszGDAL_NETCDF_REPORT_EXTRA_DIM_VALUES)
    8969             :                         {
    8970           2 :                             bListDimValues = CPLTestBool(
    8971             :                                 pszGDAL_NETCDF_REPORT_EXTRA_DIM_VALUES);
    8972             :                         }
    8973          70 :                         else if (!bListDimValues && !bIsLocal &&
    8974           1 :                                  !bREPORT_EXTRA_DIM_VALUESWarningEmitted)
    8975             :                         {
    8976           1 :                             bREPORT_EXTRA_DIM_VALUESWarningEmitted = true;
    8977           1 :                             CPLDebug(
    8978             :                                 "GDAL_netCDF",
    8979             :                                 "Listing extra dimension values is skipped "
    8980             :                                 "because this dataset is hosted on a network "
    8981             :                                 "file system, and such an operation could be "
    8982             :                                 "slow. If you still want to proceed, set the "
    8983             :                                 "GDAL_NETCDF_REPORT_EXTRA_DIM_VALUES "
    8984             :                                 "configuration option to YES");
    8985             :                         }
    8986          72 :                         if (bListDimValues)
    8987             :                         {
    8988          70 :                             char *pszTemp = nullptr;
    8989          70 :                             if (NCDFGet1DVar(nIdxGroupID, nIdxVarID,
    8990          70 :                                              &pszTemp) == CE_None)
    8991             :                             {
    8992          70 :                                 snprintf(szTemp, sizeof(szTemp),
    8993             :                                          "NETCDF_DIM_%s_VALUES", szDimName);
    8994          70 :                                 poDS->papszMetadata = CSLSetNameValue(
    8995             :                                     poDS->papszMetadata, szTemp, pszTemp);
    8996          70 :                                 CPLFree(pszTemp);
    8997             :                             }
    8998             :                         }
    8999             :                     }
    9000             :                 }
    9001             :                 else
    9002             :                 {
    9003           0 :                     poDS->m_anExtraDimGroupIds.push_back(-1);
    9004           0 :                     poDS->m_anExtraDimVarIds.push_back(-1);
    9005             :                 }
    9006             : 
    9007          81 :                 nDim++;
    9008             :             }
    9009             :         }
    9010          62 :         osExtraDimNames += "}";
    9011          62 :         poDS->papszMetadata = CSLSetNameValue(
    9012             :             poDS->papszMetadata, "NETCDF_DIM_EXTRA", osExtraDimNames);
    9013             :     }
    9014             : 
    9015             :     // Store Metadata.
    9016         365 :     for (const auto &osStr : aosRemovedMDItems)
    9017          10 :         poDS->papszMetadata =
    9018          10 :             CSLSetNameValue(poDS->papszMetadata, osStr.c_str(), nullptr);
    9019             : 
    9020         355 :     poDS->GDALPamDataset::SetMetadata(poDS->papszMetadata);
    9021             : 
    9022             :     // Create bands.
    9023             : 
    9024             :     // Arbitrary threshold.
    9025             :     int nMaxBandCount =
    9026         355 :         atoi(CPLGetConfigOption("GDAL_MAX_BAND_COUNT", "32768"));
    9027         355 :     if (nMaxBandCount <= 0)
    9028           0 :         nMaxBandCount = 32768;
    9029         355 :     if (nTotLevCount > static_cast<unsigned int>(nMaxBandCount))
    9030             :     {
    9031           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9032             :                  "Limiting number of bands to %d instead of %u", nMaxBandCount,
    9033             :                  static_cast<unsigned int>(nTotLevCount));
    9034           0 :         nTotLevCount = static_cast<unsigned int>(nMaxBandCount);
    9035             :     }
    9036         355 :     if (poDS->nRasterXSize == 0 || poDS->nRasterYSize == 0)
    9037             :     {
    9038           0 :         poDS->nRasterXSize = 0;
    9039           0 :         poDS->nRasterYSize = 0;
    9040           0 :         nTotLevCount = 0;
    9041           0 :         if (poDS->GetLayerCount() == 0)
    9042             :         {
    9043           0 :             CPLFree(panBandZLev);
    9044           0 :             CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    9045             :                 // deadlock with GDALDataset own mutex.
    9046           0 :             delete poDS;
    9047           0 :             CPLAcquireMutex(hNCMutex, 1000.0);
    9048           0 :             return nullptr;
    9049             :         }
    9050             :     }
    9051         355 :     if (bSeveralVariablesAsBands)
    9052             :     {
    9053           6 :         const auto &listVariables = oMap2DDimsToGroupAndVar.begin()->second;
    9054          24 :         for (int iBand = 0; iBand < static_cast<int>(listVariables.size());
    9055             :              ++iBand)
    9056             :         {
    9057          18 :             int bandVarGroupId = listVariables[iBand].first;
    9058          18 :             int bandVarId = listVariables[iBand].second;
    9059             :             netCDFRasterBand *poBand = new netCDFRasterBand(
    9060           0 :                 netCDFRasterBand::CONSTRUCTOR_OPEN(), poDS, bandVarGroupId,
    9061          18 :                 bandVarId, nDim, 0, nullptr, anBandDimPos.data(), iBand + 1);
    9062          18 :             poDS->SetBand(iBand + 1, poBand);
    9063             :         }
    9064             :     }
    9065             :     else
    9066             :     {
    9067         812 :         for (unsigned int lev = 0; lev < nTotLevCount; lev++)
    9068             :         {
    9069             :             netCDFRasterBand *poBand = new netCDFRasterBand(
    9070           0 :                 netCDFRasterBand::CONSTRUCTOR_OPEN(), poDS, cdfid, var, nDim,
    9071         463 :                 lev, panBandZLev, anBandDimPos.data(), lev + 1);
    9072         463 :             poDS->SetBand(lev + 1, poBand);
    9073             :         }
    9074             :     }
    9075             : 
    9076         355 :     if (panBandZLev)
    9077          62 :         CPLFree(panBandZLev);
    9078             :     // Handle angular geographic coordinates here
    9079             : 
    9080             :     // Initialize any PAM information.
    9081         355 :     if (bTreatAsSubdataset)
    9082             :     {
    9083          60 :         poDS->SetPhysicalFilename(poDS->osFilename);
    9084          60 :         poDS->SetSubdatasetName(osSubdatasetName);
    9085             :     }
    9086             : 
    9087         355 :     CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock with
    9088             :         // GDALDataset own mutex.
    9089         355 :     poDS->TryLoadXML();
    9090             : 
    9091         355 :     if (bTreatAsSubdataset)
    9092          60 :         poDS->oOvManager.Initialize(poDS, ":::VIRTUAL:::");
    9093             :     else
    9094         295 :         poDS->oOvManager.Initialize(poDS, poDS->osFilename);
    9095             : 
    9096         355 :     CPLAcquireMutex(hNCMutex, 1000.0);
    9097             : 
    9098         355 :     return poDS;
    9099             : }
    9100             : 
    9101             : /************************************************************************/
    9102             : /*                            CopyMetadata()                            */
    9103             : /*                                                                      */
    9104             : /*      Create a copy of metadata for NC_GLOBAL or a variable           */
    9105             : /************************************************************************/
    9106             : 
    9107         157 : static void CopyMetadata(GDALDataset *poSrcDS, GDALRasterBand *poSrcBand,
    9108             :                          GDALRasterBand *poDstBand, int nCdfId, int CDFVarID,
    9109             :                          const char *pszPrefix)
    9110             : {
    9111             :     // Remove the following band meta but set them later from band data.
    9112         157 :     const char *const papszIgnoreBand[] = {
    9113             :         CF_ADD_OFFSET,  CF_SCALE_FACTOR, "valid_range", "_Unsigned",
    9114             :         NCDF_FillValue, "coordinates",   nullptr};
    9115         157 :     const char *const papszIgnoreGlobal[] = {"NETCDF_DIM_EXTRA", nullptr};
    9116             : 
    9117         157 :     CSLConstList papszMetadata = nullptr;
    9118         157 :     if (poSrcDS)
    9119             :     {
    9120          66 :         papszMetadata = poSrcDS->GetMetadata();
    9121             :     }
    9122          91 :     else if (poSrcBand)
    9123             :     {
    9124          91 :         papszMetadata = poSrcBand->GetMetadata();
    9125             :     }
    9126             : 
    9127         637 :     for (const auto &[pszKey, pszValue] : cpl::IterateNameValue(papszMetadata))
    9128             :     {
    9129             : #ifdef NCDF_DEBUG
    9130             :         CPLDebug("GDAL_netCDF", "copy metadata [%s]=[%s]", pszKey, pszValue);
    9131             : #endif
    9132             : 
    9133         480 :         CPLString osMetaName(pszKey);
    9134             : 
    9135             :         // Check for items that match pszPrefix if applicable.
    9136         480 :         if (pszPrefix && !EQUAL(pszPrefix, ""))
    9137             :         {
    9138             :             // Remove prefix.
    9139         115 :             if (STARTS_WITH(osMetaName.c_str(), pszPrefix))
    9140             :             {
    9141          17 :                 osMetaName = osMetaName.substr(strlen(pszPrefix));
    9142             :             }
    9143             :             // Only copy items that match prefix.
    9144             :             else
    9145             :             {
    9146          98 :                 continue;
    9147             :             }
    9148             :         }
    9149             : 
    9150             :         // Fix various issues with metadata translation.
    9151         382 :         if (CDFVarID == NC_GLOBAL)
    9152             :         {
    9153             :             // Do not copy items in papszIgnoreGlobal and NETCDF_DIM_*.
    9154         481 :             if ((CSLFindString(papszIgnoreGlobal, osMetaName) != -1) ||
    9155         238 :                 (STARTS_WITH(osMetaName, "NETCDF_DIM_")))
    9156          21 :                 continue;
    9157             :             // Remove NC_GLOBAL prefix for netcdf global Metadata.
    9158         222 :             else if (STARTS_WITH(osMetaName, "NC_GLOBAL#"))
    9159             :             {
    9160          33 :                 osMetaName = osMetaName.substr(strlen("NC_GLOBAL#"));
    9161             :             }
    9162             :             // GDAL Metadata renamed as GDAL-[meta].
    9163         189 :             else if (strstr(osMetaName, "#") == nullptr)
    9164             :             {
    9165          16 :                 osMetaName = "GDAL_" + osMetaName;
    9166             :             }
    9167             :             // Keep time, lev and depth information for safe-keeping.
    9168             :             // Time and vertical coordinate handling need improvements.
    9169             :             /*
    9170             :             else if( STARTS_WITH(szMetaName, "time#") )
    9171             :             {
    9172             :                 szMetaName[4] = '-';
    9173             :             }
    9174             :             else if( STARTS_WITH(szMetaName, "lev#") )
    9175             :             {
    9176             :                 szMetaName[3] = '-';
    9177             :             }
    9178             :             else if( STARTS_WITH(szMetaName, "depth#") )
    9179             :             {
    9180             :                 szMetaName[5] = '-';
    9181             :             }
    9182             :             */
    9183             :             // Only copy data without # (previously all data was copied).
    9184         222 :             if (strstr(osMetaName, "#") != nullptr)
    9185         173 :                 continue;
    9186             :             // netCDF attributes do not like the '#' character.
    9187             :             // for( unsigned int h=0; h < strlen(szMetaName) -1 ; h++ ) {
    9188             :             //     if( szMetaName[h] == '#') szMetaName[h] = '-';
    9189             :             // }
    9190             :         }
    9191             :         else
    9192             :         {
    9193             :             // Do not copy varname, stats, NETCDF_DIM_*, nodata
    9194             :             // and items in papszIgnoreBand.
    9195         139 :             if (STARTS_WITH(osMetaName, "NETCDF_VARNAME") ||
    9196         107 :                 STARTS_WITH(osMetaName, "STATISTICS_") ||
    9197         107 :                 STARTS_WITH(osMetaName, "NETCDF_DIM_") ||
    9198          74 :                 STARTS_WITH(osMetaName, "missing_value") ||
    9199         293 :                 STARTS_WITH(osMetaName, "_FillValue") ||
    9200          47 :                 CSLFindString(papszIgnoreBand, osMetaName) != -1)
    9201          97 :                 continue;
    9202             :         }
    9203             : 
    9204             : #ifdef NCDF_DEBUG
    9205             :         CPLDebug("GDAL_netCDF", "copy name=[%s] value=[%s]", osMetaName.c_str(),
    9206             :                  pszValue);
    9207             : #endif
    9208          91 :         if (NCDFPutAttr(nCdfId, CDFVarID, osMetaName, pszValue) != CE_None)
    9209             :         {
    9210           0 :             CPLDebug("GDAL_netCDF", "NCDFPutAttr(%d, %d, %s, %s) failed",
    9211             :                      nCdfId, CDFVarID, osMetaName.c_str(), pszValue);
    9212             :         }
    9213             :     }
    9214             : 
    9215             :     // Set add_offset and scale_factor here if present.
    9216         157 :     if (poSrcBand && poDstBand)
    9217             :     {
    9218             : 
    9219          91 :         int bGotAddOffset = FALSE;
    9220          91 :         const double dfAddOffset = poSrcBand->GetOffset(&bGotAddOffset);
    9221          91 :         int bGotScale = FALSE;
    9222          91 :         const double dfScale = poSrcBand->GetScale(&bGotScale);
    9223             : 
    9224          91 :         if (bGotAddOffset && dfAddOffset != 0.0)
    9225           1 :             poDstBand->SetOffset(dfAddOffset);
    9226          91 :         if (bGotScale && dfScale != 1.0)
    9227           1 :             poDstBand->SetScale(dfScale);
    9228             :     }
    9229         157 : }
    9230             : 
    9231             : /************************************************************************/
    9232             : /*                            CreateLL()                                */
    9233             : /*                                                                      */
    9234             : /*      Shared functionality between netCDFDataset::Create() and        */
    9235             : /*      netCDF::CreateCopy() for creating netcdf file based on a set of */
    9236             : /*      options and a configuration.                                    */
    9237             : /************************************************************************/
    9238             : 
    9239         199 : netCDFDataset *netCDFDataset::CreateLL(const char *pszFilename, int nXSize,
    9240             :                                        int nYSize, int nBandsIn,
    9241             :                                        char **papszOptions)
    9242             : {
    9243         199 :     if (!((nXSize == 0 && nYSize == 0 && nBandsIn == 0) ||
    9244         126 :           (nXSize > 0 && nYSize > 0 && nBandsIn > 0)))
    9245             :     {
    9246           1 :         return nullptr;
    9247             :     }
    9248             : 
    9249         198 :     CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock with
    9250             :         // GDALDataset own mutex.
    9251         198 :     netCDFDataset *poDS = new netCDFDataset();
    9252         198 :     CPLAcquireMutex(hNCMutex, 1000.0);
    9253             : 
    9254         198 :     poDS->nRasterXSize = nXSize;
    9255         198 :     poDS->nRasterYSize = nYSize;
    9256         198 :     poDS->eAccess = GA_Update;
    9257         198 :     poDS->osFilename = pszFilename;
    9258             : 
    9259             :     // From gtiff driver, is this ok?
    9260             :     /*
    9261             :     poDS->nBlockXSize = nXSize;
    9262             :     poDS->nBlockYSize = 1;
    9263             :     poDS->nBlocksPerBand =
    9264             :         DIV_ROUND_UP((nYSize, poDS->nBlockYSize))
    9265             :         * DIV_ROUND_UP((nXSize, poDS->nBlockXSize));
    9266             :         */
    9267             : 
    9268             :     // process options.
    9269         198 :     poDS->papszCreationOptions = CSLDuplicate(papszOptions);
    9270         198 :     poDS->ProcessCreationOptions();
    9271             : 
    9272         198 :     if (poDS->eMultipleLayerBehavior == SEPARATE_FILES)
    9273             :     {
    9274             :         VSIStatBuf sStat;
    9275           3 :         if (VSIStat(pszFilename, &sStat) == 0)
    9276             :         {
    9277           0 :             if (!VSI_ISDIR(sStat.st_mode))
    9278             :             {
    9279           0 :                 CPLError(CE_Failure, CPLE_FileIO,
    9280             :                          "%s is an existing file, but not a directory",
    9281             :                          pszFilename);
    9282           0 :                 CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    9283             :                     // deadlock with GDALDataset own
    9284             :                     // mutex.
    9285           0 :                 delete poDS;
    9286           0 :                 CPLAcquireMutex(hNCMutex, 1000.0);
    9287           0 :                 return nullptr;
    9288             :             }
    9289             :         }
    9290           3 :         else if (VSIMkdir(pszFilename, 0755) != 0)
    9291             :         {
    9292           1 :             CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s directory",
    9293             :                      pszFilename);
    9294           1 :             CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    9295             :                 // deadlock with GDALDataset own mutex.
    9296           1 :             delete poDS;
    9297           1 :             CPLAcquireMutex(hNCMutex, 1000.0);
    9298           1 :             return nullptr;
    9299             :         }
    9300             : 
    9301           2 :         return poDS;
    9302             :     }
    9303             :     // Create the dataset.
    9304         390 :     CPLString osFilenameForNCCreate(pszFilename);
    9305             : #if defined(_WIN32) && !defined(NETCDF_USES_UTF8)
    9306             :     if (CPLTestBool(CPLGetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")))
    9307             :     {
    9308             :         char *pszTemp =
    9309             :             CPLRecode(osFilenameForNCCreate, CPL_ENC_UTF8, "CP_ACP");
    9310             :         osFilenameForNCCreate = pszTemp;
    9311             :         CPLFree(pszTemp);
    9312             :     }
    9313             : #endif
    9314             : 
    9315             : #if defined(_WIN32)
    9316             :     {
    9317             :         // Works around bug of msys2 netCDF 4.9.0 package where nc_create()
    9318             :         // crashes
    9319             :         VSIStatBuf sStat;
    9320             :         const std::string osDirname =
    9321             :             CPLGetDirnameSafe(osFilenameForNCCreate.c_str());
    9322             :         if (VSIStat(osDirname.c_str(), &sStat) != 0)
    9323             :         {
    9324             :             CPLError(CE_Failure, CPLE_OpenFailed,
    9325             :                      "Unable to create netCDF file %s: non existing output "
    9326             :                      "directory",
    9327             :                      pszFilename);
    9328             :             CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll
    9329             :                 // deadlock with GDALDataset own mutex.
    9330             :             delete poDS;
    9331             :             CPLAcquireMutex(hNCMutex, 1000.0);
    9332             :             return nullptr;
    9333             :         }
    9334             :     }
    9335             : #endif
    9336             : 
    9337             :     int status =
    9338         195 :         nc_create(osFilenameForNCCreate, poDS->nCreateMode, &(poDS->cdfid));
    9339             : 
    9340             :     // Put into define mode.
    9341         195 :     poDS->SetDefineMode(true);
    9342             : 
    9343         195 :     if (status != NC_NOERR)
    9344             :     {
    9345          30 :         CPLError(CE_Failure, CPLE_OpenFailed,
    9346             :                  "Unable to create netCDF file %s (Error code %d): %s .",
    9347             :                  pszFilename, status, nc_strerror(status));
    9348          30 :         CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock
    9349             :             // with GDALDataset own mutex.
    9350          30 :         delete poDS;
    9351          30 :         CPLAcquireMutex(hNCMutex, 1000.0);
    9352          30 :         return nullptr;
    9353             :     }
    9354             : 
    9355             :     // Define dimensions.
    9356         165 :     if (nXSize > 0 && nYSize > 0)
    9357             :     {
    9358         112 :         poDS->papszDimName.AddString(NCDF_DIMNAME_X);
    9359             :         status =
    9360         112 :             nc_def_dim(poDS->cdfid, NCDF_DIMNAME_X, nXSize, &(poDS->nXDimID));
    9361         112 :         NCDF_ERR(status);
    9362         112 :         CPLDebug("GDAL_netCDF", "status nc_def_dim(%d, %s, %d, -) got id %d",
    9363             :                  poDS->cdfid, NCDF_DIMNAME_X, nXSize, poDS->nXDimID);
    9364             : 
    9365         112 :         poDS->papszDimName.AddString(NCDF_DIMNAME_Y);
    9366             :         status =
    9367         112 :             nc_def_dim(poDS->cdfid, NCDF_DIMNAME_Y, nYSize, &(poDS->nYDimID));
    9368         112 :         NCDF_ERR(status);
    9369         112 :         CPLDebug("GDAL_netCDF", "status nc_def_dim(%d, %s, %d, -) got id %d",
    9370             :                  poDS->cdfid, NCDF_DIMNAME_Y, nYSize, poDS->nYDimID);
    9371             :     }
    9372             : 
    9373         165 :     return poDS;
    9374             : }
    9375             : 
    9376             : /************************************************************************/
    9377             : /*                            Create()                                  */
    9378             : /************************************************************************/
    9379             : 
    9380         127 : GDALDataset *netCDFDataset::Create(const char *pszFilename, int nXSize,
    9381             :                                    int nYSize, int nBandsIn, GDALDataType eType,
    9382             :                                    char **papszOptions)
    9383             : {
    9384         127 :     CPLDebug("GDAL_netCDF", "\n=====\nnetCDFDataset::Create(%s, ...)",
    9385             :              pszFilename);
    9386             : 
    9387             :     const char *legacyCreationOp =
    9388         127 :         CSLFetchNameValueDef(papszOptions, "GEOMETRY_ENCODING", "CF_1.8");
    9389         254 :     std::string legacyCreationOp_s = std::string(legacyCreationOp);
    9390             : 
    9391             :     // Check legacy creation op FIRST
    9392             : 
    9393         127 :     bool legacyCreateMode = false;
    9394             : 
    9395         127 :     if (nXSize != 0 || nYSize != 0 || nBandsIn != 0)
    9396             :     {
    9397          56 :         legacyCreateMode = true;
    9398             :     }
    9399          71 :     else if (legacyCreationOp_s == "CF_1.8")
    9400             :     {
    9401          54 :         legacyCreateMode = false;
    9402             :     }
    9403             : 
    9404          17 :     else if (legacyCreationOp_s == "WKT")
    9405             :     {
    9406          17 :         legacyCreateMode = true;
    9407             :     }
    9408             : 
    9409             :     else
    9410             :     {
    9411           0 :         CPLError(
    9412             :             CE_Failure, CPLE_NotSupported,
    9413             :             "Dataset creation option GEOMETRY_ENCODING=%s is not supported.",
    9414             :             legacyCreationOp_s.c_str());
    9415           0 :         return nullptr;
    9416             :     }
    9417             : 
    9418         254 :     CPLStringList aosOptions(CSLDuplicate(papszOptions));
    9419         240 :     if (aosOptions.FetchNameValue("FORMAT") == nullptr &&
    9420         113 :         (eType == GDT_UInt16 || eType == GDT_UInt32 || eType == GDT_UInt64 ||
    9421             :          eType == GDT_Int64))
    9422             :     {
    9423          10 :         CPLDebug("netCDF", "Selecting FORMAT=NC4 due to data type");
    9424          10 :         aosOptions.SetNameValue("FORMAT", "NC4");
    9425             :     }
    9426             : 
    9427         254 :     CPLStringList aosBandNames;
    9428         127 :     if (const char *pszBandNames = aosOptions.FetchNameValue("BAND_NAMES"))
    9429             :     {
    9430             :         aosBandNames =
    9431           2 :             CSLTokenizeString2(pszBandNames, ",", CSLT_HONOURSTRINGS);
    9432             : 
    9433           2 :         if (aosBandNames.Count() != nBandsIn)
    9434             :         {
    9435           1 :             CPLError(CE_Failure, CPLE_OpenFailed,
    9436             :                      "Attempted to create netCDF with %d bands but %d names "
    9437             :                      "provided in BAND_NAMES.",
    9438             :                      nBandsIn, aosBandNames.Count());
    9439             : 
    9440           1 :             return nullptr;
    9441             :         }
    9442             :     }
    9443             : 
    9444         252 :     CPLMutexHolderD(&hNCMutex);
    9445             : 
    9446         126 :     auto poDS = netCDFDataset::CreateLL(pszFilename, nXSize, nYSize, nBandsIn,
    9447             :                                         aosOptions.List());
    9448             : 
    9449         126 :     if (!poDS)
    9450          19 :         return nullptr;
    9451             : 
    9452         107 :     if (!legacyCreateMode)
    9453             :     {
    9454          37 :         poDS->bSGSupport = true;
    9455          37 :         poDS->vcdf.enableFullVirtualMode();
    9456             :     }
    9457             : 
    9458             :     else
    9459             :     {
    9460          70 :         poDS->bSGSupport = false;
    9461             :     }
    9462             : 
    9463             :     // Should we write signed or unsigned byte?
    9464             :     // TODO should this only be done in Create()
    9465         107 :     poDS->bSignedData = true;
    9466         107 :     const char *pszValue = CSLFetchNameValueDef(papszOptions, "PIXELTYPE", "");
    9467         107 :     if (eType == GDT_Byte && !EQUAL(pszValue, "SIGNEDBYTE"))
    9468          15 :         poDS->bSignedData = false;
    9469             : 
    9470             :     // Add Conventions, GDAL info and history.
    9471         107 :     if (poDS->cdfid >= 0)
    9472             :     {
    9473             :         const char *CF_Vector_Conv =
    9474         173 :             poDS->bSGSupport ||
    9475             :                     // Use of variable length strings require CF-1.8
    9476          68 :                     EQUAL(aosOptions.FetchNameValueDef("FORMAT", ""), "NC4")
    9477             :                 ? NCDF_CONVENTIONS_CF_V1_8
    9478         173 :                 : NCDF_CONVENTIONS_CF_V1_6;
    9479         105 :         poDS->bWriteGDALVersion = CPLTestBool(
    9480             :             CSLFetchNameValueDef(papszOptions, "WRITE_GDAL_VERSION", "YES"));
    9481         105 :         poDS->bWriteGDALHistory = CPLTestBool(
    9482             :             CSLFetchNameValueDef(papszOptions, "WRITE_GDAL_HISTORY", "YES"));
    9483         105 :         NCDFAddGDALHistory(poDS->cdfid, pszFilename, poDS->bWriteGDALVersion,
    9484         105 :                            poDS->bWriteGDALHistory, "", "Create",
    9485             :                            (nBandsIn == 0) ? CF_Vector_Conv
    9486             :                                            : GDAL_DEFAULT_NCDF_CONVENTIONS);
    9487             :     }
    9488             : 
    9489             :     // Define bands.
    9490         198 :     for (int iBand = 1; iBand <= nBandsIn; iBand++)
    9491             :     {
    9492             :         const char *pszBandName =
    9493          91 :             aosBandNames.empty() ? nullptr : aosBandNames[iBand - 1];
    9494             : 
    9495          91 :         poDS->SetBand(iBand, new netCDFRasterBand(
    9496          91 :                                  netCDFRasterBand::CONSTRUCTOR_CREATE(), poDS,
    9497          91 :                                  eType, iBand, poDS->bSignedData, pszBandName));
    9498             :     }
    9499             : 
    9500         107 :     CPLDebug("GDAL_netCDF", "netCDFDataset::Create(%s, ...) done", pszFilename);
    9501             :     // Return same dataset.
    9502         107 :     return poDS;
    9503             : }
    9504             : 
    9505             : template <class T>
    9506          91 : static CPLErr NCDFCopyBand(GDALRasterBand *poSrcBand, GDALRasterBand *poDstBand,
    9507             :                            int nXSize, int nYSize, GDALProgressFunc pfnProgress,
    9508             :                            void *pProgressData)
    9509             : {
    9510          91 :     GDALDataType eDT = poSrcBand->GetRasterDataType();
    9511          91 :     CPLErr eErr = CE_None;
    9512          91 :     T *patScanline = static_cast<T *>(CPLMalloc(nXSize * sizeof(T)));
    9513             : 
    9514        6308 :     for (int iLine = 0; iLine < nYSize && eErr == CE_None; iLine++)
    9515             :     {
    9516        6217 :         eErr = poSrcBand->RasterIO(GF_Read, 0, iLine, nXSize, 1, patScanline,
    9517             :                                    nXSize, 1, eDT, 0, 0, nullptr);
    9518        6217 :         if (eErr != CE_None)
    9519             :         {
    9520           0 :             CPLDebug(
    9521             :                 "GDAL_netCDF",
    9522             :                 "NCDFCopyBand(), poSrcBand->RasterIO() returned error code %d",
    9523             :                 eErr);
    9524             :         }
    9525             :         else
    9526             :         {
    9527        6217 :             eErr =
    9528             :                 poDstBand->RasterIO(GF_Write, 0, iLine, nXSize, 1, patScanline,
    9529             :                                     nXSize, 1, eDT, 0, 0, nullptr);
    9530        6217 :             if (eErr != CE_None)
    9531           0 :                 CPLDebug("GDAL_netCDF",
    9532             :                          "NCDFCopyBand(), poDstBand->RasterIO() returned error "
    9533             :                          "code %d",
    9534             :                          eErr);
    9535             :         }
    9536             : 
    9537        6217 :         if (nYSize > 10 && (iLine % (nYSize / 10) == 1))
    9538             :         {
    9539         277 :             if (!pfnProgress(1.0 * iLine / nYSize, nullptr, pProgressData))
    9540             :             {
    9541           0 :                 eErr = CE_Failure;
    9542           0 :                 CPLError(CE_Failure, CPLE_UserInterrupt,
    9543             :                          "User terminated CreateCopy()");
    9544             :             }
    9545             :         }
    9546             :     }
    9547             : 
    9548          91 :     CPLFree(patScanline);
    9549             : 
    9550          91 :     pfnProgress(1.0, nullptr, pProgressData);
    9551             : 
    9552          91 :     return eErr;
    9553             : }
    9554             : 
    9555             : /************************************************************************/
    9556             : /*                            CreateCopy()                              */
    9557             : /************************************************************************/
    9558             : 
    9559             : GDALDataset *
    9560          83 : netCDFDataset::CreateCopy(const char *pszFilename, GDALDataset *poSrcDS,
    9561             :                           CPL_UNUSED int bStrict, char **papszOptions,
    9562             :                           GDALProgressFunc pfnProgress, void *pProgressData)
    9563             : {
    9564         166 :     CPLMutexHolderD(&hNCMutex);
    9565             : 
    9566          83 :     CPLDebug("GDAL_netCDF", "\n=====\nnetCDFDataset::CreateCopy(%s, ...)",
    9567             :              pszFilename);
    9568             : 
    9569          83 :     if (poSrcDS->GetRootGroup())
    9570             :     {
    9571           6 :         auto poDrv = GDALDriver::FromHandle(GDALGetDriverByName("netCDF"));
    9572           6 :         if (poDrv)
    9573             :         {
    9574           6 :             return poDrv->DefaultCreateCopy(pszFilename, poSrcDS, bStrict,
    9575             :                                             papszOptions, pfnProgress,
    9576           6 :                                             pProgressData);
    9577             :         }
    9578             :     }
    9579             : 
    9580          77 :     const int nBands = poSrcDS->GetRasterCount();
    9581          77 :     const int nXSize = poSrcDS->GetRasterXSize();
    9582          77 :     const int nYSize = poSrcDS->GetRasterYSize();
    9583          77 :     const char *pszWKT = poSrcDS->GetProjectionRef();
    9584             : 
    9585             :     // Check input bands for errors.
    9586          77 :     if (nBands == 0)
    9587             :     {
    9588           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    9589             :                  "NetCDF driver does not support "
    9590             :                  "source dataset with zero band.");
    9591           1 :         return nullptr;
    9592             :     }
    9593             : 
    9594          76 :     GDALDataType eDT = GDT_Unknown;
    9595          76 :     GDALRasterBand *poSrcBand = nullptr;
    9596         181 :     for (int iBand = 1; iBand <= nBands; iBand++)
    9597             :     {
    9598         109 :         poSrcBand = poSrcDS->GetRasterBand(iBand);
    9599         109 :         eDT = poSrcBand->GetRasterDataType();
    9600         109 :         if (eDT == GDT_Unknown || GDALDataTypeIsComplex(eDT))
    9601             :         {
    9602           4 :             CPLError(CE_Failure, CPLE_NotSupported,
    9603             :                      "NetCDF driver does not support source dataset with band "
    9604             :                      "of complex type.");
    9605           4 :             return nullptr;
    9606             :         }
    9607             :     }
    9608             : 
    9609         144 :     CPLStringList aosBandNames;
    9610          72 :     if (const char *pszBandNames =
    9611          72 :             CSLFetchNameValue(papszOptions, "BAND_NAMES"))
    9612             :     {
    9613             :         aosBandNames =
    9614           2 :             CSLTokenizeString2(pszBandNames, ",", CSLT_HONOURSTRINGS);
    9615             : 
    9616           2 :         if (aosBandNames.Count() != nBands)
    9617             :         {
    9618           1 :             CPLError(CE_Failure, CPLE_OpenFailed,
    9619             :                      "Attempted to create netCDF with %d bands but %d names "
    9620             :                      "provided in BAND_NAMES.",
    9621             :                      nBands, aosBandNames.Count());
    9622             : 
    9623           1 :             return nullptr;
    9624             :         }
    9625             :     }
    9626             : 
    9627          71 :     if (!pfnProgress(0.0, nullptr, pProgressData))
    9628           0 :         return nullptr;
    9629             : 
    9630             :     // Same as in Create().
    9631         142 :     CPLStringList aosOptions(CSLDuplicate(papszOptions));
    9632         133 :     if (aosOptions.FetchNameValue("FORMAT") == nullptr &&
    9633          62 :         (eDT == GDT_UInt16 || eDT == GDT_UInt32 || eDT == GDT_UInt64 ||
    9634             :          eDT == GDT_Int64))
    9635             :     {
    9636           6 :         CPLDebug("netCDF", "Selecting FORMAT=NC4 due to data type");
    9637           6 :         aosOptions.SetNameValue("FORMAT", "NC4");
    9638             :     }
    9639          71 :     netCDFDataset *poDS = netCDFDataset::CreateLL(pszFilename, nXSize, nYSize,
    9640             :                                                   nBands, aosOptions.List());
    9641          71 :     if (!poDS)
    9642          13 :         return nullptr;
    9643             : 
    9644             :     // Copy global metadata.
    9645             :     // Add Conventions, GDAL info and history.
    9646          58 :     CopyMetadata(poSrcDS, nullptr, nullptr, poDS->cdfid, NC_GLOBAL, nullptr);
    9647          58 :     const bool bWriteGDALVersion = CPLTestBool(
    9648             :         CSLFetchNameValueDef(papszOptions, "WRITE_GDAL_VERSION", "YES"));
    9649          58 :     const bool bWriteGDALHistory = CPLTestBool(
    9650             :         CSLFetchNameValueDef(papszOptions, "WRITE_GDAL_HISTORY", "YES"));
    9651          58 :     NCDFAddGDALHistory(
    9652             :         poDS->cdfid, pszFilename, bWriteGDALVersion, bWriteGDALHistory,
    9653          58 :         poSrcDS->GetMetadataItem("NC_GLOBAL#history"), "CreateCopy",
    9654          58 :         poSrcDS->GetMetadataItem("NC_GLOBAL#Conventions"));
    9655             : 
    9656          58 :     pfnProgress(0.1, nullptr, pProgressData);
    9657             : 
    9658             :     // Check for extra dimensions.
    9659          58 :     int nDim = 2;
    9660             :     char **papszExtraDimNames =
    9661          58 :         NCDFTokenizeArray(poSrcDS->GetMetadataItem("NETCDF_DIM_EXTRA", ""));
    9662          58 :     char **papszExtraDimValues = nullptr;
    9663             : 
    9664          58 :     if (papszExtraDimNames != nullptr && CSLCount(papszExtraDimNames) > 0)
    9665             :     {
    9666           5 :         size_t nDimSizeTot = 1;
    9667             :         // first make sure dimensions lengths compatible with band count
    9668             :         // for( int i=0; i<CSLCount(papszExtraDimNames ); i++ ) {
    9669          13 :         for (int i = CSLCount(papszExtraDimNames) - 1; i >= 0; i--)
    9670             :         {
    9671             :             char szTemp[NC_MAX_NAME + 32 + 1];
    9672           8 :             snprintf(szTemp, sizeof(szTemp), "NETCDF_DIM_%s_DEF",
    9673           8 :                      papszExtraDimNames[i]);
    9674             :             papszExtraDimValues =
    9675           8 :                 NCDFTokenizeArray(poSrcDS->GetMetadataItem(szTemp, ""));
    9676           8 :             const size_t nDimSize = atol(papszExtraDimValues[0]);
    9677           8 :             CSLDestroy(papszExtraDimValues);
    9678           8 :             nDimSizeTot *= nDimSize;
    9679             :         }
    9680           5 :         if (nDimSizeTot == (size_t)nBands)
    9681             :         {
    9682           5 :             nDim = 2 + CSLCount(papszExtraDimNames);
    9683             :         }
    9684             :         else
    9685             :         {
    9686             :             // if nBands != #bands computed raise a warning
    9687             :             // just issue a debug message, because it was probably intentional
    9688           0 :             CPLDebug("GDAL_netCDF",
    9689             :                      "Warning: Number of bands (%d) is not compatible with "
    9690             :                      "dimensions "
    9691             :                      "(total=%ld names=%s)",
    9692             :                      nBands, (long)nDimSizeTot,
    9693           0 :                      poSrcDS->GetMetadataItem("NETCDF_DIM_EXTRA", ""));
    9694           0 :             CSLDestroy(papszExtraDimNames);
    9695           0 :             papszExtraDimNames = nullptr;
    9696             :         }
    9697             :     }
    9698             : 
    9699          58 :     int *panDimIds = static_cast<int *>(CPLCalloc(nDim, sizeof(int)));
    9700          58 :     int *panBandDimPos = static_cast<int *>(CPLCalloc(nDim, sizeof(int)));
    9701             : 
    9702             :     nc_type nVarType;
    9703          58 :     int *panBandZLev = nullptr;
    9704          58 :     int *panDimVarIds = nullptr;
    9705             : 
    9706          58 :     if (nDim > 2)
    9707             :     {
    9708           5 :         panBandZLev = static_cast<int *>(CPLCalloc(nDim - 2, sizeof(int)));
    9709           5 :         panDimVarIds = static_cast<int *>(CPLCalloc(nDim - 2, sizeof(int)));
    9710             : 
    9711             :         // Define all dims.
    9712          13 :         for (int i = CSLCount(papszExtraDimNames) - 1; i >= 0; i--)
    9713             :         {
    9714           8 :             poDS->papszDimName.AddString(papszExtraDimNames[i]);
    9715             :             char szTemp[NC_MAX_NAME + 32 + 1];
    9716           8 :             snprintf(szTemp, sizeof(szTemp), "NETCDF_DIM_%s_DEF",
    9717           8 :                      papszExtraDimNames[i]);
    9718             :             papszExtraDimValues =
    9719           8 :                 NCDFTokenizeArray(poSrcDS->GetMetadataItem(szTemp, ""));
    9720           8 :             const int nDimSize = papszExtraDimValues && papszExtraDimValues[0]
    9721          16 :                                      ? atoi(papszExtraDimValues[0])
    9722             :                                      : 0;
    9723             :             // nc_type is an enum in netcdf-3, needs casting.
    9724           8 :             nVarType = static_cast<nc_type>(papszExtraDimValues &&
    9725           8 :                                                     papszExtraDimValues[0] &&
    9726           8 :                                                     papszExtraDimValues[1]
    9727           8 :                                                 ? atol(papszExtraDimValues[1])
    9728             :                                                 : 0);
    9729           8 :             CSLDestroy(papszExtraDimValues);
    9730           8 :             panBandZLev[i] = nDimSize;
    9731           8 :             panBandDimPos[i + 2] = i;  // Save Position of ZDim.
    9732             : 
    9733             :             // Define dim.
    9734          16 :             int status = nc_def_dim(poDS->cdfid, papszExtraDimNames[i],
    9735           8 :                                     nDimSize, &(panDimIds[i]));
    9736           8 :             NCDF_ERR(status);
    9737             : 
    9738             :             // Define dim var.
    9739           8 :             int anDim[1] = {panDimIds[i]};
    9740          16 :             status = nc_def_var(poDS->cdfid, papszExtraDimNames[i], nVarType, 1,
    9741           8 :                                 anDim, &(panDimVarIds[i]));
    9742           8 :             NCDF_ERR(status);
    9743             : 
    9744             :             // Add dim metadata, using global var# items.
    9745           8 :             snprintf(szTemp, sizeof(szTemp), "%s#", papszExtraDimNames[i]);
    9746           8 :             CopyMetadata(poSrcDS, nullptr, nullptr, poDS->cdfid,
    9747           8 :                          panDimVarIds[i], szTemp);
    9748             :         }
    9749             :     }
    9750             : 
    9751             :     // Copy GeoTransform and Projection.
    9752             : 
    9753             :     // Copy geolocation info.
    9754          58 :     char **papszGeolocationInfo = poSrcDS->GetMetadata("GEOLOCATION");
    9755          58 :     if (papszGeolocationInfo != nullptr)
    9756           5 :         poDS->GDALPamDataset::SetMetadata(papszGeolocationInfo, "GEOLOCATION");
    9757             : 
    9758             :     // Copy geotransform.
    9759          58 :     bool bGotGeoTransform = false;
    9760          58 :     GDALGeoTransform gt;
    9761          58 :     CPLErr eErr = poSrcDS->GetGeoTransform(gt);
    9762          58 :     if (eErr == CE_None)
    9763             :     {
    9764          40 :         poDS->SetGeoTransform(gt);
    9765             :         // Disable AddProjectionVars() from being called.
    9766          40 :         bGotGeoTransform = true;
    9767          40 :         poDS->m_bHasGeoTransform = false;
    9768             :     }
    9769             : 
    9770             :     // Copy projection.
    9771          58 :     void *pScaledProgress = nullptr;
    9772          58 :     if (bGotGeoTransform || (pszWKT && pszWKT[0] != 0))
    9773             :     {
    9774          41 :         poDS->SetProjection(pszWKT ? pszWKT : "");
    9775             : 
    9776             :         // Now we can call AddProjectionVars() directly.
    9777          41 :         poDS->m_bHasGeoTransform = bGotGeoTransform;
    9778          41 :         poDS->AddProjectionVars(true, nullptr, nullptr);
    9779             :         pScaledProgress =
    9780          41 :             GDALCreateScaledProgress(0.1, 0.25, pfnProgress, pProgressData);
    9781          41 :         poDS->AddProjectionVars(false, GDALScaledProgress, pScaledProgress);
    9782          41 :         GDALDestroyScaledProgress(pScaledProgress);
    9783             :     }
    9784             :     else
    9785             :     {
    9786          17 :         poDS->bBottomUp =
    9787          17 :             CPL_TO_BOOL(CSLFetchBoolean(papszOptions, "WRITE_BOTTOMUP", TRUE));
    9788          17 :         if (papszGeolocationInfo)
    9789             :         {
    9790           4 :             poDS->AddProjectionVars(true, nullptr, nullptr);
    9791           4 :             poDS->AddProjectionVars(false, nullptr, nullptr);
    9792             :         }
    9793             :     }
    9794             : 
    9795             :     // Save X,Y dim positions.
    9796          58 :     panDimIds[nDim - 1] = poDS->nXDimID;
    9797          58 :     panBandDimPos[0] = nDim - 1;
    9798          58 :     panDimIds[nDim - 2] = poDS->nYDimID;
    9799          58 :     panBandDimPos[1] = nDim - 2;
    9800             : 
    9801             :     // Write extra dim values - after projection for optimization.
    9802          58 :     if (nDim > 2)
    9803             :     {
    9804             :         // Make sure we are in data mode.
    9805           5 :         static_cast<netCDFDataset *>(poDS)->SetDefineMode(false);
    9806          13 :         for (int i = CSLCount(papszExtraDimNames) - 1; i >= 0; i--)
    9807             :         {
    9808             :             char szTemp[NC_MAX_NAME + 32 + 1];
    9809           8 :             snprintf(szTemp, sizeof(szTemp), "NETCDF_DIM_%s_VALUES",
    9810           8 :                      papszExtraDimNames[i]);
    9811           8 :             if (poSrcDS->GetMetadataItem(szTemp) != nullptr)
    9812             :             {
    9813           8 :                 NCDFPut1DVar(poDS->cdfid, panDimVarIds[i],
    9814           8 :                              poSrcDS->GetMetadataItem(szTemp));
    9815             :             }
    9816             :         }
    9817             :     }
    9818             : 
    9819          58 :     pfnProgress(0.25, nullptr, pProgressData);
    9820             : 
    9821             :     // Define Bands.
    9822          58 :     netCDFRasterBand *poBand = nullptr;
    9823          58 :     int nBandID = -1;
    9824             : 
    9825         149 :     for (int iBand = 1; iBand <= nBands; iBand++)
    9826             :     {
    9827          91 :         CPLDebug("GDAL_netCDF", "creating band # %d/%d nDim = %d", iBand,
    9828             :                  nBands, nDim);
    9829             : 
    9830          91 :         poSrcBand = poSrcDS->GetRasterBand(iBand);
    9831          91 :         eDT = poSrcBand->GetRasterDataType();
    9832             : 
    9833             :         // Get var name from NETCDF_VARNAME.
    9834             :         const char *pszNETCDF_VARNAME =
    9835          91 :             poSrcBand->GetMetadataItem("NETCDF_VARNAME");
    9836             :         char szBandName[NC_MAX_NAME + 1];
    9837          91 :         if (!aosBandNames.empty())
    9838             :         {
    9839           2 :             snprintf(szBandName, sizeof(szBandName), "%s",
    9840             :                      aosBandNames[iBand - 1]);
    9841             :         }
    9842          89 :         else if (pszNETCDF_VARNAME)
    9843             :         {
    9844          32 :             if (nBands > 1 && papszExtraDimNames == nullptr)
    9845           0 :                 snprintf(szBandName, sizeof(szBandName), "%s%d",
    9846             :                          pszNETCDF_VARNAME, iBand);
    9847             :             else
    9848          32 :                 snprintf(szBandName, sizeof(szBandName), "%s",
    9849             :                          pszNETCDF_VARNAME);
    9850             :         }
    9851             :         else
    9852             :         {
    9853          57 :             szBandName[0] = '\0';
    9854             :         }
    9855             : 
    9856             :         // Get long_name from <var>#long_name.
    9857          91 :         const char *pszLongName = "";
    9858          91 :         if (pszNETCDF_VARNAME)
    9859             :         {
    9860             :             pszLongName =
    9861          64 :                 poSrcDS->GetMetadataItem(std::string(pszNETCDF_VARNAME)
    9862          32 :                                              .append("#")
    9863          32 :                                              .append(CF_LNG_NAME)
    9864          32 :                                              .c_str());
    9865          32 :             if (!pszLongName)
    9866          25 :                 pszLongName = "";
    9867             :         }
    9868             : 
    9869          91 :         constexpr bool bSignedData = false;
    9870             : 
    9871          91 :         if (nDim > 2)
    9872          27 :             poBand = new netCDFRasterBand(
    9873          27 :                 netCDFRasterBand::CONSTRUCTOR_CREATE(), poDS, eDT, iBand,
    9874             :                 bSignedData, szBandName, pszLongName, nBandID, nDim, iBand - 1,
    9875          27 :                 panBandZLev, panBandDimPos, panDimIds);
    9876             :         else
    9877          64 :             poBand = new netCDFRasterBand(
    9878          64 :                 netCDFRasterBand::CONSTRUCTOR_CREATE(), poDS, eDT, iBand,
    9879          64 :                 bSignedData, szBandName, pszLongName);
    9880             : 
    9881          91 :         poDS->SetBand(iBand, poBand);
    9882             : 
    9883             :         // Set nodata value, if any.
    9884          91 :         GDALCopyNoDataValue(poBand, poSrcBand);
    9885             : 
    9886             :         // Copy Metadata for band.
    9887          91 :         CopyMetadata(nullptr, poSrcDS->GetRasterBand(iBand), poBand,
    9888             :                      poDS->cdfid, poBand->nZId);
    9889             : 
    9890             :         // If more than 2D pass the first band's netcdf var ID to subsequent
    9891             :         // bands.
    9892          91 :         if (nDim > 2)
    9893          27 :             nBandID = poBand->nZId;
    9894             :     }
    9895             : 
    9896             :     // Write projection variable to band variable.
    9897          58 :     poDS->AddGridMappingRef();
    9898             : 
    9899          58 :     pfnProgress(0.5, nullptr, pProgressData);
    9900             : 
    9901             :     // Write bands.
    9902             : 
    9903             :     // Make sure we are in data mode.
    9904          58 :     poDS->SetDefineMode(false);
    9905             : 
    9906          58 :     double dfTemp = 0.5;
    9907             : 
    9908          58 :     eErr = CE_None;
    9909             : 
    9910         149 :     for (int iBand = 1; iBand <= nBands && eErr == CE_None; iBand++)
    9911             :     {
    9912          91 :         const double dfTemp2 = dfTemp + 0.4 / nBands;
    9913          91 :         pScaledProgress = GDALCreateScaledProgress(dfTemp, dfTemp2, pfnProgress,
    9914             :                                                    pProgressData);
    9915          91 :         dfTemp = dfTemp2;
    9916             : 
    9917          91 :         CPLDebug("GDAL_netCDF", "copying band data # %d/%d ", iBand, nBands);
    9918             : 
    9919          91 :         poSrcBand = poSrcDS->GetRasterBand(iBand);
    9920          91 :         eDT = poSrcBand->GetRasterDataType();
    9921             : 
    9922          91 :         GDALRasterBand *poDstBand = poDS->GetRasterBand(iBand);
    9923             : 
    9924             :         // Copy band data.
    9925          91 :         if (eDT == GDT_Byte)
    9926             :         {
    9927          51 :             CPLDebug("GDAL_netCDF", "GByte Band#%d", iBand);
    9928          51 :             eErr = NCDFCopyBand<GByte>(poSrcBand, poDstBand, nXSize, nYSize,
    9929             :                                        GDALScaledProgress, pScaledProgress);
    9930             :         }
    9931          40 :         else if (eDT == GDT_Int8)
    9932             :         {
    9933           1 :             CPLDebug("GDAL_netCDF", "GInt8 Band#%d", iBand);
    9934           1 :             eErr = NCDFCopyBand<GInt8>(poSrcBand, poDstBand, nXSize, nYSize,
    9935             :                                        GDALScaledProgress, pScaledProgress);
    9936             :         }
    9937          39 :         else if (eDT == GDT_UInt16)
    9938             :         {
    9939           2 :             CPLDebug("GDAL_netCDF", "GUInt16 Band#%d", iBand);
    9940           2 :             eErr = NCDFCopyBand<GInt16>(poSrcBand, poDstBand, nXSize, nYSize,
    9941             :                                         GDALScaledProgress, pScaledProgress);
    9942             :         }
    9943          37 :         else if (eDT == GDT_Int16)
    9944             :         {
    9945           5 :             CPLDebug("GDAL_netCDF", "GInt16 Band#%d", iBand);
    9946           5 :             eErr = NCDFCopyBand<GUInt16>(poSrcBand, poDstBand, nXSize, nYSize,
    9947             :                                          GDALScaledProgress, pScaledProgress);
    9948             :         }
    9949          32 :         else if (eDT == GDT_UInt32)
    9950             :         {
    9951           2 :             CPLDebug("GDAL_netCDF", "GUInt32 Band#%d", iBand);
    9952           2 :             eErr = NCDFCopyBand<GUInt32>(poSrcBand, poDstBand, nXSize, nYSize,
    9953             :                                          GDALScaledProgress, pScaledProgress);
    9954             :         }
    9955          30 :         else if (eDT == GDT_Int32)
    9956             :         {
    9957          18 :             CPLDebug("GDAL_netCDF", "GInt32 Band#%d", iBand);
    9958          18 :             eErr = NCDFCopyBand<GInt32>(poSrcBand, poDstBand, nXSize, nYSize,
    9959             :                                         GDALScaledProgress, pScaledProgress);
    9960             :         }
    9961          12 :         else if (eDT == GDT_UInt64)
    9962             :         {
    9963           2 :             CPLDebug("GDAL_netCDF", "GUInt64 Band#%d", iBand);
    9964           2 :             eErr = NCDFCopyBand<std::uint64_t>(poSrcBand, poDstBand, nXSize,
    9965             :                                                nYSize, GDALScaledProgress,
    9966             :                                                pScaledProgress);
    9967             :         }
    9968          10 :         else if (eDT == GDT_Int64)
    9969             :         {
    9970           2 :             CPLDebug("GDAL_netCDF", "GInt64 Band#%d", iBand);
    9971             :             eErr =
    9972           2 :                 NCDFCopyBand<std::int64_t>(poSrcBand, poDstBand, nXSize, nYSize,
    9973             :                                            GDALScaledProgress, pScaledProgress);
    9974             :         }
    9975           8 :         else if (eDT == GDT_Float32)
    9976             :         {
    9977           6 :             CPLDebug("GDAL_netCDF", "float Band#%d", iBand);
    9978           6 :             eErr = NCDFCopyBand<float>(poSrcBand, poDstBand, nXSize, nYSize,
    9979             :                                        GDALScaledProgress, pScaledProgress);
    9980             :         }
    9981           2 :         else if (eDT == GDT_Float64)
    9982             :         {
    9983           2 :             CPLDebug("GDAL_netCDF", "double Band#%d", iBand);
    9984           2 :             eErr = NCDFCopyBand<double>(poSrcBand, poDstBand, nXSize, nYSize,
    9985             :                                         GDALScaledProgress, pScaledProgress);
    9986             :         }
    9987             :         else
    9988             :         {
    9989           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    9990             :                      "The NetCDF driver does not support GDAL data type %d",
    9991             :                      eDT);
    9992             :         }
    9993             : 
    9994          91 :         GDALDestroyScaledProgress(pScaledProgress);
    9995             :     }
    9996             : 
    9997          58 :     delete (poDS);
    9998             : 
    9999          58 :     CPLFree(panDimIds);
   10000          58 :     CPLFree(panBandDimPos);
   10001          58 :     CPLFree(panBandZLev);
   10002          58 :     CPLFree(panDimVarIds);
   10003          58 :     if (papszExtraDimNames)
   10004           5 :         CSLDestroy(papszExtraDimNames);
   10005             : 
   10006          58 :     if (eErr != CE_None)
   10007           0 :         return nullptr;
   10008             : 
   10009          58 :     pfnProgress(0.95, nullptr, pProgressData);
   10010             : 
   10011             :     // Re-open dataset so we can return it.
   10012         116 :     CPLStringList aosOpenOptions;
   10013          58 :     aosOpenOptions.AddString("VARIABLES_AS_BANDS=YES");
   10014          58 :     GDALOpenInfo oOpenInfo(pszFilename, GA_Update);
   10015          58 :     oOpenInfo.nOpenFlags = GDAL_OF_RASTER | GDAL_OF_UPDATE;
   10016          58 :     oOpenInfo.papszOpenOptions = aosOpenOptions.List();
   10017          58 :     auto poRetDS = Open(&oOpenInfo);
   10018             : 
   10019             :     // PAM cloning is disabled. See bug #4244.
   10020             :     // if( poDS )
   10021             :     //     poDS->CloneInfo(poSrcDS, GCIF_PAM_DEFAULT);
   10022             : 
   10023          58 :     pfnProgress(1.0, nullptr, pProgressData);
   10024             : 
   10025          58 :     return poRetDS;
   10026             : }
   10027             : 
   10028             : // Note: some logic depends on bIsProjected and bIsGeoGraphic.
   10029             : // May not be known when Create() is called, see AddProjectionVars().
   10030         256 : void netCDFDataset::ProcessCreationOptions()
   10031             : {
   10032             :     const char *pszConfig =
   10033         256 :         CSLFetchNameValue(papszCreationOptions, "CONFIG_FILE");
   10034         256 :     if (pszConfig != nullptr)
   10035             :     {
   10036           4 :         if (oWriterConfig.Parse(pszConfig))
   10037             :         {
   10038             :             // Override dataset creation options from the config file
   10039           2 :             std::map<CPLString, CPLString>::iterator oIter;
   10040           3 :             for (oIter = oWriterConfig.m_oDatasetCreationOptions.begin();
   10041           3 :                  oIter != oWriterConfig.m_oDatasetCreationOptions.end();
   10042           1 :                  ++oIter)
   10043             :             {
   10044           2 :                 papszCreationOptions = CSLSetNameValue(
   10045           2 :                     papszCreationOptions, oIter->first, oIter->second);
   10046             :             }
   10047             :         }
   10048             :     }
   10049             : 
   10050             :     // File format.
   10051         256 :     eFormat = NCDF_FORMAT_NC;
   10052         256 :     const char *pszValue = CSLFetchNameValue(papszCreationOptions, "FORMAT");
   10053         256 :     if (pszValue != nullptr)
   10054             :     {
   10055          94 :         if (EQUAL(pszValue, "NC"))
   10056             :         {
   10057           3 :             eFormat = NCDF_FORMAT_NC;
   10058             :         }
   10059             : #ifdef NETCDF_HAS_NC2
   10060          91 :         else if (EQUAL(pszValue, "NC2"))
   10061             :         {
   10062           1 :             eFormat = NCDF_FORMAT_NC2;
   10063             :         }
   10064             : #endif
   10065          90 :         else if (EQUAL(pszValue, "NC4"))
   10066             :         {
   10067          86 :             eFormat = NCDF_FORMAT_NC4;
   10068             :         }
   10069           4 :         else if (EQUAL(pszValue, "NC4C"))
   10070             :         {
   10071           4 :             eFormat = NCDF_FORMAT_NC4C;
   10072             :         }
   10073             :         else
   10074             :         {
   10075           0 :             CPLError(CE_Failure, CPLE_NotSupported,
   10076             :                      "FORMAT=%s in not supported, using the default NC format.",
   10077             :                      pszValue);
   10078             :         }
   10079             :     }
   10080             : 
   10081             :     // COMPRESS option.
   10082         256 :     pszValue = CSLFetchNameValue(papszCreationOptions, "COMPRESS");
   10083         256 :     if (pszValue != nullptr)
   10084             :     {
   10085           3 :         if (EQUAL(pszValue, "NONE"))
   10086             :         {
   10087           1 :             eCompress = NCDF_COMPRESS_NONE;
   10088             :         }
   10089           2 :         else if (EQUAL(pszValue, "DEFLATE"))
   10090             :         {
   10091           2 :             eCompress = NCDF_COMPRESS_DEFLATE;
   10092           2 :             if (!((eFormat == NCDF_FORMAT_NC4) ||
   10093           2 :                   (eFormat == NCDF_FORMAT_NC4C)))
   10094             :             {
   10095           1 :                 CPLError(CE_Warning, CPLE_IllegalArg,
   10096             :                          "NOTICE: Format set to NC4C because compression is "
   10097             :                          "set to DEFLATE.");
   10098           1 :                 eFormat = NCDF_FORMAT_NC4C;
   10099             :             }
   10100             :         }
   10101             :         else
   10102             :         {
   10103           0 :             CPLError(CE_Failure, CPLE_NotSupported,
   10104             :                      "COMPRESS=%s is not supported.", pszValue);
   10105             :         }
   10106             :     }
   10107             : 
   10108             :     // ZLEVEL option.
   10109         256 :     pszValue = CSLFetchNameValue(papszCreationOptions, "ZLEVEL");
   10110         256 :     if (pszValue != nullptr)
   10111             :     {
   10112           1 :         nZLevel = atoi(pszValue);
   10113           1 :         if (!(nZLevel >= 1 && nZLevel <= 9))
   10114             :         {
   10115           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
   10116             :                      "ZLEVEL=%s value not recognised, ignoring.", pszValue);
   10117           0 :             nZLevel = NCDF_DEFLATE_LEVEL;
   10118             :         }
   10119             :     }
   10120             : 
   10121             :     // CHUNKING option.
   10122         256 :     bChunking =
   10123         256 :         CPL_TO_BOOL(CSLFetchBoolean(papszCreationOptions, "CHUNKING", TRUE));
   10124             : 
   10125             :     // MULTIPLE_LAYERS option.
   10126             :     const char *pszMultipleLayerBehavior =
   10127         256 :         CSLFetchNameValueDef(papszCreationOptions, "MULTIPLE_LAYERS", "NO");
   10128         512 :     const char *pszGeometryEnc = CSLFetchNameValueDef(
   10129         256 :         papszCreationOptions, "GEOMETRY_ENCODING", "CF_1.8");
   10130         256 :     if (EQUAL(pszMultipleLayerBehavior, "NO") ||
   10131           4 :         EQUAL(pszGeometryEnc, "CF_1.8"))
   10132             :     {
   10133         252 :         eMultipleLayerBehavior = SINGLE_LAYER;
   10134             :     }
   10135           4 :     else if (EQUAL(pszMultipleLayerBehavior, "SEPARATE_FILES"))
   10136             :     {
   10137           3 :         eMultipleLayerBehavior = SEPARATE_FILES;
   10138             :     }
   10139           1 :     else if (EQUAL(pszMultipleLayerBehavior, "SEPARATE_GROUPS"))
   10140             :     {
   10141           1 :         if (eFormat == NCDF_FORMAT_NC4)
   10142             :         {
   10143           1 :             eMultipleLayerBehavior = SEPARATE_GROUPS;
   10144             :         }
   10145             :         else
   10146             :         {
   10147           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
   10148             :                      "MULTIPLE_LAYERS=%s is recognised only with FORMAT=NC4",
   10149             :                      pszMultipleLayerBehavior);
   10150             :         }
   10151             :     }
   10152             :     else
   10153             :     {
   10154           0 :         CPLError(CE_Warning, CPLE_IllegalArg,
   10155             :                  "MULTIPLE_LAYERS=%s not recognised", pszMultipleLayerBehavior);
   10156             :     }
   10157             : 
   10158             :     // Set nCreateMode based on eFormat.
   10159         256 :     switch (eFormat)
   10160             :     {
   10161             : #ifdef NETCDF_HAS_NC2
   10162           1 :         case NCDF_FORMAT_NC2:
   10163           1 :             nCreateMode = NC_CLOBBER | NC_64BIT_OFFSET;
   10164           1 :             break;
   10165             : #endif
   10166          86 :         case NCDF_FORMAT_NC4:
   10167          86 :             nCreateMode = NC_CLOBBER | NC_NETCDF4;
   10168          86 :             break;
   10169           5 :         case NCDF_FORMAT_NC4C:
   10170           5 :             nCreateMode = NC_CLOBBER | NC_NETCDF4 | NC_CLASSIC_MODEL;
   10171           5 :             break;
   10172         164 :         case NCDF_FORMAT_NC:
   10173             :         default:
   10174         164 :             nCreateMode = NC_CLOBBER;
   10175         164 :             break;
   10176             :     }
   10177             : 
   10178         256 :     CPLDebug("GDAL_netCDF", "file options: format=%d compress=%d zlevel=%d",
   10179         256 :              eFormat, eCompress, nZLevel);
   10180         256 : }
   10181             : 
   10182         278 : int netCDFDataset::DefVarDeflate(int nVarId, bool bChunkingArg)
   10183             : {
   10184         278 :     if (eCompress == NCDF_COMPRESS_DEFLATE)
   10185             :     {
   10186             :         // Must set chunk size to avoid huge performance hit (set
   10187             :         // bChunkingArg=TRUE)
   10188             :         // perhaps another solution it to change the chunk cache?
   10189             :         // http://www.unidata.ucar.edu/software/netcdf/docs/netcdf.html#Chunk-Cache
   10190             :         // TODO: make sure this is okay.
   10191           2 :         CPLDebug("GDAL_netCDF", "DefVarDeflate(%d, %d) nZlevel=%d", nVarId,
   10192             :                  static_cast<int>(bChunkingArg), nZLevel);
   10193             : 
   10194           2 :         int status = nc_def_var_deflate(cdfid, nVarId, 1, 1, nZLevel);
   10195           2 :         NCDF_ERR(status);
   10196             : 
   10197           2 :         if (status == NC_NOERR && bChunkingArg && bChunking)
   10198             :         {
   10199             :             // set chunking to be 1 for all dims, except X dim
   10200             :             // size_t chunksize[] = { 1, (size_t)nRasterXSize };
   10201             :             size_t chunksize[MAX_NC_DIMS];
   10202             :             int nd;
   10203           2 :             nc_inq_varndims(cdfid, nVarId, &nd);
   10204           2 :             chunksize[0] = (size_t)1;
   10205           2 :             chunksize[1] = (size_t)1;
   10206           2 :             for (int i = 2; i < nd; i++)
   10207           0 :                 chunksize[i] = (size_t)1;
   10208           2 :             chunksize[nd - 1] = (size_t)nRasterXSize;
   10209             : 
   10210             :             // Config options just for testing purposes
   10211             :             const char *pszBlockXSize =
   10212           2 :                 CPLGetConfigOption("BLOCKXSIZE", nullptr);
   10213           2 :             if (pszBlockXSize)
   10214           0 :                 chunksize[nd - 1] = (size_t)atoi(pszBlockXSize);
   10215             : 
   10216             :             const char *pszBlockYSize =
   10217           2 :                 CPLGetConfigOption("BLOCKYSIZE", nullptr);
   10218           2 :             if (nd >= 2 && pszBlockYSize)
   10219           0 :                 chunksize[nd - 2] = (size_t)atoi(pszBlockYSize);
   10220             : 
   10221           2 :             CPLDebug("GDAL_netCDF",
   10222             :                      "DefVarDeflate() chunksize={%ld, %ld} chunkX=%ld nd=%d",
   10223           2 :                      (long)chunksize[0], (long)chunksize[1],
   10224           2 :                      (long)chunksize[nd - 1], nd);
   10225             : #ifdef NCDF_DEBUG
   10226             :             for (int i = 0; i < nd; i++)
   10227             :                 CPLDebug("GDAL_netCDF", "DefVarDeflate() chunk[%d]=%ld", i,
   10228             :                          chunksize[i]);
   10229             : #endif
   10230             : 
   10231           2 :             status = nc_def_var_chunking(cdfid, nVarId, NC_CHUNKED, chunksize);
   10232           2 :             NCDF_ERR(status);
   10233             :         }
   10234             :         else
   10235             :         {
   10236           0 :             CPLDebug("GDAL_netCDF", "chunksize not set");
   10237             :         }
   10238           2 :         return status;
   10239             :     }
   10240         276 :     return NC_NOERR;
   10241             : }
   10242             : 
   10243             : /************************************************************************/
   10244             : /*                           NCDFUnloadDriver()                         */
   10245             : /************************************************************************/
   10246             : 
   10247           8 : static void NCDFUnloadDriver(CPL_UNUSED GDALDriver *poDriver)
   10248             : {
   10249           8 :     if (hNCMutex != nullptr)
   10250           4 :         CPLDestroyMutex(hNCMutex);
   10251           8 :     hNCMutex = nullptr;
   10252           8 : }
   10253             : 
   10254             : /************************************************************************/
   10255             : /*                          GDALRegister_netCDF()                       */
   10256             : /************************************************************************/
   10257             : 
   10258             : class GDALnetCDFDriver final : public GDALDriver
   10259             : {
   10260             :   public:
   10261          19 :     GDALnetCDFDriver() = default;
   10262             : 
   10263             :     const char *GetMetadataItem(const char *pszName,
   10264             :                                 const char *pszDomain) override;
   10265             : 
   10266          90 :     char **GetMetadata(const char *pszDomain) override
   10267             :     {
   10268         180 :         std::lock_guard oLock(m_oMutex);
   10269          90 :         InitializeDCAPVirtualIO();
   10270         180 :         return GDALDriver::GetMetadata(pszDomain);
   10271             :     }
   10272             : 
   10273             :   private:
   10274             :     std::recursive_mutex m_oMutex{};
   10275             :     bool m_bInitialized = false;
   10276             : 
   10277         103 :     void InitializeDCAPVirtualIO()
   10278             :     {
   10279         103 :         if (!m_bInitialized)
   10280             :         {
   10281          12 :             m_bInitialized = true;
   10282             : 
   10283             : #ifdef ENABLE_UFFD
   10284          12 :             if (CPLIsUserFaultMappingSupported())
   10285             :             {
   10286          12 :                 SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
   10287             :             }
   10288             : #endif
   10289             :         }
   10290         103 :     }
   10291             : };
   10292             : 
   10293        1393 : const char *GDALnetCDFDriver::GetMetadataItem(const char *pszName,
   10294             :                                               const char *pszDomain)
   10295             : {
   10296        2786 :     std::lock_guard oLock(m_oMutex);
   10297        1393 :     if (EQUAL(pszName, GDAL_DCAP_VIRTUALIO))
   10298             :     {
   10299          13 :         InitializeDCAPVirtualIO();
   10300             :     }
   10301        2786 :     return GDALDriver::GetMetadataItem(pszName, pszDomain);
   10302             : }
   10303             : 
   10304          19 : void GDALRegister_netCDF()
   10305             : 
   10306             : {
   10307          19 :     if (!GDAL_CHECK_VERSION("netCDF driver"))
   10308           0 :         return;
   10309             : 
   10310          19 :     if (GDALGetDriverByName(DRIVER_NAME) != nullptr)
   10311           0 :         return;
   10312             : 
   10313          19 :     GDALDriver *poDriver = new GDALnetCDFDriver();
   10314          19 :     netCDFDriverSetCommonMetadata(poDriver);
   10315             : 
   10316          19 :     poDriver->SetMetadataItem("NETCDF_CONVENTIONS",
   10317          19 :                               GDAL_DEFAULT_NCDF_CONVENTIONS);
   10318          19 :     poDriver->SetMetadataItem("NETCDF_VERSION", nc_inq_libvers());
   10319             : 
   10320             :     // Set pfns and register driver.
   10321          19 :     poDriver->pfnOpen = netCDFDataset::Open;
   10322          19 :     poDriver->pfnCreateCopy = netCDFDataset::CreateCopy;
   10323          19 :     poDriver->pfnCreate = netCDFDataset::Create;
   10324          19 :     poDriver->pfnCreateMultiDimensional = netCDFDataset::CreateMultiDimensional;
   10325          19 :     poDriver->pfnUnloadDriver = NCDFUnloadDriver;
   10326             : 
   10327          19 :     GetGDALDriverManager()->RegisterDriver(poDriver);
   10328             : }
   10329             : 
   10330             : /************************************************************************/
   10331             : /*                          New functions                               */
   10332             : /************************************************************************/
   10333             : 
   10334             : /* Test for GDAL version string >= target */
   10335         241 : static bool NCDFIsGDALVersionGTE(const char *pszVersion, int nTarget)
   10336             : {
   10337             : 
   10338             :     // Valid strings are "GDAL 1.9dev, released 2011/01/18" and "GDAL 1.8.1 ".
   10339         241 :     if (pszVersion == nullptr || EQUAL(pszVersion, ""))
   10340           0 :         return false;
   10341         241 :     else if (!STARTS_WITH_CI(pszVersion, "GDAL "))
   10342           0 :         return false;
   10343             :     // 2.0dev of 2011/12/29 has been later renamed as 1.10dev.
   10344         241 :     else if (EQUAL("GDAL 2.0dev, released 2011/12/29", pszVersion))
   10345           0 :         return nTarget <= GDAL_COMPUTE_VERSION(1, 10, 0);
   10346         241 :     else if (STARTS_WITH_CI(pszVersion, "GDAL 1.9dev"))
   10347           2 :         return nTarget <= 1900;
   10348         239 :     else if (STARTS_WITH_CI(pszVersion, "GDAL 1.8dev"))
   10349           0 :         return nTarget <= 1800;
   10350             : 
   10351         239 :     char **papszTokens = CSLTokenizeString2(pszVersion + 5, ".", 0);
   10352             : 
   10353         239 :     int nVersions[] = {0, 0, 0, 0};
   10354         956 :     for (int iToken = 0; papszTokens && iToken < 4 && papszTokens[iToken];
   10355             :          iToken++)
   10356             :     {
   10357         717 :         nVersions[iToken] = atoi(papszTokens[iToken]);
   10358         717 :         if (nVersions[iToken] < 0)
   10359           0 :             nVersions[iToken] = 0;
   10360         717 :         else if (nVersions[iToken] > 99)
   10361           0 :             nVersions[iToken] = 99;
   10362             :     }
   10363             : 
   10364         239 :     int nVersion = 0;
   10365         239 :     if (nVersions[0] > 1 || nVersions[1] >= 10)
   10366         239 :         nVersion =
   10367         239 :             GDAL_COMPUTE_VERSION(nVersions[0], nVersions[1], nVersions[2]);
   10368             :     else
   10369           0 :         nVersion = nVersions[0] * 1000 + nVersions[1] * 100 +
   10370           0 :                    nVersions[2] * 10 + nVersions[3];
   10371             : 
   10372         239 :     CSLDestroy(papszTokens);
   10373         239 :     return nTarget <= nVersion;
   10374             : }
   10375             : 
   10376             : // Add Conventions, GDAL version and history.
   10377         167 : static void NCDFAddGDALHistory(int fpImage, const char *pszFilename,
   10378             :                                bool bWriteGDALVersion, bool bWriteGDALHistory,
   10379             :                                const char *pszOldHist,
   10380             :                                const char *pszFunctionName,
   10381             :                                const char *pszCFVersion)
   10382             : {
   10383         167 :     if (pszCFVersion == nullptr)
   10384             :     {
   10385          42 :         pszCFVersion = GDAL_DEFAULT_NCDF_CONVENTIONS;
   10386             :     }
   10387         167 :     int status = nc_put_att_text(fpImage, NC_GLOBAL, "Conventions",
   10388             :                                  strlen(pszCFVersion), pszCFVersion);
   10389         167 :     NCDF_ERR(status);
   10390             : 
   10391         167 :     if (bWriteGDALVersion)
   10392             :     {
   10393         165 :         const char *pszNCDF_GDAL = GDALVersionInfo("--version");
   10394         165 :         status = nc_put_att_text(fpImage, NC_GLOBAL, "GDAL",
   10395             :                                  strlen(pszNCDF_GDAL), pszNCDF_GDAL);
   10396         165 :         NCDF_ERR(status);
   10397             :     }
   10398             : 
   10399         167 :     if (bWriteGDALHistory)
   10400             :     {
   10401             :         // Add history.
   10402         330 :         CPLString osTmp;
   10403             : #ifdef GDAL_SET_CMD_LINE_DEFINED_TMP
   10404             :         if (!EQUAL(GDALGetCmdLine(), ""))
   10405             :             osTmp = GDALGetCmdLine();
   10406             :         else
   10407             :             osTmp =
   10408             :                 CPLSPrintf("GDAL %s( %s, ... )", pszFunctionName, pszFilename);
   10409             : #else
   10410         165 :         osTmp = CPLSPrintf("GDAL %s( %s, ... )", pszFunctionName, pszFilename);
   10411             : #endif
   10412             : 
   10413         165 :         NCDFAddHistory(fpImage, osTmp.c_str(), pszOldHist);
   10414             :     }
   10415           2 :     else if (pszOldHist != nullptr)
   10416             :     {
   10417           0 :         status = nc_put_att_text(fpImage, NC_GLOBAL, "history",
   10418             :                                  strlen(pszOldHist), pszOldHist);
   10419           0 :         NCDF_ERR(status);
   10420             :     }
   10421         167 : }
   10422             : 
   10423             : // Code taken from cdo and libcdi, used for writing the history attribute.
   10424             : 
   10425             : // void cdoDefHistory(int fileID, char *histstring)
   10426         165 : static void NCDFAddHistory(int fpImage, const char *pszAddHist,
   10427             :                            const char *pszOldHist)
   10428             : {
   10429             :     // Check pszOldHist - as if there was no previous history, it will be
   10430             :     // a null pointer - if so set as empty.
   10431         165 :     if (nullptr == pszOldHist)
   10432             :     {
   10433          53 :         pszOldHist = "";
   10434             :     }
   10435             : 
   10436             :     char strtime[32];
   10437         165 :     strtime[0] = '\0';
   10438             : 
   10439         165 :     time_t tp = time(nullptr);
   10440         165 :     if (tp != -1)
   10441             :     {
   10442             :         struct tm ltime;
   10443         165 :         VSILocalTime(&tp, &ltime);
   10444         165 :         (void)strftime(strtime, sizeof(strtime),
   10445             :                        "%a %b %d %H:%M:%S %Y: ", &ltime);
   10446             :     }
   10447             : 
   10448             :     // status = nc_get_att_text(fpImage, NC_GLOBAL,
   10449             :     //                           "history", pszOldHist);
   10450             :     // printf("status: %d pszOldHist: [%s]\n",status,pszOldHist);
   10451             : 
   10452         165 :     size_t nNewHistSize =
   10453         165 :         strlen(pszOldHist) + strlen(strtime) + strlen(pszAddHist) + 1 + 1;
   10454             :     char *pszNewHist =
   10455         165 :         static_cast<char *>(CPLMalloc(nNewHistSize * sizeof(char)));
   10456             : 
   10457         165 :     strcpy(pszNewHist, strtime);
   10458         165 :     strcat(pszNewHist, pszAddHist);
   10459             : 
   10460             :     // int disableHistory = FALSE;
   10461             :     // if( !disableHistory )
   10462             :     {
   10463         165 :         if (!EQUAL(pszOldHist, ""))
   10464           3 :             strcat(pszNewHist, "\n");
   10465         165 :         strcat(pszNewHist, pszOldHist);
   10466             :     }
   10467             : 
   10468         165 :     const int status = nc_put_att_text(fpImage, NC_GLOBAL, "history",
   10469             :                                        strlen(pszNewHist), pszNewHist);
   10470         165 :     NCDF_ERR(status);
   10471             : 
   10472         165 :     CPLFree(pszNewHist);
   10473         165 : }
   10474             : 
   10475        6185 : static CPLErr NCDFSafeStrcat(char **ppszDest, const char *pszSrc,
   10476             :                              size_t *nDestSize)
   10477             : {
   10478             :     /* Reallocate the data string until the content fits */
   10479        6185 :     while (*nDestSize < (strlen(*ppszDest) + strlen(pszSrc) + 1))
   10480             :     {
   10481         408 :         (*nDestSize) *= 2;
   10482         408 :         *ppszDest = static_cast<char *>(
   10483         408 :             CPLRealloc(reinterpret_cast<void *>(*ppszDest), *nDestSize));
   10484             : #ifdef NCDF_DEBUG
   10485             :         CPLDebug("GDAL_netCDF", "NCDFSafeStrcat() resized str from %ld to %ld",
   10486             :                  (*nDestSize) / 2, *nDestSize);
   10487             : #endif
   10488             :     }
   10489        5777 :     strcat(*ppszDest, pszSrc);
   10490             : 
   10491        5777 :     return CE_None;
   10492             : }
   10493             : 
   10494             : /* helper function for NCDFGetAttr() */
   10495             : /* if pdfValue != nullptr, sets *pdfValue to first value returned */
   10496             : /* if ppszValue != nullptr, sets *ppszValue with all attribute values */
   10497             : /* *ppszValue is the responsibility of the caller and must be freed */
   10498       63669 : static CPLErr NCDFGetAttr1(int nCdfId, int nVarId, const char *pszAttrName,
   10499             :                            double *pdfValue, char **ppszValue)
   10500             : {
   10501       63669 :     nc_type nAttrType = NC_NAT;
   10502       63669 :     size_t nAttrLen = 0;
   10503             : 
   10504       63669 :     if (ppszValue)
   10505       62514 :         *ppszValue = nullptr;
   10506             : 
   10507       63669 :     int status = nc_inq_att(nCdfId, nVarId, pszAttrName, &nAttrType, &nAttrLen);
   10508       63669 :     if (status != NC_NOERR)
   10509       34177 :         return CE_Failure;
   10510             : 
   10511             : #ifdef NCDF_DEBUG
   10512             :     CPLDebug("GDAL_netCDF", "NCDFGetAttr1(%s) len=%ld type=%d", pszAttrName,
   10513             :              nAttrLen, nAttrType);
   10514             : #endif
   10515       29492 :     if (nAttrLen == 0 && nAttrType != NC_CHAR)
   10516           1 :         return CE_Failure;
   10517             : 
   10518             :     /* Allocate guaranteed minimum size (use 10 or 20 if not a string) */
   10519       29491 :     size_t nAttrValueSize = nAttrLen + 1;
   10520       29491 :     if (nAttrType != NC_CHAR && nAttrValueSize < 10)
   10521        3232 :         nAttrValueSize = 10;
   10522       29491 :     if (nAttrType == NC_DOUBLE && nAttrValueSize < 20)
   10523        1578 :         nAttrValueSize = 20;
   10524       29491 :     if (nAttrType == NC_INT64 && nAttrValueSize < 20)
   10525          22 :         nAttrValueSize = 22;
   10526             :     char *pszAttrValue =
   10527       29491 :         static_cast<char *>(CPLCalloc(nAttrValueSize, sizeof(char)));
   10528       29491 :     *pszAttrValue = '\0';
   10529             : 
   10530       29491 :     if (nAttrLen > 1 && nAttrType != NC_CHAR)
   10531         602 :         NCDFSafeStrcat(&pszAttrValue, "{", &nAttrValueSize);
   10532             : 
   10533       29491 :     double dfValue = 0.0;
   10534       29491 :     size_t m = 0;
   10535             :     char szTemp[256];
   10536       29491 :     bool bSetDoubleFromStr = false;
   10537             : 
   10538       29491 :     switch (nAttrType)
   10539             :     {
   10540       26257 :         case NC_CHAR:
   10541       26257 :             CPL_IGNORE_RET_VAL(
   10542       26257 :                 nc_get_att_text(nCdfId, nVarId, pszAttrName, pszAttrValue));
   10543       26257 :             pszAttrValue[nAttrLen] = '\0';
   10544       26257 :             bSetDoubleFromStr = true;
   10545       26257 :             dfValue = 0.0;
   10546       26257 :             break;
   10547          94 :         case NC_BYTE:
   10548             :         {
   10549             :             signed char *pscTemp = static_cast<signed char *>(
   10550          94 :                 CPLCalloc(nAttrLen, sizeof(signed char)));
   10551          94 :             nc_get_att_schar(nCdfId, nVarId, pszAttrName, pscTemp);
   10552          94 :             dfValue = static_cast<double>(pscTemp[0]);
   10553          94 :             if (nAttrLen > 1)
   10554             :             {
   10555          24 :                 for (m = 0; m < nAttrLen - 1; m++)
   10556             :                 {
   10557          13 :                     snprintf(szTemp, sizeof(szTemp), "%d,", pscTemp[m]);
   10558          13 :                     NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10559             :                 }
   10560             :             }
   10561          94 :             snprintf(szTemp, sizeof(szTemp), "%d", pscTemp[m]);
   10562          94 :             NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10563          94 :             CPLFree(pscTemp);
   10564          94 :             break;
   10565             :         }
   10566         487 :         case NC_SHORT:
   10567             :         {
   10568             :             short *psTemp =
   10569         487 :                 static_cast<short *>(CPLCalloc(nAttrLen, sizeof(short)));
   10570         487 :             nc_get_att_short(nCdfId, nVarId, pszAttrName, psTemp);
   10571         487 :             dfValue = static_cast<double>(psTemp[0]);
   10572         487 :             if (nAttrLen > 1)
   10573             :             {
   10574         768 :                 for (m = 0; m < nAttrLen - 1; m++)
   10575             :                 {
   10576         384 :                     snprintf(szTemp, sizeof(szTemp), "%d,", psTemp[m]);
   10577         384 :                     NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10578             :                 }
   10579             :             }
   10580         487 :             snprintf(szTemp, sizeof(szTemp), "%d", psTemp[m]);
   10581         487 :             NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10582         487 :             CPLFree(psTemp);
   10583         487 :             break;
   10584             :         }
   10585         528 :         case NC_INT:
   10586             :         {
   10587         528 :             int *pnTemp = static_cast<int *>(CPLCalloc(nAttrLen, sizeof(int)));
   10588         528 :             nc_get_att_int(nCdfId, nVarId, pszAttrName, pnTemp);
   10589         528 :             dfValue = static_cast<double>(pnTemp[0]);
   10590         528 :             if (nAttrLen > 1)
   10591             :             {
   10592         218 :                 for (m = 0; m < nAttrLen - 1; m++)
   10593             :                 {
   10594         139 :                     snprintf(szTemp, sizeof(szTemp), "%d,", pnTemp[m]);
   10595         139 :                     NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10596             :                 }
   10597             :             }
   10598         528 :             snprintf(szTemp, sizeof(szTemp), "%d", pnTemp[m]);
   10599         528 :             NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10600         528 :             CPLFree(pnTemp);
   10601         528 :             break;
   10602             :         }
   10603         395 :         case NC_FLOAT:
   10604             :         {
   10605             :             float *pfTemp =
   10606         395 :                 static_cast<float *>(CPLCalloc(nAttrLen, sizeof(float)));
   10607         395 :             nc_get_att_float(nCdfId, nVarId, pszAttrName, pfTemp);
   10608         395 :             dfValue = static_cast<double>(pfTemp[0]);
   10609         395 :             if (nAttrLen > 1)
   10610             :             {
   10611          60 :                 for (m = 0; m < nAttrLen - 1; m++)
   10612             :                 {
   10613          30 :                     CPLsnprintf(szTemp, sizeof(szTemp), "%.8g,", pfTemp[m]);
   10614          30 :                     NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10615             :                 }
   10616             :             }
   10617         395 :             CPLsnprintf(szTemp, sizeof(szTemp), "%.8g", pfTemp[m]);
   10618         395 :             NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10619         395 :             CPLFree(pfTemp);
   10620         395 :             break;
   10621             :         }
   10622        1578 :         case NC_DOUBLE:
   10623             :         {
   10624             :             double *pdfTemp =
   10625        1578 :                 static_cast<double *>(CPLCalloc(nAttrLen, sizeof(double)));
   10626        1578 :             nc_get_att_double(nCdfId, nVarId, pszAttrName, pdfTemp);
   10627        1578 :             dfValue = pdfTemp[0];
   10628        1578 :             if (nAttrLen > 1)
   10629             :             {
   10630         166 :                 for (m = 0; m < nAttrLen - 1; m++)
   10631             :                 {
   10632          90 :                     CPLsnprintf(szTemp, sizeof(szTemp), "%.16g,", pdfTemp[m]);
   10633          90 :                     NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10634             :                 }
   10635             :             }
   10636        1578 :             CPLsnprintf(szTemp, sizeof(szTemp), "%.16g", pdfTemp[m]);
   10637        1578 :             NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10638        1578 :             CPLFree(pdfTemp);
   10639        1578 :             break;
   10640             :         }
   10641          10 :         case NC_STRING:
   10642             :         {
   10643             :             char **ppszTemp =
   10644          10 :                 static_cast<char **>(CPLCalloc(nAttrLen, sizeof(char *)));
   10645          10 :             nc_get_att_string(nCdfId, nVarId, pszAttrName, ppszTemp);
   10646          10 :             bSetDoubleFromStr = true;
   10647          10 :             dfValue = 0.0;
   10648          10 :             if (nAttrLen > 1)
   10649             :             {
   10650          19 :                 for (m = 0; m < nAttrLen - 1; m++)
   10651             :                 {
   10652          12 :                     NCDFSafeStrcat(&pszAttrValue,
   10653          12 :                                    ppszTemp[m] ? ppszTemp[m] : "{NULL}",
   10654             :                                    &nAttrValueSize);
   10655          12 :                     NCDFSafeStrcat(&pszAttrValue, ",", &nAttrValueSize);
   10656             :                 }
   10657             :             }
   10658          10 :             NCDFSafeStrcat(&pszAttrValue, ppszTemp[m] ? ppszTemp[m] : "{NULL}",
   10659             :                            &nAttrValueSize);
   10660          10 :             nc_free_string(nAttrLen, ppszTemp);
   10661          10 :             CPLFree(ppszTemp);
   10662          10 :             break;
   10663             :         }
   10664          28 :         case NC_UBYTE:
   10665             :         {
   10666             :             unsigned char *pucTemp = static_cast<unsigned char *>(
   10667          28 :                 CPLCalloc(nAttrLen, sizeof(unsigned char)));
   10668          28 :             nc_get_att_uchar(nCdfId, nVarId, pszAttrName, pucTemp);
   10669          28 :             dfValue = static_cast<double>(pucTemp[0]);
   10670          28 :             if (nAttrLen > 1)
   10671             :             {
   10672           0 :                 for (m = 0; m < nAttrLen - 1; m++)
   10673             :                 {
   10674           0 :                     CPLsnprintf(szTemp, sizeof(szTemp), "%u,", pucTemp[m]);
   10675           0 :                     NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10676             :                 }
   10677             :             }
   10678          28 :             CPLsnprintf(szTemp, sizeof(szTemp), "%u", pucTemp[m]);
   10679          28 :             NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10680          28 :             CPLFree(pucTemp);
   10681          28 :             break;
   10682             :         }
   10683          26 :         case NC_USHORT:
   10684             :         {
   10685             :             unsigned short *pusTemp;
   10686             :             pusTemp = static_cast<unsigned short *>(
   10687          26 :                 CPLCalloc(nAttrLen, sizeof(unsigned short)));
   10688          26 :             nc_get_att_ushort(nCdfId, nVarId, pszAttrName, pusTemp);
   10689          26 :             dfValue = static_cast<double>(pusTemp[0]);
   10690          26 :             if (nAttrLen > 1)
   10691             :             {
   10692          10 :                 for (m = 0; m < nAttrLen - 1; m++)
   10693             :                 {
   10694           5 :                     CPLsnprintf(szTemp, sizeof(szTemp), "%u,", pusTemp[m]);
   10695           5 :                     NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10696             :                 }
   10697             :             }
   10698          26 :             CPLsnprintf(szTemp, sizeof(szTemp), "%u", pusTemp[m]);
   10699          26 :             NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10700          26 :             CPLFree(pusTemp);
   10701          26 :             break;
   10702             :         }
   10703          18 :         case NC_UINT:
   10704             :         {
   10705             :             unsigned int *punTemp =
   10706          18 :                 static_cast<unsigned int *>(CPLCalloc(nAttrLen, sizeof(int)));
   10707          18 :             nc_get_att_uint(nCdfId, nVarId, pszAttrName, punTemp);
   10708          18 :             dfValue = static_cast<double>(punTemp[0]);
   10709          18 :             if (nAttrLen > 1)
   10710             :             {
   10711           0 :                 for (m = 0; m < nAttrLen - 1; m++)
   10712             :                 {
   10713           0 :                     CPLsnprintf(szTemp, sizeof(szTemp), "%u,", punTemp[m]);
   10714           0 :                     NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10715             :                 }
   10716             :             }
   10717          18 :             CPLsnprintf(szTemp, sizeof(szTemp), "%u", punTemp[m]);
   10718          18 :             NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10719          18 :             CPLFree(punTemp);
   10720          18 :             break;
   10721             :         }
   10722          22 :         case NC_INT64:
   10723             :         {
   10724             :             GIntBig *panTemp =
   10725          22 :                 static_cast<GIntBig *>(CPLCalloc(nAttrLen, sizeof(GIntBig)));
   10726          22 :             nc_get_att_longlong(nCdfId, nVarId, pszAttrName, panTemp);
   10727          22 :             dfValue = static_cast<double>(panTemp[0]);
   10728          22 :             if (nAttrLen > 1)
   10729             :             {
   10730           0 :                 for (m = 0; m < nAttrLen - 1; m++)
   10731             :                 {
   10732           0 :                     CPLsnprintf(szTemp, sizeof(szTemp), CPL_FRMT_GIB ",",
   10733           0 :                                 panTemp[m]);
   10734           0 :                     NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10735             :                 }
   10736             :             }
   10737          22 :             CPLsnprintf(szTemp, sizeof(szTemp), CPL_FRMT_GIB, panTemp[m]);
   10738          22 :             NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10739          22 :             CPLFree(panTemp);
   10740          22 :             break;
   10741             :         }
   10742          22 :         case NC_UINT64:
   10743             :         {
   10744             :             GUIntBig *panTemp =
   10745          22 :                 static_cast<GUIntBig *>(CPLCalloc(nAttrLen, sizeof(GUIntBig)));
   10746          22 :             nc_get_att_ulonglong(nCdfId, nVarId, pszAttrName, panTemp);
   10747          22 :             dfValue = static_cast<double>(panTemp[0]);
   10748          22 :             if (nAttrLen > 1)
   10749             :             {
   10750           0 :                 for (m = 0; m < nAttrLen - 1; m++)
   10751             :                 {
   10752           0 :                     CPLsnprintf(szTemp, sizeof(szTemp), CPL_FRMT_GUIB ",",
   10753           0 :                                 panTemp[m]);
   10754           0 :                     NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10755             :                 }
   10756             :             }
   10757          22 :             CPLsnprintf(szTemp, sizeof(szTemp), CPL_FRMT_GUIB, panTemp[m]);
   10758          22 :             NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
   10759          22 :             CPLFree(panTemp);
   10760          22 :             break;
   10761             :         }
   10762          26 :         default:
   10763          26 :             CPLDebug("GDAL_netCDF",
   10764             :                      "NCDFGetAttr unsupported type %d for attribute %s",
   10765             :                      nAttrType, pszAttrName);
   10766          26 :             break;
   10767             :     }
   10768             : 
   10769       29491 :     if (nAttrLen > 1 && nAttrType != NC_CHAR)
   10770         602 :         NCDFSafeStrcat(&pszAttrValue, "}", &nAttrValueSize);
   10771             : 
   10772       29491 :     if (bSetDoubleFromStr)
   10773             :     {
   10774       26267 :         if (CPLGetValueType(pszAttrValue) == CPL_VALUE_STRING)
   10775             :         {
   10776       26085 :             if (ppszValue == nullptr && pdfValue != nullptr)
   10777             :             {
   10778           1 :                 CPLFree(pszAttrValue);
   10779           1 :                 return CE_Failure;
   10780             :             }
   10781             :         }
   10782       26266 :         dfValue = CPLAtof(pszAttrValue);
   10783             :     }
   10784             : 
   10785             :     /* set return values */
   10786       29490 :     if (ppszValue)
   10787       29178 :         *ppszValue = pszAttrValue;
   10788             :     else
   10789         312 :         CPLFree(pszAttrValue);
   10790             : 
   10791       29490 :     if (pdfValue)
   10792         312 :         *pdfValue = dfValue;
   10793             : 
   10794       29490 :     return CE_None;
   10795             : }
   10796             : 
   10797             : /* sets pdfValue to first value found */
   10798        1155 : CPLErr NCDFGetAttr(int nCdfId, int nVarId, const char *pszAttrName,
   10799             :                    double *pdfValue)
   10800             : {
   10801        1155 :     return NCDFGetAttr1(nCdfId, nVarId, pszAttrName, pdfValue, nullptr);
   10802             : }
   10803             : 
   10804             : /* pszValue is the responsibility of the caller and must be freed */
   10805       62514 : CPLErr NCDFGetAttr(int nCdfId, int nVarId, const char *pszAttrName,
   10806             :                    char **pszValue)
   10807             : {
   10808       62514 :     return NCDFGetAttr1(nCdfId, nVarId, pszAttrName, nullptr, pszValue);
   10809             : }
   10810             : 
   10811             : /* By default write NC_CHAR, but detect for int/float/double and */
   10812             : /* NC4 string arrays */
   10813         106 : static CPLErr NCDFPutAttr(int nCdfId, int nVarId, const char *pszAttrName,
   10814             :                           const char *pszValue)
   10815             : {
   10816         106 :     int status = 0;
   10817         106 :     char *pszTemp = nullptr;
   10818             : 
   10819             :     /* get the attribute values as tokens */
   10820         106 :     char **papszValues = NCDFTokenizeArray(pszValue);
   10821         106 :     if (papszValues == nullptr)
   10822           0 :         return CE_Failure;
   10823             : 
   10824         106 :     size_t nAttrLen = CSLCount(papszValues);
   10825             : 
   10826             :     /* first detect type */
   10827         106 :     nc_type nAttrType = NC_CHAR;
   10828         106 :     nc_type nTmpAttrType = NC_CHAR;
   10829         225 :     for (size_t i = 0; i < nAttrLen; i++)
   10830             :     {
   10831         119 :         nTmpAttrType = NC_CHAR;
   10832         119 :         bool bFoundType = false;
   10833         119 :         errno = 0;
   10834         119 :         int nValue = static_cast<int>(strtol(papszValues[i], &pszTemp, 10));
   10835             :         /* test for int */
   10836             :         /* TODO test for Byte and short - can this be done safely? */
   10837         119 :         if (errno == 0 && papszValues[i] != pszTemp && *pszTemp == 0)
   10838             :         {
   10839             :             char szTemp[256];
   10840          19 :             CPLsnprintf(szTemp, sizeof(szTemp), "%d", nValue);
   10841          19 :             if (EQUAL(szTemp, papszValues[i]))
   10842             :             {
   10843          19 :                 bFoundType = true;
   10844          19 :                 nTmpAttrType = NC_INT;
   10845             :             }
   10846             :             else
   10847             :             {
   10848             :                 unsigned int unValue = static_cast<unsigned int>(
   10849           0 :                     strtoul(papszValues[i], &pszTemp, 10));
   10850           0 :                 CPLsnprintf(szTemp, sizeof(szTemp), "%u", unValue);
   10851           0 :                 if (EQUAL(szTemp, papszValues[i]))
   10852             :                 {
   10853           0 :                     bFoundType = true;
   10854           0 :                     nTmpAttrType = NC_UINT;
   10855             :                 }
   10856             :             }
   10857             :         }
   10858         119 :         if (!bFoundType)
   10859             :         {
   10860             :             /* test for double */
   10861         100 :             errno = 0;
   10862         100 :             double dfValue = CPLStrtod(papszValues[i], &pszTemp);
   10863         100 :             if ((errno == 0) && (papszValues[i] != pszTemp) && (*pszTemp == 0))
   10864             :             {
   10865             :                 // Test for float instead of double.
   10866             :                 // strtof() is C89, which is not available in MSVC.
   10867             :                 // See if we loose precision if we cast to float and write to
   10868             :                 // char*.
   10869          14 :                 float fValue = float(dfValue);
   10870             :                 char szTemp[256];
   10871          14 :                 CPLsnprintf(szTemp, sizeof(szTemp), "%.8g", fValue);
   10872          14 :                 if (EQUAL(szTemp, papszValues[i]))
   10873           8 :                     nTmpAttrType = NC_FLOAT;
   10874             :                 else
   10875           6 :                     nTmpAttrType = NC_DOUBLE;
   10876             :             }
   10877             :         }
   10878         119 :         if ((nTmpAttrType <= NC_DOUBLE && nAttrType <= NC_DOUBLE &&
   10879          99 :              nTmpAttrType > nAttrType) ||
   10880          99 :             (nTmpAttrType == NC_UINT && nAttrType < NC_FLOAT) ||
   10881           5 :             (nTmpAttrType >= NC_FLOAT && nAttrType == NC_UINT))
   10882          20 :             nAttrType = nTmpAttrType;
   10883             :     }
   10884             : 
   10885             : #ifdef DEBUG
   10886         106 :     if (EQUAL(pszAttrName, "DEBUG_EMPTY_DOUBLE_ATTR"))
   10887             :     {
   10888           0 :         nAttrType = NC_DOUBLE;
   10889           0 :         nAttrLen = 0;
   10890             :     }
   10891             : #endif
   10892             : 
   10893             :     /* now write the data */
   10894         106 :     if (nAttrType == NC_CHAR)
   10895             :     {
   10896          86 :         int nTmpFormat = 0;
   10897          86 :         if (nAttrLen > 1)
   10898             :         {
   10899           0 :             status = nc_inq_format(nCdfId, &nTmpFormat);
   10900           0 :             NCDF_ERR(status);
   10901             :         }
   10902          86 :         if (nAttrLen > 1 && nTmpFormat == NCDF_FORMAT_NC4)
   10903           0 :             status = nc_put_att_string(nCdfId, nVarId, pszAttrName, nAttrLen,
   10904             :                                        const_cast<const char **>(papszValues));
   10905             :         else
   10906          86 :             status = nc_put_att_text(nCdfId, nVarId, pszAttrName,
   10907             :                                      strlen(pszValue), pszValue);
   10908          86 :         NCDF_ERR(status);
   10909             :     }
   10910             :     else
   10911             :     {
   10912          20 :         switch (nAttrType)
   10913             :         {
   10914          11 :             case NC_INT:
   10915             :             {
   10916             :                 int *pnTemp =
   10917          11 :                     static_cast<int *>(CPLCalloc(nAttrLen, sizeof(int)));
   10918          30 :                 for (size_t i = 0; i < nAttrLen; i++)
   10919             :                 {
   10920          19 :                     pnTemp[i] =
   10921          19 :                         static_cast<int>(strtol(papszValues[i], &pszTemp, 10));
   10922             :                 }
   10923          11 :                 status = nc_put_att_int(nCdfId, nVarId, pszAttrName, NC_INT,
   10924             :                                         nAttrLen, pnTemp);
   10925          11 :                 NCDF_ERR(status);
   10926          11 :                 CPLFree(pnTemp);
   10927          11 :                 break;
   10928             :             }
   10929           0 :             case NC_UINT:
   10930             :             {
   10931             :                 unsigned int *punTemp = static_cast<unsigned int *>(
   10932           0 :                     CPLCalloc(nAttrLen, sizeof(unsigned int)));
   10933           0 :                 for (size_t i = 0; i < nAttrLen; i++)
   10934             :                 {
   10935           0 :                     punTemp[i] = static_cast<unsigned int>(
   10936           0 :                         strtol(papszValues[i], &pszTemp, 10));
   10937             :                 }
   10938           0 :                 status = nc_put_att_uint(nCdfId, nVarId, pszAttrName, NC_UINT,
   10939             :                                          nAttrLen, punTemp);
   10940           0 :                 NCDF_ERR(status);
   10941           0 :                 CPLFree(punTemp);
   10942           0 :                 break;
   10943             :             }
   10944           6 :             case NC_FLOAT:
   10945             :             {
   10946             :                 float *pfTemp =
   10947           6 :                     static_cast<float *>(CPLCalloc(nAttrLen, sizeof(float)));
   10948          14 :                 for (size_t i = 0; i < nAttrLen; i++)
   10949             :                 {
   10950           8 :                     pfTemp[i] =
   10951           8 :                         static_cast<float>(CPLStrtod(papszValues[i], &pszTemp));
   10952             :                 }
   10953           6 :                 status = nc_put_att_float(nCdfId, nVarId, pszAttrName, NC_FLOAT,
   10954             :                                           nAttrLen, pfTemp);
   10955           6 :                 NCDF_ERR(status);
   10956           6 :                 CPLFree(pfTemp);
   10957           6 :                 break;
   10958             :             }
   10959           3 :             case NC_DOUBLE:
   10960             :             {
   10961             :                 double *pdfTemp =
   10962           3 :                     static_cast<double *>(CPLCalloc(nAttrLen, sizeof(double)));
   10963           9 :                 for (size_t i = 0; i < nAttrLen; i++)
   10964             :                 {
   10965           6 :                     pdfTemp[i] = CPLStrtod(papszValues[i], &pszTemp);
   10966             :                 }
   10967           3 :                 status = nc_put_att_double(nCdfId, nVarId, pszAttrName,
   10968             :                                            NC_DOUBLE, nAttrLen, pdfTemp);
   10969           3 :                 NCDF_ERR(status);
   10970           3 :                 CPLFree(pdfTemp);
   10971           3 :                 break;
   10972             :             }
   10973           0 :             default:
   10974           0 :                 if (papszValues)
   10975           0 :                     CSLDestroy(papszValues);
   10976           0 :                 return CE_Failure;
   10977             :         }
   10978             :     }
   10979             : 
   10980         106 :     if (papszValues)
   10981         106 :         CSLDestroy(papszValues);
   10982             : 
   10983         106 :     return CE_None;
   10984             : }
   10985             : 
   10986          78 : static CPLErr NCDFGet1DVar(int nCdfId, int nVarId, char **pszValue)
   10987             : {
   10988             :     /* get var information */
   10989          78 :     int nVarDimId = -1;
   10990          78 :     int status = nc_inq_varndims(nCdfId, nVarId, &nVarDimId);
   10991          78 :     if (status != NC_NOERR || nVarDimId != 1)
   10992           0 :         return CE_Failure;
   10993             : 
   10994          78 :     status = nc_inq_vardimid(nCdfId, nVarId, &nVarDimId);
   10995          78 :     if (status != NC_NOERR)
   10996           0 :         return CE_Failure;
   10997             : 
   10998          78 :     nc_type nVarType = NC_NAT;
   10999          78 :     status = nc_inq_vartype(nCdfId, nVarId, &nVarType);
   11000          78 :     if (status != NC_NOERR)
   11001           0 :         return CE_Failure;
   11002             : 
   11003          78 :     size_t nVarLen = 0;
   11004          78 :     status = nc_inq_dimlen(nCdfId, nVarDimId, &nVarLen);
   11005          78 :     if (status != NC_NOERR)
   11006           0 :         return CE_Failure;
   11007             : 
   11008          78 :     size_t start[1] = {0};
   11009          78 :     size_t count[1] = {nVarLen};
   11010             : 
   11011             :     /* Allocate guaranteed minimum size */
   11012          78 :     size_t nVarValueSize = NCDF_MAX_STR_LEN;
   11013             :     char *pszVarValue =
   11014          78 :         static_cast<char *>(CPLCalloc(nVarValueSize, sizeof(char)));
   11015          78 :     *pszVarValue = '\0';
   11016             : 
   11017          78 :     if (nVarLen == 0)
   11018             :     {
   11019             :         /* set return values */
   11020           1 :         *pszValue = pszVarValue;
   11021             : 
   11022           1 :         return CE_None;
   11023             :     }
   11024             : 
   11025          77 :     if (nVarLen > 1 && nVarType != NC_CHAR)
   11026          42 :         NCDFSafeStrcat(&pszVarValue, "{", &nVarValueSize);
   11027             : 
   11028          77 :     switch (nVarType)
   11029             :     {
   11030           0 :         case NC_CHAR:
   11031           0 :             nc_get_vara_text(nCdfId, nVarId, start, count, pszVarValue);
   11032           0 :             pszVarValue[nVarLen] = '\0';
   11033           0 :             break;
   11034           0 :         case NC_BYTE:
   11035             :         {
   11036             :             signed char *pscTemp = static_cast<signed char *>(
   11037           0 :                 CPLCalloc(nVarLen, sizeof(signed char)));
   11038           0 :             nc_get_vara_schar(nCdfId, nVarId, start, count, pscTemp);
   11039             :             char szTemp[256];
   11040           0 :             size_t m = 0;
   11041           0 :             for (; m < nVarLen - 1; m++)
   11042             :             {
   11043           0 :                 snprintf(szTemp, sizeof(szTemp), "%d,", pscTemp[m]);
   11044           0 :                 NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11045             :             }
   11046           0 :             snprintf(szTemp, sizeof(szTemp), "%d", pscTemp[m]);
   11047           0 :             NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11048           0 :             CPLFree(pscTemp);
   11049           0 :             break;
   11050             :         }
   11051           0 :         case NC_SHORT:
   11052             :         {
   11053             :             short *psTemp =
   11054           0 :                 static_cast<short *>(CPLCalloc(nVarLen, sizeof(short)));
   11055           0 :             nc_get_vara_short(nCdfId, nVarId, start, count, psTemp);
   11056             :             char szTemp[256];
   11057           0 :             size_t m = 0;
   11058           0 :             for (; m < nVarLen - 1; m++)
   11059             :             {
   11060           0 :                 snprintf(szTemp, sizeof(szTemp), "%d,", psTemp[m]);
   11061           0 :                 NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11062             :             }
   11063           0 :             snprintf(szTemp, sizeof(szTemp), "%d", psTemp[m]);
   11064           0 :             NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11065           0 :             CPLFree(psTemp);
   11066           0 :             break;
   11067             :         }
   11068          21 :         case NC_INT:
   11069             :         {
   11070          21 :             int *pnTemp = static_cast<int *>(CPLCalloc(nVarLen, sizeof(int)));
   11071          21 :             nc_get_vara_int(nCdfId, nVarId, start, count, pnTemp);
   11072             :             char szTemp[256];
   11073          21 :             size_t m = 0;
   11074          44 :             for (; m < nVarLen - 1; m++)
   11075             :             {
   11076          23 :                 snprintf(szTemp, sizeof(szTemp), "%d,", pnTemp[m]);
   11077          23 :                 NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11078             :             }
   11079          21 :             snprintf(szTemp, sizeof(szTemp), "%d", pnTemp[m]);
   11080          21 :             NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11081          21 :             CPLFree(pnTemp);
   11082          21 :             break;
   11083             :         }
   11084           8 :         case NC_FLOAT:
   11085             :         {
   11086             :             float *pfTemp =
   11087           8 :                 static_cast<float *>(CPLCalloc(nVarLen, sizeof(float)));
   11088           8 :             nc_get_vara_float(nCdfId, nVarId, start, count, pfTemp);
   11089             :             char szTemp[256];
   11090           8 :             size_t m = 0;
   11091         325 :             for (; m < nVarLen - 1; m++)
   11092             :             {
   11093         317 :                 CPLsnprintf(szTemp, sizeof(szTemp), "%.8g,", pfTemp[m]);
   11094         317 :                 NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11095             :             }
   11096           8 :             CPLsnprintf(szTemp, sizeof(szTemp), "%.8g", pfTemp[m]);
   11097           8 :             NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11098           8 :             CPLFree(pfTemp);
   11099           8 :             break;
   11100             :         }
   11101          47 :         case NC_DOUBLE:
   11102             :         {
   11103             :             double *pdfTemp =
   11104          47 :                 static_cast<double *>(CPLCalloc(nVarLen, sizeof(double)));
   11105          47 :             nc_get_vara_double(nCdfId, nVarId, start, count, pdfTemp);
   11106             :             char szTemp[256];
   11107          47 :             size_t m = 0;
   11108         225 :             for (; m < nVarLen - 1; m++)
   11109             :             {
   11110         178 :                 CPLsnprintf(szTemp, sizeof(szTemp), "%.16g,", pdfTemp[m]);
   11111         178 :                 NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11112             :             }
   11113          47 :             CPLsnprintf(szTemp, sizeof(szTemp), "%.16g", pdfTemp[m]);
   11114          47 :             NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11115          47 :             CPLFree(pdfTemp);
   11116          47 :             break;
   11117             :         }
   11118           0 :         case NC_STRING:
   11119             :         {
   11120             :             char **ppszTemp =
   11121           0 :                 static_cast<char **>(CPLCalloc(nVarLen, sizeof(char *)));
   11122           0 :             nc_get_vara_string(nCdfId, nVarId, start, count, ppszTemp);
   11123           0 :             size_t m = 0;
   11124           0 :             for (; m < nVarLen - 1; m++)
   11125             :             {
   11126           0 :                 NCDFSafeStrcat(&pszVarValue, ppszTemp[m], &nVarValueSize);
   11127           0 :                 NCDFSafeStrcat(&pszVarValue, ",", &nVarValueSize);
   11128             :             }
   11129           0 :             NCDFSafeStrcat(&pszVarValue, ppszTemp[m], &nVarValueSize);
   11130           0 :             nc_free_string(nVarLen, ppszTemp);
   11131           0 :             CPLFree(ppszTemp);
   11132           0 :             break;
   11133             :         }
   11134           0 :         case NC_UBYTE:
   11135             :         {
   11136             :             unsigned char *pucTemp;
   11137             :             pucTemp = static_cast<unsigned char *>(
   11138           0 :                 CPLCalloc(nVarLen, sizeof(unsigned char)));
   11139           0 :             nc_get_vara_uchar(nCdfId, nVarId, start, count, pucTemp);
   11140             :             char szTemp[256];
   11141           0 :             size_t m = 0;
   11142           0 :             for (; m < nVarLen - 1; m++)
   11143             :             {
   11144           0 :                 CPLsnprintf(szTemp, sizeof(szTemp), "%u,", pucTemp[m]);
   11145           0 :                 NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11146             :             }
   11147           0 :             CPLsnprintf(szTemp, sizeof(szTemp), "%u", pucTemp[m]);
   11148           0 :             NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11149           0 :             CPLFree(pucTemp);
   11150           0 :             break;
   11151             :         }
   11152           0 :         case NC_USHORT:
   11153             :         {
   11154             :             unsigned short *pusTemp;
   11155             :             pusTemp = static_cast<unsigned short *>(
   11156           0 :                 CPLCalloc(nVarLen, sizeof(unsigned short)));
   11157           0 :             nc_get_vara_ushort(nCdfId, nVarId, start, count, pusTemp);
   11158             :             char szTemp[256];
   11159           0 :             size_t m = 0;
   11160           0 :             for (; m < nVarLen - 1; m++)
   11161             :             {
   11162           0 :                 CPLsnprintf(szTemp, sizeof(szTemp), "%u,", pusTemp[m]);
   11163           0 :                 NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11164             :             }
   11165           0 :             CPLsnprintf(szTemp, sizeof(szTemp), "%u", pusTemp[m]);
   11166           0 :             NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11167           0 :             CPLFree(pusTemp);
   11168           0 :             break;
   11169             :         }
   11170           0 :         case NC_UINT:
   11171             :         {
   11172             :             unsigned int *punTemp;
   11173             :             punTemp = static_cast<unsigned int *>(
   11174           0 :                 CPLCalloc(nVarLen, sizeof(unsigned int)));
   11175           0 :             nc_get_vara_uint(nCdfId, nVarId, start, count, punTemp);
   11176             :             char szTemp[256];
   11177           0 :             size_t m = 0;
   11178           0 :             for (; m < nVarLen - 1; m++)
   11179             :             {
   11180           0 :                 CPLsnprintf(szTemp, sizeof(szTemp), "%u,", punTemp[m]);
   11181           0 :                 NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11182             :             }
   11183           0 :             CPLsnprintf(szTemp, sizeof(szTemp), "%u", punTemp[m]);
   11184           0 :             NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11185           0 :             CPLFree(punTemp);
   11186           0 :             break;
   11187             :         }
   11188           1 :         case NC_INT64:
   11189             :         {
   11190             :             long long *pnTemp =
   11191           1 :                 static_cast<long long *>(CPLCalloc(nVarLen, sizeof(long long)));
   11192           1 :             nc_get_vara_longlong(nCdfId, nVarId, start, count, pnTemp);
   11193             :             char szTemp[256];
   11194           1 :             size_t m = 0;
   11195           2 :             for (; m < nVarLen - 1; m++)
   11196             :             {
   11197           1 :                 snprintf(szTemp, sizeof(szTemp), CPL_FRMT_GIB ",", pnTemp[m]);
   11198           1 :                 NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11199             :             }
   11200           1 :             snprintf(szTemp, sizeof(szTemp), CPL_FRMT_GIB, pnTemp[m]);
   11201           1 :             NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11202           1 :             CPLFree(pnTemp);
   11203           1 :             break;
   11204             :         }
   11205           0 :         case NC_UINT64:
   11206             :         {
   11207             :             unsigned long long *pnTemp = static_cast<unsigned long long *>(
   11208           0 :                 CPLCalloc(nVarLen, sizeof(unsigned long long)));
   11209           0 :             nc_get_vara_ulonglong(nCdfId, nVarId, start, count, pnTemp);
   11210             :             char szTemp[256];
   11211           0 :             size_t m = 0;
   11212           0 :             for (; m < nVarLen - 1; m++)
   11213             :             {
   11214           0 :                 snprintf(szTemp, sizeof(szTemp), CPL_FRMT_GUIB ",", pnTemp[m]);
   11215           0 :                 NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11216             :             }
   11217           0 :             snprintf(szTemp, sizeof(szTemp), CPL_FRMT_GUIB, pnTemp[m]);
   11218           0 :             NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
   11219           0 :             CPLFree(pnTemp);
   11220           0 :             break;
   11221             :         }
   11222           0 :         default:
   11223           0 :             CPLDebug("GDAL_netCDF", "NCDFGetVar1D unsupported type %d",
   11224             :                      nVarType);
   11225           0 :             CPLFree(pszVarValue);
   11226           0 :             pszVarValue = nullptr;
   11227           0 :             break;
   11228             :     }
   11229             : 
   11230          77 :     if (pszVarValue != nullptr && nVarLen > 1 && nVarType != NC_CHAR)
   11231          42 :         NCDFSafeStrcat(&pszVarValue, "}", &nVarValueSize);
   11232             : 
   11233             :     /* set return values */
   11234          77 :     *pszValue = pszVarValue;
   11235             : 
   11236          77 :     return CE_None;
   11237             : }
   11238             : 
   11239           8 : static CPLErr NCDFPut1DVar(int nCdfId, int nVarId, const char *pszValue)
   11240             : {
   11241           8 :     if (EQUAL(pszValue, ""))
   11242           0 :         return CE_Failure;
   11243             : 
   11244             :     /* get var information */
   11245           8 :     int nVarDimId = -1;
   11246           8 :     int status = nc_inq_varndims(nCdfId, nVarId, &nVarDimId);
   11247           8 :     if (status != NC_NOERR || nVarDimId != 1)
   11248           0 :         return CE_Failure;
   11249             : 
   11250           8 :     status = nc_inq_vardimid(nCdfId, nVarId, &nVarDimId);
   11251           8 :     if (status != NC_NOERR)
   11252           0 :         return CE_Failure;
   11253             : 
   11254           8 :     nc_type nVarType = NC_CHAR;
   11255           8 :     status = nc_inq_vartype(nCdfId, nVarId, &nVarType);
   11256           8 :     if (status != NC_NOERR)
   11257           0 :         return CE_Failure;
   11258             : 
   11259           8 :     size_t nVarLen = 0;
   11260           8 :     status = nc_inq_dimlen(nCdfId, nVarDimId, &nVarLen);
   11261           8 :     if (status != NC_NOERR)
   11262           0 :         return CE_Failure;
   11263             : 
   11264           8 :     size_t start[1] = {0};
   11265           8 :     size_t count[1] = {nVarLen};
   11266             : 
   11267             :     /* get the values as tokens */
   11268           8 :     char **papszValues = NCDFTokenizeArray(pszValue);
   11269           8 :     if (papszValues == nullptr)
   11270           0 :         return CE_Failure;
   11271             : 
   11272           8 :     nVarLen = CSLCount(papszValues);
   11273             : 
   11274             :     /* now write the data */
   11275           8 :     if (nVarType == NC_CHAR)
   11276             :     {
   11277           0 :         status = nc_put_vara_text(nCdfId, nVarId, start, count, pszValue);
   11278           0 :         NCDF_ERR(status);
   11279             :     }
   11280             :     else
   11281             :     {
   11282           8 :         switch (nVarType)
   11283             :         {
   11284           0 :             case NC_BYTE:
   11285             :             {
   11286             :                 signed char *pscTemp = static_cast<signed char *>(
   11287           0 :                     CPLCalloc(nVarLen, sizeof(signed char)));
   11288           0 :                 for (size_t i = 0; i < nVarLen; i++)
   11289             :                 {
   11290           0 :                     char *pszTemp = nullptr;
   11291           0 :                     pscTemp[i] = static_cast<signed char>(
   11292           0 :                         strtol(papszValues[i], &pszTemp, 10));
   11293             :                 }
   11294             :                 status =
   11295           0 :                     nc_put_vara_schar(nCdfId, nVarId, start, count, pscTemp);
   11296           0 :                 NCDF_ERR(status);
   11297           0 :                 CPLFree(pscTemp);
   11298           0 :                 break;
   11299             :             }
   11300           0 :             case NC_SHORT:
   11301             :             {
   11302             :                 short *psTemp =
   11303           0 :                     static_cast<short *>(CPLCalloc(nVarLen, sizeof(short)));
   11304           0 :                 for (size_t i = 0; i < nVarLen; i++)
   11305             :                 {
   11306           0 :                     char *pszTemp = nullptr;
   11307           0 :                     psTemp[i] = static_cast<short>(
   11308           0 :                         strtol(papszValues[i], &pszTemp, 10));
   11309             :                 }
   11310             :                 status =
   11311           0 :                     nc_put_vara_short(nCdfId, nVarId, start, count, psTemp);
   11312           0 :                 NCDF_ERR(status);
   11313           0 :                 CPLFree(psTemp);
   11314           0 :                 break;
   11315             :             }
   11316           3 :             case NC_INT:
   11317             :             {
   11318             :                 int *pnTemp =
   11319           3 :                     static_cast<int *>(CPLCalloc(nVarLen, sizeof(int)));
   11320          11 :                 for (size_t i = 0; i < nVarLen; i++)
   11321             :                 {
   11322           8 :                     char *pszTemp = nullptr;
   11323           8 :                     pnTemp[i] =
   11324           8 :                         static_cast<int>(strtol(papszValues[i], &pszTemp, 10));
   11325             :                 }
   11326           3 :                 status = nc_put_vara_int(nCdfId, nVarId, start, count, pnTemp);
   11327           3 :                 NCDF_ERR(status);
   11328           3 :                 CPLFree(pnTemp);
   11329           3 :                 break;
   11330             :             }
   11331           0 :             case NC_FLOAT:
   11332             :             {
   11333             :                 float *pfTemp =
   11334           0 :                     static_cast<float *>(CPLCalloc(nVarLen, sizeof(float)));
   11335           0 :                 for (size_t i = 0; i < nVarLen; i++)
   11336             :                 {
   11337           0 :                     char *pszTemp = nullptr;
   11338           0 :                     pfTemp[i] =
   11339           0 :                         static_cast<float>(CPLStrtod(papszValues[i], &pszTemp));
   11340             :                 }
   11341             :                 status =
   11342           0 :                     nc_put_vara_float(nCdfId, nVarId, start, count, pfTemp);
   11343           0 :                 NCDF_ERR(status);
   11344           0 :                 CPLFree(pfTemp);
   11345           0 :                 break;
   11346             :             }
   11347           5 :             case NC_DOUBLE:
   11348             :             {
   11349             :                 double *pdfTemp =
   11350           5 :                     static_cast<double *>(CPLCalloc(nVarLen, sizeof(double)));
   11351          19 :                 for (size_t i = 0; i < nVarLen; i++)
   11352             :                 {
   11353          14 :                     char *pszTemp = nullptr;
   11354          14 :                     pdfTemp[i] = CPLStrtod(papszValues[i], &pszTemp);
   11355             :                 }
   11356             :                 status =
   11357           5 :                     nc_put_vara_double(nCdfId, nVarId, start, count, pdfTemp);
   11358           5 :                 NCDF_ERR(status);
   11359           5 :                 CPLFree(pdfTemp);
   11360           5 :                 break;
   11361             :             }
   11362           0 :             default:
   11363             :             {
   11364           0 :                 int nTmpFormat = 0;
   11365           0 :                 status = nc_inq_format(nCdfId, &nTmpFormat);
   11366           0 :                 NCDF_ERR(status);
   11367           0 :                 if (nTmpFormat == NCDF_FORMAT_NC4)
   11368             :                 {
   11369           0 :                     switch (nVarType)
   11370             :                     {
   11371           0 :                         case NC_STRING:
   11372             :                         {
   11373             :                             status =
   11374           0 :                                 nc_put_vara_string(nCdfId, nVarId, start, count,
   11375             :                                                    (const char **)papszValues);
   11376           0 :                             NCDF_ERR(status);
   11377           0 :                             break;
   11378             :                         }
   11379           0 :                         case NC_UBYTE:
   11380             :                         {
   11381             :                             unsigned char *pucTemp =
   11382             :                                 static_cast<unsigned char *>(
   11383           0 :                                     CPLCalloc(nVarLen, sizeof(unsigned char)));
   11384           0 :                             for (size_t i = 0; i < nVarLen; i++)
   11385             :                             {
   11386           0 :                                 char *pszTemp = nullptr;
   11387           0 :                                 pucTemp[i] = static_cast<unsigned char>(
   11388           0 :                                     strtoul(papszValues[i], &pszTemp, 10));
   11389             :                             }
   11390           0 :                             status = nc_put_vara_uchar(nCdfId, nVarId, start,
   11391             :                                                        count, pucTemp);
   11392           0 :                             NCDF_ERR(status);
   11393           0 :                             CPLFree(pucTemp);
   11394           0 :                             break;
   11395             :                         }
   11396           0 :                         case NC_USHORT:
   11397             :                         {
   11398             :                             unsigned short *pusTemp =
   11399             :                                 static_cast<unsigned short *>(
   11400           0 :                                     CPLCalloc(nVarLen, sizeof(unsigned short)));
   11401           0 :                             for (size_t i = 0; i < nVarLen; i++)
   11402             :                             {
   11403           0 :                                 char *pszTemp = nullptr;
   11404           0 :                                 pusTemp[i] = static_cast<unsigned short>(
   11405           0 :                                     strtoul(papszValues[i], &pszTemp, 10));
   11406             :                             }
   11407           0 :                             status = nc_put_vara_ushort(nCdfId, nVarId, start,
   11408             :                                                         count, pusTemp);
   11409           0 :                             NCDF_ERR(status);
   11410           0 :                             CPLFree(pusTemp);
   11411           0 :                             break;
   11412             :                         }
   11413           0 :                         case NC_UINT:
   11414             :                         {
   11415             :                             unsigned int *punTemp = static_cast<unsigned int *>(
   11416           0 :                                 CPLCalloc(nVarLen, sizeof(unsigned int)));
   11417           0 :                             for (size_t i = 0; i < nVarLen; i++)
   11418             :                             {
   11419           0 :                                 char *pszTemp = nullptr;
   11420           0 :                                 punTemp[i] = static_cast<unsigned int>(
   11421           0 :                                     strtoul(papszValues[i], &pszTemp, 10));
   11422             :                             }
   11423           0 :                             status = nc_put_vara_uint(nCdfId, nVarId, start,
   11424             :                                                       count, punTemp);
   11425           0 :                             NCDF_ERR(status);
   11426           0 :                             CPLFree(punTemp);
   11427           0 :                             break;
   11428             :                         }
   11429           0 :                         default:
   11430           0 :                             if (papszValues)
   11431           0 :                                 CSLDestroy(papszValues);
   11432           0 :                             return CE_Failure;
   11433             :                     }
   11434             :                 }
   11435           0 :                 break;
   11436             :             }
   11437             :         }
   11438             :     }
   11439             : 
   11440           8 :     if (papszValues)
   11441           8 :         CSLDestroy(papszValues);
   11442             : 
   11443           8 :     return CE_None;
   11444             : }
   11445             : 
   11446             : /************************************************************************/
   11447             : /*                           GetDefaultNoDataValue()                    */
   11448             : /************************************************************************/
   11449             : 
   11450         196 : double NCDFGetDefaultNoDataValue(int nCdfId, int nVarId, int nVarType,
   11451             :                                  bool &bGotNoData)
   11452             : 
   11453             : {
   11454         196 :     int nNoFill = 0;
   11455         196 :     double dfNoData = 0.0;
   11456             : 
   11457         196 :     switch (nVarType)
   11458             :     {
   11459           0 :         case NC_CHAR:
   11460             :         case NC_BYTE:
   11461             :         case NC_UBYTE:
   11462             :             // Don't do default fill-values for bytes, too risky.
   11463             :             // This function should not be called in those cases.
   11464           0 :             CPLAssert(false);
   11465             :             break;
   11466          24 :         case NC_SHORT:
   11467             :         {
   11468          24 :             short nFillVal = 0;
   11469          24 :             if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) ==
   11470             :                 NC_NOERR)
   11471             :             {
   11472          24 :                 if (!nNoFill)
   11473             :                 {
   11474          23 :                     bGotNoData = true;
   11475          23 :                     dfNoData = nFillVal;
   11476             :                 }
   11477             :             }
   11478             :             else
   11479           0 :                 dfNoData = NC_FILL_SHORT;
   11480          24 :             break;
   11481             :         }
   11482          26 :         case NC_INT:
   11483             :         {
   11484          26 :             int nFillVal = 0;
   11485          26 :             if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) ==
   11486             :                 NC_NOERR)
   11487             :             {
   11488          26 :                 if (!nNoFill)
   11489             :                 {
   11490          25 :                     bGotNoData = true;
   11491          25 :                     dfNoData = nFillVal;
   11492             :                 }
   11493             :             }
   11494             :             else
   11495           0 :                 dfNoData = NC_FILL_INT;
   11496          26 :             break;
   11497             :         }
   11498          79 :         case NC_FLOAT:
   11499             :         {
   11500          79 :             float fFillVal = 0;
   11501          79 :             if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &fFillVal) ==
   11502             :                 NC_NOERR)
   11503             :             {
   11504          79 :                 if (!nNoFill)
   11505             :                 {
   11506          75 :                     bGotNoData = true;
   11507          75 :                     dfNoData = fFillVal;
   11508             :                 }
   11509             :             }
   11510             :             else
   11511           0 :                 dfNoData = NC_FILL_FLOAT;
   11512          79 :             break;
   11513             :         }
   11514          34 :         case NC_DOUBLE:
   11515             :         {
   11516          34 :             if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &dfNoData) ==
   11517             :                 NC_NOERR)
   11518             :             {
   11519          34 :                 if (!nNoFill)
   11520             :                 {
   11521          34 :                     bGotNoData = true;
   11522             :                 }
   11523             :             }
   11524             :             else
   11525           0 :                 dfNoData = NC_FILL_DOUBLE;
   11526          34 :             break;
   11527             :         }
   11528           7 :         case NC_USHORT:
   11529             :         {
   11530           7 :             unsigned short nFillVal = 0;
   11531           7 :             if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) ==
   11532             :                 NC_NOERR)
   11533             :             {
   11534           7 :                 if (!nNoFill)
   11535             :                 {
   11536           7 :                     bGotNoData = true;
   11537           7 :                     dfNoData = nFillVal;
   11538             :                 }
   11539             :             }
   11540             :             else
   11541           0 :                 dfNoData = NC_FILL_USHORT;
   11542           7 :             break;
   11543             :         }
   11544           7 :         case NC_UINT:
   11545             :         {
   11546           7 :             unsigned int nFillVal = 0;
   11547           7 :             if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) ==
   11548             :                 NC_NOERR)
   11549             :             {
   11550           7 :                 if (!nNoFill)
   11551             :                 {
   11552           7 :                     bGotNoData = true;
   11553           7 :                     dfNoData = nFillVal;
   11554             :                 }
   11555             :             }
   11556             :             else
   11557           0 :                 dfNoData = NC_FILL_UINT;
   11558           7 :             break;
   11559             :         }
   11560          19 :         default:
   11561          19 :             dfNoData = 0.0;
   11562          19 :             break;
   11563             :     }
   11564             : 
   11565         196 :     return dfNoData;
   11566             : }
   11567             : 
   11568             : /************************************************************************/
   11569             : /*                      NCDFGetDefaultNoDataValueAsInt64()              */
   11570             : /************************************************************************/
   11571             : 
   11572           2 : int64_t NCDFGetDefaultNoDataValueAsInt64(int nCdfId, int nVarId,
   11573             :                                          bool &bGotNoData)
   11574             : 
   11575             : {
   11576           2 :     int nNoFill = 0;
   11577           2 :     long long nFillVal = 0;
   11578           2 :     if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) == NC_NOERR)
   11579             :     {
   11580           2 :         if (!nNoFill)
   11581             :         {
   11582           2 :             bGotNoData = true;
   11583           2 :             return static_cast<int64_t>(nFillVal);
   11584             :         }
   11585             :     }
   11586             :     else
   11587           0 :         return static_cast<int64_t>(NC_FILL_INT64);
   11588           0 :     return 0;
   11589             : }
   11590             : 
   11591             : /************************************************************************/
   11592             : /*                     NCDFGetDefaultNoDataValueAsUInt64()              */
   11593             : /************************************************************************/
   11594             : 
   11595           1 : uint64_t NCDFGetDefaultNoDataValueAsUInt64(int nCdfId, int nVarId,
   11596             :                                            bool &bGotNoData)
   11597             : 
   11598             : {
   11599           1 :     int nNoFill = 0;
   11600           1 :     unsigned long long nFillVal = 0;
   11601           1 :     if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) == NC_NOERR)
   11602             :     {
   11603           1 :         if (!nNoFill)
   11604             :         {
   11605           1 :             bGotNoData = true;
   11606           1 :             return static_cast<uint64_t>(nFillVal);
   11607             :         }
   11608             :     }
   11609             :     else
   11610           0 :         return static_cast<uint64_t>(NC_FILL_UINT64);
   11611           0 :     return 0;
   11612             : }
   11613             : 
   11614       11152 : static int NCDFDoesVarContainAttribVal(int nCdfId,
   11615             :                                        const char *const *papszAttribNames,
   11616             :                                        const char *const *papszAttribValues,
   11617             :                                        int nVarId, const char *pszVarName,
   11618             :                                        bool bStrict = true)
   11619             : {
   11620       11152 :     if (nVarId == -1 && pszVarName != nullptr)
   11621        8156 :         NCDFResolveVar(nCdfId, pszVarName, &nCdfId, &nVarId);
   11622             : 
   11623       11152 :     if (nVarId == -1)
   11624         878 :         return -1;
   11625             : 
   11626       10274 :     bool bFound = false;
   11627       47959 :     for (int i = 0; !bFound && papszAttribNames != nullptr &&
   11628       45679 :                     papszAttribNames[i] != nullptr;
   11629             :          i++)
   11630             :     {
   11631       37685 :         char *pszTemp = nullptr;
   11632       37685 :         if (NCDFGetAttr(nCdfId, nVarId, papszAttribNames[i], &pszTemp) ==
   11633       54137 :                 CE_None &&
   11634       16452 :             pszTemp != nullptr)
   11635             :         {
   11636       16452 :             if (bStrict)
   11637             :             {
   11638       16452 :                 if (EQUAL(pszTemp, papszAttribValues[i]))
   11639        2280 :                     bFound = true;
   11640             :             }
   11641             :             else
   11642             :             {
   11643           0 :                 if (EQUALN(pszTemp, papszAttribValues[i],
   11644             :                            strlen(papszAttribValues[i])))
   11645           0 :                     bFound = true;
   11646             :             }
   11647       16452 :             CPLFree(pszTemp);
   11648             :         }
   11649             :     }
   11650       10274 :     return bFound;
   11651             : }
   11652             : 
   11653        1962 : static int NCDFDoesVarContainAttribVal2(int nCdfId, const char *papszAttribName,
   11654             :                                         const char *const *papszAttribValues,
   11655             :                                         int nVarId, const char *pszVarName,
   11656             :                                         int bStrict = true)
   11657             : {
   11658        1962 :     if (nVarId == -1 && pszVarName != nullptr)
   11659        1579 :         NCDFResolveVar(nCdfId, pszVarName, &nCdfId, &nVarId);
   11660             : 
   11661        1962 :     if (nVarId == -1)
   11662           0 :         return -1;
   11663             : 
   11664        1962 :     bool bFound = false;
   11665        1962 :     char *pszTemp = nullptr;
   11666        2341 :     if (NCDFGetAttr(nCdfId, nVarId, papszAttribName, &pszTemp) != CE_None ||
   11667         379 :         pszTemp == nullptr)
   11668        1583 :         return FALSE;
   11669             : 
   11670        7703 :     for (int i = 0; !bFound && i < CSLCount(papszAttribValues); i++)
   11671             :     {
   11672        7324 :         if (bStrict)
   11673             :         {
   11674        7296 :             if (EQUAL(pszTemp, papszAttribValues[i]))
   11675          31 :                 bFound = true;
   11676             :         }
   11677             :         else
   11678             :         {
   11679          28 :             if (EQUALN(pszTemp, papszAttribValues[i],
   11680             :                        strlen(papszAttribValues[i])))
   11681           0 :                 bFound = true;
   11682             :         }
   11683             :     }
   11684             : 
   11685         379 :     CPLFree(pszTemp);
   11686             : 
   11687         379 :     return bFound;
   11688             : }
   11689             : 
   11690         876 : static bool NCDFEqual(const char *papszName, const char *const *papszValues)
   11691             : {
   11692         876 :     if (papszName == nullptr || EQUAL(papszName, ""))
   11693           0 :         return false;
   11694             : 
   11695        2392 :     for (int i = 0; papszValues && papszValues[i]; ++i)
   11696             :     {
   11697        1636 :         if (EQUAL(papszName, papszValues[i]))
   11698         120 :             return true;
   11699             :     }
   11700             : 
   11701         756 :     return false;
   11702             : }
   11703             : 
   11704             : // Test that a variable is longitude/latitude coordinate,
   11705             : // following CF 4.1 and 4.2.
   11706        3816 : bool NCDFIsVarLongitude(int nCdfId, int nVarId, const char *pszVarName)
   11707             : {
   11708             :     // Check for matching attributes.
   11709        3816 :     int bVal = NCDFDoesVarContainAttribVal(nCdfId, papszCFLongitudeAttribNames,
   11710             :                                            papszCFLongitudeAttribValues, nVarId,
   11711             :                                            pszVarName);
   11712             :     // If not found using attributes then check using var name
   11713             :     // unless GDAL_NETCDF_VERIFY_DIMS=STRICT.
   11714        3816 :     if (bVal == -1)
   11715             :     {
   11716         280 :         if (!EQUAL(CPLGetConfigOption("GDAL_NETCDF_VERIFY_DIMS", "YES"),
   11717             :                    "STRICT"))
   11718         280 :             bVal = NCDFEqual(pszVarName, papszCFLongitudeVarNames);
   11719             :         else
   11720           0 :             bVal = FALSE;
   11721             :     }
   11722        3536 :     else if (bVal)
   11723             :     {
   11724             :         // Check that the units is not 'm' or '1'. See #6759
   11725         795 :         char *pszTemp = nullptr;
   11726        1175 :         if (NCDFGetAttr(nCdfId, nVarId, "units", &pszTemp) == CE_None &&
   11727         380 :             pszTemp != nullptr)
   11728             :         {
   11729         380 :             if (EQUAL(pszTemp, "m") || EQUAL(pszTemp, "1"))
   11730          97 :                 bVal = false;
   11731         380 :             CPLFree(pszTemp);
   11732             :         }
   11733             :     }
   11734             : 
   11735        3816 :     return CPL_TO_BOOL(bVal);
   11736             : }
   11737             : 
   11738        2178 : bool NCDFIsVarLatitude(int nCdfId, int nVarId, const char *pszVarName)
   11739             : {
   11740        2178 :     int bVal = NCDFDoesVarContainAttribVal(nCdfId, papszCFLatitudeAttribNames,
   11741             :                                            papszCFLatitudeAttribValues, nVarId,
   11742             :                                            pszVarName);
   11743        2178 :     if (bVal == -1)
   11744             :     {
   11745         163 :         if (!EQUAL(CPLGetConfigOption("GDAL_NETCDF_VERIFY_DIMS", "YES"),
   11746             :                    "STRICT"))
   11747         163 :             bVal = NCDFEqual(pszVarName, papszCFLatitudeVarNames);
   11748             :         else
   11749           0 :             bVal = FALSE;
   11750             :     }
   11751        2015 :     else if (bVal)
   11752             :     {
   11753             :         // Check that the units is not 'm' or '1'. See #6759
   11754         548 :         char *pszTemp = nullptr;
   11755         690 :         if (NCDFGetAttr(nCdfId, nVarId, "units", &pszTemp) == CE_None &&
   11756         142 :             pszTemp != nullptr)
   11757             :         {
   11758         142 :             if (EQUAL(pszTemp, "m") || EQUAL(pszTemp, "1"))
   11759          36 :                 bVal = false;
   11760         142 :             CPLFree(pszTemp);
   11761             :         }
   11762             :     }
   11763             : 
   11764        2178 :     return CPL_TO_BOOL(bVal);
   11765             : }
   11766             : 
   11767        2305 : bool NCDFIsVarProjectionX(int nCdfId, int nVarId, const char *pszVarName)
   11768             : {
   11769        2305 :     int bVal = NCDFDoesVarContainAttribVal(
   11770             :         nCdfId, papszCFProjectionXAttribNames, papszCFProjectionXAttribValues,
   11771             :         nVarId, pszVarName);
   11772        2305 :     if (bVal == -1)
   11773             :     {
   11774         274 :         if (!EQUAL(CPLGetConfigOption("GDAL_NETCDF_VERIFY_DIMS", "YES"),
   11775             :                    "STRICT"))
   11776         274 :             bVal = NCDFEqual(pszVarName, papszCFProjectionXVarNames);
   11777             :         else
   11778           0 :             bVal = FALSE;
   11779             :     }
   11780        2031 :     else if (bVal)
   11781             :     {
   11782             :         // Check that the units is not '1'
   11783         381 :         char *pszTemp = nullptr;
   11784         544 :         if (NCDFGetAttr(nCdfId, nVarId, "units", &pszTemp) == CE_None &&
   11785         163 :             pszTemp != nullptr)
   11786             :         {
   11787         163 :             if (EQUAL(pszTemp, "1"))
   11788           5 :                 bVal = false;
   11789         163 :             CPLFree(pszTemp);
   11790             :         }
   11791             :     }
   11792             : 
   11793        2305 :     return CPL_TO_BOOL(bVal);
   11794             : }
   11795             : 
   11796        1629 : bool NCDFIsVarProjectionY(int nCdfId, int nVarId, const char *pszVarName)
   11797             : {
   11798        1629 :     int bVal = NCDFDoesVarContainAttribVal(
   11799             :         nCdfId, papszCFProjectionYAttribNames, papszCFProjectionYAttribValues,
   11800             :         nVarId, pszVarName);
   11801        1629 :     if (bVal == -1)
   11802             :     {
   11803         159 :         if (!EQUAL(CPLGetConfigOption("GDAL_NETCDF_VERIFY_DIMS", "YES"),
   11804             :                    "STRICT"))
   11805         159 :             bVal = NCDFEqual(pszVarName, papszCFProjectionYVarNames);
   11806             :         else
   11807           0 :             bVal = FALSE;
   11808             :     }
   11809        1470 :     else if (bVal)
   11810             :     {
   11811             :         // Check that the units is not '1'
   11812         377 :         char *pszTemp = nullptr;
   11813         537 :         if (NCDFGetAttr(nCdfId, nVarId, "units", &pszTemp) == CE_None &&
   11814         160 :             pszTemp != nullptr)
   11815             :         {
   11816         160 :             if (EQUAL(pszTemp, "1"))
   11817           5 :                 bVal = false;
   11818         160 :             CPLFree(pszTemp);
   11819             :         }
   11820             :     }
   11821             : 
   11822        1629 :     return CPL_TO_BOOL(bVal);
   11823             : }
   11824             : 
   11825             : /* test that a variable is a vertical coordinate, following CF 4.3 */
   11826        1022 : bool NCDFIsVarVerticalCoord(int nCdfId, int nVarId, const char *pszVarName)
   11827             : {
   11828             :     /* check for matching attributes */
   11829        1022 :     if (NCDFDoesVarContainAttribVal(nCdfId, papszCFVerticalAttribNames,
   11830             :                                     papszCFVerticalAttribValues, nVarId,
   11831        1022 :                                     pszVarName))
   11832          72 :         return true;
   11833             :     /* check for matching units */
   11834         950 :     else if (NCDFDoesVarContainAttribVal2(nCdfId, CF_UNITS,
   11835             :                                           papszCFVerticalUnitsValues, nVarId,
   11836         950 :                                           pszVarName))
   11837          31 :         return true;
   11838             :     /* check for matching standard name */
   11839         919 :     else if (NCDFDoesVarContainAttribVal2(nCdfId, CF_STD_NAME,
   11840             :                                           papszCFVerticalStandardNameValues,
   11841         919 :                                           nVarId, pszVarName))
   11842           0 :         return true;
   11843             :     else
   11844         919 :         return false;
   11845             : }
   11846             : 
   11847             : /* test that a variable is a time coordinate, following CF 4.4 */
   11848         202 : bool NCDFIsVarTimeCoord(int nCdfId, int nVarId, const char *pszVarName)
   11849             : {
   11850             :     /* check for matching attributes */
   11851         202 :     if (NCDFDoesVarContainAttribVal(nCdfId, papszCFTimeAttribNames,
   11852             :                                     papszCFTimeAttribValues, nVarId,
   11853         202 :                                     pszVarName))
   11854         109 :         return true;
   11855             :     /* check for matching units */
   11856          93 :     else if (NCDFDoesVarContainAttribVal2(nCdfId, CF_UNITS,
   11857             :                                           papszCFTimeUnitsValues, nVarId,
   11858          93 :                                           pszVarName, false))
   11859           0 :         return true;
   11860             :     else
   11861          93 :         return false;
   11862             : }
   11863             : 
   11864             : // Parse a string, and return as a string list.
   11865             : // If it an array of the form {a,b}, then tokenize it.
   11866             : // Otherwise, return a copy.
   11867         188 : static char **NCDFTokenizeArray(const char *pszValue)
   11868             : {
   11869         188 :     if (pszValue == nullptr || EQUAL(pszValue, ""))
   11870          53 :         return nullptr;
   11871             : 
   11872         135 :     char **papszValues = nullptr;
   11873         135 :     const int nLen = static_cast<int>(strlen(pszValue));
   11874             : 
   11875         135 :     if (pszValue[0] == '{' && nLen > 2 && pszValue[nLen - 1] == '}')
   11876             :     {
   11877          41 :         char *pszTemp = static_cast<char *>(CPLMalloc((nLen - 2) + 1));
   11878          41 :         strncpy(pszTemp, pszValue + 1, nLen - 2);
   11879          41 :         pszTemp[nLen - 2] = '\0';
   11880          41 :         papszValues = CSLTokenizeString2(pszTemp, ",", CSLT_ALLOWEMPTYTOKENS);
   11881          41 :         CPLFree(pszTemp);
   11882             :     }
   11883             :     else
   11884             :     {
   11885          94 :         papszValues = static_cast<char **>(CPLCalloc(2, sizeof(char *)));
   11886          94 :         papszValues[0] = CPLStrdup(pszValue);
   11887          94 :         papszValues[1] = nullptr;
   11888             :     }
   11889             : 
   11890         135 :     return papszValues;
   11891             : }
   11892             : 
   11893             : // Open a NetCDF subdataset from full path /group1/group2/.../groupn/var.
   11894             : // Leading slash is optional.
   11895         415 : static CPLErr NCDFOpenSubDataset(int nCdfId, const char *pszSubdatasetName,
   11896             :                                  int *pnGroupId, int *pnVarId)
   11897             : {
   11898         415 :     *pnGroupId = -1;
   11899         415 :     *pnVarId = -1;
   11900             : 
   11901             :     // Open group.
   11902             :     char *pszGroupFullName =
   11903         415 :         CPLStrdup(CPLGetPathSafe(pszSubdatasetName).c_str());
   11904             :     // Add a leading slash if needed.
   11905         415 :     if (pszGroupFullName[0] != '/')
   11906             :     {
   11907         398 :         char *old = pszGroupFullName;
   11908         398 :         pszGroupFullName = CPLStrdup(CPLSPrintf("/%s", pszGroupFullName));
   11909         398 :         CPLFree(old);
   11910             :     }
   11911             :     // Detect root group.
   11912         415 :     if (EQUAL(pszGroupFullName, "/"))
   11913             :     {
   11914         398 :         *pnGroupId = nCdfId;
   11915         398 :         CPLFree(pszGroupFullName);
   11916             :     }
   11917             :     else
   11918             :     {
   11919          17 :         int status = nc_inq_grp_full_ncid(nCdfId, pszGroupFullName, pnGroupId);
   11920          17 :         CPLFree(pszGroupFullName);
   11921          17 :         NCDF_ERR_RET(status);
   11922             :     }
   11923             : 
   11924             :     // Open var.
   11925         415 :     const char *pszVarName = CPLGetFilename(pszSubdatasetName);
   11926         415 :     NCDF_ERR_RET(nc_inq_varid(*pnGroupId, pszVarName, pnVarId));
   11927             : 
   11928         415 :     return CE_None;
   11929             : }
   11930             : 
   11931             : // Get all dimensions visible from a given NetCDF (or group) ID and any of
   11932             : // its parents.
   11933         355 : static CPLErr NCDFGetVisibleDims(int nGroupId, int *pnDims, int **ppanDimIds)
   11934             : {
   11935         355 :     int nDims = 0;
   11936         355 :     int *panDimIds = nullptr;
   11937         355 :     NCDF_ERR_RET(nc_inq_dimids(nGroupId, &nDims, nullptr, true));
   11938             : 
   11939         355 :     panDimIds = static_cast<int *>(CPLMalloc(nDims * sizeof(int)));
   11940             : 
   11941         355 :     int status = nc_inq_dimids(nGroupId, nullptr, panDimIds, true);
   11942         355 :     if (status != NC_NOERR)
   11943           0 :         CPLFree(panDimIds);
   11944         355 :     NCDF_ERR_RET(status);
   11945             : 
   11946         355 :     *pnDims = nDims;
   11947         355 :     *ppanDimIds = panDimIds;
   11948             : 
   11949         355 :     return CE_None;
   11950             : }
   11951             : 
   11952             : // Get direct sub-groups IDs of a given NetCDF (or group) ID.
   11953             : // Consider only direct children, does not get children of children.
   11954        3111 : static CPLErr NCDFGetSubGroups(int nGroupId, int *pnSubGroups,
   11955             :                                int **ppanSubGroupIds)
   11956             : {
   11957        3111 :     *pnSubGroups = 0;
   11958        3111 :     *ppanSubGroupIds = nullptr;
   11959             : 
   11960             :     int nSubGroups;
   11961        3111 :     NCDF_ERR_RET(nc_inq_grps(nGroupId, &nSubGroups, nullptr));
   11962             :     int *panSubGroupIds =
   11963        3111 :         static_cast<int *>(CPLMalloc(nSubGroups * sizeof(int)));
   11964        3111 :     NCDF_ERR_RET(nc_inq_grps(nGroupId, nullptr, panSubGroupIds));
   11965        3111 :     *pnSubGroups = nSubGroups;
   11966        3111 :     *ppanSubGroupIds = panSubGroupIds;
   11967             : 
   11968        3111 :     return CE_None;
   11969             : }
   11970             : 
   11971             : // Get the full name of a given NetCDF (or group) ID
   11972             : // (e.g. /group1/group2/.../groupn).
   11973             : // bNC3Compat remove the leading slash for top-level variables for
   11974             : // backward compatibility (top-level variables are the ones in the root group).
   11975       15659 : static CPLErr NCDFGetGroupFullName(int nGroupId, char **ppszFullName,
   11976             :                                    bool bNC3Compat)
   11977             : {
   11978       15659 :     *ppszFullName = nullptr;
   11979             : 
   11980             :     size_t nFullNameLen;
   11981       15659 :     NCDF_ERR_RET(nc_inq_grpname_len(nGroupId, &nFullNameLen));
   11982       15659 :     *ppszFullName =
   11983       15659 :         static_cast<char *>(CPLMalloc((nFullNameLen + 1) * sizeof(char)));
   11984       15659 :     int status = nc_inq_grpname_full(nGroupId, &nFullNameLen, *ppszFullName);
   11985       15659 :     if (status != NC_NOERR)
   11986             :     {
   11987           0 :         CPLFree(*ppszFullName);
   11988           0 :         *ppszFullName = nullptr;
   11989           0 :         NCDF_ERR_RET(status);
   11990             :     }
   11991             : 
   11992       15659 :     if (bNC3Compat && EQUAL(*ppszFullName, "/"))
   11993        8010 :         (*ppszFullName)[0] = '\0';
   11994             : 
   11995       15659 :     return CE_None;
   11996             : }
   11997             : 
   11998        7441 : CPLString NCDFGetGroupFullName(int nGroupId)
   11999             : {
   12000        7441 :     char *pszFullname = nullptr;
   12001        7441 :     NCDFGetGroupFullName(nGroupId, &pszFullname, false);
   12002        7441 :     CPLString osRet(pszFullname ? pszFullname : "");
   12003        7441 :     CPLFree(pszFullname);
   12004       14882 :     return osRet;
   12005             : }
   12006             : 
   12007             : // Get the full name of a given NetCDF variable ID
   12008             : // (e.g. /group1/group2/.../groupn/var).
   12009             : // Handle also NC_GLOBAL as nVarId.
   12010             : // bNC3Compat remove the leading slash for top-level variables for
   12011             : // backward compatibility (top-level variables are the ones in the root group).
   12012        8169 : static CPLErr NCDFGetVarFullName(int nGroupId, int nVarId, char **ppszFullName,
   12013             :                                  bool bNC3Compat)
   12014             : {
   12015        8169 :     *ppszFullName = nullptr;
   12016        8169 :     char *pszGroupFullName = nullptr;
   12017        8169 :     ERR_RET(NCDFGetGroupFullName(nGroupId, &pszGroupFullName, bNC3Compat));
   12018             :     char szVarName[NC_MAX_NAME + 1];
   12019        8169 :     if (nVarId == NC_GLOBAL)
   12020             :     {
   12021        1103 :         strcpy(szVarName, "NC_GLOBAL");
   12022             :     }
   12023             :     else
   12024             :     {
   12025        7066 :         int status = nc_inq_varname(nGroupId, nVarId, szVarName);
   12026        7066 :         if (status != NC_NOERR)
   12027             :         {
   12028           0 :             CPLFree(pszGroupFullName);
   12029           0 :             NCDF_ERR_RET(status);
   12030             :         }
   12031             :     }
   12032        8169 :     const char *pszSep = "/";
   12033        8169 :     if (EQUAL(pszGroupFullName, "/") || EQUAL(pszGroupFullName, ""))
   12034        7963 :         pszSep = "";
   12035        8169 :     *ppszFullName =
   12036        8169 :         CPLStrdup(CPLSPrintf("%s%s%s", pszGroupFullName, pszSep, szVarName));
   12037        8169 :     CPLFree(pszGroupFullName);
   12038        8169 :     return CE_None;
   12039             : }
   12040             : 
   12041             : // Get the NetCDF root group ID of a given group ID.
   12042           0 : static CPLErr NCDFGetRootGroup(int nStartGroupId, int *pnRootGroupId)
   12043             : {
   12044           0 :     *pnRootGroupId = -1;
   12045             :     // Recurse on parent group.
   12046             :     int nParentGroupId;
   12047           0 :     int status = nc_inq_grp_parent(nStartGroupId, &nParentGroupId);
   12048           0 :     if (status == NC_NOERR)
   12049           0 :         return NCDFGetRootGroup(nParentGroupId, pnRootGroupId);
   12050           0 :     else if (status != NC_ENOGRP)
   12051           0 :         NCDF_ERR_RET(status);
   12052             :     else  // No more parent group.
   12053             :     {
   12054           0 :         *pnRootGroupId = nStartGroupId;
   12055             :     }
   12056             : 
   12057           0 :     return CE_None;
   12058             : }
   12059             : 
   12060             : // Implementation of NCDFResolveVar/Att.
   12061       13260 : static CPLErr NCDFResolveElem(int nStartGroupId, const char *pszVar,
   12062             :                               const char *pszAtt, int *pnGroupId, int *pnId,
   12063             :                               bool bMandatory)
   12064             : {
   12065       13260 :     if (!pszVar && !pszAtt)
   12066             :     {
   12067           0 :         CPLError(CE_Failure, CPLE_IllegalArg,
   12068             :                  "pszVar and pszAtt NCDFResolveElem() args are both null.");
   12069           0 :         return CE_Failure;
   12070             :     }
   12071             : 
   12072             :     enum
   12073             :     {
   12074             :         NCRM_PARENT,
   12075             :         NCRM_WIDTH_WISE
   12076       13260 :     } eNCResolveMode = NCRM_PARENT;
   12077             : 
   12078       26520 :     std::queue<int> aoQueueGroupIdsToVisit;
   12079       13260 :     aoQueueGroupIdsToVisit.push(nStartGroupId);
   12080             : 
   12081       14985 :     while (!aoQueueGroupIdsToVisit.empty())
   12082             :     {
   12083             :         // Get the first group of the FIFO queue.
   12084       13454 :         *pnGroupId = aoQueueGroupIdsToVisit.front();
   12085       13454 :         aoQueueGroupIdsToVisit.pop();
   12086             : 
   12087             :         // Look if this group contains the searched element.
   12088             :         int status;
   12089       13454 :         if (pszVar)
   12090       13234 :             status = nc_inq_varid(*pnGroupId, pszVar, pnId);
   12091             :         else  // pszAtt != nullptr.
   12092         220 :             status = nc_inq_attid(*pnGroupId, NC_GLOBAL, pszAtt, pnId);
   12093             : 
   12094       13454 :         if (status == NC_NOERR)
   12095             :         {
   12096       11729 :             return CE_None;
   12097             :         }
   12098        1725 :         else if ((pszVar && status != NC_ENOTVAR) ||
   12099         217 :                  (pszAtt && status != NC_ENOTATT))
   12100             :         {
   12101           0 :             NCDF_ERR(status);
   12102             :         }
   12103             :         // Element not found, in NC4 case we must search in other groups
   12104             :         // following the CF logic.
   12105             : 
   12106             :         // The first resolve mode consists to search on parent groups.
   12107        1725 :         if (eNCResolveMode == NCRM_PARENT)
   12108             :         {
   12109        1606 :             int nParentGroupId = -1;
   12110        1606 :             int status2 = nc_inq_grp_parent(*pnGroupId, &nParentGroupId);
   12111        1606 :             if (status2 == NC_NOERR)
   12112          62 :                 aoQueueGroupIdsToVisit.push(nParentGroupId);
   12113        1544 :             else if (status2 != NC_ENOGRP)
   12114           0 :                 NCDF_ERR(status2);
   12115        1544 :             else if (pszVar)
   12116             :                 // When resolving a variable, if there is no more
   12117             :                 // parent group then we switch to width-wise search mode
   12118             :                 // starting from the latest found parent group.
   12119        1330 :                 eNCResolveMode = NCRM_WIDTH_WISE;
   12120             :         }
   12121             : 
   12122             :         // The second resolve mode is a width-wise search.
   12123        1725 :         if (eNCResolveMode == NCRM_WIDTH_WISE)
   12124             :         {
   12125             :             // Enqueue all direct sub-groups.
   12126        1449 :             int nSubGroups = 0;
   12127        1449 :             int *panSubGroupIds = nullptr;
   12128        1449 :             NCDFGetSubGroups(*pnGroupId, &nSubGroups, &panSubGroupIds);
   12129        1581 :             for (int i = 0; i < nSubGroups; i++)
   12130         132 :                 aoQueueGroupIdsToVisit.push(panSubGroupIds[i]);
   12131        1449 :             CPLFree(panSubGroupIds);
   12132             :         }
   12133             :     }
   12134             : 
   12135        1531 :     if (bMandatory)
   12136             :     {
   12137           0 :         char *pszStartGroupFullName = nullptr;
   12138           0 :         NCDFGetGroupFullName(nStartGroupId, &pszStartGroupFullName);
   12139           0 :         CPLError(CE_Failure, CPLE_AppDefined,
   12140             :                  "Cannot resolve mandatory %s %s from group %s",
   12141             :                  (pszVar ? pszVar : pszAtt),
   12142             :                  (pszVar ? "variable" : "attribute"),
   12143           0 :                  (pszStartGroupFullName ? pszStartGroupFullName : ""));
   12144           0 :         CPLFree(pszStartGroupFullName);
   12145             :     }
   12146             : 
   12147        1531 :     *pnGroupId = -1;
   12148        1531 :     *pnId = -1;
   12149        1531 :     return CE_Failure;
   12150             : }
   12151             : 
   12152             : // Resolve a variable name from a given starting group following the CF logic:
   12153             : // - if var name is an absolute path then directly open it
   12154             : // - first search in the starting group and its parent groups
   12155             : // - then if there is no more parent group we switch to a width-wise search
   12156             : //   mode starting from the latest found parent group.
   12157             : // The full CF logic is described here:
   12158             : // https://github.com/diwg/cf2/blob/master/group/cf2-group.adoc#scope
   12159             : // If bMandatory then print an error if resolving fails.
   12160             : // TODO: implement support of relative paths.
   12161             : // TODO: to follow strictly the CF logic, when searching for a coordinate
   12162             : //       variable, we must stop the parent search mode once the corresponding
   12163             : //       dimension is found and start the width-wise search from this group.
   12164             : // TODO: to follow strictly the CF logic, when searching in width-wise mode
   12165             : //       we should skip every groups already visited during the parent
   12166             : //       search mode (but revisiting them should have no impact so we could
   12167             : //       let as it is if it is simpler...)
   12168             : // TODO: CF specifies that the width-wise search order is "left-to-right" so
   12169             : //       maybe we must sort sibling groups alphabetically? but maybe not
   12170             : //       necessary if nc_inq_grps() already sort them?
   12171       13043 : CPLErr NCDFResolveVar(int nStartGroupId, const char *pszVar, int *pnGroupId,
   12172             :                       int *pnVarId, bool bMandatory)
   12173             : {
   12174       13043 :     *pnGroupId = -1;
   12175       13043 :     *pnVarId = -1;
   12176       13043 :     int nGroupId = nStartGroupId, nVarId;
   12177       13043 :     if (pszVar[0] == '/')
   12178             :     {
   12179             :         // This is an absolute path: we can open the var directly.
   12180             :         int nRootGroupId;
   12181           0 :         ERR_RET(NCDFGetRootGroup(nStartGroupId, &nRootGroupId));
   12182           0 :         ERR_RET(NCDFOpenSubDataset(nRootGroupId, pszVar, &nGroupId, &nVarId));
   12183             :     }
   12184             :     else
   12185             :     {
   12186             :         // We have to search the variable following the CF logic.
   12187       13043 :         ERR_RET(NCDFResolveElem(nStartGroupId, pszVar, nullptr, &nGroupId,
   12188             :                                 &nVarId, bMandatory));
   12189             :     }
   12190       11726 :     *pnGroupId = nGroupId;
   12191       11726 :     *pnVarId = nVarId;
   12192       11726 :     return CE_None;
   12193             : }
   12194             : 
   12195             : // Like NCDFResolveVar but returns directly the var full name.
   12196        1384 : static CPLErr NCDFResolveVarFullName(int nStartGroupId, const char *pszVar,
   12197             :                                      char **ppszFullName, bool bMandatory)
   12198             : {
   12199        1384 :     *ppszFullName = nullptr;
   12200             :     int nGroupId, nVarId;
   12201        1384 :     ERR_RET(
   12202             :         NCDFResolveVar(nStartGroupId, pszVar, &nGroupId, &nVarId, bMandatory));
   12203        1358 :     return NCDFGetVarFullName(nGroupId, nVarId, ppszFullName);
   12204             : }
   12205             : 
   12206             : // Like NCDFResolveVar but resolves an attribute instead a variable and
   12207             : // returns its integer value.
   12208             : // Only GLOBAL attributes are supported for the moment.
   12209         217 : static CPLErr NCDFResolveAttInt(int nStartGroupId, int nStartVarId,
   12210             :                                 const char *pszAtt, int *pnAtt, bool bMandatory)
   12211             : {
   12212         217 :     int nGroupId = nStartGroupId, nAttId = nStartVarId;
   12213         217 :     ERR_RET(NCDFResolveElem(nStartGroupId, nullptr, pszAtt, &nGroupId, &nAttId,
   12214             :                             bMandatory));
   12215           3 :     NCDF_ERR_RET(nc_get_att_int(nGroupId, NC_GLOBAL, pszAtt, pnAtt));
   12216           3 :     return CE_None;
   12217             : }
   12218             : 
   12219             : // Filter variables to keep only valid 2+D raster bands and vector fields in
   12220             : // a given a NetCDF (or group) ID and its sub-groups.
   12221             : // Coordinate or boundary variables are ignored.
   12222             : // It also creates corresponding vector layers.
   12223         531 : CPLErr netCDFDataset::FilterVars(
   12224             :     int nCdfId, bool bKeepRasters, bool bKeepVectors, char **papszIgnoreVars,
   12225             :     int *pnRasterVars, int *pnGroupId, int *pnVarId, int *pnIgnoredVars,
   12226             :     std::map<std::array<int, 3>, std::vector<std::pair<int, int>>>
   12227             :         &oMap2DDimsToGroupAndVar)
   12228             : {
   12229         531 :     int nVars = 0;
   12230         531 :     int nRasterVars = 0;
   12231         531 :     NCDF_ERR(nc_inq(nCdfId, nullptr, &nVars, nullptr, nullptr));
   12232             : 
   12233        1062 :     std::vector<int> anPotentialVectorVarID;
   12234             :     // oMapDimIdToCount[x] = number of times dim x is the first dimension of
   12235             :     // potential vector variables
   12236        1062 :     std::map<int, int> oMapDimIdToCount;
   12237         531 :     int nVarXId = -1;
   12238         531 :     int nVarYId = -1;
   12239         531 :     int nVarZId = -1;
   12240         531 :     int nVarTimeId = -1;
   12241         531 :     int nVarTimeDimId = -1;
   12242         531 :     bool bIsVectorOnly = true;
   12243         531 :     int nProfileDimId = -1;
   12244         531 :     int nParentIndexVarID = -1;
   12245             : 
   12246        3234 :     for (int v = 0; v < nVars; v++)
   12247             :     {
   12248             :         int nVarDims;
   12249        2703 :         NCDF_ERR_RET(nc_inq_varndims(nCdfId, v, &nVarDims));
   12250             :         // Should we ignore this variable?
   12251             :         char szTemp[NC_MAX_NAME + 1];
   12252        2703 :         szTemp[0] = '\0';
   12253        2703 :         NCDF_ERR_RET(nc_inq_varname(nCdfId, v, szTemp));
   12254             : 
   12255        2703 :         if (strstr(szTemp, "_node_coordinates") ||
   12256        2703 :             strstr(szTemp, "_node_count"))
   12257             :         {
   12258             :             // Ignore CF-1.8 Simple Geometries helper variables
   12259          69 :             continue;
   12260             :         }
   12261             : 
   12262        3933 :         if (nVarDims == 1 && (NCDFIsVarLongitude(nCdfId, -1, szTemp) ||
   12263        1299 :                               NCDFIsVarProjectionX(nCdfId, -1, szTemp)))
   12264             :         {
   12265         360 :             nVarXId = v;
   12266             :         }
   12267        3213 :         else if (nVarDims == 1 && (NCDFIsVarLatitude(nCdfId, -1, szTemp) ||
   12268         939 :                                    NCDFIsVarProjectionY(nCdfId, -1, szTemp)))
   12269             :         {
   12270         359 :             nVarYId = v;
   12271             :         }
   12272        1915 :         else if (nVarDims == 1 && NCDFIsVarVerticalCoord(nCdfId, -1, szTemp))
   12273             :         {
   12274          78 :             nVarZId = v;
   12275             :         }
   12276             :         else
   12277             :         {
   12278        1837 :             char *pszVarFullName = nullptr;
   12279        1837 :             CPLErr eErr = NCDFGetVarFullName(nCdfId, v, &pszVarFullName);
   12280        1837 :             if (eErr != CE_None)
   12281             :             {
   12282           0 :                 CPLFree(pszVarFullName);
   12283           0 :                 continue;
   12284             :             }
   12285             :             bool bIgnoreVar =
   12286        1837 :                 (CSLFindString(papszIgnoreVars, pszVarFullName) != -1);
   12287        1837 :             CPLFree(pszVarFullName);
   12288        1837 :             if (bIgnoreVar)
   12289             :             {
   12290         104 :                 if (nVarDims == 1 && NCDFIsVarTimeCoord(nCdfId, -1, szTemp))
   12291             :                 {
   12292          11 :                     nVarTimeId = v;
   12293          11 :                     nc_inq_vardimid(nCdfId, v, &nVarTimeDimId);
   12294             :                 }
   12295          93 :                 else if (nVarDims > 1)
   12296             :                 {
   12297          89 :                     (*pnIgnoredVars)++;
   12298          89 :                     CPLDebug("GDAL_netCDF", "variable #%d [%s] was ignored", v,
   12299             :                              szTemp);
   12300             :                 }
   12301             :             }
   12302             :             // Only accept 2+D vars.
   12303        1733 :             else if (nVarDims >= 2)
   12304             :             {
   12305         707 :                 bool bRasterCandidate = true;
   12306             :                 // Identify variables that might be vector variables
   12307         707 :                 if (nVarDims == 2)
   12308             :                 {
   12309         631 :                     int anDimIds[2] = {-1, -1};
   12310         631 :                     nc_inq_vardimid(nCdfId, v, anDimIds);
   12311             : 
   12312         631 :                     nc_type vartype = NC_NAT;
   12313         631 :                     nc_inq_vartype(nCdfId, v, &vartype);
   12314             : 
   12315             :                     char szDimNameFirst[NC_MAX_NAME + 1];
   12316             :                     char szDimNameSecond[NC_MAX_NAME + 1];
   12317         631 :                     szDimNameFirst[0] = '\0';
   12318         631 :                     szDimNameSecond[0] = '\0';
   12319        1419 :                     if (vartype == NC_CHAR &&
   12320         157 :                         nc_inq_dimname(nCdfId, anDimIds[0], szDimNameFirst) ==
   12321         157 :                             NC_NOERR &&
   12322         157 :                         nc_inq_dimname(nCdfId, anDimIds[1], szDimNameSecond) ==
   12323         157 :                             NC_NOERR &&
   12324         157 :                         !NCDFIsVarLongitude(nCdfId, -1, szDimNameSecond) &&
   12325         157 :                         !NCDFIsVarProjectionX(nCdfId, -1, szDimNameSecond) &&
   12326         945 :                         !NCDFIsVarLatitude(nCdfId, -1, szDimNameFirst) &&
   12327         157 :                         !NCDFIsVarProjectionY(nCdfId, -1, szDimNameFirst))
   12328             :                     {
   12329         157 :                         anPotentialVectorVarID.push_back(v);
   12330         157 :                         oMapDimIdToCount[anDimIds[0]]++;
   12331         157 :                         if (strstr(szDimNameSecond, "_max_width"))
   12332             :                         {
   12333         127 :                             bRasterCandidate = false;
   12334             :                         }
   12335             :                         else
   12336             :                         {
   12337          30 :                             std::array<int, 3> oKey{anDimIds[0], anDimIds[1],
   12338          30 :                                                     vartype};
   12339          30 :                             oMap2DDimsToGroupAndVar[oKey].emplace_back(
   12340          30 :                                 std::pair(nCdfId, v));
   12341             :                         }
   12342             :                     }
   12343             :                     else
   12344             :                     {
   12345         474 :                         std::array<int, 3> oKey{anDimIds[0], anDimIds[1],
   12346         474 :                                                 vartype};
   12347         474 :                         oMap2DDimsToGroupAndVar[oKey].emplace_back(
   12348         474 :                             std::pair(nCdfId, v));
   12349         474 :                         bIsVectorOnly = false;
   12350             :                     }
   12351             :                 }
   12352             :                 else
   12353             :                 {
   12354          76 :                     bIsVectorOnly = false;
   12355             :                 }
   12356         707 :                 if (bKeepRasters && bRasterCandidate)
   12357             :                 {
   12358         551 :                     *pnGroupId = nCdfId;
   12359         551 :                     *pnVarId = v;
   12360         551 :                     nRasterVars++;
   12361             :                 }
   12362             :             }
   12363        1026 :             else if (nVarDims == 1)
   12364             :             {
   12365         730 :                 nc_type atttype = NC_NAT;
   12366         730 :                 size_t attlen = 0;
   12367         730 :                 if (nc_inq_att(nCdfId, v, "instance_dimension", &atttype,
   12368          14 :                                &attlen) == NC_NOERR &&
   12369         730 :                     atttype == NC_CHAR && attlen < NC_MAX_NAME)
   12370             :                 {
   12371             :                     char szInstanceDimension[NC_MAX_NAME + 1];
   12372          14 :                     if (nc_get_att_text(nCdfId, v, "instance_dimension",
   12373          14 :                                         szInstanceDimension) == NC_NOERR)
   12374             :                     {
   12375          14 :                         szInstanceDimension[attlen] = 0;
   12376          14 :                         int status = nc_inq_dimid(nCdfId, szInstanceDimension,
   12377             :                                                   &nProfileDimId);
   12378          14 :                         if (status == NC_NOERR)
   12379          14 :                             nParentIndexVarID = v;
   12380             :                         else
   12381           0 :                             nProfileDimId = -1;
   12382          14 :                         if (status == NC_EBADDIM)
   12383           0 :                             CPLError(CE_Warning, CPLE_AppDefined,
   12384             :                                      "Attribute instance_dimension='%s' refers "
   12385             :                                      "to a non existing dimension",
   12386             :                                      szInstanceDimension);
   12387             :                         else
   12388          14 :                             NCDF_ERR(status);
   12389             :                     }
   12390             :                 }
   12391         730 :                 if (v != nParentIndexVarID)
   12392             :                 {
   12393         716 :                     anPotentialVectorVarID.push_back(v);
   12394         716 :                     int nDimId = -1;
   12395         716 :                     nc_inq_vardimid(nCdfId, v, &nDimId);
   12396         716 :                     oMapDimIdToCount[nDimId]++;
   12397             :                 }
   12398             :             }
   12399             :         }
   12400             :     }
   12401             : 
   12402             :     // If we are opened in raster-only mode and that there are only 1D or 2D
   12403             :     // variables and that the 2D variables have no X/Y dim, and all
   12404             :     // variables refer to the same main dimension (or 2 dimensions for
   12405             :     // featureType=profile), then it is a pure vector dataset
   12406             :     CPLString osFeatureType(
   12407         531 :         CSLFetchNameValueDef(papszMetadata, "NC_GLOBAL#featureType", ""));
   12408         420 :     if (bKeepRasters && !bKeepVectors && bIsVectorOnly && nRasterVars > 0 &&
   12409         951 :         !anPotentialVectorVarID.empty() &&
   12410           0 :         (oMapDimIdToCount.size() == 1 ||
   12411           0 :          (EQUAL(osFeatureType, "profile") && oMapDimIdToCount.size() == 2 &&
   12412           0 :           nProfileDimId >= 0)))
   12413             :     {
   12414           0 :         anPotentialVectorVarID.resize(0);
   12415             :     }
   12416             :     else
   12417             :     {
   12418         531 :         *pnRasterVars += nRasterVars;
   12419             :     }
   12420             : 
   12421         531 :     if (!anPotentialVectorVarID.empty() && bKeepVectors)
   12422             :     {
   12423             :         // Take the dimension that is referenced the most times.
   12424          64 :         if (!(oMapDimIdToCount.size() == 1 ||
   12425          27 :               (EQUAL(osFeatureType, "profile") &&
   12426          26 :                oMapDimIdToCount.size() == 2 && nProfileDimId >= 0)))
   12427             :         {
   12428           1 :             CPLError(CE_Warning, CPLE_AppDefined,
   12429             :                      "The dataset has several variables that could be "
   12430             :                      "identified as vector fields, but not all share the same "
   12431             :                      "primary dimension. Consequently they will be ignored.");
   12432             :         }
   12433             :         else
   12434             :         {
   12435          50 :             if (nVarTimeId >= 0 &&
   12436          50 :                 oMapDimIdToCount.find(nVarTimeDimId) != oMapDimIdToCount.end())
   12437             :             {
   12438           1 :                 anPotentialVectorVarID.push_back(nVarTimeId);
   12439             :             }
   12440          49 :             CreateGrpVectorLayers(nCdfId, osFeatureType, anPotentialVectorVarID,
   12441             :                                   oMapDimIdToCount, nVarXId, nVarYId, nVarZId,
   12442             :                                   nProfileDimId, nParentIndexVarID,
   12443             :                                   bKeepRasters);
   12444             :         }
   12445             :     }
   12446             : 
   12447             :     // Recurse on sub-groups.
   12448         531 :     int nSubGroups = 0;
   12449         531 :     int *panSubGroupIds = nullptr;
   12450         531 :     NCDFGetSubGroups(nCdfId, &nSubGroups, &panSubGroupIds);
   12451         566 :     for (int i = 0; i < nSubGroups; i++)
   12452             :     {
   12453          35 :         FilterVars(panSubGroupIds[i], bKeepRasters, bKeepVectors,
   12454             :                    papszIgnoreVars, pnRasterVars, pnGroupId, pnVarId,
   12455             :                    pnIgnoredVars, oMap2DDimsToGroupAndVar);
   12456             :     }
   12457         531 :     CPLFree(panSubGroupIds);
   12458             : 
   12459         531 :     return CE_None;
   12460             : }
   12461             : 
   12462             : // Create vector layers from given potentially identified vector variables
   12463             : // resulting from the scanning of a NetCDF (or group) ID.
   12464          49 : CPLErr netCDFDataset::CreateGrpVectorLayers(
   12465             :     int nCdfId, const CPLString &osFeatureType,
   12466             :     const std::vector<int> &anPotentialVectorVarID,
   12467             :     const std::map<int, int> &oMapDimIdToCount, int nVarXId, int nVarYId,
   12468             :     int nVarZId, int nProfileDimId, int nParentIndexVarID, bool bKeepRasters)
   12469             : {
   12470          49 :     char *pszGroupName = nullptr;
   12471          49 :     NCDFGetGroupFullName(nCdfId, &pszGroupName);
   12472          49 :     if (pszGroupName == nullptr || pszGroupName[0] == '\0')
   12473             :     {
   12474          47 :         CPLFree(pszGroupName);
   12475          47 :         pszGroupName = CPLStrdup(CPLGetBasenameSafe(osFilename).c_str());
   12476             :     }
   12477          49 :     OGRwkbGeometryType eGType = wkbUnknown;
   12478             :     CPLString osLayerName = CSLFetchNameValueDef(
   12479          98 :         papszMetadata, "NC_GLOBAL#ogr_layer_name", pszGroupName);
   12480          49 :     CPLFree(pszGroupName);
   12481          49 :     papszMetadata =
   12482          49 :         CSLSetNameValue(papszMetadata, "NC_GLOBAL#ogr_layer_name", nullptr);
   12483             : 
   12484          49 :     if (EQUAL(osFeatureType, "point") || EQUAL(osFeatureType, "profile"))
   12485             :     {
   12486          33 :         papszMetadata =
   12487          33 :             CSLSetNameValue(papszMetadata, "NC_GLOBAL#featureType", nullptr);
   12488          33 :         eGType = wkbPoint;
   12489             :     }
   12490             : 
   12491             :     const char *pszLayerType =
   12492          49 :         CSLFetchNameValue(papszMetadata, "NC_GLOBAL#ogr_layer_type");
   12493          49 :     if (pszLayerType != nullptr)
   12494             :     {
   12495           9 :         eGType = OGRFromOGCGeomType(pszLayerType);
   12496           9 :         papszMetadata =
   12497           9 :             CSLSetNameValue(papszMetadata, "NC_GLOBAL#ogr_layer_type", nullptr);
   12498             :     }
   12499             : 
   12500             :     CPLString osGeometryField =
   12501          98 :         CSLFetchNameValueDef(papszMetadata, "NC_GLOBAL#ogr_geometry_field", "");
   12502          49 :     papszMetadata =
   12503          49 :         CSLSetNameValue(papszMetadata, "NC_GLOBAL#ogr_geometry_field", nullptr);
   12504             : 
   12505          49 :     int nFirstVarId = -1;
   12506          49 :     int nVectorDim = oMapDimIdToCount.rbegin()->first;
   12507          49 :     if (EQUAL(osFeatureType, "profile") && oMapDimIdToCount.size() == 2)
   12508             :     {
   12509          13 :         if (nVectorDim == nProfileDimId)
   12510           0 :             nVectorDim = oMapDimIdToCount.begin()->first;
   12511             :     }
   12512             :     else
   12513             :     {
   12514          36 :         nProfileDimId = -1;
   12515             :     }
   12516          62 :     for (size_t j = 0; j < anPotentialVectorVarID.size(); j++)
   12517             :     {
   12518          62 :         int anDimIds[2] = {-1, -1};
   12519          62 :         nc_inq_vardimid(nCdfId, anPotentialVectorVarID[j], anDimIds);
   12520          62 :         if (nVectorDim == anDimIds[0])
   12521             :         {
   12522          49 :             nFirstVarId = anPotentialVectorVarID[j];
   12523          49 :             break;
   12524             :         }
   12525             :     }
   12526             : 
   12527             :     // In case where coordinates are explicitly specified for one of the
   12528             :     // field/variable, use them in priority over the ones that might have been
   12529             :     // identified above.
   12530          49 :     char *pszCoordinates = nullptr;
   12531          49 :     if (NCDFGetAttr(nCdfId, nFirstVarId, "coordinates", &pszCoordinates) ==
   12532             :         CE_None)
   12533             :     {
   12534          34 :         char **papszTokens = NCDFTokenizeCoordinatesAttribute(pszCFCoordinates);
   12535          34 :         for (int i = 0; papszTokens != nullptr && papszTokens[i] != nullptr;
   12536             :              i++)
   12537             :         {
   12538           0 :             if (NCDFIsVarLongitude(nCdfId, -1, papszTokens[i]) ||
   12539           0 :                 NCDFIsVarProjectionX(nCdfId, -1, papszTokens[i]))
   12540             :             {
   12541           0 :                 nVarXId = -1;
   12542           0 :                 CPL_IGNORE_RET_VAL(
   12543           0 :                     nc_inq_varid(nCdfId, papszTokens[i], &nVarXId));
   12544             :             }
   12545           0 :             else if (NCDFIsVarLatitude(nCdfId, -1, papszTokens[i]) ||
   12546           0 :                      NCDFIsVarProjectionY(nCdfId, -1, papszTokens[i]))
   12547             :             {
   12548           0 :                 nVarYId = -1;
   12549           0 :                 CPL_IGNORE_RET_VAL(
   12550           0 :                     nc_inq_varid(nCdfId, papszTokens[i], &nVarYId));
   12551             :             }
   12552           0 :             else if (NCDFIsVarVerticalCoord(nCdfId, -1, papszTokens[i]))
   12553             :             {
   12554           0 :                 nVarZId = -1;
   12555           0 :                 CPL_IGNORE_RET_VAL(
   12556           0 :                     nc_inq_varid(nCdfId, papszTokens[i], &nVarZId));
   12557             :             }
   12558             :         }
   12559          34 :         CSLDestroy(papszTokens);
   12560             :     }
   12561          49 :     CPLFree(pszCoordinates);
   12562             : 
   12563             :     // Check that the X,Y,Z vars share 1D and share the same dimension as
   12564             :     // attribute variables.
   12565          49 :     if (nVarXId >= 0 && nVarYId >= 0)
   12566             :     {
   12567          38 :         int nVarDimCount = -1;
   12568          38 :         int nVarDimId = -1;
   12569          38 :         if (nc_inq_varndims(nCdfId, nVarXId, &nVarDimCount) != NC_NOERR ||
   12570          38 :             nVarDimCount != 1 ||
   12571          38 :             nc_inq_vardimid(nCdfId, nVarXId, &nVarDimId) != NC_NOERR ||
   12572          38 :             nVarDimId != ((nProfileDimId >= 0) ? nProfileDimId : nVectorDim) ||
   12573          35 :             nc_inq_varndims(nCdfId, nVarYId, &nVarDimCount) != NC_NOERR ||
   12574          35 :             nVarDimCount != 1 ||
   12575         111 :             nc_inq_vardimid(nCdfId, nVarYId, &nVarDimId) != NC_NOERR ||
   12576          35 :             nVarDimId != ((nProfileDimId >= 0) ? nProfileDimId : nVectorDim))
   12577             :         {
   12578           3 :             nVarXId = nVarYId = -1;
   12579             :         }
   12580          69 :         else if (nVarZId >= 0 &&
   12581          34 :                  (nc_inq_varndims(nCdfId, nVarZId, &nVarDimCount) != NC_NOERR ||
   12582          34 :                   nVarDimCount != 1 ||
   12583          34 :                   nc_inq_vardimid(nCdfId, nVarZId, &nVarDimId) != NC_NOERR ||
   12584          34 :                   nVarDimId != nVectorDim))
   12585             :         {
   12586           0 :             nVarZId = -1;
   12587             :         }
   12588             :     }
   12589             : 
   12590          49 :     if (eGType == wkbUnknown && nVarXId >= 0 && nVarYId >= 0)
   12591             :     {
   12592           2 :         eGType = wkbPoint;
   12593             :     }
   12594          49 :     if (eGType == wkbPoint && nVarXId >= 0 && nVarYId >= 0 && nVarZId >= 0)
   12595             :     {
   12596          34 :         eGType = wkbPoint25D;
   12597             :     }
   12598          49 :     if (eGType == wkbUnknown && osGeometryField.empty())
   12599             :     {
   12600           5 :         eGType = wkbNone;
   12601             :     }
   12602             : 
   12603             :     // Read projection info
   12604          49 :     char **papszMetadataBackup = CSLDuplicate(papszMetadata);
   12605          49 :     ReadAttributes(nCdfId, nFirstVarId);
   12606          49 :     if (!this->bSGSupport)
   12607          49 :         SetProjectionFromVar(nCdfId, nFirstVarId, true);
   12608          49 :     const char *pszValue = FetchAttr(nCdfId, nFirstVarId, CF_GRD_MAPPING);
   12609          49 :     char *pszGridMapping = (pszValue ? CPLStrdup(pszValue) : nullptr);
   12610          49 :     CSLDestroy(papszMetadata);
   12611          49 :     papszMetadata = papszMetadataBackup;
   12612             : 
   12613          49 :     OGRSpatialReference *poSRS = nullptr;
   12614          49 :     if (!m_oSRS.IsEmpty())
   12615             :     {
   12616          21 :         poSRS = m_oSRS.Clone();
   12617             :     }
   12618             :     // Reset if there's a 2D raster
   12619          49 :     m_bHasProjection = false;
   12620          49 :     m_bHasGeoTransform = false;
   12621             : 
   12622          49 :     if (!bKeepRasters)
   12623             :     {
   12624             :         // Strip out uninteresting metadata.
   12625          45 :         papszMetadata =
   12626          45 :             CSLSetNameValue(papszMetadata, "NC_GLOBAL#Conventions", nullptr);
   12627          45 :         papszMetadata =
   12628          45 :             CSLSetNameValue(papszMetadata, "NC_GLOBAL#GDAL", nullptr);
   12629          45 :         papszMetadata =
   12630          45 :             CSLSetNameValue(papszMetadata, "NC_GLOBAL#history", nullptr);
   12631             :     }
   12632             : 
   12633             :     std::shared_ptr<netCDFLayer> poLayer(
   12634          49 :         new netCDFLayer(this, nCdfId, osLayerName, eGType, poSRS));
   12635          49 :     if (poSRS != nullptr)
   12636          21 :         poSRS->Release();
   12637          49 :     poLayer->SetRecordDimID(nVectorDim);
   12638          49 :     if (wkbFlatten(eGType) == wkbPoint && nVarXId >= 0 && nVarYId >= 0)
   12639             :     {
   12640          35 :         poLayer->SetXYZVars(nVarXId, nVarYId, nVarZId);
   12641             :     }
   12642          14 :     else if (!osGeometryField.empty())
   12643             :     {
   12644           9 :         poLayer->SetWKTGeometryField(osGeometryField);
   12645             :     }
   12646          49 :     if (pszGridMapping != nullptr)
   12647             :     {
   12648          21 :         poLayer->SetGridMapping(pszGridMapping);
   12649          21 :         CPLFree(pszGridMapping);
   12650             :     }
   12651          49 :     poLayer->SetProfile(nProfileDimId, nParentIndexVarID);
   12652             : 
   12653         574 :     for (size_t j = 0; j < anPotentialVectorVarID.size(); j++)
   12654             :     {
   12655         525 :         int anDimIds[2] = {-1, -1};
   12656         525 :         nc_inq_vardimid(nCdfId, anPotentialVectorVarID[j], anDimIds);
   12657         525 :         if (anDimIds[0] == nVectorDim ||
   12658          24 :             (nProfileDimId >= 0 && anDimIds[0] == nProfileDimId))
   12659             :         {
   12660             : #ifdef NCDF_DEBUG
   12661             :             char szTemp2[NC_MAX_NAME + 1] = {};
   12662             :             CPL_IGNORE_RET_VAL(
   12663             :                 nc_inq_varname(nCdfId, anPotentialVectorVarID[j], szTemp2));
   12664             :             CPLDebug("GDAL_netCDF", "Variable %s is a vector field", szTemp2);
   12665             : #endif
   12666         525 :             poLayer->AddField(anPotentialVectorVarID[j]);
   12667             :         }
   12668             :     }
   12669             : 
   12670          49 :     if (poLayer->GetLayerDefn()->GetFieldCount() != 0 ||
   12671           0 :         poLayer->GetGeomType() != wkbNone)
   12672             :     {
   12673          49 :         papoLayers.push_back(poLayer);
   12674             :     }
   12675             : 
   12676          98 :     return CE_None;
   12677             : }
   12678             : 
   12679             : // Get all coordinate and boundary variables full names referenced in
   12680             : // a given a NetCDF (or group) ID and its sub-groups.
   12681             : // These variables are identified in other variable's
   12682             : // "coordinates" and "bounds" attribute.
   12683             : // Searching coordinate and boundary variables may need to explore
   12684             : // parents groups (or other groups in case of reference given in form of an
   12685             : // absolute path).
   12686             : // See CF sections 5.2, 5.6 and 7.1
   12687         532 : static CPLErr NCDFGetCoordAndBoundVarFullNames(int nCdfId, char ***ppapszVars)
   12688             : {
   12689         532 :     int nVars = 0;
   12690         532 :     NCDF_ERR(nc_inq(nCdfId, nullptr, &nVars, nullptr, nullptr));
   12691             : 
   12692        3249 :     for (int v = 0; v < nVars; v++)
   12693             :     {
   12694        2717 :         char *pszTemp = nullptr;
   12695        2717 :         char **papszTokens = nullptr;
   12696        2717 :         if (NCDFGetAttr(nCdfId, v, "coordinates", &pszTemp) == CE_None)
   12697         446 :             papszTokens = NCDFTokenizeCoordinatesAttribute(pszTemp);
   12698        2717 :         CPLFree(pszTemp);
   12699        2717 :         pszTemp = nullptr;
   12700        2717 :         if (NCDFGetAttr(nCdfId, v, "bounds", &pszTemp) == CE_None &&
   12701        2717 :             pszTemp != nullptr && !EQUAL(pszTemp, ""))
   12702          17 :             papszTokens = CSLAddString(papszTokens, pszTemp);
   12703        2717 :         CPLFree(pszTemp);
   12704        4005 :         for (int i = 0; papszTokens != nullptr && papszTokens[i] != nullptr;
   12705             :              i++)
   12706             :         {
   12707        1288 :             char *pszVarFullName = nullptr;
   12708        1288 :             if (NCDFResolveVarFullName(nCdfId, papszTokens[i],
   12709        1288 :                                        &pszVarFullName) == CE_None)
   12710        1262 :                 *ppapszVars = CSLAddString(*ppapszVars, pszVarFullName);
   12711        1288 :             CPLFree(pszVarFullName);
   12712             :         }
   12713        2717 :         CSLDestroy(papszTokens);
   12714             :     }
   12715             : 
   12716             :     // Recurse on sub-groups.
   12717             :     int nSubGroups;
   12718         532 :     int *panSubGroupIds = nullptr;
   12719         532 :     NCDFGetSubGroups(nCdfId, &nSubGroups, &panSubGroupIds);
   12720         567 :     for (int i = 0; i < nSubGroups; i++)
   12721             :     {
   12722          35 :         NCDFGetCoordAndBoundVarFullNames(panSubGroupIds[i], ppapszVars);
   12723             :     }
   12724         532 :     CPLFree(panSubGroupIds);
   12725             : 
   12726         532 :     return CE_None;
   12727             : }
   12728             : 
   12729             : // Check if give type is user defined
   12730        1538 : bool NCDFIsUserDefinedType(int /*ncid*/, int type)
   12731             : {
   12732        1538 :     return type >= NC_FIRSTUSERTYPEID;
   12733             : }
   12734             : 
   12735         577 : char **NCDFTokenizeCoordinatesAttribute(const char *pszCoordinates)
   12736             : {
   12737             :     // CF conventions use space as the separator for variable names in the
   12738             :     // coordinates attribute, but some products such as
   12739             :     // https://sentinel.esa.int/web/sentinel/technical-guides/sentinel-3-synergy/products-algorithms/level-2-aod-algorithms-and-products/level-2-aod-products-description
   12740             :     // use comma.
   12741         577 :     return CSLTokenizeString2(pszCoordinates, ", ", 0);
   12742             : }

Generated by: LCOV version 1.14