LCOV - code coverage report
Current view: top level - frmts/raw - envidataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 991 1256 78.9 %
Date: 2026-01-16 04:37:55 Functions: 44 46 95.7 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  ENVI .hdr Driver
       4             :  * Purpose:  Implementation of ENVI .hdr labelled raw raster support.
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  * Maintainer: Chris Padwick (cpadwick at ittvis.com)
       7             :  *
       8             :  ******************************************************************************
       9             :  * Copyright (c) 2002, Frank Warmerdam
      10             :  * Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
      11             :  *
      12             :  * SPDX-License-Identifier: MIT
      13             :  ****************************************************************************/
      14             : 
      15             : #include "cpl_port.h"
      16             : #include "envidataset.h"
      17             : #include "gdal_priv.h"
      18             : #include "rawdataset.h"
      19             : #include "gdal_cpp_functions.h"
      20             : 
      21             : #include <climits>
      22             : #include <cmath>
      23             : #include <cstdlib>
      24             : #include <cstring>
      25             : 
      26             : #include <algorithm>
      27             : #include <limits>
      28             : #include <string>
      29             : 
      30             : #include "cpl_conv.h"
      31             : #include "cpl_error.h"
      32             : #include "cpl_string.h"
      33             : #include "cpl_vsi.h"
      34             : #include "gdal.h"
      35             : #include "gdal_frmts.h"
      36             : #include "gdal_priv.h"
      37             : #include "ogr_core.h"
      38             : #include "ogr_spatialref.h"
      39             : #include "ogr_srs_api.h"
      40             : 
      41             : // TODO(schwehr): This really should be defined in port/somewhere.h.
      42             : constexpr double kdfDegToRad = M_PI / 180.0;
      43             : constexpr double kdfRadToDeg = 180.0 / M_PI;
      44             : 
      45             : #include "usgs_esri_zones.h"
      46             : 
      47             : /************************************************************************/
      48             : /*                           ITTVISToUSGSZone()                         */
      49             : /*                                                                      */
      50             : /*      Convert ITTVIS style state plane zones to NOS style state       */
      51             : /*      plane zones.  The ENVI default is to use the new NOS zones,     */
      52             : /*      but the old state plane zones can be used.  Handle this.        */
      53             : /************************************************************************/
      54             : 
      55           0 : static int ITTVISToUSGSZone(int nITTVISZone)
      56             : 
      57             : {
      58             :     // TODO(schwehr): int anUsgsEsriZones[] -> a std::set and std::map.
      59           0 :     const int nPairs = sizeof(anUsgsEsriZones) / (2 * sizeof(int));
      60             : 
      61             :     // Default is to use the zone as-is, as long as it is in the
      62             :     // available list
      63           0 :     for (int i = 0; i < nPairs; i++)
      64             :     {
      65           0 :         if (anUsgsEsriZones[i * 2] == nITTVISZone)
      66           0 :             return anUsgsEsriZones[i * 2];
      67             :     }
      68             : 
      69             :     // If not found in the new style, see if it is present in the
      70             :     // old style list and convert it.  We don't expect to see this
      71             :     // often, but older files allowed it and may still exist.
      72           0 :     for (int i = 0; i < nPairs; i++)
      73             :     {
      74           0 :         if (anUsgsEsriZones[i * 2 + 1] == nITTVISZone)
      75           0 :             return anUsgsEsriZones[i * 2];
      76             :     }
      77             : 
      78           0 :     return nITTVISZone;  // Perhaps it *is* the USGS zone?
      79             : }
      80             : 
      81             : /************************************************************************/
      82             : /*                            ENVIDataset()                             */
      83             : /************************************************************************/
      84             : 
      85         259 : ENVIDataset::ENVIDataset()
      86             :     : fpImage(nullptr), fp(nullptr), pszHDRFilename(nullptr),
      87         259 :       bFoundMapinfo(false), bHeaderDirty(false), bFillFile(false)
      88             : {
      89         259 : }
      90             : 
      91             : /************************************************************************/
      92             : /*                            ~ENVIDataset()                            */
      93             : /************************************************************************/
      94             : 
      95         518 : ENVIDataset::~ENVIDataset()
      96             : 
      97             : {
      98         259 :     ENVIDataset::Close();
      99         518 : }
     100             : 
     101             : /************************************************************************/
     102             : /*                              Close()                                 */
     103             : /************************************************************************/
     104             : 
     105         506 : CPLErr ENVIDataset::Close(GDALProgressFunc, void *)
     106             : {
     107         506 :     CPLErr eErr = CE_None;
     108         506 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     109             :     {
     110         259 :         if (ENVIDataset::FlushCache(true) != CE_None)
     111           0 :             eErr = CE_Failure;
     112             : 
     113         259 :         if (fpImage)
     114             :         {
     115             :             // Make sure the binary file has the expected size
     116         252 :             if (!IsMarkedSuppressOnClose() && bFillFile && nBands > 0)
     117             :             {
     118          93 :                 const int nDataSize = GDALGetDataTypeSizeBytes(
     119             :                     GetRasterBand(1)->GetRasterDataType());
     120          93 :                 const vsi_l_offset nExpectedFileSize =
     121          93 :                     static_cast<vsi_l_offset>(nRasterXSize) * nRasterYSize *
     122          93 :                     nBands * nDataSize;
     123          93 :                 if (VSIFSeekL(fpImage, 0, SEEK_END) != 0)
     124             :                 {
     125           0 :                     eErr = CE_Failure;
     126           0 :                     CPLError(CE_Failure, CPLE_FileIO, "I/O error");
     127             :                 }
     128          93 :                 if (VSIFTellL(fpImage) < nExpectedFileSize)
     129             :                 {
     130          42 :                     GByte byVal = 0;
     131          42 :                     if (VSIFSeekL(fpImage, nExpectedFileSize - 1, SEEK_SET) !=
     132          84 :                             0 ||
     133          42 :                         VSIFWriteL(&byVal, 1, 1, fpImage) == 0)
     134             :                     {
     135           0 :                         eErr = CE_Failure;
     136           0 :                         CPLError(CE_Failure, CPLE_FileIO, "I/O error");
     137             :                     }
     138             :                 }
     139             :             }
     140         252 :             if (VSIFCloseL(fpImage) != 0)
     141             :             {
     142           0 :                 eErr = CE_Failure;
     143           0 :                 CPLError(CE_Failure, CPLE_FileIO, "I/O error");
     144             :             }
     145             :         }
     146         259 :         if (fp)
     147             :         {
     148         259 :             if (VSIFCloseL(fp) != 0)
     149             :             {
     150           0 :                 eErr = CE_Failure;
     151           0 :                 CPLError(CE_Failure, CPLE_FileIO, "I/O error");
     152             :             }
     153             :         }
     154         259 :         if (!m_asGCPs.empty())
     155             :         {
     156           2 :             GDALDeinitGCPs(static_cast<int>(m_asGCPs.size()), m_asGCPs.data());
     157             :         }
     158             : 
     159             :         // Should be called before pszHDRFilename is freed.
     160         259 :         CleanupPostFileClosing();
     161             : 
     162         259 :         CPLFree(pszHDRFilename);
     163             : 
     164         259 :         if (GDALPamDataset::Close() != CE_None)
     165           0 :             eErr = CE_Failure;
     166             :     }
     167         506 :     return eErr;
     168             : }
     169             : 
     170             : /************************************************************************/
     171             : /*                             FlushCache()                             */
     172             : /************************************************************************/
     173             : 
     174         269 : CPLErr ENVIDataset::FlushCache(bool bAtClosing)
     175             : 
     176             : {
     177         269 :     CPLErr eErr = RawDataset::FlushCache(bAtClosing);
     178             : 
     179         269 :     GDALRasterBand *band = GetRasterCount() > 0 ? GetRasterBand(1) : nullptr;
     180             : 
     181         269 :     if (!band || !bHeaderDirty || (bAtClosing && IsMarkedSuppressOnClose()))
     182         185 :         return eErr;
     183             : 
     184             :     // If opening an existing file in Update mode (i.e. "r+") we need to make
     185             :     // sure any existing content is cleared, otherwise the file may contain
     186             :     // trailing content from the previous write.
     187          84 :     if (VSIFTruncateL(fp, 0) != 0)
     188           0 :         return CE_Failure;
     189             : 
     190          84 :     if (VSIFSeekL(fp, 0, SEEK_SET) != 0)
     191           0 :         return CE_Failure;
     192             : 
     193             :     // Rewrite out the header.
     194          84 :     bool bOK = VSIFPrintfL(fp, "ENVI\n") >= 0;
     195          84 :     if ("" != sDescription)
     196          84 :         bOK &= VSIFPrintfL(fp, "description = {\n%s}\n",
     197          84 :                            sDescription.c_str()) >= 0;
     198          84 :     bOK &= VSIFPrintfL(fp, "samples = %d\nlines   = %d\nbands   = %d\n",
     199          84 :                        nRasterXSize, nRasterYSize, nBands) >= 0;
     200             : 
     201          84 :     char **catNames = band->GetCategoryNames();
     202             : 
     203          84 :     bOK &= VSIFPrintfL(fp, "header offset = 0\n") >= 0;
     204          84 :     if (nullptr == catNames)
     205          83 :         bOK &= VSIFPrintfL(fp, "file type = ENVI Standard\n") >= 0;
     206             :     else
     207           1 :         bOK &= VSIFPrintfL(fp, "file type = ENVI Classification\n") >= 0;
     208             : 
     209          84 :     const int iENVIType = GetEnviType(band->GetRasterDataType());
     210          84 :     bOK &= VSIFPrintfL(fp, "data type = %d\n", iENVIType) >= 0;
     211          84 :     const char *pszInterleaving = nullptr;
     212          84 :     switch (eInterleave)
     213             :     {
     214           4 :         case Interleave::BIP:
     215           4 :             pszInterleaving = "bip";  // Interleaved by pixel.
     216           4 :             break;
     217           2 :         case Interleave::BIL:
     218           2 :             pszInterleaving = "bil";  // Interleaved by line.
     219           2 :             break;
     220          78 :         case Interleave::BSQ:
     221          78 :             pszInterleaving = "bsq";  // Band sequential by default.
     222          78 :             break;
     223           0 :         default:
     224           0 :             pszInterleaving = "bsq";
     225           0 :             break;
     226             :     }
     227          84 :     bOK &= VSIFPrintfL(fp, "interleave = %s\n", pszInterleaving) >= 0;
     228             : 
     229          84 :     const char *pszByteOrder = m_aosHeader["byte_order"];
     230          84 :     if (pszByteOrder)
     231             :     {
     232             :         // Supposed to be required
     233          84 :         bOK &= VSIFPrintfL(fp, "byte order = %s\n", pszByteOrder) >= 0;
     234             :     }
     235             : 
     236             :     // Write class and color information.
     237          84 :     catNames = band->GetCategoryNames();
     238          84 :     if (nullptr != catNames)
     239             :     {
     240           1 :         int nrClasses = 0;
     241           3 :         while (*catNames++)
     242           2 :             ++nrClasses;
     243             : 
     244           1 :         if (nrClasses > 0)
     245             :         {
     246           1 :             bOK &= VSIFPrintfL(fp, "classes = %d\n", nrClasses) >= 0;
     247             : 
     248           1 :             GDALColorTable *colorTable = band->GetColorTable();
     249           1 :             if (nullptr != colorTable)
     250             :             {
     251             :                 const int nrColors =
     252           1 :                     std::min(nrClasses, colorTable->GetColorEntryCount());
     253           1 :                 bOK &= VSIFPrintfL(fp, "class lookup = {\n") >= 0;
     254           3 :                 for (int i = 0; i < nrColors; ++i)
     255             :                 {
     256           2 :                     const GDALColorEntry *color = colorTable->GetColorEntry(i);
     257           4 :                     bOK &= VSIFPrintfL(fp, "%d, %d, %d", color->c1, color->c2,
     258           2 :                                        color->c3) >= 0;
     259           2 :                     if (i < nrColors - 1)
     260             :                     {
     261           1 :                         bOK &= VSIFPrintfL(fp, ", ") >= 0;
     262           1 :                         if (0 == (i + 1) % 5)
     263           0 :                             bOK &= VSIFPrintfL(fp, "\n") >= 0;
     264             :                     }
     265             :                 }
     266           1 :                 bOK &= VSIFPrintfL(fp, "}\n") >= 0;
     267             :             }
     268             : 
     269           1 :             catNames = band->GetCategoryNames();
     270           1 :             if (nullptr != *catNames)
     271             :             {
     272           1 :                 bOK &= VSIFPrintfL(fp, "class names = {\n%s", *catNames) >= 0;
     273           1 :                 catNames++;
     274           1 :                 int i = 0;
     275           2 :                 while (*catNames)
     276             :                 {
     277           1 :                     bOK &= VSIFPrintfL(fp, ",") >= 0;
     278           1 :                     if (0 == (++i) % 5)
     279           0 :                         bOK &= VSIFPrintfL(fp, "\n") >= 0;
     280           1 :                     bOK &= VSIFPrintfL(fp, " %s", *catNames) >= 0;
     281           1 :                     catNames++;
     282             :                 }
     283           1 :                 bOK &= VSIFPrintfL(fp, "}\n") >= 0;
     284             :             }
     285             :         }
     286             :     }
     287             : 
     288             :     // Write the rest of header.
     289             : 
     290             :     // Only one map info type should be set:
     291             :     //     - rpc
     292             :     //     - pseudo/gcp
     293             :     //     - standard
     294          84 :     if (!WriteRpcInfo())  // Are rpcs in the metadata?
     295             :     {
     296          83 :         if (!WritePseudoGcpInfo())  // are gcps in the metadata
     297             :         {
     298          82 :             WriteProjectionInfo();  // standard - affine xform/coord sys str
     299             :         }
     300             :     }
     301             : 
     302          84 :     bOK &= VSIFPrintfL(fp, "band names = {\n") >= 0;
     303         252 :     for (int i = 1; i <= nBands; i++)
     304             :     {
     305         336 :         CPLString sBandDesc = GetRasterBand(i)->GetDescription();
     306             : 
     307         168 :         if (sBandDesc == "")
     308         142 :             sBandDesc = CPLSPrintf("Band %d", i);
     309         168 :         bOK &= VSIFPrintfL(fp, "%s", sBandDesc.c_str()) >= 0;
     310         168 :         if (i != nBands)
     311          84 :             bOK &= VSIFPrintfL(fp, ",\n") >= 0;
     312             :     }
     313          84 :     bOK &= VSIFPrintfL(fp, "}\n") >= 0;
     314             : 
     315          84 :     int bHasNoData = FALSE;
     316          84 :     double dfNoDataValue = band->GetNoDataValue(&bHasNoData);
     317          84 :     if (bHasNoData)
     318             :     {
     319           6 :         bOK &=
     320           6 :             VSIFPrintfL(fp, "data ignore value = %.17g\n", dfNoDataValue) >= 0;
     321             :     }
     322             : 
     323             :     // Write "data offset values", if needed
     324             :     {
     325          84 :         bool bHasOffset = false;
     326         252 :         for (int i = 1; i <= nBands; i++)
     327             :         {
     328         168 :             int bHasValue = FALSE;
     329         168 :             CPL_IGNORE_RET_VAL(GetRasterBand(i)->GetOffset(&bHasValue));
     330         168 :             if (bHasValue)
     331           1 :                 bHasOffset = true;
     332             :         }
     333          84 :         if (bHasOffset)
     334             :         {
     335           1 :             bOK &= VSIFPrintfL(fp, "data offset values = {") >= 0;
     336           4 :             for (int i = 1; i <= nBands; i++)
     337             :             {
     338           3 :                 int bHasValue = FALSE;
     339           3 :                 double dfValue = GetRasterBand(i)->GetOffset(&bHasValue);
     340           3 :                 if (!bHasValue)
     341           2 :                     dfValue = 0;
     342           3 :                 bOK &= VSIFPrintfL(fp, "%.17g", dfValue) >= 0;
     343           3 :                 if (i != nBands)
     344           2 :                     bOK &= VSIFPrintfL(fp, ", ") >= 0;
     345             :             }
     346           1 :             bOK &= VSIFPrintfL(fp, "}\n") >= 0;
     347             :         }
     348             :     }
     349             : 
     350             :     // Write "data gain values", if needed
     351             :     {
     352          84 :         bool bHasScale = false;
     353         252 :         for (int i = 1; i <= nBands; i++)
     354             :         {
     355         168 :             int bHasValue = FALSE;
     356         168 :             CPL_IGNORE_RET_VAL(GetRasterBand(i)->GetScale(&bHasValue));
     357         168 :             if (bHasValue)
     358           1 :                 bHasScale = true;
     359             :         }
     360          84 :         if (bHasScale)
     361             :         {
     362           1 :             bOK &= VSIFPrintfL(fp, "data gain values = {") >= 0;
     363           4 :             for (int i = 1; i <= nBands; i++)
     364             :             {
     365           3 :                 int bHasValue = FALSE;
     366           3 :                 double dfValue = GetRasterBand(i)->GetScale(&bHasValue);
     367           3 :                 if (!bHasValue)
     368           2 :                     dfValue = 1;
     369           3 :                 bOK &= VSIFPrintfL(fp, "%.17g", dfValue) >= 0;
     370           3 :                 if (i != nBands)
     371           2 :                     bOK &= VSIFPrintfL(fp, ", ") >= 0;
     372             :             }
     373           1 :             bOK &= VSIFPrintfL(fp, "}\n") >= 0;
     374             :         }
     375             :     }
     376             : 
     377             :     // Write the metadata that was read into the ENVI domain.
     378          84 :     CSLConstList papszENVIMetadata = GetMetadata("ENVI");
     379         168 :     if (CSLFetchNameValue(papszENVIMetadata, "default bands") == nullptr &&
     380          84 :         CSLFetchNameValue(papszENVIMetadata, "default_bands") == nullptr)
     381             :     {
     382          83 :         int nGrayBand = 0;
     383          83 :         int nRBand = 0;
     384          83 :         int nGBand = 0;
     385          83 :         int nBBand = 0;
     386         250 :         for (int i = 1; i <= nBands; i++)
     387             :         {
     388         167 :             const auto eInterp = GetRasterBand(i)->GetColorInterpretation();
     389         167 :             if (eInterp == GCI_GrayIndex)
     390             :             {
     391           5 :                 if (nGrayBand == 0)
     392           4 :                     nGrayBand = i;
     393             :                 else
     394           1 :                     nGrayBand = -1;
     395             :             }
     396         162 :             else if (eInterp == GCI_RedBand)
     397             :             {
     398           5 :                 if (nRBand == 0)
     399           4 :                     nRBand = i;
     400             :                 else
     401           1 :                     nRBand = -1;
     402             :             }
     403         157 :             else if (eInterp == GCI_GreenBand)
     404             :             {
     405           5 :                 if (nGBand == 0)
     406           4 :                     nGBand = i;
     407             :                 else
     408           1 :                     nGBand = -1;
     409             :             }
     410         152 :             else if (eInterp == GCI_BlueBand)
     411             :             {
     412           5 :                 if (nBBand == 0)
     413           4 :                     nBBand = i;
     414             :                 else
     415           1 :                     nBBand = -1;
     416             :             }
     417             :         }
     418          83 :         if (nRBand > 0 && nGBand > 0 && nBBand > 0)
     419             :         {
     420           3 :             bOK &= VSIFPrintfL(fp, "default bands = {%d, %d, %d}\n", nRBand,
     421           3 :                                nGBand, nBBand) >= 0;
     422             :         }
     423          80 :         else if (nGrayBand > 0 && nRBand == 0 && nGBand == 0 && nBBand == 0)
     424             :         {
     425           3 :             bOK &= VSIFPrintfL(fp, "default bands = {%d}\n", nGrayBand) >= 0;
     426             :         }
     427             :     }
     428             : 
     429          84 :     const int count = CSLCount(papszENVIMetadata);
     430             : 
     431             :     // For every item of metadata in the ENVI domain.
     432         763 :     for (int i = 0; i < count; i++)
     433             :     {
     434             :         // Split the entry into two parts at the = character.
     435         679 :         const char *pszEntry = papszENVIMetadata[i];
     436             :         const CPLStringList aosTokens(CSLTokenizeString2(
     437         679 :             pszEntry, "=", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
     438             : 
     439         679 :         if (aosTokens.size() != 2)
     440             :         {
     441           1 :             CPLDebug("ENVI",
     442             :                      "Line of header file could not be split at = into "
     443             :                      "two elements: %s",
     444           1 :                      papszENVIMetadata[i]);
     445           1 :             continue;
     446             :         }
     447             :         // Replace _'s in the string with spaces
     448         678 :         std::string poKey(aosTokens[0]);
     449         678 :         std::replace(poKey.begin(), poKey.end(), '_', ' ');
     450             : 
     451             :         // Don't write it out if it is one of the bits of metadata that is
     452             :         // written out elsewhere in this routine.
     453        1861 :         if (poKey == "description" || poKey == "samples" || poKey == "lines" ||
     454        1275 :             poKey == "bands" || poKey == "header offset" ||
     455         777 :             poKey == "file type" || poKey == "data type" ||
     456         279 :             poKey == "interleave" || poKey == "byte order" ||
     457          27 :             poKey == "class names" || poKey == "band names" ||
     458          17 :             poKey == "map info" || poKey == "projection info" ||
     459          15 :             poKey == "data ignore value" || poKey == "data offset values" ||
     460        1358 :             poKey == "data gain values" || poKey == "coordinate system string")
     461             :         {
     462         676 :             continue;
     463             :         }
     464           2 :         bOK &= VSIFPrintfL(fp, "%s = %s\n", poKey.c_str(), aosTokens[1]) >= 0;
     465             :     }
     466             : 
     467          84 :     if (!bOK)
     468           0 :         return CE_Failure;
     469             : 
     470          84 :     bHeaderDirty = false;
     471          84 :     return eErr;
     472             : }
     473             : 
     474             : /************************************************************************/
     475             : /*                            GetFileList()                             */
     476             : /************************************************************************/
     477             : 
     478          54 : char **ENVIDataset::GetFileList()
     479             : 
     480             : {
     481             :     // Main data file, etc.
     482          54 :     char **papszFileList = RawDataset::GetFileList();
     483             : 
     484             :     // Header file.
     485          54 :     papszFileList = CSLAddString(papszFileList, pszHDRFilename);
     486             : 
     487             :     // Statistics file
     488          54 :     if (!osStaFilename.empty())
     489           0 :         papszFileList = CSLAddString(papszFileList, osStaFilename);
     490             : 
     491          54 :     return papszFileList;
     492             : }
     493             : 
     494             : /************************************************************************/
     495             : /*                           GetEPSGGeogCS()                            */
     496             : /*                                                                      */
     497             : /*      Try to establish what the EPSG code for this coordinate         */
     498             : /*      systems GEOGCS might be.  Returns -1 if no reasonable guess     */
     499             : /*      can be made.                                                    */
     500             : /*                                                                      */
     501             : /*      TODO: We really need to do some name lookups.                   */
     502             : /************************************************************************/
     503             : 
     504          67 : static int ENVIGetEPSGGeogCS(const OGRSpatialReference *poThis)
     505             : 
     506             : {
     507          67 :     const char *pszAuthName = poThis->GetAuthorityName("GEOGCS");
     508             : 
     509             :     // Do we already have it?
     510          67 :     if (pszAuthName != nullptr && EQUAL(pszAuthName, "epsg"))
     511          15 :         return atoi(poThis->GetAuthorityCode("GEOGCS"));
     512             : 
     513             :     // Get the datum and geogcs names.
     514          52 :     const char *pszGEOGCS = poThis->GetAttrValue("GEOGCS");
     515          52 :     const char *pszDatum = poThis->GetAttrValue("DATUM");
     516             : 
     517             :     // We can only operate on coordinate systems with a geogcs.
     518          52 :     if (pszGEOGCS == nullptr || pszDatum == nullptr)
     519           0 :         return -1;
     520             : 
     521             :     // Is this a "well known" geographic coordinate system?
     522           6 :     const bool bWGS = strstr(pszGEOGCS, "WGS") || strstr(pszDatum, "WGS") ||
     523           6 :                       strstr(pszGEOGCS, "World Geodetic System") ||
     524           6 :                       strstr(pszGEOGCS, "World_Geodetic_System") ||
     525          64 :                       strstr(pszDatum, "World Geodetic System") ||
     526           6 :                       strstr(pszDatum, "World_Geodetic_System");
     527             : 
     528          51 :     const bool bNAD = strstr(pszGEOGCS, "NAD") || strstr(pszDatum, "NAD") ||
     529          51 :                       strstr(pszGEOGCS, "North American") ||
     530          51 :                       strstr(pszGEOGCS, "North_American") ||
     531         154 :                       strstr(pszDatum, "North American") ||
     532          51 :                       strstr(pszDatum, "North_American");
     533             : 
     534          52 :     if (bWGS && (strstr(pszGEOGCS, "84") || strstr(pszDatum, "84")))
     535          46 :         return 4326;
     536             : 
     537           6 :     if (bWGS && (strstr(pszGEOGCS, "72") || strstr(pszDatum, "72")))
     538           0 :         return 4322;
     539             : 
     540           6 :     if (bNAD && (strstr(pszGEOGCS, "83") || strstr(pszDatum, "83")))
     541           1 :         return 4269;
     542             : 
     543           5 :     if (bNAD && (strstr(pszGEOGCS, "27") || strstr(pszDatum, "27")))
     544           0 :         return 4267;
     545             : 
     546             :     // If we know the datum, associate the most likely GCS with it.
     547           5 :     pszAuthName = poThis->GetAuthorityName("GEOGCS|DATUM");
     548             : 
     549           5 :     if (pszAuthName != nullptr && EQUAL(pszAuthName, "epsg") &&
     550           0 :         poThis->GetPrimeMeridian() == 0.0)
     551             :     {
     552           0 :         const int nDatum = atoi(poThis->GetAuthorityCode("GEOGCS|DATUM"));
     553             : 
     554           0 :         if (nDatum >= 6000 && nDatum <= 6999)
     555           0 :             return nDatum - 2000;
     556             :     }
     557             : 
     558           5 :     return -1;
     559             : }
     560             : 
     561             : /************************************************************************/
     562             : /*                        WriteProjectionInfo()                         */
     563             : /************************************************************************/
     564             : 
     565          82 : void ENVIDataset::WriteProjectionInfo()
     566             : 
     567             : {
     568             :     // Format the location (geotransform) portion of the map info line.
     569          82 :     CPLString osLocation;
     570          82 :     CPLString osRotation;
     571             : 
     572          82 :     const double dfPixelXSize = sqrt(m_gt[1] * m_gt[1] + m_gt[2] * m_gt[2]);
     573          82 :     const double dfPixelYSize = sqrt(m_gt[4] * m_gt[4] + m_gt[5] * m_gt[5]);
     574         100 :     const bool bHasNonDefaultGT = m_gt[0] != 0.0 || m_gt[1] != 1.0 ||
     575          16 :                                   m_gt[2] != 0.0 || m_gt[3] != 0.0 ||
     576         100 :                                   m_gt[4] != 0.0 || m_gt[5] != 1.0;
     577          82 :     if (m_gt[1] > 0.0 && m_gt[2] == 0.0 && m_gt[4] == 0.0 && m_gt[5] > 0.0)
     578             :     {
     579          16 :         osRotation = ", rotation=180";
     580             :     }
     581          66 :     else if (bHasNonDefaultGT)
     582             :     {
     583          66 :         const double dfRotation1 = -atan2(-m_gt[2], m_gt[1]) * kdfRadToDeg;
     584          66 :         const double dfRotation2 = -atan2(-m_gt[4], -m_gt[5]) * kdfRadToDeg;
     585          66 :         const double dfRotation = (dfRotation1 + dfRotation2) / 2.0;
     586             : 
     587          66 :         if (fabs(dfRotation1 - dfRotation2) > 1e-5)
     588             :         {
     589           0 :             CPLDebug("ENVI", "rot1 = %.15g, rot2 = %.15g", dfRotation1,
     590             :                      dfRotation2);
     591           0 :             CPLError(CE_Warning, CPLE_AppDefined,
     592             :                      "Geotransform matrix has non rotational terms");
     593             :         }
     594          66 :         if (fabs(dfRotation) > 1e-5)
     595             :         {
     596           1 :             osRotation.Printf(", rotation=%.15g", dfRotation);
     597             :         }
     598             :     }
     599             : 
     600          82 :     osLocation.Printf("1, 1, %.15g, %.15g, %.15g, %.15g", m_gt[0], m_gt[3],
     601          82 :                       dfPixelXSize, dfPixelYSize);
     602             : 
     603             :     // Minimal case - write out simple geotransform if we have a
     604             :     // non-default geotransform.
     605          82 :     if (m_oSRS.IsEmpty() || m_oSRS.IsLocal())
     606             :     {
     607          15 :         if (bHasNonDefaultGT)
     608             :         {
     609           2 :             const char *pszHemisphere = "North";
     610           2 :             if (VSIFPrintfL(fp, "map info = {Arbitrary, %s, %d, %s%s}\n",
     611             :                             osLocation.c_str(), 0, pszHemisphere,
     612           2 :                             osRotation.c_str()) < 0)
     613           0 :                 return;
     614             :         }
     615          15 :         return;
     616             :     }
     617             : 
     618             :     // Try to translate the datum and get major/minor ellipsoid values.
     619          67 :     const OGRSpatialReference &oSRS = m_oSRS;
     620          67 :     const int nEPSG_GCS = ENVIGetEPSGGeogCS(&oSRS);
     621         134 :     CPLString osDatum;
     622             : 
     623          67 :     if (nEPSG_GCS == 4326)
     624          59 :         osDatum = "WGS-84";
     625           8 :     else if (nEPSG_GCS == 4322)
     626           0 :         osDatum = "WGS-72";
     627           8 :     else if (nEPSG_GCS == 4269)
     628           1 :         osDatum = "North America 1983";
     629           7 :     else if (nEPSG_GCS == 4267)
     630           2 :         osDatum = "North America 1927";
     631           5 :     else if (nEPSG_GCS == 4230)
     632           0 :         osDatum = "European 1950";
     633           5 :     else if (nEPSG_GCS == 4277)
     634           0 :         osDatum = "Ordnance Survey of Great Britain '36";
     635           5 :     else if (nEPSG_GCS == 4291)
     636           0 :         osDatum = "SAD-69/Brazil";
     637           5 :     else if (nEPSG_GCS == 4283)
     638           0 :         osDatum = "Geocentric Datum of Australia 1994";
     639           5 :     else if (nEPSG_GCS == 4275)
     640           0 :         osDatum = "Nouvelle Triangulation Francaise IGN";
     641             : 
     642         201 :     const CPLString osCommaDatum = osDatum.empty() ? "" : ("," + osDatum);
     643             : 
     644          67 :     const double dfA = oSRS.GetSemiMajor();
     645          67 :     const double dfB = oSRS.GetSemiMinor();
     646             : 
     647             :     // Do we have unusual linear units?
     648          67 :     const double dfFeetPerMeter = 0.3048;
     649             :     const CPLString osOptionalUnits =
     650          67 :         fabs(oSRS.GetLinearUnits() - dfFeetPerMeter) < 0.0001 ? ", units=Feet"
     651         134 :                                                               : "";
     652             : 
     653             :     // Handle UTM case.
     654          67 :     const char *pszProjName = oSRS.GetAttrValue("PROJECTION");
     655          67 :     int bNorth = FALSE;
     656          67 :     const int iUTMZone = oSRS.GetUTMZone(&bNorth);
     657          67 :     bool bOK = true;
     658          67 :     if (iUTMZone)
     659             :     {
     660           3 :         const char *pszHemisphere = bNorth ? "North" : "South";
     661             : 
     662           3 :         bOK &= VSIFPrintfL(fp, "map info = {UTM, %s, %d, %s%s%s%s}\n",
     663             :                            osLocation.c_str(), iUTMZone, pszHemisphere,
     664             :                            osCommaDatum.c_str(), osOptionalUnits.c_str(),
     665           3 :                            osRotation.c_str()) >= 0;
     666             :     }
     667          64 :     else if (oSRS.IsGeographic())
     668             :     {
     669          57 :         bOK &= VSIFPrintfL(fp, "map info = {Geographic Lat/Lon, %s%s%s}\n",
     670             :                            osLocation.c_str(), osCommaDatum.c_str(),
     671          57 :                            osRotation.c_str()) >= 0;
     672             :     }
     673           7 :     else if (pszProjName == nullptr)
     674             :     {
     675             :         // What to do?
     676             :     }
     677           7 :     else if (EQUAL(pszProjName, SRS_PT_NEW_ZEALAND_MAP_GRID))
     678             :     {
     679           0 :         bOK &= VSIFPrintfL(fp, "map info = {New Zealand Map Grid, %s%s%s%s}\n",
     680             :                            osLocation.c_str(), osCommaDatum.c_str(),
     681           0 :                            osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     682             : 
     683           0 :         bOK &= VSIFPrintfL(fp,
     684             :                            "projection info = {39, %.16g, %.16g, %.16g, %.16g, "
     685             :                            "%.16g, %.16g%s, New Zealand Map Grid}\n",
     686             :                            dfA, dfB,
     687             :                            oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0),
     688             :                            oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0),
     689             :                            oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     690             :                            oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     691           0 :                            osCommaDatum.c_str()) >= 0;
     692             :     }
     693           7 :     else if (EQUAL(pszProjName, SRS_PT_TRANSVERSE_MERCATOR))
     694             :     {
     695           1 :         bOK &= VSIFPrintfL(fp, "map info = {Transverse Mercator, %s%s%s%s}\n",
     696             :                            osLocation.c_str(), osCommaDatum.c_str(),
     697           1 :                            osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     698             : 
     699           1 :         bOK &= VSIFPrintfL(fp,
     700             :                            "projection info = {3, %.16g, %.16g, %.16g, "
     701             :                            "%.16g, %.16g, "
     702             :                            "%.16g, %.16g%s, Transverse Mercator}\n",
     703             :                            dfA, dfB,
     704             :                            oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0),
     705             :                            oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0),
     706             :                            oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     707             :                            oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     708             :                            oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0),
     709           1 :                            osCommaDatum.c_str()) >= 0;
     710             :     }
     711           6 :     else if (EQUAL(pszProjName, SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP) ||
     712           4 :              EQUAL(pszProjName, SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP_BELGIUM))
     713             :     {
     714           2 :         bOK &=
     715           2 :             VSIFPrintfL(fp, "map info = {Lambert Conformal Conic, %s%s%s%s}\n",
     716             :                         osLocation.c_str(), osCommaDatum.c_str(),
     717           2 :                         osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     718             : 
     719           2 :         bOK &=
     720           2 :             VSIFPrintfL(
     721             :                 fp,
     722             :                 "projection info = {4, %.16g, %.16g, %.16g, %.16g, %.16g, "
     723             :                 "%.16g, %.16g, %.16g%s, Lambert Conformal Conic}\n",
     724             :                 dfA, dfB, oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0),
     725             :                 oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0),
     726             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     727             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     728             :                 oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, 0.0),
     729             :                 oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_2, 0.0),
     730           2 :                 osCommaDatum.c_str()) >= 0;
     731             :     }
     732           4 :     else if (EQUAL(pszProjName,
     733             :                    SRS_PT_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN))
     734             :     {
     735           0 :         bOK &= VSIFPrintfL(fp,
     736             :                            "map info = {Hotine Oblique Mercator A, %s%s%s%s}\n",
     737             :                            osLocation.c_str(), osCommaDatum.c_str(),
     738           0 :                            osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     739             : 
     740           0 :         bOK &=
     741           0 :             VSIFPrintfL(
     742             :                 fp,
     743             :                 "projection info = {5, %.16g, %.16g, %.16g, %.16g, %.16g, "
     744             :                 "%.16g, %.16g, %.16g, %.16g, %.16g%s, "
     745             :                 "Hotine Oblique Mercator A}\n",
     746             :                 dfA, dfB, oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0),
     747             :                 oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_POINT_1, 0.0),
     748             :                 oSRS.GetNormProjParm(SRS_PP_LONGITUDE_OF_POINT_1, 0.0),
     749             :                 oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_POINT_2, 0.0),
     750             :                 oSRS.GetNormProjParm(SRS_PP_LONGITUDE_OF_POINT_2, 0.0),
     751             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     752             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     753             :                 oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0),
     754           0 :                 osCommaDatum.c_str()) >= 0;
     755             :     }
     756           4 :     else if (EQUAL(pszProjName, SRS_PT_HOTINE_OBLIQUE_MERCATOR))
     757             :     {
     758           0 :         bOK &= VSIFPrintfL(fp,
     759             :                            "map info = {Hotine Oblique Mercator B, %s%s%s%s}\n",
     760             :                            osLocation.c_str(), osCommaDatum.c_str(),
     761           0 :                            osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     762             : 
     763           0 :         bOK &=
     764           0 :             VSIFPrintfL(
     765             :                 fp,
     766             :                 "projection info = {6, %.16g, %.16g, %.16g, %.16g, %.16g, "
     767             :                 "%.16g, %.16g, %.16g%s, Hotine Oblique Mercator B}\n",
     768             :                 dfA, dfB, oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0),
     769             :                 oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0),
     770             :                 oSRS.GetNormProjParm(SRS_PP_AZIMUTH, 0.0),
     771             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     772             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     773             :                 oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0),
     774           0 :                 osCommaDatum.c_str()) >= 0;
     775             :     }
     776           4 :     else if (EQUAL(pszProjName, SRS_PT_STEREOGRAPHIC) ||
     777           4 :              EQUAL(pszProjName, SRS_PT_OBLIQUE_STEREOGRAPHIC))
     778             :     {
     779           0 :         bOK &= VSIFPrintfL(fp,
     780             :                            "map info = {Stereographic (ellipsoid), %s%s%s%s}\n",
     781             :                            osLocation.c_str(), osCommaDatum.c_str(),
     782           0 :                            osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     783             : 
     784           0 :         bOK &=
     785           0 :             VSIFPrintfL(
     786             :                 fp,
     787             :                 "projection info = {7, %.16g, %.16g, %.16g, %.16g, %.16g, "
     788             :                 "%.16g, %.16g, %s, Stereographic (ellipsoid)}\n",
     789             :                 dfA, dfB, oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0),
     790             :                 oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0),
     791             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     792             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     793             :                 oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0),
     794           0 :                 osCommaDatum.c_str()) >= 0;
     795             :     }
     796           4 :     else if (EQUAL(pszProjName, SRS_PT_ALBERS_CONIC_EQUAL_AREA))
     797             :     {
     798           3 :         bOK &= VSIFPrintfL(fp,
     799             :                            "map info = {Albers Conical Equal Area, %s%s%s%s}\n",
     800             :                            osLocation.c_str(), osCommaDatum.c_str(),
     801           3 :                            osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     802             : 
     803           3 :         bOK &=
     804           3 :             VSIFPrintfL(
     805             :                 fp,
     806             :                 "projection info = {9, %.16g, %.16g, %.16g, %.16g, %.16g, "
     807             :                 "%.16g, %.16g, %.16g%s, Albers Conical Equal Area}\n",
     808             :                 dfA, dfB, oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0),
     809             :                 oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0),
     810             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     811             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     812             :                 oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, 0.0),
     813             :                 oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_2, 0.0),
     814           3 :                 osCommaDatum.c_str()) >= 0;
     815             :     }
     816           1 :     else if (EQUAL(pszProjName, SRS_PT_POLYCONIC))
     817             :     {
     818           0 :         bOK &= VSIFPrintfL(fp, "map info = {Polyconic, %s%s%s%s}\n",
     819             :                            osLocation.c_str(), osCommaDatum.c_str(),
     820           0 :                            osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     821             : 
     822           0 :         bOK &=
     823           0 :             VSIFPrintfL(
     824             :                 fp,
     825             :                 "projection info = {10, %.16g, %.16g, %.16g, %.16g, %.16g, "
     826             :                 "%.16g%s, Polyconic}\n",
     827             :                 dfA, dfB, oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0),
     828             :                 oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0),
     829             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     830             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     831           0 :                 osCommaDatum.c_str()) >= 0;
     832             :     }
     833           1 :     else if (EQUAL(pszProjName, SRS_PT_LAMBERT_AZIMUTHAL_EQUAL_AREA))
     834             :     {
     835           1 :         bOK &= VSIFPrintfL(
     836             :                    fp, "map info = {Lambert Azimuthal Equal Area, %s%s%s%s}\n",
     837             :                    osLocation.c_str(), osCommaDatum.c_str(),
     838           1 :                    osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     839             : 
     840           1 :         bOK &=
     841           1 :             VSIFPrintfL(
     842             :                 fp,
     843             :                 "projection info = {11, %.16g, %.16g, %.16g, %.16g, %.16g, "
     844             :                 "%.16g%s, Lambert Azimuthal Equal Area}\n",
     845             :                 dfA, dfB, oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0),
     846             :                 oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0),
     847             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     848             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     849           1 :                 osCommaDatum.c_str()) >= 0;
     850             :     }
     851           0 :     else if (EQUAL(pszProjName, SRS_PT_AZIMUTHAL_EQUIDISTANT))
     852             :     {
     853           0 :         bOK &= VSIFPrintfL(fp, "map info = {Azimuthal Equadistant, %s%s%s%s}\n",
     854             :                            osLocation.c_str(), osCommaDatum.c_str(),
     855           0 :                            osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     856             : 
     857           0 :         bOK &=
     858           0 :             VSIFPrintfL(
     859             :                 fp,
     860             :                 "projection info = {12, %.16g, %.16g, %.16g, %.16g, %.16g, "
     861             :                 "%.16g%s, Azimuthal Equadistant}\n",
     862             :                 dfA, dfB, oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0),
     863             :                 oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0),
     864             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     865             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     866           0 :                 osCommaDatum.c_str()) >= 0;
     867             :     }
     868           0 :     else if (EQUAL(pszProjName, SRS_PT_POLAR_STEREOGRAPHIC))
     869             :     {
     870           0 :         bOK &= VSIFPrintfL(fp, "map info = {Polar Stereographic, %s%s%s%s}\n",
     871             :                            osLocation.c_str(), osCommaDatum.c_str(),
     872           0 :                            osOptionalUnits.c_str(), osRotation.c_str()) >= 0;
     873             : 
     874           0 :         bOK &=
     875           0 :             VSIFPrintfL(
     876             :                 fp,
     877             :                 "projection info = {31, %.16g, %.16g, %.16g, %.16g, %.16g, "
     878             :                 "%.16g%s, Polar Stereographic}\n",
     879             :                 dfA, dfB, oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 90.0),
     880             :                 oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0),
     881             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0),
     882             :                 oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0),
     883           0 :                 osCommaDatum.c_str()) >= 0;
     884             :     }
     885             :     else
     886             :     {
     887           0 :         bOK &= VSIFPrintfL(fp, "map info = {%s, %s}\n", pszProjName,
     888           0 :                            osLocation.c_str()) >= 0;
     889             :     }
     890             : 
     891             :     // write out coordinate system string
     892          67 :     char *pszProjESRI = nullptr;
     893          67 :     const char *const apszOptions[] = {"FORMAT=WKT1_ESRI", nullptr};
     894          67 :     if (oSRS.exportToWkt(&pszProjESRI, apszOptions) == OGRERR_NONE)
     895             :     {
     896          67 :         if (strlen(pszProjESRI))
     897          67 :             bOK &= VSIFPrintfL(fp, "coordinate system string = {%s}\n",
     898          67 :                                pszProjESRI) >= 0;
     899             :     }
     900          67 :     CPLFree(pszProjESRI);
     901          67 :     pszProjESRI = nullptr;
     902             : 
     903          67 :     if (!bOK)
     904             :     {
     905           0 :         CPLError(CE_Failure, CPLE_FileIO, "Write error");
     906             :     }
     907             : }
     908             : 
     909             : /************************************************************************/
     910             : /*                ParseRpcCoeffsMetaDataString()                        */
     911             : /************************************************************************/
     912             : 
     913           4 : bool ENVIDataset::ParseRpcCoeffsMetaDataString(const char *psName,
     914             :                                                CPLStringList &aosVal)
     915             : {
     916             :     // Separate one string with 20 coefficients into an array of 20 strings.
     917           4 :     const char *psz20Vals = GetMetadataItem(psName, "RPC");
     918           4 :     if (!psz20Vals)
     919           0 :         return false;
     920             : 
     921           4 :     const CPLStringList aosArr(CSLTokenizeString2(psz20Vals, " ", 0));
     922           4 :     int x = 0;
     923          84 :     while ((x < 20) && (x < aosArr.size()))
     924             :     {
     925          80 :         aosVal.push_back(aosArr[x]);
     926          80 :         x++;
     927             :     }
     928             : 
     929           4 :     return x == 20;
     930             : }
     931             : 
     932             : /************************************************************************/
     933             : /*                          WriteRpcInfo()                              */
     934             : /************************************************************************/
     935             : 
     936          84 : bool ENVIDataset::WriteRpcInfo()
     937             : {
     938             :     // Write out 90 rpc coeffs into the envi header plus 3 envi specific rpc
     939             :     // values returns 0 if the coeffs are not present or not valid.
     940         168 :     CPLStringList aosVal;
     941             : 
     942          10 :     for (const char *pszItem : {"LINE_OFF", "SAMP_OFF", "LAT_OFF", "LONG_OFF",
     943             :                                 "HEIGHT_OFF", "LINE_SCALE", "SAMP_SCALE",
     944          94 :                                 "LAT_SCALE", "LONG_SCALE", "HEIGHT_SCALE"})
     945             :     {
     946          93 :         const char *pszValue = GetMetadataItem(pszItem, "RPC");
     947          93 :         if (!pszValue)
     948          83 :             return false;
     949          10 :         aosVal.push_back(pszValue);
     950             :     }
     951             : 
     952           1 :     if (!ParseRpcCoeffsMetaDataString("LINE_NUM_COEFF", aosVal) ||
     953           1 :         !ParseRpcCoeffsMetaDataString("LINE_DEN_COEFF", aosVal) ||
     954           3 :         !ParseRpcCoeffsMetaDataString("SAMP_NUM_COEFF", aosVal) ||
     955           1 :         !ParseRpcCoeffsMetaDataString("SAMP_DEN_COEFF", aosVal))
     956             :     {
     957           0 :         return false;
     958             :     }
     959             : 
     960           3 :     for (const char *pszItem :
     961           4 :          {"TILE_ROW_OFFSET", "TILE_COL_OFFSET", "ENVI_RPC_EMULATION"})
     962             :     {
     963           3 :         const char *pszValue = GetMetadataItem(pszItem, "RPC");
     964           3 :         if (!pszValue)
     965           0 :             return false;
     966           3 :         aosVal.push_back(pszValue);
     967             :     }
     968             : 
     969           1 :     CPLAssert(aosVal.size() == 93);
     970             : 
     971             :     // All the needed 93 values are present so write the rpcs into the envi
     972             :     // header.
     973           1 :     bool bRet = true;
     974             :     {
     975           1 :         int x = 1;
     976           1 :         bRet &= VSIFPrintfL(fp, "rpc info = {\n") >= 0;
     977          94 :         for (int iR = 0; iR < 93; iR++)
     978             :         {
     979          93 :             if (aosVal[iR][0] == '-')
     980           8 :                 bRet &= VSIFPrintfL(fp, " %s", aosVal[iR]) >= 0;
     981             :             else
     982          85 :                 bRet &= VSIFPrintfL(fp, "  %s", aosVal[iR]) >= 0;
     983             : 
     984          93 :             if (iR < 92)
     985          92 :                 bRet &= VSIFPrintfL(fp, ",") >= 0;
     986             : 
     987          93 :             if ((x % 4) == 0)
     988          23 :                 bRet &= VSIFPrintfL(fp, "\n") >= 0;
     989             : 
     990          93 :             x++;
     991          93 :             if (x > 4)
     992          23 :                 x = 1;
     993             :         }
     994             :     }
     995           1 :     bRet &= VSIFPrintfL(fp, "}\n") >= 0;
     996             : 
     997           1 :     return bRet;
     998             : }
     999             : 
    1000             : /************************************************************************/
    1001             : /*                        WritePseudoGcpInfo()                          */
    1002             : /************************************************************************/
    1003             : 
    1004          83 : bool ENVIDataset::WritePseudoGcpInfo()
    1005             : {
    1006             :     // Write out gcps into the envi header
    1007             :     // returns 0 if the gcps are not present.
    1008             : 
    1009          83 :     const int iNum = std::min(GetGCPCount(), 4);
    1010          83 :     if (iNum == 0)
    1011          82 :         return false;
    1012             : 
    1013           1 :     const GDAL_GCP *pGcpStructs = GetGCPs();
    1014             : 
    1015             :     // double dfGCPPixel; /** Pixel (x) location of GCP on raster */
    1016             :     // double dfGCPLine;  /** Line (y) location of GCP on raster */
    1017             :     // double dfGCPX;     /** X position of GCP in georeferenced space */
    1018             :     // double dfGCPY;     /** Y position of GCP in georeferenced space */
    1019             : 
    1020           1 :     bool bRet = VSIFPrintfL(fp, "geo points = {\n") >= 0;
    1021           2 :     for (int iR = 0; iR < iNum; iR++)
    1022             :     {
    1023             :         // Add 1 to pixel and line for ENVI convention
    1024           1 :         bRet &=
    1025           2 :             VSIFPrintfL(fp, " %#0.4f, %#0.4f, %#0.8f, %#0.8f",
    1026           1 :                         1 + pGcpStructs[iR].dfGCPPixel,
    1027           1 :                         1 + pGcpStructs[iR].dfGCPLine, pGcpStructs[iR].dfGCPY,
    1028           1 :                         pGcpStructs[iR].dfGCPX) >= 0;
    1029           1 :         if (iR < iNum - 1)
    1030           0 :             bRet &= VSIFPrintfL(fp, ",\n") >= 0;
    1031             :     }
    1032             : 
    1033           1 :     bRet &= VSIFPrintfL(fp, "}\n") >= 0;
    1034             : 
    1035           1 :     return bRet;
    1036             : }
    1037             : 
    1038             : /************************************************************************/
    1039             : /*                          GetSpatialRef()                             */
    1040             : /************************************************************************/
    1041             : 
    1042          24 : const OGRSpatialReference *ENVIDataset::GetSpatialRef() const
    1043             : {
    1044          24 :     return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
    1045             : }
    1046             : 
    1047             : /************************************************************************/
    1048             : /*                          SetSpatialRef()                             */
    1049             : /************************************************************************/
    1050             : 
    1051          66 : CPLErr ENVIDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    1052             : 
    1053             : {
    1054          66 :     m_oSRS.Clear();
    1055          66 :     if (poSRS)
    1056          66 :         m_oSRS = *poSRS;
    1057             : 
    1058          66 :     bHeaderDirty = true;
    1059             : 
    1060          66 :     return CE_None;
    1061             : }
    1062             : 
    1063             : /************************************************************************/
    1064             : /*                          GetGeoTransform()                           */
    1065             : /************************************************************************/
    1066             : 
    1067          58 : CPLErr ENVIDataset::GetGeoTransform(GDALGeoTransform &gt) const
    1068             : 
    1069             : {
    1070          58 :     gt = m_gt;
    1071             : 
    1072          58 :     if (bFoundMapinfo)
    1073          56 :         return CE_None;
    1074             : 
    1075           2 :     return CE_Failure;
    1076             : }
    1077             : 
    1078             : /************************************************************************/
    1079             : /*                          SetGeoTransform()                           */
    1080             : /************************************************************************/
    1081             : 
    1082          67 : CPLErr ENVIDataset::SetGeoTransform(const GDALGeoTransform &gt)
    1083             : {
    1084          67 :     m_gt = gt;
    1085             : 
    1086          67 :     bHeaderDirty = true;
    1087          67 :     bFoundMapinfo = true;
    1088             : 
    1089          67 :     return CE_None;
    1090             : }
    1091             : 
    1092             : /************************************************************************/
    1093             : /*                           SetDescription()                           */
    1094             : /************************************************************************/
    1095             : 
    1096         252 : void ENVIDataset::SetDescription(const char *pszDescription)
    1097             : {
    1098         252 :     bHeaderDirty = true;
    1099         252 :     RawDataset::SetDescription(pszDescription);
    1100         252 : }
    1101             : 
    1102             : /************************************************************************/
    1103             : /*                             SetMetadata()                            */
    1104             : /************************************************************************/
    1105             : 
    1106          32 : CPLErr ENVIDataset::SetMetadata(CSLConstList papszMetadata,
    1107             :                                 const char *pszDomain)
    1108             : {
    1109          32 :     if (pszDomain && (EQUAL(pszDomain, "RPC") || EQUAL(pszDomain, "ENVI")))
    1110             :     {
    1111           2 :         bHeaderDirty = true;
    1112             :     }
    1113          32 :     return RawDataset::SetMetadata(papszMetadata, pszDomain);
    1114             : }
    1115             : 
    1116             : /************************************************************************/
    1117             : /*                             SetMetadataItem()                        */
    1118             : /************************************************************************/
    1119             : 
    1120        3083 : CPLErr ENVIDataset::SetMetadataItem(const char *pszName, const char *pszValue,
    1121             :                                     const char *pszDomain)
    1122             : {
    1123        3083 :     if (pszDomain && (EQUAL(pszDomain, "RPC") || EQUAL(pszDomain, "ENVI")))
    1124             :     {
    1125        2588 :         bHeaderDirty = true;
    1126             :     }
    1127        3083 :     return RawDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    1128             : }
    1129             : 
    1130             : /************************************************************************/
    1131             : /*                               SetGCPs()                              */
    1132             : /************************************************************************/
    1133             : 
    1134           1 : CPLErr ENVIDataset::SetGCPs(int nGCPCount, const GDAL_GCP *pasGCPList,
    1135             :                             const OGRSpatialReference *poSRS)
    1136             : {
    1137           1 :     bHeaderDirty = true;
    1138             : 
    1139           1 :     return RawDataset::SetGCPs(nGCPCount, pasGCPList, poSRS);
    1140             : }
    1141             : 
    1142             : /************************************************************************/
    1143             : /*                             SplitList()                              */
    1144             : /*                                                                      */
    1145             : /*      Split an ENVI value list into component fields, and strip       */
    1146             : /*      white space.                                                    */
    1147             : /************************************************************************/
    1148             : 
    1149         133 : CPLStringList ENVIDataset::SplitList(const char *pszCleanInput)
    1150             : 
    1151             : {
    1152         133 :     return GDALENVISplitList(pszCleanInput);
    1153             : }
    1154             : 
    1155             : /************************************************************************/
    1156             : /*                            SetENVIDatum()                            */
    1157             : /************************************************************************/
    1158             : 
    1159           2 : void ENVIDataset::SetENVIDatum(OGRSpatialReference *poSRS,
    1160             :                                const char *pszENVIDatumName)
    1161             : 
    1162             : {
    1163             :     // Datums.
    1164           2 :     if (EQUAL(pszENVIDatumName, "WGS-84"))
    1165           2 :         poSRS->SetWellKnownGeogCS("WGS84");
    1166           0 :     else if (EQUAL(pszENVIDatumName, "WGS-72"))
    1167           0 :         poSRS->SetWellKnownGeogCS("WGS72");
    1168           0 :     else if (EQUAL(pszENVIDatumName, "North America 1983"))
    1169           0 :         poSRS->SetWellKnownGeogCS("NAD83");
    1170           0 :     else if (EQUAL(pszENVIDatumName, "North America 1927") ||
    1171           0 :              strstr(pszENVIDatumName, "NAD27") ||
    1172           0 :              strstr(pszENVIDatumName, "NAD-27"))
    1173           0 :         poSRS->SetWellKnownGeogCS("NAD27");
    1174           0 :     else if (STARTS_WITH_CI(pszENVIDatumName, "European 1950"))
    1175           0 :         poSRS->SetWellKnownGeogCS("EPSG:4230");
    1176           0 :     else if (EQUAL(pszENVIDatumName, "Ordnance Survey of Great Britain '36"))
    1177           0 :         poSRS->SetWellKnownGeogCS("EPSG:4277");
    1178           0 :     else if (EQUAL(pszENVIDatumName, "SAD-69/Brazil"))
    1179           0 :         poSRS->SetWellKnownGeogCS("EPSG:4291");
    1180           0 :     else if (EQUAL(pszENVIDatumName, "Geocentric Datum of Australia 1994"))
    1181           0 :         poSRS->SetWellKnownGeogCS("EPSG:4283");
    1182           0 :     else if (EQUAL(pszENVIDatumName, "Australian Geodetic 1984"))
    1183           0 :         poSRS->SetWellKnownGeogCS("EPSG:4203");
    1184           0 :     else if (EQUAL(pszENVIDatumName, "Nouvelle Triangulation Francaise IGN"))
    1185           0 :         poSRS->SetWellKnownGeogCS("EPSG:4275");
    1186             : 
    1187             :     // Ellipsoids
    1188           0 :     else if (EQUAL(pszENVIDatumName, "GRS 80"))
    1189           0 :         poSRS->SetWellKnownGeogCS("NAD83");
    1190           0 :     else if (EQUAL(pszENVIDatumName, "Airy"))
    1191           0 :         poSRS->SetWellKnownGeogCS("EPSG:4001");
    1192           0 :     else if (EQUAL(pszENVIDatumName, "Australian National"))
    1193           0 :         poSRS->SetWellKnownGeogCS("EPSG:4003");
    1194           0 :     else if (EQUAL(pszENVIDatumName, "Bessel 1841"))
    1195           0 :         poSRS->SetWellKnownGeogCS("EPSG:4004");
    1196           0 :     else if (EQUAL(pszENVIDatumName, "Clark 1866"))
    1197           0 :         poSRS->SetWellKnownGeogCS("EPSG:4008");
    1198             :     else
    1199             :     {
    1200           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    1201             :                  "Unrecognized datum '%s', defaulting to WGS84.",
    1202             :                  pszENVIDatumName);
    1203           0 :         poSRS->SetWellKnownGeogCS("WGS84");
    1204             :     }
    1205           2 : }
    1206             : 
    1207             : /************************************************************************/
    1208             : /*                           SetENVIEllipse()                           */
    1209             : /************************************************************************/
    1210             : 
    1211           9 : void ENVIDataset::SetENVIEllipse(OGRSpatialReference *poSRS,
    1212             :                                  CSLConstList papszPI_EI)
    1213             : 
    1214             : {
    1215           9 :     const double dfA = CPLAtofM(papszPI_EI[0]);
    1216           9 :     const double dfB = CPLAtofM(papszPI_EI[1]);
    1217             : 
    1218           9 :     double dfInvF = 0.0;
    1219           9 :     if (fabs(dfA - dfB) >= 0.1)
    1220           9 :         dfInvF = dfA / (dfA - dfB);
    1221             : 
    1222           9 :     poSRS->SetGeogCS("Ellipse Based", "Ellipse Based", "Unnamed", dfA, dfInvF);
    1223           9 : }
    1224             : 
    1225             : /************************************************************************/
    1226             : /*                           ProcessMapinfo()                           */
    1227             : /*                                                                      */
    1228             : /*      Extract projection, and geotransform from a mapinfo value in    */
    1229             : /*      the header.                                                     */
    1230             : /************************************************************************/
    1231             : 
    1232         105 : bool ENVIDataset::ProcessMapinfo(const char *pszMapinfo)
    1233             : 
    1234             : {
    1235         210 :     const CPLStringList aosFields(SplitList(pszMapinfo));
    1236         105 :     const char *pszUnits = nullptr;
    1237         105 :     double dfRotation = 0.0;
    1238         105 :     bool bUpsideDown = false;
    1239         105 :     const int nCount = aosFields.size();
    1240             : 
    1241         105 :     if (nCount < 7)
    1242             :     {
    1243           0 :         return false;
    1244             :     }
    1245             : 
    1246             :     // Retrieve named values
    1247         975 :     for (int i = 0; i < nCount; ++i)
    1248             :     {
    1249         870 :         if (STARTS_WITH(aosFields[i], "units="))
    1250             :         {
    1251           2 :             pszUnits = aosFields[i] + strlen("units=");
    1252             :         }
    1253         868 :         else if (STARTS_WITH(aosFields[i], "rotation="))
    1254             :         {
    1255           9 :             dfRotation = CPLAtof(aosFields[i] + strlen("rotation="));
    1256           9 :             bUpsideDown = fabs(dfRotation) == 180.0;
    1257           9 :             dfRotation *= kdfDegToRad * -1.0;
    1258             :         }
    1259             :     }
    1260             : 
    1261             :     // Check if we have coordinate system string, and if so parse it.
    1262         210 :     CPLStringList aosCSS;
    1263         105 :     const char *pszCSS = m_aosHeader["coordinate_system_string"];
    1264         105 :     if (pszCSS != nullptr)
    1265             :     {
    1266          76 :         aosCSS = CSLTokenizeString2(pszCSS, "{}", CSLT_PRESERVEQUOTES);
    1267             :     }
    1268             : 
    1269             :     // Check if we have projection info, and if so parse it.
    1270         210 :     CPLStringList aosPI;
    1271         105 :     int nPICount = 0;
    1272         105 :     const char *pszPI = m_aosHeader["projection_info"];
    1273         105 :     if (pszPI != nullptr)
    1274             :     {
    1275          23 :         aosPI = SplitList(pszPI);
    1276          23 :         nPICount = aosPI.size();
    1277             :     }
    1278             : 
    1279             :     // Capture geotransform.
    1280         105 :     const double xReference = CPLAtof(aosFields[1]);
    1281         105 :     const double yReference = CPLAtof(aosFields[2]);
    1282         105 :     const double pixelEasting = CPLAtof(aosFields[3]);
    1283         105 :     const double pixelNorthing = CPLAtof(aosFields[4]);
    1284         105 :     const double xPixelSize = CPLAtof(aosFields[5]);
    1285         105 :     const double yPixelSize = CPLAtof(aosFields[6]);
    1286             : 
    1287         105 :     m_gt[0] = pixelEasting - (xReference - 1) * xPixelSize;
    1288         105 :     m_gt[1] = cos(dfRotation) * xPixelSize;
    1289         105 :     m_gt[2] = -sin(dfRotation) * xPixelSize;
    1290         105 :     m_gt[3] = pixelNorthing + (yReference - 1) * yPixelSize;
    1291         105 :     m_gt[4] = -sin(dfRotation) * yPixelSize;
    1292         105 :     m_gt[5] = -cos(dfRotation) * yPixelSize;
    1293         105 :     if (bUpsideDown)  // to avoid numeric approximations
    1294             :     {
    1295           5 :         m_gt[1] = xPixelSize;
    1296           5 :         m_gt[2] = 0;
    1297           5 :         m_gt[4] = 0;
    1298           5 :         m_gt[5] = yPixelSize;
    1299             :     }
    1300             : 
    1301             :     // TODO(schwehr): Symbolic constants for the fields.
    1302             :     // Capture projection.
    1303         105 :     OGRSpatialReference oSRS;
    1304         105 :     bool bGeogCRSSet = false;
    1305         105 :     if (oSRS.importFromESRI(aosCSS.List()) != OGRERR_NONE)
    1306             :     {
    1307          29 :         oSRS.Clear();
    1308             : 
    1309          29 :         if (STARTS_WITH_CI(aosFields[0], "UTM") && nCount >= 9)
    1310             :         {
    1311          17 :             oSRS.SetUTM(atoi(aosFields[7]), !EQUAL(aosFields[8], "South"));
    1312          17 :             if (nCount >= 10 && strstr(aosFields[9], "=") == nullptr)
    1313           2 :                 SetENVIDatum(&oSRS, aosFields[9]);
    1314             :             else
    1315          15 :                 oSRS.SetWellKnownGeogCS("NAD27");
    1316          17 :             bGeogCRSSet = true;
    1317             :         }
    1318          12 :         else if (STARTS_WITH_CI(aosFields[0], "State Plane (NAD 27)") &&
    1319             :                  nCount > 7)
    1320             :         {
    1321           0 :             oSRS.SetStatePlane(ITTVISToUSGSZone(atoi(aosFields[7])), FALSE);
    1322           0 :             bGeogCRSSet = true;
    1323             :         }
    1324          12 :         else if (STARTS_WITH_CI(aosFields[0], "State Plane (NAD 83)") &&
    1325             :                  nCount > 7)
    1326             :         {
    1327           0 :             oSRS.SetStatePlane(ITTVISToUSGSZone(atoi(aosFields[7])), TRUE);
    1328           0 :             bGeogCRSSet = true;
    1329             :         }
    1330          12 :         else if (STARTS_WITH_CI(aosFields[0], "Geographic Lat") && nCount > 7)
    1331             :         {
    1332           0 :             if (strstr(aosFields[7], "=") == nullptr)
    1333           0 :                 SetENVIDatum(&oSRS, aosFields[7]);
    1334             :             else
    1335           0 :                 oSRS.SetWellKnownGeogCS("WGS84");
    1336           0 :             bGeogCRSSet = true;
    1337             :         }
    1338          12 :         else if (nPICount > 8 && atoi(aosPI[0]) == 3)  // TM
    1339             :         {
    1340           0 :             oSRS.SetTM(CPLAtofM(aosPI[3]), CPLAtofM(aosPI[4]),
    1341           0 :                        CPLAtofM(aosPI[7]), CPLAtofM(aosPI[5]),
    1342           0 :                        CPLAtofM(aosPI[6]));
    1343             :         }
    1344          12 :         else if (nPICount > 8 && atoi(aosPI[0]) == 4)
    1345             :         {
    1346             :             // Lambert Conformal Conic
    1347           0 :             oSRS.SetLCC(CPLAtofM(aosPI[7]), CPLAtofM(aosPI[8]),
    1348           0 :                         CPLAtofM(aosPI[3]), CPLAtofM(aosPI[4]),
    1349           0 :                         CPLAtofM(aosPI[5]), CPLAtofM(aosPI[6]));
    1350             :         }
    1351          12 :         else if (nPICount > 10 && atoi(aosPI[0]) == 5)
    1352             :         {
    1353             :             // Oblique Merc (2 point).
    1354           0 :             oSRS.SetHOM2PNO(CPLAtofM(aosPI[3]), CPLAtofM(aosPI[4]),
    1355           0 :                             CPLAtofM(aosPI[5]), CPLAtofM(aosPI[6]),
    1356           0 :                             CPLAtofM(aosPI[7]), CPLAtofM(aosPI[10]),
    1357           0 :                             CPLAtofM(aosPI[8]), CPLAtofM(aosPI[9]));
    1358             :         }
    1359          12 :         else if (nPICount > 8 && atoi(aosPI[0]) == 6)  // Oblique Merc
    1360             :         {
    1361           0 :             oSRS.SetHOM(CPLAtofM(aosPI[3]), CPLAtofM(aosPI[4]),
    1362           0 :                         CPLAtofM(aosPI[5]), 0.0, CPLAtofM(aosPI[8]),
    1363           0 :                         CPLAtofM(aosPI[6]), CPLAtofM(aosPI[7]));
    1364             :         }
    1365          12 :         else if (nPICount > 8 && atoi(aosPI[0]) == 7)  // Stereographic
    1366             :         {
    1367           0 :             oSRS.SetStereographic(CPLAtofM(aosPI[3]), CPLAtofM(aosPI[4]),
    1368           0 :                                   CPLAtofM(aosPI[7]), CPLAtofM(aosPI[5]),
    1369           0 :                                   CPLAtofM(aosPI[6]));
    1370             :         }
    1371          12 :         else if (nPICount > 8 && atoi(aosPI[0]) == 9)  // Albers Equal Area
    1372             :         {
    1373           9 :             oSRS.SetACEA(CPLAtofM(aosPI[7]), CPLAtofM(aosPI[8]),
    1374           9 :                          CPLAtofM(aosPI[3]), CPLAtofM(aosPI[4]),
    1375           9 :                          CPLAtofM(aosPI[5]), CPLAtofM(aosPI[6]));
    1376             :         }
    1377           3 :         else if (nPICount > 6 && atoi(aosPI[0]) == 10)  // Polyconic
    1378             :         {
    1379           0 :             oSRS.SetPolyconic(CPLAtofM(aosPI[3]), CPLAtofM(aosPI[4]),
    1380           0 :                               CPLAtofM(aosPI[5]), CPLAtofM(aosPI[6]));
    1381             :         }
    1382           3 :         else if (nPICount > 6 && atoi(aosPI[0]) == 11)  // LAEA
    1383             :         {
    1384           0 :             oSRS.SetLAEA(CPLAtofM(aosPI[3]), CPLAtofM(aosPI[4]),
    1385           0 :                          CPLAtofM(aosPI[5]), CPLAtofM(aosPI[6]));
    1386             :         }
    1387           3 :         else if (nPICount > 6 && atoi(aosPI[0]) == 12)  // Azimuthal Equid.
    1388             :         {
    1389           0 :             oSRS.SetAE(CPLAtofM(aosPI[3]), CPLAtofM(aosPI[4]),
    1390           0 :                        CPLAtofM(aosPI[5]), CPLAtofM(aosPI[6]));
    1391             :         }
    1392           3 :         else if (nPICount > 6 && atoi(aosPI[0]) == 31)  // Polar Stereographic
    1393             :         {
    1394           0 :             oSRS.SetPS(CPLAtofM(aosPI[3]), CPLAtofM(aosPI[4]), 1.0,
    1395           0 :                        CPLAtofM(aosPI[5]), CPLAtofM(aosPI[6]));
    1396             :         }
    1397             :     }
    1398             :     else
    1399             :     {
    1400          76 :         bGeogCRSSet = CPL_TO_BOOL(oSRS.IsProjected());
    1401             :     }
    1402             : 
    1403             :     // Still lots more that could be added for someone with the patience.
    1404             : 
    1405             :     // Fallback to localcs if we don't recognise things.
    1406         105 :     if (oSRS.IsEmpty())
    1407           3 :         oSRS.SetLocalCS(aosFields[0]);
    1408             : 
    1409             :     // Try to set datum from projection info line if we have a
    1410             :     // projected coordinate system without a GEOGCS explicitly set.
    1411         105 :     if (oSRS.IsProjected() && !bGeogCRSSet && nPICount > 3)
    1412             :     {
    1413             :         // Do we have a datum on the projection info line?
    1414           9 :         int iDatum = nPICount - 1;
    1415             : 
    1416             :         // Ignore units= items.
    1417           9 :         if (strstr(aosPI[iDatum], "=") != nullptr)
    1418           0 :             iDatum--;
    1419             : 
    1420             :         // Skip past the name.
    1421           9 :         iDatum--;
    1422             : 
    1423          18 :         const CPLString osDatumName = aosPI[iDatum];
    1424           9 :         if (osDatumName.find_first_of("abcdefghijklmnopqrstuvwxyz"
    1425           9 :                                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ") !=
    1426             :             CPLString::npos)
    1427             :         {
    1428           0 :             SetENVIDatum(&oSRS, osDatumName);
    1429             :         }
    1430             :         else
    1431             :         {
    1432           9 :             SetENVIEllipse(&oSRS, aosPI + 1);
    1433             :         }
    1434             :     }
    1435             : 
    1436             :     // Try to process specialized units.
    1437         105 :     if (pszUnits != nullptr)
    1438             :     {
    1439             :         // Handle linear units first.
    1440           2 :         if (EQUAL(pszUnits, "Feet"))
    1441           0 :             oSRS.SetLinearUnitsAndUpdateParameters(SRS_UL_FOOT,
    1442             :                                                    CPLAtof(SRS_UL_FOOT_CONV));
    1443           2 :         else if (EQUAL(pszUnits, "Meters"))
    1444           2 :             oSRS.SetLinearUnitsAndUpdateParameters(SRS_UL_METER, 1.0);
    1445           0 :         else if (EQUAL(pszUnits, "Km"))
    1446           0 :             oSRS.SetLinearUnitsAndUpdateParameters("Kilometer", 1000.0);
    1447           0 :         else if (EQUAL(pszUnits, "Yards"))
    1448           0 :             oSRS.SetLinearUnitsAndUpdateParameters("Yard", 0.9144);
    1449           0 :         else if (EQUAL(pszUnits, "Miles"))
    1450           0 :             oSRS.SetLinearUnitsAndUpdateParameters("Mile", 1609.344);
    1451           0 :         else if (EQUAL(pszUnits, "Nautical Miles"))
    1452           0 :             oSRS.SetLinearUnitsAndUpdateParameters(
    1453             :                 SRS_UL_NAUTICAL_MILE, CPLAtof(SRS_UL_NAUTICAL_MILE_CONV));
    1454             : 
    1455             :         // Only handle angular units if we know the projection is geographic.
    1456           2 :         if (oSRS.IsGeographic())
    1457             :         {
    1458           0 :             if (EQUAL(pszUnits, "Radians"))
    1459             :             {
    1460           0 :                 oSRS.SetAngularUnits(SRS_UA_RADIAN, 1.0);
    1461             :             }
    1462             :             else
    1463             :             {
    1464             :                 // Degrees, minutes and seconds will all be represented
    1465             :                 // as degrees.
    1466           0 :                 oSRS.SetAngularUnits(SRS_UA_DEGREE,
    1467             :                                      CPLAtof(SRS_UA_DEGREE_CONV));
    1468             : 
    1469           0 :                 double conversionFactor = 1.0;
    1470           0 :                 if (EQUAL(pszUnits, "Minutes"))
    1471           0 :                     conversionFactor = 60.0;
    1472           0 :                 else if (EQUAL(pszUnits, "Seconds"))
    1473           0 :                     conversionFactor = 3600.0;
    1474           0 :                 m_gt[0] /= conversionFactor;
    1475           0 :                 m_gt[1] /= conversionFactor;
    1476           0 :                 m_gt[2] /= conversionFactor;
    1477           0 :                 m_gt[3] /= conversionFactor;
    1478           0 :                 m_gt[4] /= conversionFactor;
    1479           0 :                 m_gt[5] /= conversionFactor;
    1480             :             }
    1481             :         }
    1482             :     }
    1483             : 
    1484             :     // Try to identify the CRS with the database
    1485         105 :     auto poBestCRSMatch = oSRS.FindBestMatch();
    1486         105 :     if (poBestCRSMatch)
    1487             :     {
    1488          62 :         m_oSRS = *poBestCRSMatch;
    1489          62 :         poBestCRSMatch->Release();
    1490             :     }
    1491             :     else
    1492             :     {
    1493          43 :         m_oSRS = std::move(oSRS);
    1494             :     }
    1495         105 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    1496             : 
    1497         105 :     return true;
    1498             : }
    1499             : 
    1500             : /************************************************************************/
    1501             : /*                           ProcessRPCinfo()                           */
    1502             : /*                                                                      */
    1503             : /*      Extract RPC transformation coefficients if they are present     */
    1504             : /*      and sets into the standard metadata fields for RPC.             */
    1505             : /************************************************************************/
    1506             : 
    1507           3 : void ENVIDataset::ProcessRPCinfo(const char *pszRPCinfo, int numCols,
    1508             :                                  int numRows)
    1509             : {
    1510           3 :     const CPLStringList aosFields(SplitList(pszRPCinfo));
    1511           3 :     const int nCount = aosFields.size();
    1512             : 
    1513           3 :     if (nCount < 90)
    1514             :     {
    1515           0 :         return;
    1516             :     }
    1517             : 
    1518           3 :     char sVal[1280] = {'\0'};
    1519           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g", CPLAtof(aosFields[0]));
    1520           3 :     SetMetadataItem("LINE_OFF", sVal, "RPC");
    1521           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g", CPLAtof(aosFields[5]));
    1522           3 :     SetMetadataItem("LINE_SCALE", sVal, "RPC");
    1523           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g", CPLAtof(aosFields[1]));
    1524           3 :     SetMetadataItem("SAMP_OFF", sVal, "RPC");
    1525           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g", CPLAtof(aosFields[6]));
    1526           3 :     SetMetadataItem("SAMP_SCALE", sVal, "RPC");
    1527           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g", CPLAtof(aosFields[2]));
    1528           3 :     SetMetadataItem("LAT_OFF", sVal, "RPC");
    1529           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g", CPLAtof(aosFields[7]));
    1530           3 :     SetMetadataItem("LAT_SCALE", sVal, "RPC");
    1531           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g", CPLAtof(aosFields[3]));
    1532           3 :     SetMetadataItem("LONG_OFF", sVal, "RPC");
    1533           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g", CPLAtof(aosFields[8]));
    1534           3 :     SetMetadataItem("LONG_SCALE", sVal, "RPC");
    1535           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g", CPLAtof(aosFields[4]));
    1536           3 :     SetMetadataItem("HEIGHT_OFF", sVal, "RPC");
    1537           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g", CPLAtof(aosFields[9]));
    1538           3 :     SetMetadataItem("HEIGHT_SCALE", sVal, "RPC");
    1539             : 
    1540           3 :     sVal[0] = '\0';
    1541          63 :     for (int i = 0; i < 20; i++)
    1542          60 :         CPLsnprintf(sVal + strlen(sVal), sizeof(sVal) - strlen(sVal), "%.16g ",
    1543             :                     CPLAtof(aosFields[10 + i]));
    1544           3 :     SetMetadataItem("LINE_NUM_COEFF", sVal, "RPC");
    1545             : 
    1546           3 :     sVal[0] = '\0';
    1547          63 :     for (int i = 0; i < 20; i++)
    1548          60 :         CPLsnprintf(sVal + strlen(sVal), sizeof(sVal) - strlen(sVal), "%.16g ",
    1549             :                     CPLAtof(aosFields[30 + i]));
    1550           3 :     SetMetadataItem("LINE_DEN_COEFF", sVal, "RPC");
    1551             : 
    1552           3 :     sVal[0] = '\0';
    1553          63 :     for (int i = 0; i < 20; i++)
    1554          60 :         CPLsnprintf(sVal + strlen(sVal), sizeof(sVal) - strlen(sVal), "%.16g ",
    1555             :                     CPLAtof(aosFields[50 + i]));
    1556           3 :     SetMetadataItem("SAMP_NUM_COEFF", sVal, "RPC");
    1557             : 
    1558           3 :     sVal[0] = '\0';
    1559          63 :     for (int i = 0; i < 20; i++)
    1560          60 :         CPLsnprintf(sVal + strlen(sVal), sizeof(sVal) - strlen(sVal), "%.16g ",
    1561             :                     CPLAtof(aosFields[70 + i]));
    1562           3 :     SetMetadataItem("SAMP_DEN_COEFF", sVal, "RPC");
    1563             : 
    1564           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g",
    1565           3 :                 CPLAtof(aosFields[3]) - CPLAtof(aosFields[8]));
    1566           3 :     SetMetadataItem("MIN_LONG", sVal, "RPC");
    1567             : 
    1568           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g",
    1569           3 :                 CPLAtof(aosFields[3]) + CPLAtof(aosFields[8]));
    1570           3 :     SetMetadataItem("MAX_LONG", sVal, "RPC");
    1571             : 
    1572           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g",
    1573           3 :                 CPLAtof(aosFields[2]) - CPLAtof(aosFields[7]));
    1574           3 :     SetMetadataItem("MIN_LAT", sVal, "RPC");
    1575             : 
    1576           3 :     CPLsnprintf(sVal, sizeof(sVal), "%.16g",
    1577           3 :                 CPLAtof(aosFields[2]) + CPLAtof(aosFields[7]));
    1578           3 :     SetMetadataItem("MAX_LAT", sVal, "RPC");
    1579             : 
    1580           3 :     if (nCount == 93)
    1581             :     {
    1582           3 :         SetMetadataItem("TILE_ROW_OFFSET", aosFields[90], "RPC");
    1583           3 :         SetMetadataItem("TILE_COL_OFFSET", aosFields[91], "RPC");
    1584           3 :         SetMetadataItem("ENVI_RPC_EMULATION", aosFields[92], "RPC");
    1585             :     }
    1586             : 
    1587             :     // Handle the chipping case where the image is a subset.
    1588           3 :     const double rowOffset = (nCount == 93) ? CPLAtof(aosFields[90]) : 0;
    1589           3 :     const double colOffset = (nCount == 93) ? CPLAtof(aosFields[91]) : 0;
    1590           3 :     if (rowOffset != 0.0 || colOffset != 0.0)
    1591             :     {
    1592           0 :         SetMetadataItem("ICHIP_SCALE_FACTOR", "1");
    1593           0 :         SetMetadataItem("ICHIP_ANAMORPH_CORR", "0");
    1594           0 :         SetMetadataItem("ICHIP_SCANBLK_NUM", "0");
    1595             : 
    1596           0 :         SetMetadataItem("ICHIP_OP_ROW_11", "0.5");
    1597           0 :         SetMetadataItem("ICHIP_OP_COL_11", "0.5");
    1598           0 :         SetMetadataItem("ICHIP_OP_ROW_12", "0.5");
    1599           0 :         SetMetadataItem("ICHIP_OP_COL_21", "0.5");
    1600           0 :         CPLsnprintf(sVal, sizeof(sVal), "%.16g", numCols - 0.5);
    1601           0 :         SetMetadataItem("ICHIP_OP_COL_12", sVal);
    1602           0 :         SetMetadataItem("ICHIP_OP_COL_22", sVal);
    1603           0 :         CPLsnprintf(sVal, sizeof(sVal), "%.16g", numRows - 0.5);
    1604           0 :         SetMetadataItem("ICHIP_OP_ROW_21", sVal);
    1605           0 :         SetMetadataItem("ICHIP_OP_ROW_22", sVal);
    1606             : 
    1607           0 :         CPLsnprintf(sVal, sizeof(sVal), "%.16g", rowOffset + 0.5);
    1608           0 :         SetMetadataItem("ICHIP_FI_ROW_11", sVal);
    1609           0 :         SetMetadataItem("ICHIP_FI_ROW_12", sVal);
    1610           0 :         CPLsnprintf(sVal, sizeof(sVal), "%.16g", colOffset + 0.5);
    1611           0 :         SetMetadataItem("ICHIP_FI_COL_11", sVal);
    1612           0 :         SetMetadataItem("ICHIP_FI_COL_21", sVal);
    1613           0 :         CPLsnprintf(sVal, sizeof(sVal), "%.16g", colOffset + numCols - 0.5);
    1614           0 :         SetMetadataItem("ICHIP_FI_COL_12", sVal);
    1615           0 :         SetMetadataItem("ICHIP_FI_COL_22", sVal);
    1616           0 :         CPLsnprintf(sVal, sizeof(sVal), "%.16g", rowOffset + numRows - 0.5);
    1617           0 :         SetMetadataItem("ICHIP_FI_ROW_21", sVal);
    1618           0 :         SetMetadataItem("ICHIP_FI_ROW_22", sVal);
    1619             :     }
    1620             : }
    1621             : 
    1622             : /************************************************************************/
    1623             : /*                             GetGCPCount()                            */
    1624             : /************************************************************************/
    1625             : 
    1626          97 : int ENVIDataset::GetGCPCount()
    1627             : {
    1628          97 :     int nGCPCount = RawDataset::GetGCPCount();
    1629          97 :     if (nGCPCount)
    1630           1 :         return nGCPCount;
    1631          96 :     return static_cast<int>(m_asGCPs.size());
    1632             : }
    1633             : 
    1634             : /************************************************************************/
    1635             : /*                              GetGCPs()                               */
    1636             : /************************************************************************/
    1637             : 
    1638           2 : const GDAL_GCP *ENVIDataset::GetGCPs()
    1639             : {
    1640           2 :     int nGCPCount = RawDataset::GetGCPCount();
    1641           2 :     if (nGCPCount)
    1642           1 :         return RawDataset::GetGCPs();
    1643           1 :     if (!m_asGCPs.empty())
    1644           1 :         return m_asGCPs.data();
    1645           0 :     return nullptr;
    1646             : }
    1647             : 
    1648             : /************************************************************************/
    1649             : /*                         ProcessGeoPoints()                           */
    1650             : /*                                                                      */
    1651             : /*      Extract GCPs                                                    */
    1652             : /************************************************************************/
    1653             : 
    1654           2 : void ENVIDataset::ProcessGeoPoints(const char *pszGeoPoints)
    1655             : {
    1656           2 :     const CPLStringList aosFields(SplitList(pszGeoPoints));
    1657           2 :     const int nCount = aosFields.size();
    1658             : 
    1659           2 :     if ((nCount % 4) != 0)
    1660             :     {
    1661           0 :         return;
    1662             :     }
    1663           2 :     m_asGCPs.resize(nCount / 4);
    1664           2 :     if (!m_asGCPs.empty())
    1665             :     {
    1666           2 :         GDALInitGCPs(static_cast<int>(m_asGCPs.size()), m_asGCPs.data());
    1667             :     }
    1668           4 :     for (int i = 0; i < static_cast<int>(m_asGCPs.size()); i++)
    1669             :     {
    1670             :         // Subtract 1 to pixel and line for ENVI convention
    1671           2 :         m_asGCPs[i].dfGCPPixel = CPLAtof(aosFields[i * 4 + 0]) - 1;
    1672           2 :         m_asGCPs[i].dfGCPLine = CPLAtof(aosFields[i * 4 + 1]) - 1;
    1673           2 :         m_asGCPs[i].dfGCPY = CPLAtof(aosFields[i * 4 + 2]);
    1674           2 :         m_asGCPs[i].dfGCPX = CPLAtof(aosFields[i * 4 + 3]);
    1675           2 :         m_asGCPs[i].dfGCPZ = 0;
    1676             :     }
    1677             : }
    1678             : 
    1679           1 : static unsigned byteSwapUInt(unsigned swapMe)
    1680             : {
    1681           1 :     CPL_MSBPTR32(&swapMe);
    1682           1 :     return swapMe;
    1683             : }
    1684             : 
    1685         252 : void ENVIDataset::ProcessStatsFile()
    1686             : {
    1687         252 :     osStaFilename = CPLResetExtensionSafe(pszHDRFilename, "sta");
    1688         252 :     VSILFILE *fpStaFile = VSIFOpenL(osStaFilename, "rb");
    1689             : 
    1690         252 :     if (!fpStaFile)
    1691             :     {
    1692         251 :         osStaFilename = "";
    1693         251 :         return;
    1694             :     }
    1695             : 
    1696           1 :     int lTestHeader[10] = {0};
    1697           1 :     if (VSIFReadL(lTestHeader, sizeof(int), 10, fpStaFile) != 10)
    1698             :     {
    1699           0 :         CPL_IGNORE_RET_VAL(VSIFCloseL(fpStaFile));
    1700           0 :         osStaFilename = "";
    1701           0 :         return;
    1702             :     }
    1703             : 
    1704           1 :     const bool isFloat = byteSwapInt(lTestHeader[0]) == 1111838282;
    1705             : 
    1706           1 :     int nb = byteSwapInt(lTestHeader[3]);
    1707             : 
    1708           1 :     if (nb < 0 || nb > nBands)
    1709             :     {
    1710           0 :         CPLDebug("ENVI",
    1711             :                  ".sta file has statistics for %d bands, "
    1712             :                  "whereas the dataset has only %d bands",
    1713             :                  nb, nBands);
    1714           0 :         nb = nBands;
    1715             :     }
    1716             : 
    1717             :     // TODO(schwehr): What are 1, 4, 8, and 40?
    1718           1 :     unsigned lOffset = 0;
    1719           1 :     if (VSIFSeekL(fpStaFile, 40 + static_cast<vsi_l_offset>(nb + 1) * 4,
    1720           1 :                   SEEK_SET) == 0 &&
    1721           2 :         VSIFReadL(&lOffset, sizeof(lOffset), 1, fpStaFile) == 1 &&
    1722           1 :         VSIFSeekL(fpStaFile,
    1723           2 :                   40 + static_cast<vsi_l_offset>(nb + 1) * 8 +
    1724           1 :                       byteSwapUInt(lOffset) + nb,
    1725             :                   SEEK_SET) == 0)
    1726             :     {
    1727             :         // This should be the beginning of the statistics.
    1728           1 :         if (isFloat)
    1729             :         {
    1730           0 :             float *fStats = static_cast<float *>(CPLCalloc(nb * 4, 4));
    1731           0 :             if (static_cast<int>(VSIFReadL(fStats, 4, nb * 4, fpStaFile)) ==
    1732           0 :                 nb * 4)
    1733             :             {
    1734           0 :                 for (int i = 0; i < nb; i++)
    1735             :                 {
    1736           0 :                     GetRasterBand(i + 1)->SetStatistics(
    1737           0 :                         byteSwapFloat(fStats[i]), byteSwapFloat(fStats[nb + i]),
    1738           0 :                         byteSwapFloat(fStats[2 * nb + i]),
    1739           0 :                         byteSwapFloat(fStats[3 * nb + i]));
    1740             :                 }
    1741             :             }
    1742           0 :             CPLFree(fStats);
    1743             :         }
    1744             :         else
    1745             :         {
    1746           1 :             double *dStats = static_cast<double *>(CPLCalloc(nb * 4, 8));
    1747           1 :             if (static_cast<int>(VSIFReadL(dStats, 8, nb * 4, fpStaFile)) ==
    1748           1 :                 nb * 4)
    1749             :             {
    1750           7 :                 for (int i = 0; i < nb; i++)
    1751             :                 {
    1752           6 :                     const double dMin = byteSwapDouble(dStats[i]);
    1753           6 :                     const double dMax = byteSwapDouble(dStats[nb + i]);
    1754           6 :                     const double dMean = byteSwapDouble(dStats[2 * nb + i]);
    1755           6 :                     const double dStd = byteSwapDouble(dStats[3 * nb + i]);
    1756           6 :                     if (dMin != dMax && dStd != 0)
    1757           6 :                         GetRasterBand(i + 1)->SetStatistics(dMin, dMax, dMean,
    1758           6 :                                                             dStd);
    1759             :                 }
    1760             :             }
    1761           1 :             CPLFree(dStats);
    1762             :         }
    1763             :     }
    1764           1 :     CPL_IGNORE_RET_VAL(VSIFCloseL(fpStaFile));
    1765             : }
    1766             : 
    1767           2 : int ENVIDataset::byteSwapInt(int swapMe)
    1768             : {
    1769           2 :     CPL_MSBPTR32(&swapMe);
    1770           2 :     return swapMe;
    1771             : }
    1772             : 
    1773           0 : float ENVIDataset::byteSwapFloat(float swapMe)
    1774             : {
    1775           0 :     CPL_MSBPTR32(&swapMe);
    1776           0 :     return swapMe;
    1777             : }
    1778             : 
    1779          24 : double ENVIDataset::byteSwapDouble(double swapMe)
    1780             : {
    1781          24 :     CPL_MSBPTR64(&swapMe);
    1782          24 :     return swapMe;
    1783             : }
    1784             : 
    1785             : /************************************************************************/
    1786             : /*                        GetRawBinaryLayout()                          */
    1787             : /************************************************************************/
    1788             : 
    1789           4 : bool ENVIDataset::GetRawBinaryLayout(GDALDataset::RawBinaryLayout &sLayout)
    1790             : {
    1791             :     const bool bIsCompressed =
    1792           4 :         atoi(m_aosHeader.FetchNameValueDef("file_compression", "0")) != 0;
    1793           4 :     if (bIsCompressed)
    1794           0 :         return false;
    1795           4 :     if (!RawDataset::GetRawBinaryLayout(sLayout))
    1796           0 :         return false;
    1797           4 :     sLayout.osRawFilename = GetDescription();
    1798           4 :     return true;
    1799             : }
    1800             : 
    1801             : /************************************************************************/
    1802             : /*                                Open()                                */
    1803             : /************************************************************************/
    1804             : 
    1805       32273 : GDALDataset *ENVIDataset::Open(GDALOpenInfo *poOpenInfo)
    1806             : {
    1807       32273 :     return Open(poOpenInfo, true);
    1808             : }
    1809             : 
    1810       32367 : ENVIDataset *ENVIDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck)
    1811             : 
    1812             : {
    1813             :     // Assume the caller is pointing to the binary (i.e. .bil) file.
    1814       33969 :     if (poOpenInfo->nHeaderBytes < 2 ||
    1815        3203 :         (!poOpenInfo->IsSingleAllowedDriver("ENVI") &&
    1816        1601 :          poOpenInfo->IsExtensionEqualToCI("zarr")))
    1817             :     {
    1818       30765 :         return nullptr;
    1819             :     }
    1820             : 
    1821             :     // Do we have a .hdr file?  Try upper and lower case, and
    1822             :     // replacing the extension as well as appending the extension
    1823             :     // to whatever we currently have.
    1824             : 
    1825        1602 :     const char *pszMode = nullptr;
    1826        1602 :     if (poOpenInfo->eAccess == GA_Update)
    1827         114 :         pszMode = "r+";
    1828             :     else
    1829        1488 :         pszMode = "r";
    1830             : 
    1831        3204 :     CPLString osHdrFilename;
    1832        1602 :     VSILFILE *fpHeader = nullptr;
    1833        1602 :     CSLConstList papszSiblingFiles = poOpenInfo->GetSiblingFiles();
    1834        1602 :     if (papszSiblingFiles == nullptr)
    1835             :     {
    1836             :         // First try hdr as an extra extension
    1837             :         osHdrFilename =
    1838           8 :             CPLFormFilenameSafe(nullptr, poOpenInfo->pszFilename, "hdr");
    1839           8 :         fpHeader = VSIFOpenL(osHdrFilename, pszMode);
    1840             : 
    1841           8 :         if (fpHeader == nullptr && VSIIsCaseSensitiveFS(osHdrFilename))
    1842             :         {
    1843             :             osHdrFilename =
    1844           8 :                 CPLFormFilenameSafe(nullptr, poOpenInfo->pszFilename, "HDR");
    1845           8 :             fpHeader = VSIFOpenL(osHdrFilename, pszMode);
    1846             :         }
    1847             : 
    1848             :         // Otherwise, try .hdr as a replacement extension
    1849           8 :         if (fpHeader == nullptr)
    1850             :         {
    1851             :             osHdrFilename =
    1852           8 :                 CPLResetExtensionSafe(poOpenInfo->pszFilename, "hdr");
    1853           8 :             fpHeader = VSIFOpenL(osHdrFilename, pszMode);
    1854             :         }
    1855             : 
    1856           8 :         if (fpHeader == nullptr && VSIIsCaseSensitiveFS(osHdrFilename))
    1857             :         {
    1858             :             osHdrFilename =
    1859           7 :                 CPLResetExtensionSafe(poOpenInfo->pszFilename, "HDR");
    1860           7 :             fpHeader = VSIFOpenL(osHdrFilename, pszMode);
    1861             :         }
    1862             :     }
    1863             :     else
    1864             :     {
    1865             :         // Now we need to tear apart the filename to form a .HDR filename.
    1866        3188 :         CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename);
    1867        3188 :         CPLString osName = CPLGetFilename(poOpenInfo->pszFilename);
    1868             : 
    1869             :         // First try hdr as an extra extension
    1870             :         int iFile =
    1871        1594 :             CSLFindString(papszSiblingFiles,
    1872        3188 :                           CPLFormFilenameSafe(nullptr, osName, "hdr").c_str());
    1873        1594 :         if (iFile < 0)
    1874             :         {
    1875             :             // Otherwise, try .hdr as a replacement extension
    1876        1458 :             iFile = CSLFindString(papszSiblingFiles,
    1877        2916 :                                   CPLResetExtensionSafe(osName, "hdr").c_str());
    1878             :         }
    1879             : 
    1880        1594 :         if (iFile >= 0)
    1881             :         {
    1882             :             osHdrFilename =
    1883         339 :                 CPLFormFilenameSafe(osPath, papszSiblingFiles[iFile], nullptr);
    1884         339 :             fpHeader = VSIFOpenL(osHdrFilename, pszMode);
    1885             :         }
    1886             :     }
    1887             : 
    1888        1602 :     if (fpHeader == nullptr)
    1889        1262 :         return nullptr;
    1890             : 
    1891             :     // Check that the first line says "ENVI".
    1892         340 :     char szTestHdr[4] = {'\0'};
    1893             : 
    1894         340 :     if (VSIFReadL(szTestHdr, 4, 1, fpHeader) != 1)
    1895             :     {
    1896           0 :         CPL_IGNORE_RET_VAL(VSIFCloseL(fpHeader));
    1897           0 :         return nullptr;
    1898             :     }
    1899         340 :     if (!STARTS_WITH(szTestHdr, "ENVI"))
    1900             :     {
    1901          81 :         CPL_IGNORE_RET_VAL(VSIFCloseL(fpHeader));
    1902          81 :         return nullptr;
    1903             :     }
    1904             : 
    1905             :     // Create a corresponding GDALDataset.
    1906         518 :     auto poDS = std::make_unique<ENVIDataset>();
    1907         259 :     poDS->pszHDRFilename = CPLStrdup(osHdrFilename);
    1908         259 :     poDS->fp = fpHeader;
    1909         259 :     poDS->m_aosHeader = GDALReadENVIHeader(fpHeader);
    1910             : 
    1911             :     // Has the user selected the .hdr file to open?
    1912         259 :     if (poOpenInfo->IsExtensionEqualToCI("hdr"))
    1913             :     {
    1914           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1915             :                  "The selected file is an ENVI header file, but to "
    1916             :                  "open ENVI datasets, the data file should be selected "
    1917             :                  "instead of the .hdr file.  Please try again selecting "
    1918             :                  "the data file corresponding to the header file:  "
    1919             :                  "%s",
    1920             :                  poOpenInfo->pszFilename);
    1921           0 :         return nullptr;
    1922             :     }
    1923             : 
    1924             :     // Has the user selected the .sta (stats) file to open?
    1925         259 :     if (poOpenInfo->IsExtensionEqualToCI("sta"))
    1926             :     {
    1927           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1928             :                  "The selected file is an ENVI statistics file. "
    1929             :                  "To open ENVI datasets, the data file should be selected "
    1930             :                  "instead of the .sta file.  Please try again selecting "
    1931             :                  "the data file corresponding to the statistics file:  "
    1932             :                  "%s",
    1933             :                  poOpenInfo->pszFilename);
    1934           0 :         return nullptr;
    1935             :     }
    1936             : 
    1937             :     // Extract required values from the .hdr.
    1938         259 :     const char *pszLines = poDS->m_aosHeader.FetchNameValueDef("lines", "0");
    1939         259 :     const auto nLines64 = std::strtoll(pszLines, nullptr, 10);
    1940         259 :     const int nLines = static_cast<int>(std::min<int64_t>(nLines64, INT_MAX));
    1941         259 :     if (nLines < nLines64)
    1942             :     {
    1943           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    1944             :                  "Limiting number of lines from %s to %d due to GDAL raster "
    1945             :                  "data model limitation",
    1946             :                  pszLines, nLines);
    1947             :     }
    1948             : 
    1949             :     const char *pszSamples =
    1950         259 :         poDS->m_aosHeader.FetchNameValueDef("samples", "0");
    1951         259 :     const auto nSamples64 = std::strtoll(pszSamples, nullptr, 10);
    1952             :     const int nSamples =
    1953         259 :         static_cast<int>(std::min<int64_t>(nSamples64, INT_MAX));
    1954         259 :     if (nSamples < nSamples64)
    1955             :     {
    1956           1 :         CPLError(
    1957             :             CE_Failure, CPLE_AppDefined,
    1958             :             "Cannot handle samples=%s due to GDAL raster data model limitation",
    1959             :             pszSamples);
    1960           1 :         return nullptr;
    1961             :     }
    1962             : 
    1963         258 :     const char *pszBands = poDS->m_aosHeader.FetchNameValueDef("bands", "0");
    1964         258 :     const auto nBands64 = std::strtoll(pszBands, nullptr, 10);
    1965         258 :     const int nBands = static_cast<int>(std::min<int64_t>(nBands64, INT_MAX));
    1966         258 :     if (nBands < nBands64)
    1967             :     {
    1968           4 :         CPLError(
    1969             :             CE_Failure, CPLE_AppDefined,
    1970             :             "Cannot handle bands=%s due to GDAL raster data model limitation",
    1971             :             pszBands);
    1972           4 :         return nullptr;
    1973             :     }
    1974             : 
    1975             :     // In case, there is no interleave keyword, we try to derive it from the
    1976             :     // file extension.
    1977         254 :     CPLString osInterleave = poDS->m_aosHeader.FetchNameValueDef(
    1978         508 :         "interleave", poOpenInfo->osExtension.c_str());
    1979             : 
    1980         254 :     if (!STARTS_WITH_CI(osInterleave, "BSQ") &&
    1981         265 :         !STARTS_WITH_CI(osInterleave, "BIP") &&
    1982          11 :         !STARTS_WITH_CI(osInterleave, "BIL"))
    1983             :     {
    1984           0 :         CPLDebug("ENVI", "Unset or unknown value for 'interleave' keyword --> "
    1985             :                          "assuming BSQ interleaving");
    1986           0 :         osInterleave = "bsq";
    1987             :     }
    1988             : 
    1989         508 :     if (!GDALCheckDatasetDimensions(nSamples, nLines) ||
    1990         254 :         !GDALCheckBandCount(nBands, FALSE))
    1991             :     {
    1992           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    1993             :                  "The file appears to have an associated ENVI header, but "
    1994             :                  "one or more of the samples, lines and bands "
    1995             :                  "keywords appears to be missing or invalid.");
    1996           2 :         return nullptr;
    1997             :     }
    1998             : 
    1999             :     int nHeaderSize =
    2000         252 :         atoi(poDS->m_aosHeader.FetchNameValueDef("header_offset", "0"));
    2001             : 
    2002             :     // Translate the datatype.
    2003         252 :     GDALDataType eType = GDT_UInt8;
    2004             : 
    2005         252 :     const char *pszDataType = poDS->m_aosHeader["data_type"];
    2006         252 :     if (pszDataType != nullptr)
    2007             :     {
    2008         251 :         switch (atoi(pszDataType))
    2009             :         {
    2010         171 :             case 1:
    2011         171 :                 eType = GDT_UInt8;
    2012         171 :                 break;
    2013             : 
    2014           9 :             case 2:
    2015           9 :                 eType = GDT_Int16;
    2016           9 :                 break;
    2017             : 
    2018           7 :             case 3:
    2019           7 :                 eType = GDT_Int32;
    2020           7 :                 break;
    2021             : 
    2022          12 :             case 4:
    2023          12 :                 eType = GDT_Float32;
    2024          12 :                 break;
    2025             : 
    2026           7 :             case 5:
    2027           7 :                 eType = GDT_Float64;
    2028           7 :                 break;
    2029             : 
    2030           8 :             case 6:
    2031           8 :                 eType = GDT_CFloat32;
    2032           8 :                 break;
    2033             : 
    2034           5 :             case 9:
    2035           5 :                 eType = GDT_CFloat64;
    2036           5 :                 break;
    2037             : 
    2038          17 :             case 12:
    2039          17 :                 eType = GDT_UInt16;
    2040          17 :                 break;
    2041             : 
    2042           7 :             case 13:
    2043           7 :                 eType = GDT_UInt32;
    2044           7 :                 break;
    2045             : 
    2046           4 :             case 14:
    2047           4 :                 eType = GDT_Int64;
    2048           4 :                 break;
    2049             : 
    2050           4 :             case 15:
    2051           4 :                 eType = GDT_UInt64;
    2052           4 :                 break;
    2053             : 
    2054           0 :             default:
    2055           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2056             :                          "The file does not have a value for the data_type "
    2057             :                          "that is recognised by the GDAL ENVI driver.");
    2058           0 :                 return nullptr;
    2059             :         }
    2060             :     }
    2061             : 
    2062             :     // Translate the byte order.
    2063         252 :     RawRasterBand::ByteOrder eByteOrder = RawRasterBand::NATIVE_BYTE_ORDER;
    2064             : 
    2065         252 :     const char *pszByteOrder = poDS->m_aosHeader["byte_order"];
    2066         252 :     if (pszByteOrder != nullptr)
    2067             :     {
    2068         252 :         eByteOrder = atoi(pszByteOrder) == 0
    2069         252 :                          ? RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN
    2070             :                          : RawRasterBand::ByteOrder::ORDER_BIG_ENDIAN;
    2071             :     }
    2072             : 
    2073             :     // Warn about unsupported file types virtual mosaic and meta file.
    2074         252 :     const char *pszEnviFileType = poDS->m_aosHeader["file_type"];
    2075         252 :     if (pszEnviFileType != nullptr)
    2076             :     {
    2077             :         // When the file type is one of these we return an invalid file type err
    2078             :         // 'envi meta file'
    2079             :         // 'envi virtual mosaic'
    2080             :         // 'envi spectral library'
    2081             :         // 'envi fft result'
    2082             : 
    2083             :         // When the file type is one of these we open it
    2084             :         // 'envi standard'
    2085             :         // 'envi classification'
    2086             : 
    2087             :         // When the file type is anything else we attempt to open it as a
    2088             :         // raster.
    2089             : 
    2090             :         // envi gdal does not support any of these
    2091             :         // all others we will attempt to open
    2092         252 :         if (EQUAL(pszEnviFileType, "envi meta file") ||
    2093         252 :             EQUAL(pszEnviFileType, "envi virtual mosaic") ||
    2094         252 :             EQUAL(pszEnviFileType, "envi spectral library"))
    2095             :         {
    2096           0 :             CPLError(CE_Failure, CPLE_OpenFailed,
    2097             :                      "File %s contains an invalid file type in the ENVI .hdr "
    2098             :                      "GDAL does not support '%s' type files.",
    2099             :                      poOpenInfo->pszFilename, pszEnviFileType);
    2100           0 :             return nullptr;
    2101             :         }
    2102             :     }
    2103             : 
    2104             :     // Detect (gzipped) compressed datasets.
    2105             :     const bool bIsCompressed =
    2106         252 :         atoi(poDS->m_aosHeader.FetchNameValueDef("file_compression", "0")) != 0;
    2107             : 
    2108             :     // Capture some information from the file that is of interest.
    2109         252 :     poDS->nRasterXSize = nSamples;
    2110         252 :     poDS->nRasterYSize = nLines;
    2111         252 :     poDS->eAccess = poOpenInfo->eAccess;
    2112             : 
    2113             :     // Reopen file in update mode if necessary.
    2114         504 :     CPLString osImageFilename(poOpenInfo->pszFilename);
    2115         252 :     if (bIsCompressed)
    2116           1 :         osImageFilename = "/vsigzip/" + osImageFilename;
    2117         252 :     if (poOpenInfo->eAccess == GA_Update)
    2118             :     {
    2119          96 :         if (bIsCompressed)
    2120             :         {
    2121           0 :             CPLError(CE_Failure, CPLE_OpenFailed,
    2122             :                      "Cannot open compressed file in update mode.");
    2123           0 :             return nullptr;
    2124             :         }
    2125          96 :         poDS->fpImage = VSIFOpenL(osImageFilename, "rb+");
    2126             :     }
    2127             :     else
    2128             :     {
    2129         156 :         poDS->fpImage = VSIFOpenL(osImageFilename, "rb");
    2130             :     }
    2131             : 
    2132         252 :     if (poDS->fpImage == nullptr)
    2133             :     {
    2134           0 :         CPLError(CE_Failure, CPLE_OpenFailed,
    2135             :                  "Failed to re-open %s within ENVI driver.",
    2136             :                  poOpenInfo->pszFilename);
    2137           0 :         return nullptr;
    2138             :     }
    2139             : 
    2140             :     // Compute the line offset.
    2141         252 :     const int nDataSize = GDALGetDataTypeSizeBytes(eType);
    2142         252 :     int nPixelOffset = 0;
    2143         252 :     int nLineOffset = 0;
    2144         252 :     vsi_l_offset nBandOffset = 0;
    2145         252 :     CPLAssert(nDataSize != 0);
    2146         252 :     CPLAssert(nBands != 0);
    2147             : 
    2148         252 :     if (STARTS_WITH_CI(osInterleave, "bil"))
    2149             :     {
    2150          11 :         poDS->eInterleave = Interleave::BIL;
    2151          11 :         poDS->SetMetadataItem("INTERLEAVE", "LINE", "IMAGE_STRUCTURE");
    2152          11 :         if (nSamples > std::numeric_limits<int>::max() / (nDataSize * nBands))
    2153             :         {
    2154           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Int overflow occurred.");
    2155           0 :             return nullptr;
    2156             :         }
    2157          11 :         nLineOffset = nDataSize * nSamples * nBands;
    2158          11 :         nPixelOffset = nDataSize;
    2159          11 :         nBandOffset = static_cast<vsi_l_offset>(nDataSize) * nSamples;
    2160             :     }
    2161         241 :     else if (STARTS_WITH_CI(osInterleave, "bip"))
    2162             :     {
    2163          37 :         poDS->eInterleave = Interleave::BIP;
    2164          37 :         poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    2165          37 :         if (nSamples > std::numeric_limits<int>::max() / (nDataSize * nBands))
    2166             :         {
    2167           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Int overflow occurred.");
    2168           0 :             return nullptr;
    2169             :         }
    2170          37 :         nLineOffset = nDataSize * nSamples * nBands;
    2171          37 :         nPixelOffset = nDataSize * nBands;
    2172          37 :         nBandOffset = nDataSize;
    2173             :     }
    2174             :     else
    2175             :     {
    2176         204 :         poDS->eInterleave = Interleave::BSQ;
    2177         204 :         poDS->SetMetadataItem("INTERLEAVE", "BAND", "IMAGE_STRUCTURE");
    2178         204 :         if (nSamples > std::numeric_limits<int>::max() / nDataSize)
    2179             :         {
    2180           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Int overflow occurred.");
    2181           0 :             return nullptr;
    2182             :         }
    2183         204 :         nLineOffset = nDataSize * nSamples;
    2184         204 :         nPixelOffset = nDataSize;
    2185         204 :         if (nBands > 1)
    2186             :         {
    2187          68 :             if (nLineOffset > std::numeric_limits<int>::max() / nLines64)
    2188             :             {
    2189           0 :                 CPLError(CE_Failure, CPLE_AppDefined, "Int overflow occurred.");
    2190           0 :                 return nullptr;
    2191             :             }
    2192          68 :             nBandOffset = static_cast<vsi_l_offset>(nLineOffset) * nLines64;
    2193             :         }
    2194             :     }
    2195             : 
    2196         252 :     const char *pszMajorFrameOffset = poDS->m_aosHeader["major_frame_offsets"];
    2197         252 :     if (pszMajorFrameOffset != nullptr)
    2198             :     {
    2199             :         const CPLStringList aosMajorFrameOffsets(
    2200           0 :             poDS->SplitList(pszMajorFrameOffset));
    2201             : 
    2202           0 :         const int nTempCount = aosMajorFrameOffsets.size();
    2203           0 :         if (nTempCount == 2)
    2204             :         {
    2205           0 :             int nOffset1 = atoi(aosMajorFrameOffsets[0]);
    2206           0 :             int nOffset2 = atoi(aosMajorFrameOffsets[1]);
    2207           0 :             if (nOffset1 >= 0 && nOffset2 >= 0 &&
    2208           0 :                 nHeaderSize < INT_MAX - nOffset1 &&
    2209           0 :                 nOffset1 < INT_MAX - nOffset2 &&
    2210           0 :                 nOffset1 + nOffset2 < INT_MAX - nLineOffset)
    2211             :             {
    2212           0 :                 nHeaderSize += nOffset1;
    2213           0 :                 nLineOffset += nOffset1 + nOffset2;
    2214             :             }
    2215             :         }
    2216             :     }
    2217             : 
    2218             :     // Currently each ENVIRasterBand allocates nPixelOffset * nRasterXSize bytes
    2219             :     // so for a pixel interleaved scheme, this will allocate lots of memory!
    2220             :     // Actually this is quadratic in the number of bands!
    2221             :     // Do a few sanity checks to avoid excessive memory allocation on
    2222             :     // small files.
    2223             :     // But ultimately we should fix RawRasterBand to have a shared buffer
    2224             :     // among bands.
    2225         411 :     if (bFileSizeCheck &&
    2226         159 :         !RAWDatasetCheckMemoryUsage(
    2227         159 :             poDS->nRasterXSize, poDS->nRasterYSize, nBands, nDataSize,
    2228         159 :             nPixelOffset, nLineOffset, nHeaderSize, nBandOffset, poDS->fpImage))
    2229             :     {
    2230           0 :         return nullptr;
    2231             :     }
    2232             : 
    2233             :     // Create band information objects.
    2234        1326 :     for (int i = 0; i < nBands; i++)
    2235             :     {
    2236             :         auto poBand = std::make_unique<ENVIRasterBand>(
    2237        1074 :             poDS.get(), i + 1, poDS->fpImage, nHeaderSize + nBandOffset * i,
    2238        1074 :             nPixelOffset, nLineOffset, eType, eByteOrder);
    2239        1074 :         if (!poBand->IsValid())
    2240           0 :             return nullptr;
    2241        1074 :         poDS->SetBand(i + 1, std::move(poBand));
    2242             :     }
    2243             : 
    2244         252 :     GDALApplyENVIHeaders(poDS.get(), poDS->m_aosHeader, nullptr);
    2245             : 
    2246             :     // Set all the header metadata into the ENVI domain.
    2247             :     {
    2248         252 :         char **pTmp = poDS->m_aosHeader.List();
    2249        2786 :         while (*pTmp != nullptr)
    2250             :         {
    2251             :             const CPLStringList aosTokens(CSLTokenizeString2(
    2252        2534 :                 *pTmp, "=", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
    2253        2534 :             if (aosTokens.size() == 2)
    2254             :             {
    2255        2525 :                 poDS->SetMetadataItem(aosTokens[0], aosTokens[1], "ENVI");
    2256             :             }
    2257        2534 :             pTmp++;
    2258             :         }
    2259             :     }
    2260             : 
    2261             :     // Read the stats file if it is present.
    2262         252 :     poDS->ProcessStatsFile();
    2263             : 
    2264             :     // Look for mapinfo.
    2265         252 :     const char *pszMapInfo = poDS->m_aosHeader["map_info"];
    2266         252 :     if (pszMapInfo != nullptr)
    2267             :     {
    2268         105 :         poDS->bFoundMapinfo = CPL_TO_BOOL(poDS->ProcessMapinfo(pszMapInfo));
    2269             :     }
    2270             : 
    2271             :     // Look for RPC.
    2272         252 :     const char *pszRPCInfo = poDS->m_aosHeader["rpc_info"];
    2273         252 :     if (!poDS->bFoundMapinfo && pszRPCInfo != nullptr)
    2274             :     {
    2275           6 :         poDS->ProcessRPCinfo(pszRPCInfo, poDS->nRasterXSize,
    2276           3 :                              poDS->nRasterYSize);
    2277             :     }
    2278             : 
    2279             :     // Look for geo_points / GCP
    2280         252 :     const char *pszGeoPoints = poDS->m_aosHeader["geo_points"];
    2281         252 :     if (!poDS->bFoundMapinfo && pszGeoPoints != nullptr)
    2282             :     {
    2283           2 :         poDS->ProcessGeoPoints(pszGeoPoints);
    2284             :     }
    2285             : 
    2286             :     // Initialize any PAM information.
    2287         252 :     poDS->SetDescription(poOpenInfo->pszFilename);
    2288         252 :     poDS->TryLoadXML();
    2289             : 
    2290             :     // Check for overviews.
    2291         252 :     poDS->oOvManager.Initialize(poDS.get(), poOpenInfo->pszFilename);
    2292             : 
    2293             :     // SetMetadata() calls in Open() makes the header dirty.
    2294             :     // Don't re-write the header if nothing external has changed the metadata.
    2295         252 :     poDS->bHeaderDirty = false;
    2296             : 
    2297         252 :     return poDS.release();
    2298             : }
    2299             : 
    2300         191 : int ENVIDataset::GetEnviType(GDALDataType eType)
    2301             : {
    2302         191 :     int iENVIType = 1;
    2303         191 :     switch (eType)
    2304             :     {
    2305         118 :         case GDT_UInt8:
    2306         118 :             iENVIType = 1;
    2307         118 :             break;
    2308           7 :         case GDT_Int16:
    2309           7 :             iENVIType = 2;
    2310           7 :             break;
    2311           6 :         case GDT_Int32:
    2312           6 :             iENVIType = 3;
    2313           6 :             break;
    2314           8 :         case GDT_Float32:
    2315           8 :             iENVIType = 4;
    2316           8 :             break;
    2317           6 :         case GDT_Float64:
    2318           6 :             iENVIType = 5;
    2319           6 :             break;
    2320           7 :         case GDT_CFloat32:
    2321           7 :             iENVIType = 6;
    2322           7 :             break;
    2323           6 :         case GDT_CFloat64:
    2324           6 :             iENVIType = 9;
    2325           6 :             break;
    2326          11 :         case GDT_UInt16:
    2327          11 :             iENVIType = 12;
    2328          11 :             break;
    2329           6 :         case GDT_UInt32:
    2330           6 :             iENVIType = 13;
    2331           6 :             break;
    2332           4 :         case GDT_Int64:
    2333           4 :             iENVIType = 14;
    2334           4 :             break;
    2335           4 :         case GDT_UInt64:
    2336           4 :             iENVIType = 15;
    2337           4 :             break;
    2338           8 :         default:
    2339           8 :             CPLError(CE_Failure, CPLE_AppDefined,
    2340             :                      "Attempt to create ENVI .hdr labelled dataset with an "
    2341             :                      "illegal data type (%s).",
    2342             :                      GDALGetDataTypeName(eType));
    2343           8 :             return 1;
    2344             :     }
    2345         183 :     return iENVIType;
    2346             : }
    2347             : 
    2348             : /************************************************************************/
    2349             : /*                               Create()                               */
    2350             : /************************************************************************/
    2351             : 
    2352         107 : GDALDataset *ENVIDataset::Create(const char *pszFilename, int nXSize,
    2353             :                                  int nYSize, int nBandsIn, GDALDataType eType,
    2354             :                                  char **papszOptions)
    2355             : 
    2356             : {
    2357             :     // Verify input options.
    2358         107 :     int iENVIType = GetEnviType(eType);
    2359         107 :     if (0 == iENVIType)
    2360           0 :         return nullptr;
    2361             : 
    2362             :     // Try to create the file.
    2363         107 :     VSILFILE *fp = VSIFOpenL(pszFilename, "wb");
    2364             : 
    2365         107 :     if (fp == nullptr)
    2366             :     {
    2367           3 :         CPLError(CE_Failure, CPLE_OpenFailed,
    2368             :                  "Attempt to create file `%s' failed.", pszFilename);
    2369           3 :         return nullptr;
    2370             :     }
    2371             : 
    2372             :     // Just write out a couple of bytes to establish the binary
    2373             :     // file, and then close it.
    2374             :     {
    2375             :         const bool bRet =
    2376         104 :             VSIFWriteL(static_cast<void *>(const_cast<char *>("\0\0")), 2, 1,
    2377         104 :                        fp) == 1;
    2378         104 :         if (VSIFCloseL(fp) != 0 || !bRet)
    2379           1 :             return nullptr;
    2380             :     }
    2381             : 
    2382             :     // Create the .hdr filename.
    2383         206 :     std::string osHDRFilename;
    2384         103 :     const char *pszSuffix = CSLFetchNameValue(papszOptions, "SUFFIX");
    2385         103 :     if (pszSuffix && STARTS_WITH_CI(pszSuffix, "ADD"))
    2386           3 :         osHDRFilename = CPLFormFilenameSafe(nullptr, pszFilename, "hdr");
    2387             :     else
    2388         100 :         osHDRFilename = CPLResetExtensionSafe(pszFilename, "hdr");
    2389             : 
    2390             :     // Open the file.
    2391         103 :     fp = VSIFOpenL(osHDRFilename.c_str(), "wt");
    2392         103 :     if (fp == nullptr)
    2393             :     {
    2394           0 :         CPLError(CE_Failure, CPLE_OpenFailed,
    2395             :                  "Attempt to create file `%s' failed.", osHDRFilename.c_str());
    2396           0 :         return nullptr;
    2397             :     }
    2398             : 
    2399             :     // Write out the header.
    2400             : #ifdef CPL_LSB
    2401         103 :     int iBigEndian = 0;
    2402             : #else
    2403             :     int iBigEndian = 1;
    2404             : #endif
    2405             : 
    2406             :     // Undocumented
    2407         103 :     const char *pszByteOrder = CSLFetchNameValue(papszOptions, "@BYTE_ORDER");
    2408         103 :     if (pszByteOrder && EQUAL(pszByteOrder, "LITTLE_ENDIAN"))
    2409           1 :         iBigEndian = 0;
    2410         102 :     else if (pszByteOrder && EQUAL(pszByteOrder, "BIG_ENDIAN"))
    2411           1 :         iBigEndian = 1;
    2412             : 
    2413         103 :     bool bRet = VSIFPrintfL(fp, "ENVI\n") > 0;
    2414         103 :     bRet &= VSIFPrintfL(fp, "samples = %d\nlines   = %d\nbands   = %d\n",
    2415         103 :                         nXSize, nYSize, nBandsIn) > 0;
    2416         103 :     bRet &=
    2417         103 :         VSIFPrintfL(fp, "header offset = 0\nfile type = ENVI Standard\n") > 0;
    2418         103 :     bRet &= VSIFPrintfL(fp, "data type = %d\n", iENVIType) > 0;
    2419         103 :     const char *pszInterleaving = CSLFetchNameValue(papszOptions, "INTERLEAVE");
    2420         103 :     if (pszInterleaving)
    2421             :     {
    2422          23 :         if (STARTS_WITH_CI(pszInterleaving, "bip"))
    2423           6 :             pszInterleaving = "bip";  // interleaved by pixel
    2424          17 :         else if (STARTS_WITH_CI(pszInterleaving, "bil"))
    2425           4 :             pszInterleaving = "bil";  // interleaved by line
    2426             :         else
    2427          13 :             pszInterleaving = "bsq";  // band sequential by default
    2428             :     }
    2429             :     else
    2430             :     {
    2431          80 :         pszInterleaving = "bsq";
    2432             :     }
    2433         103 :     bRet &= VSIFPrintfL(fp, "interleave = %s\n", pszInterleaving) > 0;
    2434         103 :     bRet &= VSIFPrintfL(fp, "byte order = %d\n", iBigEndian) > 0;
    2435             : 
    2436         103 :     if (VSIFCloseL(fp) != 0 || !bRet)
    2437           9 :         return nullptr;
    2438             : 
    2439          94 :     GDALOpenInfo oOpenInfo(pszFilename, GA_Update);
    2440          94 :     ENVIDataset *poDS = Open(&oOpenInfo, false);
    2441          94 :     if (poDS)
    2442             :     {
    2443          93 :         poDS->SetFillFile();
    2444             :     }
    2445          94 :     return poDS;
    2446             : }
    2447             : 
    2448             : /************************************************************************/
    2449             : /*                           ENVIRasterBand()                           */
    2450             : /************************************************************************/
    2451             : 
    2452        1074 : ENVIRasterBand::ENVIRasterBand(GDALDataset *poDSIn, int nBandIn,
    2453             :                                VSILFILE *fpRawIn, vsi_l_offset nImgOffsetIn,
    2454             :                                int nPixelOffsetIn, int nLineOffsetIn,
    2455             :                                GDALDataType eDataTypeIn,
    2456        1074 :                                RawRasterBand::ByteOrder eByteOrderIn)
    2457             :     : RawRasterBand(poDSIn, nBandIn, fpRawIn, nImgOffsetIn, nPixelOffsetIn,
    2458             :                     nLineOffsetIn, eDataTypeIn, eByteOrderIn,
    2459        1074 :                     RawRasterBand::OwnFP::NO)
    2460             : {
    2461             :     // ENVI datasets might be sparse (see #915)
    2462        1074 :     bTruncatedFileAllowed = true;
    2463        1074 : }
    2464             : 
    2465             : /************************************************************************/
    2466             : /*                           SetDescription()                           */
    2467             : /************************************************************************/
    2468             : 
    2469         260 : void ENVIRasterBand::SetDescription(const char *pszDescription)
    2470             : {
    2471         260 :     cpl::down_cast<ENVIDataset *>(poDS)->bHeaderDirty = true;
    2472         260 :     RawRasterBand::SetDescription(pszDescription);
    2473         260 : }
    2474             : 
    2475             : /************************************************************************/
    2476             : /*                           SetCategoryNames()                         */
    2477             : /************************************************************************/
    2478             : 
    2479           4 : CPLErr ENVIRasterBand::SetCategoryNames(char **papszCategoryNamesIn)
    2480             : {
    2481           4 :     cpl::down_cast<ENVIDataset *>(poDS)->bHeaderDirty = true;
    2482           4 :     return RawRasterBand::SetCategoryNames(papszCategoryNamesIn);
    2483             : }
    2484             : 
    2485             : /************************************************************************/
    2486             : /*                            SetNoDataValue()                          */
    2487             : /************************************************************************/
    2488             : 
    2489          12 : CPLErr ENVIRasterBand::SetNoDataValue(double dfNoDataValue)
    2490             : {
    2491          12 :     cpl::down_cast<ENVIDataset *>(poDS)->bHeaderDirty = true;
    2492             : 
    2493          12 :     if (poDS->GetRasterCount() > 1)
    2494             :     {
    2495           8 :         int bOtherBandHasNoData = false;
    2496           8 :         const int nOtherBand = nBand > 1 ? 1 : 2;
    2497           8 :         double dfOtherBandNoData = poDS->GetRasterBand(nOtherBand)
    2498           8 :                                        ->GetNoDataValue(&bOtherBandHasNoData);
    2499          12 :         if (bOtherBandHasNoData &&
    2500           8 :             !(std::isnan(dfOtherBandNoData) && std::isnan(dfNoDataValue)) &&
    2501             :             dfOtherBandNoData != dfNoDataValue)
    2502             :         {
    2503           2 :             CPLError(CE_Warning, CPLE_AppDefined,
    2504             :                      "Nodata value of band %d (%.17g) is different from nodata "
    2505             :                      "value from band %d (%.17g). Only the later will be "
    2506             :                      "written in the ENVI header as the \"data ignore value\"",
    2507             :                      nBand, dfNoDataValue, nOtherBand, dfOtherBandNoData);
    2508             :         }
    2509             :     }
    2510             : 
    2511          12 :     return RawRasterBand::SetNoDataValue(dfNoDataValue);
    2512             : }
    2513             : 
    2514             : /************************************************************************/
    2515             : /*                         SetColorInterpretation()                     */
    2516             : /************************************************************************/
    2517             : 
    2518          51 : CPLErr ENVIRasterBand::SetColorInterpretation(GDALColorInterp eColorInterp)
    2519             : {
    2520          51 :     cpl::down_cast<ENVIDataset *>(poDS)->bHeaderDirty = true;
    2521          51 :     return RawRasterBand::SetColorInterpretation(eColorInterp);
    2522             : }
    2523             : 
    2524             : /************************************************************************/
    2525             : /*                             SetOffset()                              */
    2526             : /************************************************************************/
    2527             : 
    2528          10 : CPLErr ENVIRasterBand::SetOffset(double dfValue)
    2529             : {
    2530          10 :     cpl::down_cast<ENVIDataset *>(poDS)->bHeaderDirty = true;
    2531          10 :     return RawRasterBand::SetOffset(dfValue);
    2532             : }
    2533             : 
    2534             : /************************************************************************/
    2535             : /*                             SetScale()                               */
    2536             : /************************************************************************/
    2537             : 
    2538          10 : CPLErr ENVIRasterBand::SetScale(double dfValue)
    2539             : {
    2540          10 :     cpl::down_cast<ENVIDataset *>(poDS)->bHeaderDirty = true;
    2541          10 :     return RawRasterBand::SetScale(dfValue);
    2542             : }
    2543             : 
    2544             : /************************************************************************/
    2545             : /*                         GDALRegister_ENVI()                          */
    2546             : /************************************************************************/
    2547             : 
    2548        2058 : void GDALRegister_ENVI()
    2549             : {
    2550        2058 :     if (GDALGetDriverByName("ENVI") != nullptr)
    2551         283 :         return;
    2552             : 
    2553        1775 :     GDALDriver *poDriver = new GDALDriver();
    2554             : 
    2555        1775 :     poDriver->SetDescription("ENVI");
    2556        1775 :     poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
    2557        1775 :     poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "ENVI .hdr Labelled");
    2558        1775 :     poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/envi.html");
    2559        1775 :     poDriver->SetMetadataItem(GDAL_DMD_EXTENSION, "");
    2560        1775 :     poDriver->SetMetadataItem(GDAL_DMD_CREATIONDATATYPES,
    2561             :                               "Byte Int16 UInt16 Int32 UInt32 Int64 UInt64 "
    2562        1775 :                               "Float32 Float64 CFloat32 CFloat64");
    2563        1775 :     poDriver->SetMetadataItem(
    2564             :         GDAL_DMD_CREATIONOPTIONLIST,
    2565             :         "<CreationOptionList>"
    2566             :         "   <Option name='SUFFIX' type='string-select'>"
    2567             :         "       <Value>ADD</Value>"
    2568             :         "   </Option>"
    2569             :         "   <Option name='INTERLEAVE' type='string-select'>"
    2570             :         "       <Value>BIP</Value>"
    2571             :         "       <Value>BIL</Value>"
    2572             :         "       <Value>BSQ</Value>"
    2573             :         "   </Option>"
    2574        1775 :         "</CreationOptionList>");
    2575             : 
    2576        1775 :     poDriver->SetMetadataItem(GDAL_DCAP_UPDATE, "YES");
    2577        1775 :     poDriver->SetMetadataItem(GDAL_DMD_UPDATE_ITEMS,
    2578             :                               "GeoTransform SRS GCPs NoData "
    2579        1775 :                               "RasterValues DatasetMetadata");
    2580             : 
    2581        1775 :     poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
    2582        1775 :     poDriver->pfnOpen = ENVIDataset::Open;
    2583        1775 :     poDriver->pfnCreate = ENVIDataset::Create;
    2584             : 
    2585        1775 :     GetGDALDriverManager()->RegisterDriver(poDriver);
    2586             : }

Generated by: LCOV version 1.14