LTP GCOV extension - code coverage report
Current view: directory - frmts/raw - envidataset.cpp
Test: gdal_filtered.info
Date: 2010-07-12 Instrumented lines: 834
Code covered: 57.2 % Executed lines: 477

       1                 : /******************************************************************************
       2                 :  * $Id: envidataset.cpp 19977 2010-07-05 19:07:38Z chaitanya $
       3                 :  *
       4                 :  * Project:  ENVI .hdr Driver
       5                 :  * Purpose:  Implementation of ENVI .hdr labelled raw raster support.
       6                 :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       7                 :  * Maintainer: Chris Padwick (cpadwick at ittvis.com)
       8                 :  *
       9                 :  ******************************************************************************
      10                 :  * Copyright (c) 2002, Frank Warmerdam
      11                 :  *
      12                 :  * Permission is hereby granted, free of charge, to any person obtaining a
      13                 :  * copy of this software and associated documentation files (the "Software"),
      14                 :  * to deal in the Software without restriction, including without limitation
      15                 :  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
      16                 :  * and/or sell copies of the Software, and to permit persons to whom the
      17                 :  * Software is furnished to do so, subject to the following conditions:
      18                 :  *
      19                 :  * The above copyright notice and this permission notice shall be included
      20                 :  * in all copies or substantial portions of the Software.
      21                 :  *
      22                 :  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
      23                 :  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      24                 :  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
      25                 :  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      26                 :  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      27                 :  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
      28                 :  * DEALINGS IN THE SOFTWARE.
      29                 :  ****************************************************************************/
      30                 : 
      31                 : #include "rawdataset.h"
      32                 : #include "ogr_spatialref.h"
      33                 : #include "cpl_string.h"
      34                 : 
      35                 : CPL_CVSID("$Id: envidataset.cpp 19977 2010-07-05 19:07:38Z chaitanya $");
      36                 : 
      37                 : CPL_C_START
      38                 : void GDALRegister_ENVI(void);
      39                 : CPL_C_END
      40                 : 
      41                 : static const int anUsgsEsriZones[] =
      42                 : {
      43                 :   101, 3101,
      44                 :   102, 3126,
      45                 :   201, 3151,
      46                 :   202, 3176,
      47                 :   203, 3201,
      48                 :   301, 3226,
      49                 :   302, 3251,
      50                 :   401, 3276,
      51                 :   402, 3301,
      52                 :   403, 3326,
      53                 :   404, 3351,
      54                 :   405, 3376,
      55                 :   406, 3401,
      56                 :   407, 3426,
      57                 :   501, 3451,
      58                 :   502, 3476,
      59                 :   503, 3501,
      60                 :   600, 3526,
      61                 :   700, 3551,
      62                 :   901, 3601,
      63                 :   902, 3626,
      64                 :   903, 3576,
      65                 :  1001, 3651,
      66                 :  1002, 3676,
      67                 :  1101, 3701,
      68                 :  1102, 3726,
      69                 :  1103, 3751,
      70                 :  1201, 3776,
      71                 :  1202, 3801,
      72                 :  1301, 3826,
      73                 :  1302, 3851,
      74                 :  1401, 3876,
      75                 :  1402, 3901,
      76                 :  1501, 3926,
      77                 :  1502, 3951,
      78                 :  1601, 3976,
      79                 :  1602, 4001,
      80                 :  1701, 4026,
      81                 :  1702, 4051,
      82                 :  1703, 6426,
      83                 :  1801, 4076,
      84                 :  1802, 4101,
      85                 :  1900, 4126,
      86                 :  2001, 4151,
      87                 :  2002, 4176,
      88                 :  2101, 4201,
      89                 :  2102, 4226,
      90                 :  2103, 4251,
      91                 :  2111, 6351,
      92                 :  2112, 6376,
      93                 :  2113, 6401,
      94                 :  2201, 4276,
      95                 :  2202, 4301,
      96                 :  2203, 4326,
      97                 :  2301, 4351,
      98                 :  2302, 4376,
      99                 :  2401, 4401,
     100                 :  2402, 4426,
     101                 :  2403, 4451,
     102                 :  2500,    0,
     103                 :  2501, 4476,
     104                 :  2502, 4501,
     105                 :  2503, 4526,
     106                 :  2600,    0,
     107                 :  2601, 4551,
     108                 :  2602, 4576,
     109                 :  2701, 4601,
     110                 :  2702, 4626,
     111                 :  2703, 4651,
     112                 :  2800, 4676,
     113                 :  2900, 4701,
     114                 :  3001, 4726,
     115                 :  3002, 4751,
     116                 :  3003, 4776,
     117                 :  3101, 4801,
     118                 :  3102, 4826,
     119                 :  3103, 4851,
     120                 :  3104, 4876,
     121                 :  3200, 4901,
     122                 :  3301, 4926,
     123                 :  3302, 4951,
     124                 :  3401, 4976,
     125                 :  3402, 5001,
     126                 :  3501, 5026,
     127                 :  3502, 5051,
     128                 :  3601, 5076,
     129                 :  3602, 5101,
     130                 :  3701, 5126,
     131                 :  3702, 5151,
     132                 :  3800, 5176,
     133                 :  3900,    0,
     134                 :  3901, 5201,
     135                 :  3902, 5226,
     136                 :  4001, 5251,
     137                 :  4002, 5276,
     138                 :  4100, 5301,
     139                 :  4201, 5326,
     140                 :  4202, 5351,
     141                 :  4203, 5376,
     142                 :  4204, 5401,
     143                 :  4205, 5426,
     144                 :  4301, 5451,
     145                 :  4302, 5476,
     146                 :  4303, 5501,
     147                 :  4400, 5526,
     148                 :  4501, 5551,
     149                 :  4502, 5576,
     150                 :  4601, 5601,
     151                 :  4602, 5626,
     152                 :  4701, 5651,
     153                 :  4702, 5676,
     154                 :  4801, 5701,
     155                 :  4802, 5726,
     156                 :  4803, 5751,
     157                 :  4901, 5776,
     158                 :  4902, 5801,
     159                 :  4903, 5826,
     160                 :  4904, 5851,
     161                 :  5001, 6101,
     162                 :  5002, 6126,
     163                 :  5003, 6151,
     164                 :  5004, 6176,
     165                 :  5005, 6201,
     166                 :  5006, 6226,
     167                 :  5007, 6251,
     168                 :  5008, 6276,
     169                 :  5009, 6301,
     170                 :  5010, 6326,
     171                 :  5101, 5876,
     172                 :  5102, 5901,
     173                 :  5103, 5926,
     174                 :  5104, 5951,
     175                 :  5105, 5976,
     176                 :  5201, 6001,
     177                 :  5200, 6026,
     178                 :  5200, 6076,
     179                 :  5201, 6051,
     180                 :  5202, 6051,
     181                 :  5300,    0, 
     182                 :  5400,    0
     183                 : };
     184                 : 
     185                 : /************************************************************************/
     186                 : /*                           ITTVISToUSGSZone()                         */
     187                 : /*                                                                      */
     188                 : /*      Convert ITTVIS style state plane zones to NOS style state       */
     189                 : /*      plane zones.  The ENVI default is to use the new NOS zones,     */
     190                 : /*      but the old state plane zones can be used.  Handle this.        */ 
     191                 : /************************************************************************/
     192                 : 
     193               0 : static int ITTVISToUSGSZone( int nITTVISZone )
     194                 : 
     195                 : {
     196               0 :     int   nPairs = sizeof(anUsgsEsriZones) / (2*sizeof(int));
     197                 :     int   i;
     198                 :     
     199                 :   // Default is to use the zone as-is, as long as it is in the 
     200                 :   // available list
     201               0 :     for( i = 0; i < nPairs; i++ )
     202                 :     {
     203               0 :         if( anUsgsEsriZones[i*2] == nITTVISZone )
     204               0 :             return anUsgsEsriZones[i*2];
     205                 :     }
     206                 : 
     207                 :   // If not found in the new style, see if it is present in the
     208                 :   // old style list and convert it.  We don't expect to see this
     209                 :   // often, but older files allowed it and may still exist.
     210               0 :     for( i = 0; i < nPairs; i++ )
     211                 :     {
     212               0 :         if( anUsgsEsriZones[i*2+1] == nITTVISZone )
     213               0 :             return anUsgsEsriZones[i*2];
     214                 :     }
     215                 : 
     216               0 :     return nITTVISZone; // perhaps it *is* the USGS zone?
     217                 : }
     218                 : 
     219                 : /************************************************************************/
     220                 : /* ==================================================================== */
     221                 : /*        ENVIDataset       */
     222                 : /* ==================================================================== */
     223                 : /************************************************************************/
     224                 : 
     225                 : class ENVIDataset : public RawDataset
     226                 : {
     227                 :     FILE  *fpImage; // image data file.
     228                 :     FILE  *fp;    // header file
     229                 :     char  *pszHDRFilename;
     230                 : 
     231                 :     int   bFoundMapinfo;
     232                 : 
     233                 :     int         bHeaderDirty;
     234                 : 
     235                 :     double      adfGeoTransform[6];
     236                 : 
     237                 :     char  *pszProjection;
     238                 : 
     239                 :     char        **papszHeader;
     240                 : 
     241                 :     int         ReadHeader( FILE * );
     242                 :     int         ProcessMapinfo( const char * );
     243                 :     void        ProcessRPCinfo( const char * ,int ,int);
     244                 :     void        ProcessStatsFile();
     245                 :     long        byteSwapLong(long);
     246                 :     float       byteSwapFloat(float);
     247                 :     double      byteSwapDouble(double);
     248                 :     void        SetENVIDatum( OGRSpatialReference *, const char * );
     249                 :     void        SetENVIEllipse( OGRSpatialReference *, char ** );
     250                 :     void        WriteProjectionInfo();
     251                 :     
     252                 :     char        **SplitList( const char * );
     253                 : 
     254                 :     enum Interleave { BSQ, BIL, BIP } interleave;
     255                 :     static int GetEnviType(GDALDataType eType);
     256                 : 
     257                 :   public:
     258                 :             ENVIDataset();
     259                 :             ~ENVIDataset();
     260                 : 
     261                 :     virtual void    FlushCache( void );
     262                 :     virtual CPLErr  GetGeoTransform( double * padfTransform );
     263                 :     virtual CPLErr  SetGeoTransform( double * );
     264                 :     virtual const char *GetProjectionRef(void);
     265                 :     virtual CPLErr  SetProjection( const char * );
     266                 :     virtual char  **GetFileList(void); 
     267                 : 
     268                 :     static GDALDataset *Open( GDALOpenInfo * );
     269                 :     static GDALDataset *Create( const char * pszFilename,
     270                 :                                 int nXSize, int nYSize, int nBands,
     271                 :                                 GDALDataType eType, char ** papszOptions );
     272                 : };
     273                 : 
     274                 : /************************************************************************/
     275                 : /*                            ENVIDataset()                             */
     276                 : /************************************************************************/
     277                 : 
     278              98 : ENVIDataset::ENVIDataset()
     279                 : {
     280              98 :     fpImage = NULL;
     281              98 :     fp = NULL;
     282              98 :     pszHDRFilename = NULL;
     283              98 :     pszProjection = CPLStrdup("");
     284                 : 
     285              98 :     papszHeader = NULL;
     286                 : 
     287              98 :     bFoundMapinfo = FALSE;
     288                 : 
     289              98 :     bHeaderDirty = FALSE;
     290                 : 
     291              98 :     adfGeoTransform[0] = 0.0;
     292              98 :     adfGeoTransform[1] = 1.0;
     293              98 :     adfGeoTransform[2] = 0.0;
     294              98 :     adfGeoTransform[3] = 0.0;
     295              98 :     adfGeoTransform[4] = 0.0;
     296              98 :     adfGeoTransform[5] = 1.0;
     297              98 : }
     298                 : 
     299                 : /************************************************************************/
     300                 : /*                            ~ENVIDataset()                            */
     301                 : /************************************************************************/
     302                 : 
     303              98 : ENVIDataset::~ENVIDataset()
     304                 : 
     305                 : {
     306              98 :     FlushCache();
     307              98 :     if( fpImage )
     308              96 :         VSIFCloseL( fpImage );
     309              98 :     if( fp )
     310              98 :         VSIFCloseL( fp );
     311              98 :     if ( pszProjection )
     312              98 :   CPLFree( pszProjection );
     313              98 :     if ( papszHeader )
     314              98 :   CSLDestroy( papszHeader );
     315              98 :     CPLFree(pszHDRFilename);
     316              98 : }
     317                 : 
     318                 : /************************************************************************/
     319                 : /*                             FlushCache()                             */
     320                 : /************************************************************************/
     321                 : 
     322              98 : void ENVIDataset::FlushCache()
     323                 : 
     324                 : {
     325              98 :     RawDataset::FlushCache();
     326                 : 
     327              98 :     if ( !bHeaderDirty)
     328              53 :         return;
     329                 : 
     330              45 :     CPLLocaleC  oLocaleEnforcer;
     331                 : 
     332              45 :     VSIFSeekL( fp, 0, SEEK_SET );
     333                 : /* -------------------------------------------------------------------- */
     334                 : /*      Rewrite out the header.                                           */
     335                 : /* -------------------------------------------------------------------- */
     336                 :     int   iBigEndian;
     337                 : 
     338                 :     const char  *pszInterleaving;
     339                 :     char** catNames;
     340                 : 
     341                 : #ifdef CPL_LSB
     342              45 :     iBigEndian = 0;
     343                 : #else
     344                 :     iBigEndian = 1;
     345                 : #endif
     346                 : 
     347              45 :     VSIFPrintfL( fp, "ENVI\n" );
     348              45 :     if ("" != sDescription)
     349              45 :         VSIFPrintfL( fp, "description = {\n%s}\n", sDescription.c_str());
     350                 :     VSIFPrintfL( fp, "samples = %d\nlines   = %d\nbands   = %d\n",
     351              45 :     nRasterXSize, nRasterYSize, nBands );
     352                 : 
     353              45 :     GDALRasterBand* band = GetRasterBand(1);
     354              45 :     catNames = band->GetCategoryNames();
     355                 : 
     356              45 :     VSIFPrintfL( fp, "header offset = 0\n");
     357              45 :     if (0 == catNames)
     358              45 :         VSIFPrintfL( fp, "file type = ENVI Standard\n" );
     359                 :     else
     360               0 :         VSIFPrintfL( fp, "file type = ENVI Classification\n" );
     361                 : 
     362              45 :     int iENVIType = GetEnviType(band->GetRasterDataType());
     363              45 :     VSIFPrintfL( fp, "data type = %d\n", iENVIType );
     364              45 :     switch (interleave)
     365                 :     {
     366                 :       case BIP:
     367               0 :         pszInterleaving = "bip";        // interleaved by pixel
     368               0 :         break;
     369                 :       case BIL:
     370               0 :         pszInterleaving = "bil";        // interleaved by line
     371               0 :         break;
     372                 :       case BSQ:
     373              45 :         pszInterleaving = "bsq";    // band sequental by default
     374              45 :         break;
     375                 :       default:
     376               0 :       pszInterleaving = "bsq";
     377                 :         break;
     378                 :     }
     379              45 :     VSIFPrintfL( fp, "interleave = %s\n", pszInterleaving);
     380              45 :     VSIFPrintfL( fp, "byte order = %d\n", iBigEndian );
     381                 : 
     382                 : /* -------------------------------------------------------------------- */
     383                 : /*      Write class and color information                               */
     384                 : /* -------------------------------------------------------------------- */
     385              45 :     catNames = band->GetCategoryNames();
     386              45 :     if (0 != catNames)
     387                 :     {
     388               0 :         int nrClasses = 0;
     389               0 :         while (*catNames++)
     390               0 :             ++nrClasses;
     391                 : 
     392               0 :         if (nrClasses > 0)
     393                 :         {
     394               0 :             VSIFPrintfL( fp, "classes = %d\n", nrClasses );
     395                 : 
     396               0 :             GDALColorTable* colorTable = band->GetColorTable();
     397               0 :             if (0 != colorTable)
     398                 :             {
     399               0 :                 int nrColors = colorTable->GetColorEntryCount();
     400               0 :                 if (nrColors > nrClasses)
     401               0 :                     nrColors = nrClasses;
     402               0 :                 VSIFPrintfL( fp, "class lookup = {\n");
     403               0 :                 for (int i = 0; i < nrColors; ++i)
     404                 :                 {
     405               0 :                     const GDALColorEntry* color = colorTable->GetColorEntry(i);
     406               0 :                     VSIFPrintfL(fp, "%d, %d, %d", color->c1, color->c2, color->c3);
     407               0 :                     if (i < nrColors - 1)
     408                 :                     {
     409               0 :                         VSIFPrintfL(fp, ", ");
     410               0 :                         if (0 == (i+1) % 5)
     411               0 :                             VSIFPrintfL(fp, "\n");
     412                 :                     }
     413                 :                 }
     414               0 :                 VSIFPrintfL(fp, "}\n");
     415                 :             }
     416                 : 
     417               0 :             catNames = band->GetCategoryNames();
     418               0 :             if (0 != *catNames)
     419                 :             {
     420               0 :                 VSIFPrintfL( fp, "class names = {\n%s", *catNames++);
     421               0 :                 int i = 0;
     422               0 :                 while (*catNames) {
     423               0 :                     VSIFPrintfL( fp, ",");
     424               0 :                     if (0 == (++i) % 5)
     425               0 :                         VSIFPrintfL(fp, "\n");
     426               0 :                     VSIFPrintfL( fp, " %s", *catNames++);
     427                 :                 }
     428               0 :                 VSIFPrintfL( fp, "}\n");
     429                 :             }
     430                 :         }
     431                 :     }
     432                 : 
     433                 : /* -------------------------------------------------------------------- */
     434                 : /*      Write the rest of header.                                       */
     435                 : /* -------------------------------------------------------------------- */
     436              45 :     WriteProjectionInfo();
     437                 : 
     438                 : 
     439              45 :     VSIFPrintfL( fp, "band names = {\n" );
     440             130 :     for ( int i = 1; i <= nBands; i++ )
     441                 :     {
     442              85 :         CPLString sBandDesc = GetRasterBand( i )->GetDescription();
     443                 : 
     444              85 :         if ( sBandDesc == "" )
     445              83 :             sBandDesc = CPLSPrintf( "Band %d", i );
     446              85 :         VSIFPrintfL( fp, "%s", sBandDesc.c_str() );
     447              85 :         if ( i != nBands )
     448              40 :             VSIFPrintfL( fp, ",\n" );
     449                 :     }
     450              45 :     VSIFPrintfL( fp, "}\n" );
     451                 : }
     452                 : 
     453                 : /************************************************************************/
     454                 : /*                            GetFileList()                             */
     455                 : /************************************************************************/
     456                 :      
     457               6 : char **ENVIDataset::GetFileList() 
     458                 :     
     459                 : { 
     460               6 :     char **papszFileList = NULL; 
     461                 :     
     462                 :     // Main data file, etc.  
     463               6 :     papszFileList = GDALPamDataset::GetFileList(); 
     464                 :     
     465                 :     // Header file. 
     466               6 :     papszFileList = CSLAddString( papszFileList, pszHDRFilename ); 
     467                 :     
     468               6 :     return papszFileList; 
     469                 : }
     470                 : 
     471                 : /************************************************************************/
     472                 : /*                           GetEPSGGeogCS()                            */
     473                 : /*                                                                      */
     474                 : /*      Try to establish what the EPSG code for this coordinate         */
     475                 : /*      systems GEOGCS might be.  Returns -1 if no reasonable guess     */
     476                 : /*      can be made.                                                    */
     477                 : /*                                                                      */
     478                 : /*      TODO: We really need to do some name lookups.                   */
     479                 : /************************************************************************/
     480                 : 
     481              45 : static int ENVIGetEPSGGeogCS( OGRSpatialReference *poThis )
     482                 : 
     483                 : {
     484              45 :     const char *pszAuthName = poThis->GetAuthorityName( "GEOGCS" );
     485                 : 
     486                 : /* -------------------------------------------------------------------- */
     487                 : /*      Do we already have it?                                          */
     488                 : /* -------------------------------------------------------------------- */
     489              45 :     if( pszAuthName != NULL && EQUAL(pszAuthName,"epsg") )
     490              16 :         return atoi(poThis->GetAuthorityCode( "GEOGCS" ));
     491                 : 
     492                 : /* -------------------------------------------------------------------- */
     493                 : /*      Get the datum and geogcs names.                                 */
     494                 : /* -------------------------------------------------------------------- */
     495              29 :     const char *pszGEOGCS = poThis->GetAttrValue( "GEOGCS" );
     496              29 :     const char *pszDatum = poThis->GetAttrValue( "DATUM" );
     497                 : 
     498                 :     // We can only operate on coordinate systems with a geogcs.
     499              29 :     if( pszGEOGCS == NULL || pszDatum == NULL )
     500               0 :         return -1;
     501                 : 
     502                 : /* -------------------------------------------------------------------- */
     503                 : /*      Is this a "well known" geographic coordinate system?            */
     504                 : /* -------------------------------------------------------------------- */
     505                 :     int bWGS, bNAD;
     506                 : 
     507                 :     bWGS = strstr(pszGEOGCS,"WGS") != NULL
     508                 :         || strstr(pszDatum, "WGS")
     509                 :         || strstr(pszGEOGCS,"World Geodetic System")
     510                 :         || strstr(pszGEOGCS,"World_Geodetic_System")
     511                 :         || strstr(pszDatum, "World Geodetic System")
     512              29 :         || strstr(pszDatum, "World_Geodetic_System"); 
     513                 : 
     514                 :     bNAD = strstr(pszGEOGCS,"NAD") != NULL
     515                 :         || strstr(pszDatum, "NAD")
     516                 :         || strstr(pszGEOGCS,"North American")
     517                 :         || strstr(pszGEOGCS,"North_American")
     518                 :         || strstr(pszDatum, "North American")
     519              29 :         || strstr(pszDatum, "North_American"); 
     520                 : 
     521              29 :     if( bWGS && (strstr(pszGEOGCS,"84") || strstr(pszDatum,"84")) )
     522              25 :         return 4326;
     523                 : 
     524               4 :     if( bWGS && (strstr(pszGEOGCS,"72") || strstr(pszDatum,"72")) )
     525               0 :         return 4322;
     526                 : 
     527               4 :     if( bNAD && (strstr(pszGEOGCS,"83") || strstr(pszDatum,"83")) )
     528               1 :         return 4269;
     529                 : 
     530               3 :     if( bNAD && (strstr(pszGEOGCS,"27") || strstr(pszDatum,"27")) )
     531               0 :         return 4267;
     532                 : 
     533                 : /* -------------------------------------------------------------------- */
     534                 : /*      If we know the datum, associate the most likely GCS with        */
     535                 : /*      it.                                                             */
     536                 : /* -------------------------------------------------------------------- */
     537               3 :     pszAuthName = poThis->GetAuthorityName( "GEOGCS|DATUM" );
     538                 : 
     539               3 :     if( pszAuthName != NULL 
     540                 :         && EQUAL(pszAuthName,"epsg") 
     541                 :         && poThis->GetPrimeMeridian() == 0.0 )
     542                 :     {
     543               0 :         int nDatum = atoi(poThis->GetAuthorityCode("GEOGCS|DATUM"));
     544                 :         
     545               0 :         if( nDatum >= 6000 && nDatum <= 6999 )
     546               0 :             return nDatum - 2000;
     547                 :     }
     548                 : 
     549               3 :     return -1;
     550                 : }
     551                 : 
     552                 : /************************************************************************/
     553                 : /*                        WriteProjectionInfo()                         */
     554                 : /************************************************************************/
     555                 : 
     556              45 : void ENVIDataset::WriteProjectionInfo()
     557                 : 
     558                 : {
     559                 : /* -------------------------------------------------------------------- */
     560                 : /*      Format the location (geotransform) portion of the map info      */
     561                 : /*      line.                                                           */
     562                 : /* -------------------------------------------------------------------- */
     563              45 :     CPLString   osLocation;
     564                 : 
     565                 :     osLocation.Printf( "1, 1, %.15g, %.15g, %.15g, %.15g", 
     566                 :                        adfGeoTransform[0], adfGeoTransform[3], 
     567              45 :                        adfGeoTransform[1], fabs(adfGeoTransform[5]) );
     568                 :                        
     569                 : /* -------------------------------------------------------------------- */
     570                 : /*      Minimal case - write out simple geotransform if we have a       */
     571                 : /*      non-default geotransform.                                       */
     572                 : /* -------------------------------------------------------------------- */
     573              45 :     if( pszProjection == NULL || strlen(pszProjection) == 0 )
     574                 :     {
     575               0 :         if( adfGeoTransform[0] != 0.0 || adfGeoTransform[1] != 1.0
     576                 :             || adfGeoTransform[2] != 0.0 || adfGeoTransform[3] != 0.0
     577                 :             || adfGeoTransform[4] != 0.0 || adfGeoTransform[5] != 1.0 )
     578                 :         {
     579               0 :             const char* pszHemisphere = "North";
     580                 :             VSIFPrintfL( fp, "map info = {Unknown, %s, %d, %s}\n",
     581               0 :                         osLocation.c_str(), 0, pszHemisphere);
     582                 :         }
     583               0 :         return;
     584                 :     }
     585                 : 
     586                 : /* -------------------------------------------------------------------- */
     587                 : /*      Ingest WKT.                                                     */
     588                 : /* -------------------------------------------------------------------- */
     589              45 :     OGRSpatialReference oSRS;
     590                 :     
     591              45 :     char  *pszProj = pszProjection;
     592                 :     
     593              45 :     if( oSRS.importFromWkt( &pszProj ) != OGRERR_NONE )
     594                 :         return;
     595                 : 
     596                 : /* -------------------------------------------------------------------- */
     597                 : /*      Try to translate the datum and get major/minor ellipsoid        */
     598                 : /*      values.                                                         */
     599                 : /* -------------------------------------------------------------------- */
     600              45 :     int nEPSG_GCS = ENVIGetEPSGGeogCS( &oSRS );
     601              45 :     CPLString osDatum, osCommaDatum;
     602                 :     double dfA, dfB;
     603                 : 
     604              45 :     if( nEPSG_GCS == 4326 )
     605              40 :         osDatum = "WGS-84";
     606               5 :     else if( nEPSG_GCS == 4322 )
     607               0 :         osDatum = "WGS-72";
     608               5 :     else if( nEPSG_GCS == 4269 )
     609               1 :         osDatum = "North America 1983";
     610               4 :     else if( nEPSG_GCS == 4267 )
     611               0 :         osDatum = "North America 1927";
     612               4 :     else if( nEPSG_GCS == 4230 )
     613               0 :         osDatum = "European 1950";
     614               4 :     else if( nEPSG_GCS == 4277 )
     615               1 :         osDatum = "Ordnance Survey of Great Britain '36";
     616               3 :     else if( nEPSG_GCS == 4291 )
     617               0 :         osDatum = "SAD-69/Brazil";
     618               3 :     else if( nEPSG_GCS == 4283 )
     619               0 :         osDatum = "Geocentric Datum of Australia 1994";
     620               3 :     else if( nEPSG_GCS == 4275 )
     621               0 :         osDatum = "Nouvelle Triangulation Francaise IGN";
     622                 : 
     623              45 :     if( osDatum != "" )
     624              42 :         osCommaDatum.Printf( ",%s", osDatum.c_str() );
     625                 : 
     626              45 :     dfA = oSRS.GetSemiMajor();
     627              45 :     dfB = oSRS.GetSemiMinor();
     628                 : 
     629                 : /* -------------------------------------------------------------------- */
     630                 : /*      Do we have unusual linear units?                                */
     631                 : /* -------------------------------------------------------------------- */
     632              45 :     CPLString osOptionalUnits;
     633              45 :     if( fabs(oSRS.GetLinearUnits()-0.3048) < 0.0001 )
     634               0 :         osOptionalUnits = ", units=Feet";
     635                 : 
     636                 : /* -------------------------------------------------------------------- */
     637                 : /*      Handle UTM case.                                                */
     638                 : /* -------------------------------------------------------------------- */
     639                 :     const char  *pszHemisphere;
     640              45 :     const char  *pszProjName = oSRS.GetAttrValue("PROJECTION");
     641                 :     int   bNorth;
     642                 :     int   iUTMZone;
     643                 : 
     644              45 :     iUTMZone = oSRS.GetUTMZone( &bNorth );
     645              45 :     if ( iUTMZone )
     646                 :     {
     647               0 :         if ( bNorth )
     648               0 :             pszHemisphere = "North";
     649                 :         else
     650               0 :             pszHemisphere = "South";
     651                 : 
     652                 :         VSIFPrintfL( fp, "map info = {UTM, %s, %d, %s%s%s}\n",
     653                 :                     osLocation.c_str(), iUTMZone, pszHemisphere,
     654               0 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     655                 :     }
     656              45 :     else if( oSRS.IsGeographic() )
     657                 :     {
     658                 :         VSIFPrintfL( fp, "map info = {Geographic Lat/Lon, %s%s}\n",
     659              40 :                     osLocation.c_str(), osCommaDatum.c_str());
     660                 :     }
     661               5 :     else if( pszProjName == NULL )
     662                 :     {
     663                 :         // what to do? 
     664                 :     }
     665               5 :     else if( EQUAL(pszProjName,SRS_PT_NEW_ZEALAND_MAP_GRID) )
     666                 :     {
     667                 :         VSIFPrintfL( fp, "map info = {New Zealand Map Grid, %s%s%s}\n",
     668                 :                     osLocation.c_str(), 
     669               0 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     670                 : 
     671                 :         VSIFPrintfL( fp, "projection info = {39, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g%s, New Zealand Map Grid}\n",
     672                 :                     dfA, dfB, 
     673                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,0.0),
     674                 :                     oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN,0.0),
     675                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     676                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     677               0 :                     osCommaDatum.c_str() );
     678                 :     }
     679               5 :     else if( EQUAL(pszProjName,SRS_PT_TRANSVERSE_MERCATOR) )
     680                 :     {
     681                 :         VSIFPrintfL( fp, "map info = {Transverse Mercator, %s%s%s}\n",
     682                 :                     osLocation.c_str(), 
     683               1 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     684                 : 
     685                 :         VSIFPrintfL( fp, "projection info = {3, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g%s, Transverse Mercator}\n",
     686                 :                     dfA, dfB, 
     687                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,0.0),
     688                 :                     oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN,0.0),
     689                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     690                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     691                 :                     oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR,1.0),
     692               1 :                     osCommaDatum.c_str() );
     693                 :     }
     694               5 :     else if( EQUAL(pszProjName,SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP)
     695                 :          || EQUAL(pszProjName,SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP_BELGIUM) )
     696                 :     {
     697                 :         VSIFPrintfL( fp, "map info = {Lambert Conformal Conic, %s%s%s}\n",
     698                 :                     osLocation.c_str(), 
     699               1 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     700                 : 
     701                 :         VSIFPrintfL( fp, "projection info = {4, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g%s, Lambert Conformal Conic}\n",
     702                 :                     dfA, dfB, 
     703                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,0.0),
     704                 :                     oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN,0.0),
     705                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     706                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     707                 :                     oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1,0.0),
     708                 :                     oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_2,0.0),
     709               1 :                     osCommaDatum.c_str() );
     710                 :     }
     711               3 :     else if( EQUAL(pszProjName,
     712                 :                    SRS_PT_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN) )
     713                 :     {
     714                 :         VSIFPrintfL( fp, "map info = {Hotine Oblique Mercator A, %s%s%s}\n",
     715                 :                     osLocation.c_str(), 
     716               0 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     717                 : 
     718                 :         VSIFPrintfL( fp, "projection info = {5, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g%s, Hotine Oblique Mercator A}\n",
     719                 :                     dfA, dfB, 
     720                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,0.0),
     721                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_POINT_1,0.0),
     722                 :                     oSRS.GetNormProjParm(SRS_PP_LONGITUDE_OF_POINT_1,0.0),
     723                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_POINT_2,0.0),
     724                 :                     oSRS.GetNormProjParm(SRS_PP_LONGITUDE_OF_POINT_2,0.0),
     725                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     726                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     727                 :                     oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR,1.0),
     728               0 :                     osCommaDatum.c_str() );
     729                 :     }
     730               3 :     else if( EQUAL(pszProjName,SRS_PT_HOTINE_OBLIQUE_MERCATOR) )
     731                 :     {
     732                 :         VSIFPrintfL( fp, "map info = {Hotine Oblique Mercator B, %s%s%s}\n",
     733                 :                     osLocation.c_str(), 
     734               0 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     735                 : 
     736                 :         VSIFPrintfL( fp, "projection info = {6, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g%s, Hotine Oblique Mercator B}\n",
     737                 :                     dfA, dfB, 
     738                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,0.0),
     739                 :                     oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN,0.0),
     740                 :                     oSRS.GetNormProjParm(SRS_PP_AZIMUTH,0.0),
     741                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     742                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     743                 :                     oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR,1.0),
     744               0 :                     osCommaDatum.c_str() );
     745                 :     }
     746               3 :     else if( EQUAL(pszProjName,SRS_PT_STEREOGRAPHIC) 
     747                 :              || EQUAL(pszProjName,SRS_PT_OBLIQUE_STEREOGRAPHIC) )
     748                 :     {
     749                 :         VSIFPrintfL( fp, "map info = {Stereographic (ellipsoid), %s%s%s}\n",
     750                 :                     osLocation.c_str(), 
     751               0 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     752                 : 
     753                 :         VSIFPrintfL( fp, "projection info = {7, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %s, Stereographic (ellipsoid)}\n",
     754                 :                     dfA, dfB, 
     755                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,0.0),
     756                 :                     oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN,0.0),
     757                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     758                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     759                 :                     oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR,1.0),
     760               0 :                     osCommaDatum.c_str() );
     761                 :     }
     762               3 :     else if( EQUAL(pszProjName,SRS_PT_ALBERS_CONIC_EQUAL_AREA) )
     763                 :     {
     764                 :         VSIFPrintfL( fp, "map info = {Albers Conical Equal Area, %s%s%s}\n",
     765                 :                     osLocation.c_str(), 
     766               2 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     767                 : 
     768                 :        VSIFPrintfL( fp, "projection info = {9, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g%s, Albers Conical Equal Area}\n",
     769                 :                     dfA, dfB, 
     770                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,0.0),
     771                 :                     oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN,0.0),
     772                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     773                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     774                 :                     oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1,0.0),
     775                 :                     oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_2,0.0),
     776               2 :                     osCommaDatum.c_str() );
     777                 :     }
     778               1 :     else if( EQUAL(pszProjName,SRS_PT_POLYCONIC) )
     779                 :     {
     780                 :         VSIFPrintfL( fp, "map info = {Polyconic, %s%s%s}\n",
     781                 :                     osLocation.c_str(), 
     782               0 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     783                 : 
     784                 :         VSIFPrintfL( fp, "projection info = {10, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g%s, Polyconic}\n",
     785                 :                     dfA, dfB, 
     786                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,0.0),
     787                 :                     oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN,0.0),
     788                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     789                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     790               0 :                     osCommaDatum.c_str() );
     791                 :     }
     792               1 :     else if( EQUAL(pszProjName,SRS_PT_LAMBERT_AZIMUTHAL_EQUAL_AREA) )
     793                 :     {
     794                 :         VSIFPrintfL( fp, "map info = {Lambert Azimuthal Equal Area, %s%s%s}\n",
     795                 :                     osLocation.c_str(), 
     796               1 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     797                 : 
     798                 :         VSIFPrintfL( fp, "projection info = {11, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g%s, Lambert Azimuthal Equal Area}\n",
     799                 :                     dfA, dfB, 
     800                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,0.0),
     801                 :                     oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN,0.0),
     802                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     803                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     804               1 :                     osCommaDatum.c_str() );
     805                 :     }
     806               0 :     else if( EQUAL(pszProjName,SRS_PT_AZIMUTHAL_EQUIDISTANT) )
     807                 :     {
     808                 :         VSIFPrintfL( fp, "map info = {Azimuthal Equadistant, %s%s%s}\n",
     809                 :                     osLocation.c_str(), 
     810               0 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     811                 : 
     812                 :         VSIFPrintfL( fp, "projection info = {12, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g%s, Azimuthal Equadistant}\n",
     813                 :                     dfA, dfB, 
     814                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,0.0),
     815                 :                     oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN,0.0),
     816                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     817                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     818               0 :                     osCommaDatum.c_str() );
     819                 :     }
     820               0 :     else if( EQUAL(pszProjName,SRS_PT_POLAR_STEREOGRAPHIC) )
     821                 :     {
     822                 :         VSIFPrintfL( fp, "map info = {Polar Stereographic, %s%s%s}\n",
     823                 :                     osLocation.c_str(), 
     824               0 :                     osCommaDatum.c_str(), osOptionalUnits.c_str() );
     825                 : 
     826                 :         VSIFPrintfL( fp, "projection info = {31, %.16g, %.16g, %.16g, %.16g, %.16g, %.16g%s, Polar Stereographic}\n",
     827                 :                     dfA, dfB, 
     828                 :                     oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN,90.0),
     829                 :                     oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN,0.0),
     830                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING,0.0),
     831                 :                     oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING,0.0),
     832               0 :                     osCommaDatum.c_str() );
     833                 :     }
     834                 :     else
     835                 :     {
     836                 :         VSIFPrintfL( fp, "map info = {%s, %s}\n",
     837               0 :                     pszProjName, osLocation.c_str());
     838              45 :     }
     839                 : }
     840                 : 
     841                 : 
     842                 : /************************************************************************/
     843                 : /*                          GetProjectionRef()                          */
     844                 : /************************************************************************/
     845                 : 
     846              12 : const char *ENVIDataset::GetProjectionRef()
     847                 : 
     848                 : {
     849              12 :     return pszProjection;
     850                 : }
     851                 : 
     852                 : /************************************************************************/
     853                 : /*                          SetProjection()                             */
     854                 : /************************************************************************/
     855                 : 
     856              45 : CPLErr ENVIDataset::SetProjection( const char *pszNewProjection )
     857                 : 
     858                 : {
     859              45 :     if ( pszProjection )
     860              45 :   CPLFree( pszProjection );
     861              45 :     pszProjection = CPLStrdup( pszNewProjection );
     862                 : 
     863              45 :     bHeaderDirty = TRUE;
     864                 : 
     865              45 :     return CE_None;
     866                 : }
     867                 : 
     868                 : /************************************************************************/
     869                 : /*                          GetGeoTransform()                           */
     870                 : /************************************************************************/
     871                 : 
     872               7 : CPLErr ENVIDataset::GetGeoTransform( double * padfTransform )
     873                 : 
     874                 : {
     875               7 :     memcpy( padfTransform, adfGeoTransform, sizeof(double) * 6 );
     876                 :     
     877               7 :     if( bFoundMapinfo )
     878               7 :         return CE_None;
     879                 :     else
     880               0 :         return CE_Failure;
     881                 : }
     882                 : 
     883                 : /************************************************************************/
     884                 : /*                          SetGeoTransform()                           */
     885                 : /************************************************************************/
     886                 : 
     887              45 : CPLErr ENVIDataset::SetGeoTransform( double * padfTransform )
     888                 : {
     889              45 :     memcpy( adfGeoTransform, padfTransform, sizeof(double) * 6 );
     890                 : 
     891              45 :     bHeaderDirty = TRUE;
     892                 :     
     893              45 :     return CE_None;
     894                 : }
     895                 : 
     896                 : /************************************************************************/
     897                 : /*                             SplitList()                              */
     898                 : /*                                                                      */
     899                 : /*      Split an ENVI value list into component fields, and strip       */
     900                 : /*      white space.                                                    */
     901                 : /************************************************************************/
     902                 : 
     903             160 : char **ENVIDataset::SplitList( const char *pszCleanInput )
     904                 : 
     905                 : {
     906             160 :     char  **papszReturn = NULL;
     907             160 :     char  *pszInput = CPLStrdup(pszCleanInput);
     908                 : 
     909             160 :     if( pszInput[0] != '{' )
     910                 :     {
     911              48 :         CPLFree(pszInput);
     912              48 :         return NULL;
     913                 :     }
     914                 : 
     915             112 :     int iChar=1;
     916                 : 
     917                 : 
     918             839 :     while( pszInput[iChar] != '}' && pszInput[iChar] != '\0' )
     919                 :     {
     920             615 :         int iFStart=-1, iFEnd=-1;
     921                 : 
     922                 :         // Find start of token.
     923             615 :         iFStart = iChar;
     924            1676 :         while( pszInput[iFStart] == ' ' )
     925             446 :             iFStart++;
     926                 : 
     927             615 :         iFEnd = iFStart;
     928            5400 :         while( pszInput[iFEnd] != ',' 
     929                 :                && pszInput[iFEnd] != '}'
     930                 :                && pszInput[iFEnd] != '\0' )
     931            4170 :             iFEnd++;
     932                 : 
     933             615 :         if( pszInput[iFEnd] == '\0' )
     934               0 :             break;
     935                 : 
     936             615 :         iChar = iFEnd + 1;
     937             615 :         iFEnd = iFEnd - 1;
     938                 : 
     939            1230 :         while( iFEnd > iFStart && pszInput[iFEnd] == ' ' )
     940               0 :             iFEnd--;
     941                 : 
     942             615 :         pszInput[iFEnd + 1] = '\0';
     943             615 :         papszReturn = CSLAddString( papszReturn, pszInput + iFStart );
     944                 :     }
     945                 : 
     946             112 :     CPLFree( pszInput );
     947                 : 
     948             112 :     return papszReturn;
     949                 : }
     950                 : 
     951                 : /************************************************************************/
     952                 : /*                            SetENVIDatum()                            */
     953                 : /************************************************************************/
     954                 : 
     955                 : void ENVIDataset::SetENVIDatum( OGRSpatialReference *poSRS, 
     956              29 :                                 const char *pszENVIDatumName )
     957                 : 
     958                 : {
     959                 :     // datums
     960              29 :     if( EQUAL(pszENVIDatumName, "WGS-84") )
     961              25 :         poSRS->SetWellKnownGeogCS( "WGS84" );
     962               4 :     else if( EQUAL(pszENVIDatumName, "WGS-72") )
     963               0 :         poSRS->SetWellKnownGeogCS( "WGS72" );
     964               4 :     else if( EQUAL(pszENVIDatumName, "North America 1983") )
     965               2 :         poSRS->SetWellKnownGeogCS( "NAD83" );
     966               2 :     else if( EQUAL(pszENVIDatumName, "North America 1927") 
     967                 :              || strstr(pszENVIDatumName,"NAD27") 
     968                 :              || strstr(pszENVIDatumName,"NAD-27") )
     969               0 :         poSRS->SetWellKnownGeogCS( "NAD27" );
     970               2 :     else if( EQUALN(pszENVIDatumName, "European 1950",13) )
     971               0 :         poSRS->SetWellKnownGeogCS( "EPSG:4230" );
     972               2 :     else if( EQUAL(pszENVIDatumName, "Ordnance Survey of Great Britain '36") )
     973               2 :         poSRS->SetWellKnownGeogCS( "EPSG:4277" );
     974               0 :     else if( EQUAL(pszENVIDatumName, "SAD-69/Brazil") )
     975               0 :         poSRS->SetWellKnownGeogCS( "EPSG:4291" );
     976               0 :     else if( EQUAL(pszENVIDatumName, "Geocentric Datum of Australia 1994") )
     977               0 :         poSRS->SetWellKnownGeogCS( "EPSG:4283" );
     978               0 :     else if( EQUAL(pszENVIDatumName, "Australian Geodetic 1984") )
     979               0 :         poSRS->SetWellKnownGeogCS( "EPSG:4203" );
     980               0 :     else if( EQUAL(pszENVIDatumName, "Nouvelle Triangulation Francaise IGN") )
     981               0 :         poSRS->SetWellKnownGeogCS( "EPSG:4275" );
     982                 : 
     983                 :     // Ellipsoids
     984               0 :     else if( EQUAL(pszENVIDatumName, "GRS 80") )
     985               0 :         poSRS->SetWellKnownGeogCS( "NAD83" );
     986               0 :     else if( EQUAL(pszENVIDatumName, "Airy") )
     987               0 :         poSRS->SetWellKnownGeogCS( "EPSG:4001" );
     988               0 :     else if( EQUAL(pszENVIDatumName, "Australian National") )
     989               0 :         poSRS->SetWellKnownGeogCS( "EPSG:4003" );
     990               0 :     else if( EQUAL(pszENVIDatumName, "Bessel 1841") )
     991               0 :         poSRS->SetWellKnownGeogCS( "EPSG:4004" );
     992               0 :     else if( EQUAL(pszENVIDatumName, "Clark 1866") )
     993               0 :         poSRS->SetWellKnownGeogCS( "EPSG:4008" );
     994                 :     else 
     995                 :     {
     996                 :         CPLError( CE_Warning, CPLE_AppDefined,
     997               0 :                   "Unrecognised datum '%s', defaulting to WGS84.", pszENVIDatumName);
     998               0 :         poSRS->SetWellKnownGeogCS( "WGS84" );
     999                 :     }
    1000              29 : }
    1001                 : 
    1002                 : /************************************************************************/
    1003                 : /*                           SetENVIEllipse()                           */
    1004                 : /************************************************************************/
    1005                 : 
    1006                 : void ENVIDataset::SetENVIEllipse( OGRSpatialReference *poSRS, 
    1007              12 :                                   char **papszPI_EI )
    1008                 : 
    1009                 : {
    1010              12 :     double dfA = CPLAtofM(papszPI_EI[0]);
    1011              12 :     double dfB = CPLAtofM(papszPI_EI[1]);
    1012                 :     double dfInvF;
    1013                 : 
    1014              12 :     if( fabs(dfA-dfB) < 0.1 )
    1015               2 :         dfInvF = 0.0; // sphere
    1016                 :     else
    1017              10 :         dfInvF = dfA / (dfA - dfB);
    1018                 :     
    1019                 :     
    1020                 :     poSRS->SetGeogCS( "Ellipse Based", "Ellipse Based", "Unnamed", 
    1021              12 :                       dfA, dfInvF );
    1022              12 : }
    1023                 : 
    1024                 : /************************************************************************/
    1025                 : /*                           ProcessMapinfo()                           */
    1026                 : /*                                                                      */
    1027                 : /*      Extract projection, and geotransform from a mapinfo value in    */
    1028                 : /*      the header.                                                     */
    1029                 : /************************************************************************/
    1030                 : 
    1031              48 : int ENVIDataset::ProcessMapinfo( const char *pszMapinfo )
    1032                 : 
    1033                 : {
    1034                 :     char  **papszFields;    
    1035                 :     int         nCount;
    1036              48 :     OGRSpatialReference oSRS;
    1037                 : 
    1038              48 :     papszFields = SplitList( pszMapinfo );
    1039              48 :     nCount = CSLCount(papszFields);
    1040                 : 
    1041              48 :     if( nCount < 7 )
    1042                 :     {
    1043               0 :         CSLDestroy( papszFields );
    1044               0 :         return FALSE;
    1045                 :     }
    1046                 : 
    1047                 : /* -------------------------------------------------------------------- */
    1048                 : /*      Check if we have projection info, and if so parse it.           */
    1049                 : /* -------------------------------------------------------------------- */
    1050              48 :     char        **papszPI = NULL;
    1051              48 :     int         nPICount = 0;
    1052              48 :     if( CSLFetchNameValue( papszHeader, "projection_info" ) != NULL )
    1053                 :     {
    1054                 :         papszPI = SplitList( 
    1055              16 :             CSLFetchNameValue( papszHeader, "projection_info" ) );
    1056              16 :         nPICount = CSLCount(papszPI);
    1057                 :     }
    1058                 : 
    1059                 : /* -------------------------------------------------------------------- */
    1060                 : /*      Capture geotransform.                                           */
    1061                 : /* -------------------------------------------------------------------- */
    1062              48 :     adfGeoTransform[1] = atof(papszFields[5]);      // Pixel width
    1063              48 :     adfGeoTransform[5] = -atof(papszFields[6]);     // Pixel height
    1064                 :     adfGeoTransform[0] =          // Upper left X coordinate
    1065              48 :   atof(papszFields[3]) - (atof(papszFields[1]) - 1) * adfGeoTransform[1];
    1066                 :     adfGeoTransform[3] =          // Upper left Y coordinate
    1067              48 :   atof(papszFields[4]) - (atof(papszFields[2]) - 1) * adfGeoTransform[5];
    1068              48 :     adfGeoTransform[2] = 0.0;
    1069              48 :     adfGeoTransform[4] = 0.0;
    1070                 : 
    1071                 : /* -------------------------------------------------------------------- */
    1072                 : /*      Capture projection.                                             */
    1073                 : /* -------------------------------------------------------------------- */
    1074              55 :     if( EQUALN(papszFields[0],"UTM",3) && nCount >= 9 )
    1075                 :     {
    1076                 :         oSRS.SetUTM( atoi(papszFields[7]), 
    1077               7 :                      !EQUAL(papszFields[8],"South") );
    1078               7 :         if( nCount >= 10 && strstr(papszFields[9],"=") == NULL )
    1079               0 :             SetENVIDatum( &oSRS, papszFields[9] );
    1080                 :         else
    1081               7 :             oSRS.SetWellKnownGeogCS( "NAD27" );
    1082                 :     }
    1083              41 :     else if( EQUALN(papszFields[0],"State Plane (NAD 27)",19)
    1084                 :              && nCount >= 7 )
    1085                 :     {
    1086               0 :         oSRS.SetStatePlane( ITTVISToUSGSZone(atoi(papszFields[7])), FALSE );
    1087                 :     }
    1088              41 :     else if( EQUALN(papszFields[0],"State Plane (NAD 83)",19)
    1089                 :              && nCount >= 7 )
    1090                 :     {
    1091               0 :         oSRS.SetStatePlane( ITTVISToUSGSZone(atoi(papszFields[7])), TRUE );
    1092                 :     }
    1093              66 :     else if( EQUALN(papszFields[0],"Geographic Lat",14) 
    1094                 :              && nCount >= 8 )
    1095                 :     {
    1096              50 :         if( nCount >= 8 && strstr(papszFields[7],"=") == NULL )
    1097              25 :             SetENVIDatum( &oSRS, papszFields[7] );
    1098                 :         else
    1099               0 :             oSRS.SetWellKnownGeogCS( "WGS84" );
    1100                 :     }
    1101              18 :     else if( nPICount > 8 && atoi(papszPI[0]) == 3 ) // TM
    1102                 :     {
    1103                 :         oSRS.SetTM( CPLAtofM(papszPI[3]), CPLAtofM(papszPI[4]),
    1104                 :                     CPLAtofM(papszPI[7]),
    1105               2 :                     CPLAtofM(papszPI[5]), CPLAtofM(papszPI[6]) );
    1106                 :     }
    1107              16 :     else if( nPICount > 8 && atoi(papszPI[0]) == 4 ) // Lambert Conformal Conic
    1108                 :     {
    1109                 :         oSRS.SetLCC( CPLAtofM(papszPI[7]), CPLAtofM(papszPI[8]),
    1110                 :                      CPLAtofM(papszPI[3]), CPLAtofM(papszPI[4]),
    1111               2 :                      CPLAtofM(papszPI[5]), CPLAtofM(papszPI[6]) );
    1112                 :     }
    1113              12 :     else if( nPICount > 10 && atoi(papszPI[0]) == 5 ) // Oblique Merc (2 point)
    1114                 :     {
    1115                 :         oSRS.SetHOM2PNO( CPLAtofM(papszPI[3]), 
    1116                 :                          CPLAtofM(papszPI[4]), CPLAtofM(papszPI[5]), 
    1117                 :                          CPLAtofM(papszPI[6]), CPLAtofM(papszPI[7]), 
    1118                 :                          CPLAtofM(papszPI[10]), 
    1119               0 :                          CPLAtofM(papszPI[8]), CPLAtofM(papszPI[9]) );
    1120                 :     }
    1121              12 :     else if( nPICount > 8 && atoi(papszPI[0]) == 6 ) // Oblique Merc 
    1122                 :     {
    1123                 :         oSRS.SetHOM(CPLAtofM(papszPI[3]), CPLAtofM(papszPI[4]), 
    1124                 :                     CPLAtofM(papszPI[5]), 0.0,
    1125                 :                     CPLAtofM(papszPI[8]), 
    1126               0 :                     CPLAtofM(papszPI[6]), CPLAtofM(papszPI[7]) );
    1127                 :     }
    1128              12 :     else if( nPICount > 8 && atoi(papszPI[0]) == 7 ) // Stereographic
    1129                 :     {
    1130                 :         oSRS.SetStereographic( CPLAtofM(papszPI[3]), CPLAtofM(papszPI[4]),
    1131                 :                                CPLAtofM(papszPI[7]),
    1132               0 :                                CPLAtofM(papszPI[5]), CPLAtofM(papszPI[6]) );
    1133                 :     }
    1134              22 :     else if( nPICount > 8 && atoi(papszPI[0]) == 9 ) // Albers Equal Area
    1135                 :     {
    1136                 :         oSRS.SetACEA( CPLAtofM(papszPI[7]), CPLAtofM(papszPI[8]),
    1137                 :                       CPLAtofM(papszPI[3]), CPLAtofM(papszPI[4]),
    1138              10 :                       CPLAtofM(papszPI[5]), CPLAtofM(papszPI[6]) );
    1139                 :     }
    1140               2 :     else if( nPICount > 6 && atoi(papszPI[0]) == 10 ) // Polyconic
    1141                 :     {
    1142                 :         oSRS.SetPolyconic(CPLAtofM(papszPI[3]), CPLAtofM(papszPI[4]), 
    1143               0 :                           CPLAtofM(papszPI[5]), CPLAtofM(papszPI[6]) );
    1144                 :     }
    1145               4 :     else if( nPICount > 6 && atoi(papszPI[0]) == 11 ) // LAEA
    1146                 :     {
    1147                 :         oSRS.SetLAEA(CPLAtofM(papszPI[3]), CPLAtofM(papszPI[4]), 
    1148               2 :                      CPLAtofM(papszPI[5]), CPLAtofM(papszPI[6]) );
    1149                 :     }
    1150               0 :     else if( nPICount > 6 && atoi(papszPI[0]) == 12 ) // Azimuthal Equid.
    1151                 :     {
    1152                 :         oSRS.SetAE(CPLAtofM(papszPI[3]), CPLAtofM(papszPI[4]), 
    1153               0 :                    CPLAtofM(papszPI[5]), CPLAtofM(papszPI[6]) );
    1154                 :     }
    1155               0 :     else if( nPICount > 6 && atoi(papszPI[0]) == 31 ) // Polar Stereographic
    1156                 :     {
    1157                 :         oSRS.SetPS(CPLAtofM(papszPI[3]), CPLAtofM(papszPI[4]), 
    1158                 :                    1.0,
    1159               0 :                    CPLAtofM(papszPI[5]), CPLAtofM(papszPI[6]) );
    1160                 :     }
    1161                 : 
    1162                 :     // Still lots more that could be added for someone with the patience.
    1163                 : 
    1164                 : /* -------------------------------------------------------------------- */
    1165                 : /*      fallback to localcs if we don't recognise things.               */
    1166                 : /* -------------------------------------------------------------------- */
    1167              48 :     if( oSRS.GetRoot() == NULL )
    1168               0 :         oSRS.SetLocalCS( papszFields[0] );
    1169                 : 
    1170                 : /* -------------------------------------------------------------------- */
    1171                 : /*      Try to set datum from projection info line if we have a         */
    1172                 : /*      projected coordinate system without a GEOGCS.                   */
    1173                 : /* -------------------------------------------------------------------- */
    1174              48 :     if( oSRS.IsProjected() && oSRS.GetAttrNode("GEOGCS") == NULL 
    1175                 :         && nPICount > 3 )
    1176                 :     {
    1177                 :         // Do we have a datum on the projection info line?
    1178              16 :         int iDatum = nPICount-1;
    1179                 : 
    1180                 :         // Ignore units= items.
    1181              16 :         if( strstr(papszPI[iDatum],"=") != NULL )
    1182               0 :             iDatum--;
    1183                 : 
    1184                 :         // Skip past the name. 
    1185              16 :         iDatum--;
    1186                 :     
    1187              16 :         CPLString osDatumName = papszPI[iDatum];
    1188              16 :         if( osDatumName.find_first_of("abcdefghijklmnopqrstuvwxyz"
    1189                 :                                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ") 
    1190                 :             != CPLString::npos )
    1191                 :         {
    1192               4 :             SetENVIDatum( &oSRS, osDatumName );
    1193                 :         }
    1194                 :         else
    1195                 :         {
    1196              12 :             SetENVIEllipse( &oSRS, papszPI + 1 );
    1197              16 :         }
    1198                 :     }
    1199                 : 
    1200                 : 
    1201                 : /* -------------------------------------------------------------------- */
    1202                 : /*      Try to process specialized units.                               */
    1203                 : /* -------------------------------------------------------------------- */
    1204              48 :     if( EQUALN( papszFields[nCount-1],"units",5))
    1205                 :     {
    1206                 :         /* Handle linear units first. */
    1207               0 :         if (EQUAL(papszFields[nCount-1],"units=Feet") )
    1208               0 :             oSRS.SetLinearUnitsAndUpdateParameters( SRS_UL_FOOT, atof(SRS_UL_FOOT_CONV) );
    1209               0 :         else if (EQUAL(papszFields[nCount-1],"units=Meters") )
    1210               0 :             oSRS.SetLinearUnitsAndUpdateParameters( SRS_UL_METER, 1. );
    1211               0 :         else if (EQUAL(papszFields[nCount-1],"units=Km") )
    1212               0 :             oSRS.SetLinearUnitsAndUpdateParameters( "Kilometer", 1000.  );
    1213               0 :         else if (EQUAL(papszFields[nCount-1],"units=Yards") )
    1214               0 :             oSRS.SetLinearUnitsAndUpdateParameters( "Yard", .9144 );
    1215               0 :         else if (EQUAL(papszFields[nCount-1],"units=Miles") )
    1216               0 :             oSRS.SetLinearUnitsAndUpdateParameters( "Mile", 1609.344 );
    1217               0 :         else if (EQUAL(papszFields[nCount-1],"units=Nautical Miles") )
    1218               0 :             oSRS.SetLinearUnitsAndUpdateParameters( SRS_UL_NAUTICAL_MILE, atof(SRS_UL_NAUTICAL_MILE_CONV) );
    1219                 :       
    1220                 :         /* Only handle angular units if we know the projection is geographic. */
    1221               0 :         if (oSRS.IsGeographic()) 
    1222                 :         {
    1223               0 :             if (EQUAL(papszFields[nCount-1],"units=Radians") )
    1224               0 :                 oSRS.SetAngularUnits( SRS_UA_RADIAN, 1. );
    1225                 :             else 
    1226                 :             {
    1227                 :                 /* Degrees, minutes and seconds will all be represented as degrees. */
    1228               0 :                 oSRS.SetAngularUnits( SRS_UA_DEGREE,  atof(SRS_UA_DEGREE_CONV));
    1229                 : 
    1230               0 :                 double conversionFactor = 1.;
    1231               0 :                 if (EQUAL(papszFields[nCount-1],"units=Minutes") )
    1232               0 :                     conversionFactor = 60.;
    1233               0 :                 else if( EQUAL(papszFields[nCount-1],"units=Seconds") )
    1234               0 :                     conversionFactor = 3600.;
    1235               0 :                 adfGeoTransform[0] /= conversionFactor;
    1236               0 :                 adfGeoTransform[1] /= conversionFactor;
    1237               0 :                 adfGeoTransform[2] /= conversionFactor;
    1238               0 :                 adfGeoTransform[3] /= conversionFactor;
    1239               0 :                 adfGeoTransform[4] /= conversionFactor;
    1240               0 :                 adfGeoTransform[5] /= conversionFactor;
    1241                 :             }
    1242                 :         }
    1243                 :     }
    1244                 : /* -------------------------------------------------------------------- */
    1245                 : /*      Turn back into WKT.                                             */
    1246                 : /* -------------------------------------------------------------------- */
    1247              48 :     if( oSRS.GetRoot() != NULL )
    1248                 :     {
    1249              48 :         oSRS.Fixup();
    1250              48 :   if ( pszProjection )
    1251                 :   {
    1252              48 :       CPLFree( pszProjection );
    1253              48 :       pszProjection = NULL;
    1254                 :   }
    1255              48 :         oSRS.exportToWkt( &pszProjection );
    1256                 :     }
    1257                 : 
    1258              48 :     CSLDestroy( papszFields );
    1259              48 :     CSLDestroy( papszPI );
    1260              48 :     return TRUE;
    1261                 : }
    1262                 : 
    1263                 : /************************************************************************/
    1264                 : /*                           ProcessRPCinfo()                           */
    1265                 : /*                                                                      */
    1266                 : /*      Extract RPC transformation coefficients if they are present     */
    1267                 : /*      and sets into the standard metadata fields for RPC.             */
    1268                 : /************************************************************************/
    1269                 : 
    1270                 : void ENVIDataset::ProcessRPCinfo( const char *pszRPCinfo, 
    1271               0 :                                  int numCols, int numRows)
    1272                 : {
    1273                 :     char  **papszFields;
    1274                 :     char    sVal[1280];
    1275                 :     int         nCount;
    1276                 : 
    1277               0 :     papszFields = SplitList( pszRPCinfo );
    1278               0 :     nCount = CSLCount(papszFields);
    1279                 : 
    1280               0 :     if( nCount < 90 )
    1281                 :     {
    1282               0 :         CSLDestroy( papszFields );
    1283               0 :         return;
    1284                 :     }
    1285                 :   
    1286               0 :     snprintf(sVal, sizeof(sVal),  "%.16g",atof(papszFields[0]));
    1287               0 :     SetMetadataItem("LINE_OFF",sVal,"RPC");
    1288               0 :     snprintf(sVal, sizeof(sVal),  "%.16g",atof(papszFields[5]));
    1289               0 :     SetMetadataItem("LINE_SCALE",sVal,"RPC");
    1290               0 :     snprintf(sVal, sizeof(sVal),  "%.16g",atof(papszFields[1]));
    1291               0 :     SetMetadataItem("SAMP_OFF",sVal,"RPC");
    1292               0 :     snprintf(sVal, sizeof(sVal),  "%.16g",atof(papszFields[6]));
    1293               0 :     SetMetadataItem("SAMP_SCALE",sVal,"RPC");
    1294               0 :     snprintf(sVal, sizeof(sVal),  "%.16g",atof(papszFields[2]));
    1295               0 :     SetMetadataItem("LAT_OFF",sVal,"RPC");
    1296               0 :     snprintf(sVal, sizeof(sVal),  "%.16g",atof(papszFields[7]));
    1297               0 :     SetMetadataItem("LAT_SCALE",sVal,"RPC");
    1298               0 :     snprintf(sVal, sizeof(sVal),  "%.16g",atof(papszFields[3]));
    1299               0 :     SetMetadataItem("LONG_OFF",sVal,"RPC");
    1300               0 :     snprintf(sVal, sizeof(sVal),  "%.16g",atof(papszFields[8]));
    1301               0 :     SetMetadataItem("LONG_SCALE",sVal,"RPC");
    1302               0 :     snprintf(sVal, sizeof(sVal),  "%.16g",atof(papszFields[4]));
    1303               0 :     SetMetadataItem("HEIGHT_OFF",sVal,"RPC");
    1304               0 :     snprintf(sVal, sizeof(sVal),  "%.16g",atof(papszFields[9]));
    1305               0 :     SetMetadataItem("HEIGHT_SCALE",sVal,"RPC");
    1306                 : 
    1307               0 :     sVal[0] = '\0'; 
    1308                 :     int i;
    1309               0 :     for(i = 0; i < 20; i++ )
    1310                 :        snprintf(sVal+strlen(sVal), sizeof(sVal),  "%.16g ", 
    1311               0 :            atof(papszFields[10+i]));
    1312               0 :     SetMetadataItem("LINE_NUM_COEFF",sVal,"RPC");
    1313                 : 
    1314               0 :     sVal[0] = '\0'; 
    1315               0 :     for(i = 0; i < 20; i++ )
    1316                 :        snprintf(sVal+strlen(sVal), sizeof(sVal),  "%.16g ",
    1317               0 :            atof(papszFields[30+i]));
    1318               0 :     SetMetadataItem("LINE_DEN_COEFF",sVal,"RPC");
    1319                 :       
    1320               0 :     sVal[0] = '\0'; 
    1321               0 :     for(i = 0; i < 20; i++ )
    1322                 :        snprintf(sVal+strlen(sVal), sizeof(sVal),  "%.16g ",
    1323               0 :            atof(papszFields[50+i]));
    1324               0 :     SetMetadataItem("SAMP_NUM_COEFF",sVal,"RPC");
    1325                 :       
    1326               0 :     sVal[0] = '\0'; 
    1327               0 :     for(i = 0; i < 20; i++ )
    1328                 :        snprintf(sVal+strlen(sVal), sizeof(sVal),  "%.16g ",
    1329               0 :            atof(papszFields[70+i]));
    1330               0 :     SetMetadataItem("SAMP_DEN_COEFF",sVal,"RPC");
    1331                 :   
    1332                 :     snprintf(sVal, sizeof(sVal), "%.16g", 
    1333               0 :         atof(papszFields[3]) - atof(papszFields[8]));
    1334               0 :     SetMetadataItem("MIN_LONG",sVal,"RPC");
    1335                 : 
    1336                 :     snprintf(sVal, sizeof(sVal), "%.16g", 
    1337               0 :         atof(papszFields[3]) + atof(papszFields[8]) );
    1338               0 :     SetMetadataItem("MAX_LONG",sVal,"RPC");
    1339                 : 
    1340                 :     snprintf(sVal, sizeof(sVal), "%.16g",
    1341               0 :         atof(papszFields[2]) - atof(papszFields[7]));
    1342               0 :     SetMetadataItem("MIN_LAT",sVal,"RPC");
    1343                 : 
    1344                 :     snprintf(sVal, sizeof(sVal), "%.16g",
    1345               0 :         atof(papszFields[2]) + atof(papszFields[7]));
    1346               0 :     SetMetadataItem("MAX_LAT",sVal,"RPC");
    1347                 : 
    1348                 :     /*   Handle the chipping case where the image is a subset. */
    1349                 :     double rowOffset, colOffset;
    1350               0 :     rowOffset = atof(papszFields[90]);
    1351               0 :     colOffset = atof(papszFields[91]);
    1352               0 :     if (rowOffset || colOffset)
    1353                 :     {
    1354               0 :         SetMetadataItem("ICHIP_SCALE_FACTOR", "1");
    1355               0 :         SetMetadataItem("ICHIP_ANAMORPH_CORR", "0");
    1356               0 :         SetMetadataItem("ICHIP_SCANBLK_NUM", "0");
    1357                 : 
    1358               0 :         SetMetadataItem("ICHIP_OP_ROW_11", "0.5");
    1359               0 :         SetMetadataItem("ICHIP_OP_COL_11", "0.5");
    1360               0 :         SetMetadataItem("ICHIP_OP_ROW_12", "0.5");
    1361               0 :         SetMetadataItem("ICHIP_OP_COL_21", "0.5");
    1362               0 :         snprintf(sVal, sizeof(sVal), "%.16g", numCols - 0.5);
    1363               0 :         SetMetadataItem("ICHIP_OP_COL_12", sVal);
    1364               0 :         SetMetadataItem("ICHIP_OP_COL_22", sVal);
    1365               0 :         snprintf(sVal, sizeof(sVal), "%.16g", numRows - 0.5);
    1366               0 :         SetMetadataItem("ICHIP_OP_ROW_21", sVal);
    1367               0 :         SetMetadataItem("ICHIP_OP_ROW_22", sVal);
    1368                 : 
    1369               0 :         snprintf(sVal, sizeof(sVal), "%.16g", rowOffset + 0.5);
    1370               0 :         SetMetadataItem("ICHIP_FI_ROW_11", sVal);
    1371               0 :         SetMetadataItem("ICHIP_FI_ROW_12", sVal);
    1372               0 :         snprintf(sVal, sizeof(sVal), "%.16g", colOffset + 0.5);
    1373               0 :         SetMetadataItem("ICHIP_FI_COL_11", sVal);
    1374               0 :         SetMetadataItem("ICHIP_FI_COL_21", sVal);
    1375               0 :         snprintf(sVal, sizeof(sVal), "%.16g", colOffset + numCols - 0.5);
    1376               0 :         SetMetadataItem("ICHIP_FI_COL_12", sVal);
    1377               0 :         SetMetadataItem("ICHIP_FI_COL_22", sVal);
    1378               0 :         snprintf(sVal, sizeof(sVal), "%.16g", rowOffset + numRows - 0.5);
    1379               0 :         SetMetadataItem("ICHIP_FI_ROW_21", sVal);
    1380               0 :         SetMetadataItem("ICHIP_FI_ROW_22", sVal);
    1381                 :     }
    1382               0 :     CSLDestroy(papszFields);
    1383                 : }
    1384                 : 
    1385              96 : void ENVIDataset::ProcessStatsFile()
    1386                 : {
    1387              96 :     CPLString   osStaFilename;
    1388                 :     FILE  *fpStaFile;
    1389                 : 
    1390              96 :     osStaFilename = CPLResetExtension( pszHDRFilename, "sta" );
    1391              96 :     fpStaFile = VSIFOpenL( osStaFilename, "rb" );
    1392                 : 
    1393              96 :     if (!fpStaFile)
    1394              96 :         return;
    1395                 : 
    1396                 :     long lTestHeader[10],lOffset;
    1397                 : 
    1398               0 :     if( VSIFReadL( lTestHeader, sizeof(long), 10, fpStaFile ) != 10 )
    1399                 :     {
    1400               0 :         VSIFCloseL( fpStaFile );
    1401                 :         return;
    1402                 :     }
    1403                 : 
    1404                 :     int isFloat;
    1405               0 :     isFloat = (byteSwapLong(lTestHeader[0]) == 1111838282);
    1406                 : 
    1407                 :     unsigned long nb,i;
    1408                 :     float * fStats;
    1409                 :     double * dStats, dMin, dMax, dMean, dStd;
    1410                 :         
    1411               0 :     nb=byteSwapLong(lTestHeader[3]);
    1412                 :     
    1413               0 :     if (nb > (unsigned long)nBands)
    1414                 :     {
    1415                 :         CPLDebug("ENVI", ".sta file has statistics for %ld bands, "
    1416               0 :                          "whereas the dataset has only %d bands", nb, nBands);
    1417               0 :         nb = nBands;
    1418                 :     }
    1419                 :     
    1420               0 :     VSIFSeekL(fpStaFile,40+(nb+1)*4,SEEK_SET);
    1421                 : 
    1422               0 :     if (VSIFReadL(&lOffset,sizeof(long),1,fpStaFile) == 1)
    1423                 :     {
    1424               0 :         VSIFSeekL(fpStaFile,40+(nb+1)*8+byteSwapLong(lOffset)+nb,SEEK_SET);
    1425                 :         // This should be the beginning of the statistics
    1426               0 :         if (isFloat)
    1427                 :         {
    1428               0 :             fStats = (float*)CPLCalloc(nb*4,4);
    1429               0 :             if (VSIFReadL(fStats,4,nb*4,fpStaFile) == nb*4)
    1430                 :             {
    1431               0 :                 for (i=0;i<nb;i++)
    1432                 :                 {
    1433                 :                     GetRasterBand(i+1)->SetStatistics(
    1434                 :                         byteSwapFloat(fStats[i]),
    1435                 :                         byteSwapFloat(fStats[nb+i]),
    1436                 :                         byteSwapFloat(fStats[2*nb+i]), 
    1437               0 :                         byteSwapFloat(fStats[3*nb+i]));
    1438                 :                 }
    1439                 :             }
    1440               0 :             CPLFree(fStats);
    1441                 :         }
    1442                 :         else
    1443                 :         {
    1444               0 :             dStats = (double*)CPLCalloc(nb*4,8);
    1445               0 :             if (VSIFReadL(dStats,8,nb*4,fpStaFile) == nb*4)
    1446                 :             {
    1447               0 :                 for (i=0;i<nb;i++)
    1448                 :                 {
    1449               0 :                     dMin = byteSwapDouble(dStats[i]);
    1450               0 :                     dMax = byteSwapDouble(dStats[nb+i]);
    1451               0 :                     dMean = byteSwapDouble(dStats[2*nb+i]);
    1452               0 :                     dStd = byteSwapDouble(dStats[3*nb+i]);
    1453               0 :                     if (dMin != dMax && dStd != 0) 
    1454               0 :                         GetRasterBand(i+1)->SetStatistics(dMin,dMax,dMean,dStd);
    1455                 :                 }
    1456                 :             }
    1457               0 :             CPLFree(dStats);
    1458                 :         }
    1459                 :     }
    1460               0 :     VSIFCloseL( fpStaFile );
    1461                 : }
    1462               0 : long ENVIDataset::byteSwapLong(long swapMe)
    1463                 : {
    1464                 : #ifndef CPL_LSB
    1465                 :     return swapMe;
    1466                 : #endif
    1467                 :   return ((swapMe&0xFF)<<24)+((swapMe&(0xFF00))<<8)+
    1468               0 :     ((swapMe&(0xFF0000))>>8)+((swapMe&(0xFF000000))>>24);
    1469                 : }
    1470                 : 
    1471               0 : float ENVIDataset::byteSwapFloat(float swapMe)
    1472                 : {
    1473                 : #ifndef CPL_LSB
    1474                 :     return swapMe;
    1475                 : #endif
    1476                 :   long foo,bar;
    1477                 :   float retval;
    1478               0 :   memmove(&foo, &swapMe,4);
    1479               0 :   bar = byteSwapLong(foo);
    1480               0 :   memmove(&retval, &bar,4);
    1481                 : 
    1482               0 :   return retval;
    1483                 : }
    1484                 : 
    1485               0 : double ENVIDataset::byteSwapDouble(double swapMe)
    1486                 : {
    1487                 : #ifndef CPL_LSB
    1488                 :     return swapMe;
    1489                 : #endif
    1490                 : 
    1491                 :   char dblArrSrc[8],dblArrDest[8];
    1492                 :   double retval;
    1493                 :   int i;
    1494                 : 
    1495               0 :   memmove(dblArrSrc, &swapMe, 8);
    1496                 : 
    1497               0 :   for (i=0;i<8;i++)
    1498               0 :     dblArrDest[i]=dblArrSrc[7-i];
    1499                 : 
    1500               0 :   memmove(&retval,dblArrDest, 8);
    1501               0 :   return retval;
    1502                 : }
    1503                 : 
    1504                 : 
    1505                 : /************************************************************************/
    1506                 : /*                             ReadHeader()                             */
    1507                 : /************************************************************************/
    1508                 : 
    1509              98 : int ENVIDataset::ReadHeader( FILE * fpHdr )
    1510                 : 
    1511                 : {
    1512                 : 
    1513              98 :     CPLReadLineL( fpHdr );
    1514                 : 
    1515                 : /* -------------------------------------------------------------------- */
    1516                 : /*      Now start forming sets of name/value pairs.                     */
    1517                 : /* -------------------------------------------------------------------- */
    1518             943 :     while( TRUE )
    1519                 :     {
    1520                 :         const char *pszNewLine;
    1521                 :         char       *pszWorkingLine;
    1522                 : 
    1523            1041 :         pszNewLine = CPLReadLineL( fpHdr );
    1524            1041 :         if( pszNewLine == NULL )
    1525              98 :             break;
    1526                 : 
    1527             943 :         if( strstr(pszNewLine,"=") == NULL )
    1528               0 :             continue;
    1529                 : 
    1530             943 :         pszWorkingLine = CPLStrdup(pszNewLine);
    1531                 : 
    1532                 :         // Collect additional lines if we have open sqiggly bracket.
    1533             943 :         if( strstr(pszWorkingLine,"{") != NULL 
    1534                 :             && strstr(pszWorkingLine,"}") == NULL )
    1535                 :         {
    1536             119 :             do { 
    1537             119 :                 pszNewLine = CPLReadLineL( fpHdr );
    1538             119 :                 if( pszNewLine )
    1539                 :                 {
    1540                 :                     pszWorkingLine = (char *) 
    1541                 :                         CPLRealloc(pszWorkingLine, 
    1542             119 :                                  strlen(pszWorkingLine)+strlen(pszNewLine)+1);
    1543             119 :                     strcat( pszWorkingLine, pszNewLine );
    1544                 :                 }
    1545                 :             } while( pszNewLine != NULL && strstr(pszNewLine,"}") == NULL );
    1546                 :         }
    1547                 : 
    1548                 :         // Try to break input into name and value portions.  Trim whitespace.
    1549                 :         const char *pszValue;
    1550                 :         int         iEqual;
    1551                 : 
    1552             943 :         for( iEqual = 0; 
    1553                 :              pszWorkingLine[iEqual] != '\0' && pszWorkingLine[iEqual] != '=';
    1554                 :              iEqual++ ) {}
    1555                 : 
    1556             943 :         if( pszWorkingLine[iEqual] == '=' )
    1557                 :         {
    1558                 :             int   i;
    1559                 : 
    1560             943 :             pszValue = pszWorkingLine + iEqual + 1;
    1561            2829 :             while( *pszValue == ' ' )
    1562             943 :                 pszValue++;
    1563                 :             
    1564             943 :             pszWorkingLine[iEqual--] = '\0';
    1565            3221 :             while( iEqual > 0 && pszWorkingLine[iEqual] == ' ' )
    1566            1335 :                 pszWorkingLine[iEqual--] = '\0';
    1567                 : 
    1568                 :             // Convert spaces in the name to underscores.
    1569            9228 :             for( i = 0; pszWorkingLine[i] != '\0'; i++ )
    1570                 :             {
    1571            8285 :                 if( pszWorkingLine[i] == ' ' )
    1572             510 :                     pszWorkingLine[i] = '_';
    1573                 :             }
    1574                 : 
    1575                 :             papszHeader = CSLSetNameValue( papszHeader, 
    1576             943 :                                            pszWorkingLine, pszValue );
    1577                 :         }
    1578                 : 
    1579             943 :         CPLFree( pszWorkingLine );
    1580                 :     }
    1581                 : 
    1582              98 :     return TRUE;
    1583                 : }
    1584                 : 
    1585                 : /************************************************************************/
    1586                 : /*                                Open()                                */
    1587                 : /************************************************************************/
    1588                 : 
    1589            9959 : GDALDataset *ENVIDataset::Open( GDALOpenInfo * poOpenInfo )
    1590                 : 
    1591                 : {
    1592                 :     int   i;
    1593                 :     
    1594                 : /* -------------------------------------------------------------------- */
    1595                 : /*  We assume the user is pointing to the binary (ie. .bil) file. */
    1596                 : /* -------------------------------------------------------------------- */
    1597            9959 :     if( poOpenInfo->nHeaderBytes < 2 )
    1598            9304 :         return NULL;
    1599                 : 
    1600                 : /* -------------------------------------------------------------------- */
    1601                 : /*      Do we have a .hdr file?  Try upper and lower case, and          */
    1602                 : /*      replacing the extension as well as appending the extension      */
    1603                 : /*      to whatever we currently have.                                  */
    1604                 : /* -------------------------------------------------------------------- */
    1605                 :     const char  *pszMode;
    1606             655 :     CPLString   osHdrFilename;
    1607             655 :     FILE  *fpHeader = NULL;
    1608                 : 
    1609             655 :     if( poOpenInfo->eAccess == GA_Update )
    1610             183 :   pszMode = "r+";
    1611                 :     else
    1612             472 :   pszMode = "r";
    1613                 :     
    1614             655 :     if (poOpenInfo->papszSiblingFiles == NULL)
    1615                 :     {
    1616              48 :         osHdrFilename = CPLResetExtension( poOpenInfo->pszFilename, "hdr" );
    1617              48 :         fpHeader = VSIFOpenL( osHdrFilename, pszMode );
    1618                 :     
    1619                 :     #ifndef WIN32
    1620              48 :         if( fpHeader == NULL )
    1621                 :         {
    1622              42 :             osHdrFilename = CPLResetExtension( poOpenInfo->pszFilename, "HDR" );
    1623              42 :             fpHeader = VSIFOpenL( osHdrFilename, pszMode );
    1624                 :         }
    1625                 :     #endif
    1626              48 :         if( fpHeader == NULL )
    1627                 :         {
    1628                 :             osHdrFilename = CPLFormFilename( NULL, poOpenInfo->pszFilename, 
    1629              42 :                                             "hdr" );
    1630              42 :             fpHeader = VSIFOpenL( osHdrFilename, pszMode );
    1631                 :         }
    1632                 :     #ifndef WIN32
    1633              48 :         if( fpHeader == NULL )
    1634                 :         {
    1635                 :             osHdrFilename = CPLFormFilename( NULL, poOpenInfo->pszFilename, 
    1636              42 :                                             "HDR" );
    1637              42 :             fpHeader = VSIFOpenL( osHdrFilename, pszMode );
    1638                 :         }
    1639                 :     #endif
    1640                 :     }
    1641                 :     else
    1642                 :     {
    1643                 :         /* -------------------------------------------------------------------- */
    1644                 :         /*      Now we need to tear apart the filename to form a .HDR           */
    1645                 :         /*      filename.                                                       */
    1646                 :         /* -------------------------------------------------------------------- */
    1647             607 :         CPLString osPath = CPLGetPath( poOpenInfo->pszFilename );
    1648             607 :         CPLString osName = CPLGetFilename( poOpenInfo->pszFilename );
    1649                 : 
    1650                 :         int iFile = CSLFindString(poOpenInfo->papszSiblingFiles, 
    1651             607 :                                   CPLResetExtension( osName, "hdr" ) );
    1652             607 :         if( iFile >= 0 )
    1653                 :         {
    1654                 :             osHdrFilename = CPLFormFilename( osPath, poOpenInfo->papszSiblingFiles[iFile], 
    1655             186 :                                              NULL );
    1656             186 :             fpHeader = VSIFOpenL( osHdrFilename, pszMode );
    1657                 :         }
    1658                 :         else
    1659                 :         {
    1660                 :             iFile = CSLFindString(poOpenInfo->papszSiblingFiles,
    1661             421 :                                   CPLFormFilename( NULL, osName, "hdr" ));
    1662             421 :             if( iFile >= 0 )
    1663                 :             {
    1664                 :                 osHdrFilename = CPLFormFilename( osPath, poOpenInfo->papszSiblingFiles[iFile], 
    1665               0 :                                                  NULL );
    1666               0 :                 fpHeader = VSIFOpenL( osHdrFilename, pszMode );
    1667                 :             }
    1668             607 :         }
    1669                 :     }
    1670                 : 
    1671             655 :     if( fpHeader == NULL )
    1672            1118 :         return NULL;
    1673                 :     
    1674                 : /* -------------------------------------------------------------------- */
    1675                 : /*      Check that the first line says "ENVI".                          */
    1676                 : /* -------------------------------------------------------------------- */
    1677                 :     char  szTestHdr[4];
    1678                 : 
    1679             192 :     if( VSIFReadL( szTestHdr, 4, 1, fpHeader ) != 1 )
    1680                 :     {
    1681               0 :         VSIFCloseL( fpHeader );
    1682               0 :         return NULL;
    1683                 :     }
    1684             192 :     if( strncmp(szTestHdr,"ENVI",4) != 0 )
    1685                 :     {
    1686              94 :         VSIFCloseL( fpHeader );
    1687              94 :         return NULL;
    1688                 :     }
    1689                 : 
    1690                 : /* -------------------------------------------------------------------- */
    1691                 : /*      Create a corresponding GDALDataset.                             */
    1692                 : /* -------------------------------------------------------------------- */
    1693                 :     ENVIDataset   *poDS;
    1694                 : 
    1695              98 :     poDS = new ENVIDataset();
    1696             196 :     poDS->pszHDRFilename = CPLStrdup(osHdrFilename);
    1697              98 :     poDS->fp = fpHeader;
    1698                 : 
    1699                 : /* -------------------------------------------------------------------- */
    1700                 : /*      Read the header.                                                */
    1701                 : /* -------------------------------------------------------------------- */
    1702              98 :     if( !poDS->ReadHeader( fpHeader ) )
    1703                 :     {
    1704               0 :         delete poDS;
    1705               0 :         return NULL;
    1706                 :     }
    1707                 : 
    1708                 : /* -------------------------------------------------------------------- */
    1709                 : /*      Has the user selected the .hdr file to open?                    */
    1710                 : /* -------------------------------------------------------------------- */
    1711              98 :     if( EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "hdr") )
    1712                 :     {
    1713               0 :         delete poDS;
    1714                 :         CPLError( CE_Failure, CPLE_AppDefined, 
    1715                 :                   "The selected file is an ENVI header file, but to\n"
    1716                 :                   "open ENVI datasets, the data file should be selected\n"
    1717                 :                   "instead of the .hdr file.  Please try again selecting\n"
    1718                 :                   "the data file corresponding to the header file:\n"
    1719                 :                   "  %s\n", 
    1720               0 :                   poOpenInfo->pszFilename );
    1721               0 :         return NULL;
    1722                 :     }
    1723                 : 
    1724                 : /* -------------------------------------------------------------------- */
    1725                 : /*      Has the user selected the .sta (stats) file to open?            */
    1726                 : /* -------------------------------------------------------------------- */
    1727              98 :     if( EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "sta") )
    1728                 :     {
    1729               0 :         delete poDS;
    1730                 :         CPLError( CE_Failure, CPLE_AppDefined, 
    1731                 :                   "The selected file is an ENVI statistics file.\n"
    1732                 :                   "To open ENVI datasets, the data file should be selected\n"
    1733                 :                   "instead of the .sta file.  Please try again selecting\n"
    1734                 :                   "the data file corresponding to the statistics file:\n"
    1735                 :                   "  %s\n", 
    1736               0 :                   poOpenInfo->pszFilename );
    1737               0 :         return NULL;
    1738                 :     }
    1739                 : 
    1740                 : /* -------------------------------------------------------------------- */
    1741                 : /*      Extract required values from the .hdr.                          */
    1742                 : /* -------------------------------------------------------------------- */
    1743              98 :     int nLines = 0, nSamples = 0, nBands = 0, nHeaderSize = 0;
    1744              98 :     const char   *pszInterleave = NULL;
    1745                 : 
    1746              98 :     if( CSLFetchNameValue(poDS->papszHeader,"lines") )
    1747              98 :         nLines = atoi(CSLFetchNameValue(poDS->papszHeader,"lines"));
    1748                 : 
    1749              98 :     if( CSLFetchNameValue(poDS->papszHeader,"samples") )
    1750              98 :         nSamples = atoi(CSLFetchNameValue(poDS->papszHeader,"samples"));
    1751                 : 
    1752              98 :     if( CSLFetchNameValue(poDS->papszHeader,"bands") )
    1753              98 :         nBands = atoi(CSLFetchNameValue(poDS->papszHeader,"bands"));
    1754                 : 
    1755              98 :     pszInterleave = CSLFetchNameValue(poDS->papszHeader,"interleave");
    1756                 : 
    1757                 :     
    1758              98 :     if (!GDALCheckDatasetDimensions(nSamples, nLines) || !GDALCheckBandCount(nBands, FALSE) ||
    1759                 :         pszInterleave == NULL )
    1760                 :     {
    1761               2 :         delete poDS;
    1762                 :         CPLError( CE_Failure, CPLE_AppDefined, 
    1763                 :                   "The file appears to have an associated ENVI header, but\n"
    1764                 :                   "one or more of the samples, lines, bands and interleave\n"
    1765               2 :                   "keywords appears to be missing or invalid." );
    1766               2 :         return NULL;
    1767                 :     }
    1768                 : 
    1769              96 :     if( CSLFetchNameValue(poDS->papszHeader,"header_offset") )
    1770              96 :         nHeaderSize = atoi(CSLFetchNameValue(poDS->papszHeader,"header_offset"));
    1771                 : 
    1772                 : /* -------------------------------------------------------------------- */
    1773                 : /*      Translate the datatype.                                         */
    1774                 : /* -------------------------------------------------------------------- */
    1775              96 :     GDALDataType  eType = GDT_Byte;
    1776                 : 
    1777              96 :     if( CSLFetchNameValue(poDS->papszHeader,"data_type" ) != NULL )
    1778                 :     {
    1779              96 :         switch( atoi(CSLFetchNameValue(poDS->papszHeader,"data_type" )) )
    1780                 :         {
    1781                 :           case 1:
    1782              50 :             eType = GDT_Byte;
    1783              50 :             break;
    1784                 : 
    1785                 :           case 2:
    1786               6 :             eType = GDT_Int16;
    1787               6 :             break;
    1788                 : 
    1789                 :           case 3:
    1790               6 :             eType = GDT_Int32;
    1791               6 :             break;
    1792                 : 
    1793                 :           case 4:
    1794               6 :             eType = GDT_Float32;
    1795               6 :             break;
    1796                 : 
    1797                 :           case 5:
    1798               6 :             eType = GDT_Float64;
    1799               6 :             break;
    1800                 : 
    1801                 :           case 6:
    1802               5 :             eType = GDT_CFloat32;
    1803               5 :             break;
    1804                 : 
    1805                 :           case 9:
    1806               5 :             eType = GDT_CFloat64;
    1807               5 :             break;
    1808                 : 
    1809                 :           case 12:
    1810               6 :             eType = GDT_UInt16;
    1811               6 :             break;
    1812                 : 
    1813                 :           case 13:
    1814               6 :             eType = GDT_UInt32;
    1815               6 :             break;
    1816                 : 
    1817                 :             /* 14=Int64, 15=UInt64 */
    1818                 : 
    1819                 :           default:
    1820               0 :             delete poDS;
    1821                 :             CPLError( CE_Failure, CPLE_AppDefined, 
    1822                 :                       "The file does not have a value for the data_type\n"
    1823               0 :                       "that is recognised by the GDAL ENVI driver.");
    1824               0 :             return NULL;
    1825                 :         }
    1826                 :     }
    1827                 : 
    1828                 : /* -------------------------------------------------------------------- */
    1829                 : /*      Translate the byte order.         */
    1830                 : /* -------------------------------------------------------------------- */
    1831              96 :     int   bNativeOrder = TRUE;
    1832                 : 
    1833              96 :     if( CSLFetchNameValue(poDS->papszHeader,"byte_order" ) != NULL )
    1834                 :     {
    1835                 : #ifdef CPL_LSB                               
    1836                 :         bNativeOrder = atoi(CSLFetchNameValue(poDS->papszHeader,
    1837              96 :                                               "byte_order" )) == 0;
    1838                 : #else
    1839                 :         bNativeOrder = atoi(CSLFetchNameValue(poDS->papszHeader,
    1840                 :                                               "byte_order" )) != 0;
    1841                 : #endif
    1842                 :     }
    1843                 : 
    1844                 : /* -------------------------------------------------------------------- */
    1845                 : /*      Warn about unsupported file types virtual mosaic and meta file.*/
    1846                 : /* -------------------------------------------------------------------- */
    1847              96 :     if( CSLFetchNameValue(poDS->papszHeader,"file_type" ) != NULL )
    1848                 :     {
    1849                 :         const char * pszEnviFileType;
    1850              96 :         pszEnviFileType = CSLFetchNameValue(poDS->papszHeader,"file_type");
    1851              96 :         if(!EQUAL(pszEnviFileType, "ENVI Standard") &&
    1852                 :            !EQUAL(pszEnviFileType, "ENVI") &&
    1853                 :            !EQUAL(pszEnviFileType, "ENVI Classification"))
    1854                 :         {
    1855                 :             CPLError( CE_Failure, CPLE_OpenFailed, 
    1856                 :                       "File %s contains an invalid file type in the ENVI .hdr\n"
    1857                 :                       "GDAL does not support '%s' type files.",
    1858               0 :                       poOpenInfo->pszFilename, pszEnviFileType );
    1859               0 :             delete poDS;
    1860               0 :             return NULL;
    1861                 :         }
    1862                 :     }
    1863                 : 
    1864                 : /* -------------------------------------------------------------------- */
    1865                 : /*      Warn about compressed datasets.                                 */
    1866                 : /* -------------------------------------------------------------------- */
    1867              96 :     if( CSLFetchNameValue(poDS->papszHeader,"file_compression" ) != NULL )
    1868                 :     {
    1869               0 :         if( atoi(CSLFetchNameValue(poDS->papszHeader,"file_compression" )) 
    1870                 :             != 0 )
    1871                 :         {
    1872               0 :             delete poDS;
    1873                 :             CPLError( CE_Failure, CPLE_OpenFailed, 
    1874                 :                       "File %s is marked as compressed in the ENVI .hdr\n"
    1875                 :                       "GDAL does not support auto-decompression of ENVI data\n"
    1876                 :                       "files.",
    1877               0 :                       poOpenInfo->pszFilename );
    1878               0 :             return NULL;
    1879                 :         }
    1880                 :     }
    1881                 : 
    1882                 : /* -------------------------------------------------------------------- */
    1883                 : /*      Capture some information from the file that is of interest.     */
    1884                 : /* -------------------------------------------------------------------- */
    1885              96 :     poDS->nRasterXSize = nSamples;
    1886              96 :     poDS->nRasterYSize = nLines;
    1887              96 :     poDS->eAccess = poOpenInfo->eAccess;
    1888                 : 
    1889                 : /* -------------------------------------------------------------------- */
    1890                 : /*      Reopen file in update mode if necessary.                        */
    1891                 : /* -------------------------------------------------------------------- */
    1892              96 :     if( poOpenInfo->eAccess == GA_Update )
    1893              46 :         poDS->fpImage = VSIFOpenL( poOpenInfo->pszFilename, "rb+" );
    1894                 :     else
    1895              50 :         poDS->fpImage = VSIFOpenL( poOpenInfo->pszFilename, "rb" );
    1896                 : 
    1897              96 :     if( poDS->fpImage == NULL )
    1898                 :     {
    1899               0 :         delete poDS;
    1900                 :         CPLError( CE_Failure, CPLE_OpenFailed, 
    1901                 :                   "Failed to re-open %s within ENVI driver.\n", 
    1902               0 :                   poOpenInfo->pszFilename );
    1903               0 :         return NULL;
    1904                 :     }
    1905                 : 
    1906                 : /* -------------------------------------------------------------------- */
    1907                 : /*      Compute the line offset.                                        */
    1908                 : /* -------------------------------------------------------------------- */
    1909              96 :     int nDataSize = GDALGetDataTypeSize(eType)/8;
    1910                 :     int nPixelOffset, nLineOffset;
    1911                 :     vsi_l_offset nBandOffset;
    1912              96 :     int bIntOverflow = FALSE;
    1913                 :     
    1914              96 :     if( EQUALN(pszInterleave, "bsq", 3) )
    1915                 :     {
    1916              96 :         poDS->interleave = BSQ;
    1917              96 :         poDS->SetMetadataItem( "INTERLEAVE", "BAND", "IMAGE_STRUCTURE" );
    1918              96 :         if (nSamples > INT_MAX / nDataSize) bIntOverflow = TRUE;
    1919              96 :         nLineOffset = nDataSize * nSamples;
    1920              96 :         nPixelOffset = nDataSize;
    1921              96 :         nBandOffset = (vsi_l_offset)nLineOffset * nLines;
    1922                 :     }
    1923               0 :     else if( EQUALN(pszInterleave, "bil", 3) )
    1924                 :     {
    1925               0 :         poDS->interleave = BIL;
    1926               0 :         poDS->SetMetadataItem( "INTERLEAVE", "LINE", "IMAGE_STRUCTURE" );
    1927               0 :         if (nSamples > INT_MAX / (nDataSize * nBands)) bIntOverflow = TRUE;
    1928               0 :         nLineOffset = nDataSize * nSamples * nBands;
    1929               0 :         nPixelOffset = nDataSize;
    1930               0 :         nBandOffset = (vsi_l_offset)nDataSize * nSamples;
    1931                 :     }
    1932               0 :     else if( EQUALN(pszInterleave, "bip", 3) )
    1933                 :     {
    1934               0 :         poDS->interleave = BIP;
    1935               0 :         poDS->SetMetadataItem( "INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE" );
    1936               0 :         if (nSamples > INT_MAX / (nDataSize * nBands)) bIntOverflow = TRUE;
    1937               0 :         nLineOffset = nDataSize * nSamples * nBands;
    1938               0 :         nPixelOffset = nDataSize * nBands;
    1939               0 :         nBandOffset = nDataSize;
    1940                 :     }
    1941                 :     else
    1942                 :     {
    1943               0 :         delete poDS;
    1944                 :         CPLError( CE_Failure, CPLE_AppDefined, 
    1945                 :                   "The interleaving type of the file (%s) is not supported.",
    1946               0 :                   pszInterleave );
    1947               0 :         return NULL;
    1948                 :     }
    1949                 : 
    1950              96 :     if (bIntOverflow)
    1951                 :     {
    1952               0 :         delete poDS;
    1953                 :         CPLError( CE_Failure, CPLE_AppDefined, 
    1954               0 :                   "Int overflow occured.");
    1955               0 :         return NULL;
    1956                 :     }
    1957                 :     
    1958                 : /* -------------------------------------------------------------------- */
    1959                 : /*      Create band information objects.                                */
    1960                 : /* -------------------------------------------------------------------- */
    1961              96 :     poDS->nBands = nBands;
    1962             268 :     for( i = 0; i < poDS->nBands; i++ )
    1963                 :     {
    1964                 :         poDS->SetBand( i + 1,
    1965                 :                        new RawRasterBand(poDS, i + 1, poDS->fpImage,
    1966                 :                                          nHeaderSize + nBandOffset * i,
    1967                 :                                          nPixelOffset, nLineOffset, eType,
    1968             172 :                                          bNativeOrder, TRUE) );
    1969                 :     }
    1970                 : 
    1971                 : /* -------------------------------------------------------------------- */
    1972                 : /*      Apply band names if we have them.                               */
    1973                 : /*      Use wavelength for more descriptive information if possible     */
    1974                 : /* -------------------------------------------------------------------- */
    1975              96 :     if( CSLFetchNameValue( poDS->papszHeader, "band_names" ) != NULL ||
    1976                 :         CSLFetchNameValue( poDS->papszHeader, "wavelength" ) != NULL)
    1977                 :     {
    1978                 :         char  **papszBandNames = 
    1979                 :             poDS->SplitList( CSLFetchNameValue( poDS->papszHeader, 
    1980              48 :                                                 "band_names" ) );
    1981                 :         char  **papszWL = 
    1982                 :             poDS->SplitList( CSLFetchNameValue( poDS->papszHeader, 
    1983              48 :                                                 "wavelength" ) );
    1984                 : 
    1985              48 :         const char *pszWLUnits = NULL;
    1986              48 :         if (papszWL) 
    1987                 :         {
    1988                 :             /* If WL information is present, process wavelength units */
    1989                 :             pszWLUnits = CSLFetchNameValue( poDS->papszHeader, 
    1990               0 :                                             "wavelength_units" );
    1991               0 :             if (pszWLUnits)
    1992                 :             {
    1993                 :                 /* Don't show unknown or index units */
    1994               0 :                 if (EQUAL(pszWLUnits,"Unknown") ||
    1995                 :                     EQUAL(pszWLUnits,"Index") )
    1996               0 :                     pszWLUnits=0;
    1997                 :             }
    1998                 :         }
    1999                 : 
    2000             126 :         for( i = 0; i < nBands; i++ )
    2001                 :         {
    2002              78 :             CPLString osBandId, osBandName, osWavelength;
    2003                 : 
    2004                 :             /* First set up the wavelength names and units if available */
    2005              78 :             if (papszWL && CSLCount(papszWL) > i) 
    2006                 :             {
    2007               0 :                 osWavelength = papszWL[i];
    2008               0 :                 if (pszWLUnits) 
    2009                 :                 {
    2010               0 :                     osWavelength += " ";
    2011               0 :                     osWavelength += pszWLUnits;
    2012                 :                 }
    2013                 :             }
    2014                 : 
    2015                 :             /* Build the final name for this band */
    2016              78 :             if (papszBandNames && CSLCount(papszBandNames) > i)
    2017                 :             {
    2018              78 :                 osBandName = papszBandNames[i];
    2019              78 :                 if (strlen(osWavelength) > 0) 
    2020                 :                 {
    2021               0 :                     osBandName += " (";
    2022               0 :                     osBandName += osWavelength;
    2023               0 :                     osBandName += ")";
    2024                 :                 }
    2025                 :             }
    2026                 :             else   /* WL but no band names */
    2027               0 :                 osBandName = osWavelength;
    2028                 : 
    2029                 :             /* Description is for internal GDAL usage */
    2030              78 :             poDS->GetRasterBand(i + 1)->SetDescription( osBandName );
    2031                 : 
    2032                 :             /* Metadata field named Band_1, etc. needed for ArcGIS integration */
    2033              78 :             osBandId = CPLSPrintf("Band_%i", i+1);
    2034              78 :             poDS->SetMetadataItem(osBandId, osBandName);
    2035                 :         }
    2036              48 :         CSLDestroy( papszWL );
    2037              48 :         CSLDestroy( papszBandNames );
    2038                 :     }
    2039                 : /* -------------------------------------------------------------------- */
    2040                 : /*      Apply class names if we have them.                              */
    2041                 : /* -------------------------------------------------------------------- */
    2042              96 :     if( CSLFetchNameValue( poDS->papszHeader, "class_names" ) != NULL )
    2043                 :     {
    2044                 :         char  **papszClassNames = 
    2045                 :             poDS->SplitList( CSLFetchNameValue( poDS->papszHeader, 
    2046               0 :                                                 "class_names" ) );
    2047                 : 
    2048               0 :         poDS->GetRasterBand(1)->SetCategoryNames( papszClassNames );
    2049               0 :         CSLDestroy( papszClassNames );
    2050                 :     }
    2051                 :     
    2052                 : /* -------------------------------------------------------------------- */
    2053                 : /*      Apply colormap if we have one.          */
    2054                 : /* -------------------------------------------------------------------- */
    2055              96 :     if( CSLFetchNameValue( poDS->papszHeader, "class_lookup" ) != NULL )
    2056                 :     {
    2057                 :         char  **papszClassColors = 
    2058                 :             poDS->SplitList( CSLFetchNameValue( poDS->papszHeader, 
    2059               0 :                                                 "class_lookup" ) );
    2060               0 :         int nColorValueCount = CSLCount(papszClassColors);
    2061               0 :         GDALColorTable oCT;
    2062                 :     
    2063               0 :         for( i = 0; i*3+2 < nColorValueCount; i++ )
    2064                 :         {
    2065                 :             GDALColorEntry sEntry;
    2066                 : 
    2067               0 :             sEntry.c1 = atoi(papszClassColors[i*3+0]);
    2068               0 :             sEntry.c2 = atoi(papszClassColors[i*3+1]);
    2069               0 :             sEntry.c3 = atoi(papszClassColors[i*3+2]);
    2070               0 :             sEntry.c4 = 255;
    2071               0 :             oCT.SetColorEntry( i, &sEntry );
    2072                 :         }
    2073                 : 
    2074               0 :         CSLDestroy( papszClassColors );
    2075                 : 
    2076               0 :         poDS->GetRasterBand(1)->SetColorTable( &oCT );
    2077               0 :         poDS->GetRasterBand(1)->SetColorInterpretation( GCI_PaletteIndex );
    2078                 :     }
    2079                 : 
    2080                 : /* -------------------------------------------------------------------- */
    2081                 : /*      Set the nodata value if it is present                           */
    2082                 : /* -------------------------------------------------------------------- */  
    2083              96 :     if( CSLFetchNameValue(poDS->papszHeader,"data_ignore_value" ) != NULL )
    2084                 :     {
    2085               0 :         for( i = 0; i < poDS->nBands; i++ )
    2086                 :             ((RawRasterBand*)poDS->GetRasterBand(i+1))->SetNoDataValue(atof(
    2087               0 :                                                                              CSLFetchNameValue(poDS->papszHeader,"data_ignore_value")));
    2088                 :     }
    2089                 : 
    2090                 : /* -------------------------------------------------------------------- */
    2091                 : /*      Read the stats file if it is present                            */
    2092                 : /* -------------------------------------------------------------------- */  
    2093              96 :     poDS->ProcessStatsFile();
    2094                 : 
    2095                 : /* -------------------------------------------------------------------- */
    2096                 : /*      Look for mapinfo                                                */
    2097                 : /* -------------------------------------------------------------------- */
    2098              96 :     if( CSLFetchNameValue( poDS->papszHeader, "map_info" ) != NULL )
    2099                 :     {
    2100                 :         poDS->bFoundMapinfo = 
    2101                 :             poDS->ProcessMapinfo( 
    2102              48 :                 CSLFetchNameValue(poDS->papszHeader,"map_info") );
    2103                 :     }
    2104                 : 
    2105                 : /* -------------------------------------------------------------------- */
    2106                 : /*      Look for RPC mapinfo                                            */
    2107                 : /* -------------------------------------------------------------------- */
    2108              96 :     if( !poDS->bFoundMapinfo &&
    2109                 :         CSLFetchNameValue( poDS->papszHeader, "rpc_info" ) != NULL )
    2110                 :     {
    2111                 :         poDS->ProcessRPCinfo( 
    2112                 :             CSLFetchNameValue(poDS->papszHeader,"rpc_info"), 
    2113               0 :             poDS->nRasterXSize, poDS->nRasterYSize);
    2114                 :     }
    2115                 :     
    2116                 : /* -------------------------------------------------------------------- */
    2117                 : /*      Initialize any PAM information.                                 */
    2118                 : /* -------------------------------------------------------------------- */
    2119              96 :     poDS->SetDescription( poOpenInfo->pszFilename );
    2120              96 :     poDS->TryLoadXML();
    2121                 : 
    2122                 : /* -------------------------------------------------------------------- */
    2123                 : /*      Check for overviews.                                            */
    2124                 : /* -------------------------------------------------------------------- */
    2125              96 :     poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename );
    2126                 : 
    2127              96 :     return( poDS );
    2128                 : }
    2129                 : 
    2130              92 : int ENVIDataset::GetEnviType(GDALDataType eType)
    2131                 : {
    2132                 :   int iENVIType;
    2133              92 :   switch( eType )
    2134                 :   {
    2135                 :       case GDT_Byte:
    2136              38 :         iENVIType = 1;
    2137              38 :         break;
    2138                 :       case GDT_Int16:
    2139               6 :         iENVIType = 2;
    2140               6 :         break;
    2141                 :       case GDT_Int32:
    2142               6 :         iENVIType = 3;
    2143               6 :         break;
    2144                 :       case GDT_Float32:
    2145               6 :         iENVIType = 4;
    2146               6 :         break;
    2147                 :       case GDT_Float64:
    2148               6 :         iENVIType = 5;
    2149               6 :         break;
    2150                 :       case GDT_CFloat32:
    2151               6 :         iENVIType = 6;
    2152               6 :         break;
    2153                 :       case GDT_CFloat64:
    2154               6 :         iENVIType = 9;
    2155               6 :         break;
    2156                 :       case GDT_UInt16:
    2157               6 :         iENVIType = 12;
    2158               6 :         break;
    2159                 :       case GDT_UInt32:
    2160               6 :         iENVIType = 13;
    2161               6 :         break;
    2162                 : 
    2163                 :   /* 14=Int64, 15=UInt64 */
    2164                 : 
    2165                 :       default:
    2166                 :         CPLError( CE_Failure, CPLE_AppDefined,
    2167                 :               "Attempt to create ENVI .hdr labelled dataset with an illegal\n"
    2168                 :               "data type (%s).\n",
    2169               6 :               GDALGetDataTypeName(eType) );
    2170               6 :         return 1;
    2171                 :   }
    2172              86 :   return iENVIType;
    2173                 : }
    2174                 : 
    2175                 : /************************************************************************/
    2176                 : /*                               Create()                               */
    2177                 : /************************************************************************/
    2178                 : 
    2179                 : GDALDataset *ENVIDataset::Create( const char * pszFilename,
    2180                 :                                   int nXSize, int nYSize, int nBands,
    2181                 :                                   GDALDataType eType,
    2182              47 :                                   char ** papszOptions )
    2183                 : 
    2184                 : {
    2185                 : /* -------------------------------------------------------------------- */
    2186                 : /*      Verify input options.                                           */
    2187                 : /* -------------------------------------------------------------------- */
    2188              47 :     int iENVIType = GetEnviType(eType);
    2189              47 :     if (0 == iENVIType)
    2190               0 :       return 0;
    2191                 : 
    2192                 : /* -------------------------------------------------------------------- */
    2193                 : /*      Try to create the file.                                         */
    2194                 : /* -------------------------------------------------------------------- */
    2195                 :     FILE  *fp;
    2196                 : 
    2197              47 :     fp = VSIFOpenL( pszFilename, "wb" );
    2198                 : 
    2199              47 :     if( fp == NULL )
    2200                 :     {
    2201                 :         CPLError( CE_Failure, CPLE_OpenFailed,
    2202                 :                   "Attempt to create file `%s' failed.\n",
    2203               0 :                   pszFilename );
    2204               0 :         return NULL;
    2205                 :     }
    2206                 : 
    2207                 : /* -------------------------------------------------------------------- */
    2208                 : /*      Just write out a couple of bytes to establish the binary        */
    2209                 : /*      file, and then close it.                                        */
    2210                 : /* -------------------------------------------------------------------- */
    2211              47 :     VSIFWriteL( (void *) "\0\0", 2, 1, fp );
    2212              47 :     VSIFCloseL( fp );
    2213                 : 
    2214                 : /* -------------------------------------------------------------------- */
    2215                 : /*      Create the .hdr filename.                                       */
    2216                 : /* -------------------------------------------------------------------- */
    2217                 :     const char  *pszHDRFilename;
    2218                 :     const char  *pszSuffix;
    2219                 : 
    2220              47 :     pszSuffix = CSLFetchNameValue( papszOptions, "SUFFIX" );
    2221              47 :     if ( pszSuffix && EQUALN( pszSuffix, "ADD", 3 ))
    2222               0 :   pszHDRFilename = CPLFormFilename( NULL, pszFilename, "hdr" );
    2223                 :     else
    2224              47 :   pszHDRFilename = CPLResetExtension(pszFilename, "hdr" );
    2225                 : 
    2226                 : /* -------------------------------------------------------------------- */
    2227                 : /*      Open the file.                                                  */
    2228                 : /* -------------------------------------------------------------------- */
    2229              47 :     fp = VSIFOpenL( pszHDRFilename, "wt" );
    2230              47 :     if( fp == NULL )
    2231                 :     {
    2232                 :         CPLError( CE_Failure, CPLE_OpenFailed,
    2233                 :                   "Attempt to create file `%s' failed.\n",
    2234               0 :                   pszHDRFilename );
    2235               0 :         return NULL;
    2236                 :     }
    2237                 : 
    2238                 : /* -------------------------------------------------------------------- */
    2239                 : /*      Write out the header.                                           */
    2240                 : /* -------------------------------------------------------------------- */
    2241                 :     int   iBigEndian;
    2242                 :     const char  *pszInterleaving;
    2243                 :     
    2244                 : #ifdef CPL_LSB
    2245              47 :     iBigEndian = 0;
    2246                 : #else
    2247                 :     iBigEndian = 1;
    2248                 : #endif
    2249                 : 
    2250              47 :     VSIFPrintfL( fp, "ENVI\n" );
    2251                 :     VSIFPrintfL( fp, "samples = %d\nlines   = %d\nbands   = %d\n",
    2252              47 :     nXSize, nYSize, nBands );
    2253              47 :     VSIFPrintfL( fp, "header offset = 0\nfile type = ENVI Standard\n" );
    2254              47 :     VSIFPrintfL( fp, "data type = %d\n", iENVIType );
    2255              47 :     pszInterleaving = CSLFetchNameValue( papszOptions, "INTERLEAVE" );
    2256              47 :     if ( pszInterleaving )
    2257                 :     {
    2258               0 :   if ( EQUALN( pszInterleaving, "bip", 3 ) )
    2259               0 :       pszInterleaving = "bip";        // interleaved by pixel
    2260               0 :   else if ( EQUALN( pszInterleaving, "bil", 3 ) )
    2261               0 :       pszInterleaving = "bil";        // interleaved by line
    2262                 :   else
    2263               0 :       pszInterleaving = "bsq";    // band sequental by default
    2264                 :     }
    2265                 :     else
    2266              47 :   pszInterleaving = "bsq";
    2267              47 :     VSIFPrintfL( fp, "interleave = %s\n", pszInterleaving);
    2268              47 :     VSIFPrintfL( fp, "byte order = %d\n", iBigEndian );
    2269                 : 
    2270              47 :     VSIFCloseL( fp );
    2271                 : 
    2272              47 :     return (GDALDataset *) GDALOpen( pszFilename, GA_Update );
    2273                 : }
    2274                 : 
    2275                 : /************************************************************************/
    2276                 : /*                         GDALRegister_ENVI()                          */
    2277                 : /************************************************************************/
    2278                 : 
    2279             409 : void GDALRegister_ENVI()
    2280                 : {
    2281                 :     GDALDriver  *poDriver;
    2282                 : 
    2283             409 :     if( GDALGetDriverByName( "ENVI" ) == NULL )
    2284                 :     {
    2285             392 :         poDriver = new GDALDriver();
    2286                 :         
    2287             392 :         poDriver->SetDescription( "ENVI" );
    2288                 :         poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, 
    2289             392 :                                    "ENVI .hdr Labelled" );
    2290                 :         poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, 
    2291             392 :                                    "frmt_various.html#ENVI" );
    2292             392 :         poDriver->SetMetadataItem( GDAL_DMD_EXTENSION, "" );
    2293                 :         poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, 
    2294                 :                                    "Byte Int16 UInt16 Int32 UInt32 "
    2295             392 :                                    "Float32 Float64 CFloat32 CFloat64" );
    2296                 :         poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST,
    2297                 : "<CreationOptionList>"
    2298                 : "   <Option name='SUFFIX' type='string-select'>"
    2299                 : "       <Value>ADD</Value>"
    2300                 : "   </Option>"
    2301                 : "   <Option name='INTERLEAVE' type='string-select'>"
    2302                 : "       <Value>BIP</Value>"
    2303                 : "       <Value>BIL</Value>"
    2304                 : "       <Value>BSQ</Value>"
    2305                 : "   </Option>"
    2306             392 : "</CreationOptionList>" );
    2307                 : 
    2308             392 :         poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" );
    2309             392 :         poDriver->pfnOpen = ENVIDataset::Open;
    2310             392 :         poDriver->pfnCreate = ENVIDataset::Create;
    2311                 : 
    2312             392 :         GetGDALDriverManager()->RegisterDriver( poDriver );
    2313                 :     }
    2314             409 : }

Generated by: LTP GCOV extension version 1.5