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

Generated by: LCOV version 1.14