File: grass.cpp

package info (click to toggle)
libgdal-grass 3.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 368 kB
  • sloc: cpp: 1,704; makefile: 100
file content (1037 lines) | stat: -rw-r--r-- 37,238 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
/******************************************************************************
 *
 * Project:  GRASS Driver
 * Purpose:  Implement GRASS raster read/write support
 *           This version is for GRASS GIS 7+ and uses GRASS libraries
 *           directly instead of using libgrass.
 * Author:   Frank Warmerdam <warmerdam@pobox.com>
 *           Radim Blazek <blazek@itc.it>
 *
 ******************************************************************************
 * Copyright (c) 2000 Frank Warmerdam <warmerdam@pobox.com>
 * Copyright (c) 2007-2020, Even Rouault <even dot rouault at spatialys.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ****************************************************************************/

#include <stdlib.h>

#include "cpl_string.h"
#include "gdal_frmts.h"
#include "gdal_priv.h"
#include "ogr_spatialref.h"

extern "C" {
#ifdef __cplusplus
#define class _class
#endif
#include <grass/imagery.h>
#ifdef __cplusplus
#undef class
#endif

#include <grass/version.h>
#include <grass/gprojects.h>
#include <grass/gis.h>

char *GPJ_grass_to_wkt( const struct Key_Value *,
                        const struct Key_Value *,
                        int, int );
}

#define GRASS_MAX_COLORS 100000  // what is the right value

CPL_CVSID("$Id: grass.cpp a832da5b936bac8438f9c50e7c20e563fd94c9ff 2020-09-22 13:06:27 +0200 Markus Neteler $")

/************************************************************************/
/*                         Grass2CPLErrorHook()                         */
/************************************************************************/

static int Grass2CPLErrorHook( char * pszMessage, int bFatal )

{
    if( !bFatal )
        //CPLDebug( "GRASS", "%s", pszMessage );
        CPLError( CE_Warning, CPLE_AppDefined, "GRASS warning: %s", pszMessage );
    else
        CPLError( CE_Warning, CPLE_AppDefined, "GRASS fatal error: %s", pszMessage );

    return 0;
}

/************************************************************************/
/* ==================================================================== */
/*                              GRASSDataset                            */
/* ==================================================================== */
/************************************************************************/

class GRASSRasterBand;

class GRASSDataset final: public GDALDataset
{
    friend class GRASSRasterBand;

    char        *pszGisdbase;
    char        *pszLocation;  /* LOCATION_NAME */
    char        *pszElement;   /* cellhd or group */

    struct Cell_head sCellInfo; /* raster region */

    char        *pszProjection;

    double      adfGeoTransform[6];

  public:
    GRASSDataset();
    ~GRASSDataset() override;

    const char *_GetProjectionRef(void) override;
    const OGRSpatialReference* GetSpatialRef() const override {
        return GetSpatialRefFromOldGetProjectionRef();
    }
    CPLErr GetGeoTransform( double * ) override;

    static GDALDataset *Open( GDALOpenInfo * );

  private:
    static bool SplitPath ( char *, char **, char **, char **, char **, char ** );
};

/************************************************************************/
/* ==================================================================== */
/*                            GRASSRasterBand                           */
/* ==================================================================== */
/************************************************************************/

class GRASSRasterBand final: public GDALRasterBand
{
    friend class GRASSDataset;

    char        *pszCellName;
    char        *pszMapset;
    int         hCell;
    int         nGRSType; // GRASS raster type: CELL_TYPE, FCELL_TYPE, DCELL_TYPE
    bool        nativeNulls; // use GRASS native NULL values

    struct Colors sGrassColors;
    GDALColorTable *poCT;

    struct Cell_head sOpenWindow; /* the region when the raster was opened */

    int         bHaveMinMax;
    double      dfCellMin;
    double      dfCellMax;

    double      dfNoData;

    bool        valid;

  public:
    GRASSRasterBand( GRASSDataset *, int, const char *, const char * );
    ~GRASSRasterBand() override;

    CPLErr IReadBlock( int, int, void * ) override;
    CPLErr IRasterIO ( GDALRWFlag, int, int, int, int,
                       void *, int, int, GDALDataType,
                       GSpacing nPixelSpace,
                       GSpacing nLineSpace,
                       GDALRasterIOExtraArg* psExtraArg) override;
    GDALColorInterp GetColorInterpretation() override;
    GDALColorTable *GetColorTable() override;
    double GetMinimum( int *pbSuccess = NULL ) override;
    double GetMaximum( int *pbSuccess = NULL ) override;
    double GetNoDataValue( int *pbSuccess = NULL ) override;

  private:
    void SetWindow( struct Cell_head * );
    CPLErr ResetReading( struct Cell_head * );
};

/************************************************************************/
/*                          GRASSRasterBand()                           */
/************************************************************************/

GRASSRasterBand::GRASSRasterBand( GRASSDataset *poDSIn, int nBandIn,
                                  const char * pszMapsetIn,
                                  const char * pszCellNameIn )

{
    struct Cell_head sCellInfo;

    // Note: GISDBASE, LOCATION_NAME ans MAPSET was set in GRASSDataset::Open

    this->poDS = poDSIn;
    this->nBand = nBandIn;
    this->valid = false;

    this->pszCellName = G_store ( (char *) pszCellNameIn );
    this->pszMapset = G_store ( (char *) pszMapsetIn );

    Rast_get_cellhd( (char *) pszCellName, (char *) pszMapset, &sCellInfo );
    nGRSType = Rast_map_type( (char *) pszCellName, (char *) pszMapset );

/* -------------------------------------------------------------------- */
/*      Get min/max values.                                             */
/* -------------------------------------------------------------------- */
    struct FPRange sRange;

    if( Rast_read_fp_range( (char *) pszCellName, (char *) pszMapset,
                         &sRange ) == -1 )
    {
        bHaveMinMax = FALSE;
    }
    else
    {
        bHaveMinMax = TRUE;
        Rast_get_fp_range_min_max( &sRange, &dfCellMin, &dfCellMax );
    }

/* -------------------------------------------------------------------- */
/*      Setup band type, and preferred nodata value.                    */
/* -------------------------------------------------------------------- */
    // Negative values are also (?) stored as 4 bytes (format = 3)
    //       => raster with format < 3 has only positive values

    // GRASS modules usually do not waste space and only the format necessary to keep
    // full raster values range is used -> no checks if shorter type could be used

    if( nGRSType == CELL_TYPE ) {
        if ( sCellInfo.format == 0 ) {  // 1 byte / cell -> possible range 0,255
            if ( bHaveMinMax && dfCellMin > 0 ) {
                this->eDataType = GDT_Byte;
                dfNoData = 0.0;
            } else if ( bHaveMinMax && dfCellMax < 255 ) {
                this->eDataType = GDT_Byte;
                dfNoData = 255.0;
            } else { // maximum is not known or full range is used
                this->eDataType = GDT_UInt16;
                dfNoData = 256.0;
            }
            nativeNulls = false;
        } else if ( sCellInfo.format == 1 ) {  // 2 bytes / cell -> possible range 0,65535
            if ( bHaveMinMax && dfCellMin > 0 ) {
                this->eDataType = GDT_UInt16;
                dfNoData = 0.0;
            } else if ( bHaveMinMax && dfCellMax < 65535 ) {
                this->eDataType = GDT_UInt16;
                dfNoData = 65535;
            } else { // maximum is not known or full range is used
                CELL cval;
                this->eDataType = GDT_Int32;
                Rast_set_c_null_value ( &cval, 1);
                dfNoData = (double) cval;
            }
            nativeNulls = false;
        } else {  // 3-4 bytes
            CELL cval;
            this->eDataType = GDT_Int32;
            Rast_set_c_null_value ( &cval, 1);
            dfNoData = (double) cval;
            nativeNulls = true;
        }
    }
    else if( nGRSType == FCELL_TYPE ) {
        FCELL fval;
        this->eDataType = GDT_Float32;
        Rast_set_f_null_value ( &fval, 1);
        dfNoData = (double) fval;
        nativeNulls = true;
    }
    else if( nGRSType == DCELL_TYPE )
    {
        DCELL dval;
        this->eDataType = GDT_Float64;
        Rast_set_d_null_value ( &dval, 1);
        dfNoData = (double) dval;
        nativeNulls = true;
    }

    nBlockXSize = poDSIn->nRasterXSize;
    nBlockYSize = 1;

    Rast_set_window ( &(poDSIn->sCellInfo) );
    // open the raster only for actual reading
    hCell = -1;
    memcpy((void *) &sOpenWindow, (void *) &(poDSIn->sCellInfo), sizeof(struct Cell_head));

/* -------------------------------------------------------------------- */
/*      Do we have a color table?                                       */
/* -------------------------------------------------------------------- */
    poCT = NULL;
    if( Rast_read_colors( (char *) pszCellName, (char *) pszMapset, &sGrassColors ) == 1 )
    {
        int maxcolor;
        CELL min, max;

        Rast_get_c_color_range ( &min, &max, &sGrassColors);

        if ( bHaveMinMax ) {
            if ( max < dfCellMax ) {
               maxcolor = max;
            } else {
               maxcolor = (int) ceil ( dfCellMax );
            }
            if ( maxcolor > GRASS_MAX_COLORS ) {
                maxcolor = GRASS_MAX_COLORS;
                CPLDebug( "GRASS", "Too many values, color table cut to %d entries.", maxcolor );
            }
        } else {
            if ( max < GRASS_MAX_COLORS ) {
               maxcolor = max;
            } else {
               maxcolor = GRASS_MAX_COLORS;
               CPLDebug( "GRASS", "Too many values, color table set to %d entries.", maxcolor );
            }
        }

        poCT = new GDALColorTable();
        for( int iColor = 0; iColor <= maxcolor; iColor++ )
        {
            int nRed, nGreen, nBlue;
            GDALColorEntry    sColor;

            if( Rast_get_c_color( &iColor, &nRed, &nGreen, &nBlue, &sGrassColors ) )
            {
                sColor.c1 = nRed;
                sColor.c2 = nGreen;
                sColor.c3 = nBlue;
                sColor.c4 = 255;

                poCT->SetColorEntry( iColor, &sColor );
            }
            else
            {
                sColor.c1 = 0;
                sColor.c2 = 0;
                sColor.c3 = 0;
                sColor.c4 = 0;

                poCT->SetColorEntry( iColor, &sColor );
            }
        }

        /* Create metadata entries for color table rules */
        char key[200], value[200];
        int rcount = Rast_colors_count ( &sGrassColors );

        snprintf ( value, sizeof(value), "%d", rcount );
        this->SetMetadataItem( "COLOR_TABLE_RULES_COUNT", value );

        /* Add the rules in reverse order */
        for ( int i = rcount-1; i >= 0; i-- ) {
            DCELL val1, val2;
            unsigned char r1, g1, b1, r2, g2, b2;

            Rast_get_fp_color_rule ( &val1, &r1, &g1, &b1, &val2, &r2, &g2, &b2, &sGrassColors, i );

            snprintf ( key, sizeof(key), "COLOR_TABLE_RULE_RGB_%d", rcount-i-1 );
            snprintf ( value, sizeof(value), "%e %e %d %d %d %d %d %d", val1, val2, r1, g1, b1, r2, g2, b2 );
            this->SetMetadataItem( key, value );
        }
    } else {
        this->SetMetadataItem( "COLOR_TABLE_RULES_COUNT", "0" );
    }

    this->valid = true;
}

/************************************************************************/
/*                          ~GRASSRasterBand()                          */
/************************************************************************/

GRASSRasterBand::~GRASSRasterBand()
{
    if( poCT != NULL ) {
        Rast_free_colors( &sGrassColors );
        delete poCT;
    }

    if( hCell >= 0 )
        Rast_close( hCell );

    if ( pszCellName )
        G_free ( pszCellName );

    if ( pszMapset )
        G_free ( pszMapset );
}

/************************************************************************/
/*                             SetWindow                                */
/*                                                                      */
/* Helper for ResetReading                                              */
/* close the current GRASS raster band, actually set the new window,    */
/* reset GRASS variables                                                */
/*                                                                      */
/* Returns nothing                       */
/************************************************************************/
void GRASSRasterBand::SetWindow ( struct Cell_head *sNewWindow )
{
    if( hCell >= 0 ) {
        Rast_close( hCell );
        hCell = -1;
    }

    /* Set window */
    Rast_set_window( sNewWindow );

    /* Set GRASS env to the current raster, don't open the raster */
    G_setenv_nogisrc( "GISDBASE", ((GRASSDataset *)poDS)->pszGisdbase );
    G_setenv_nogisrc( "LOCATION_NAME", ((GRASSDataset *)poDS)->pszLocation );
    G_setenv_nogisrc( "MAPSET", pszMapset);
    G_reset_mapsets();
    G_add_mapset_to_search_path ( pszMapset );
}

/************************************************************************/
/*                             ResetReading                             */
/*                                                                      */
/* Reset current window for a new reading request,                      */
/* close the current GRASS raster band, reset GRASS variables           */
/*                                                                      */
/* Returns CE_Failure if fails, otherwise CE_None                       */
/************************************************************************/
CPLErr GRASSRasterBand::ResetReading ( struct Cell_head *sNewWindow )
{

    /* Check if the window has changed */
    if ( sNewWindow->north  != sOpenWindow.north  || sNewWindow->south  != sOpenWindow.south ||
         sNewWindow->east   != sOpenWindow.east   || sNewWindow->west   != sOpenWindow.west ||
         sNewWindow->ew_res != sOpenWindow.ew_res || sNewWindow->ns_res != sOpenWindow.ns_res ||
         sNewWindow->rows   != sOpenWindow.rows   || sNewWindow->cols   != sOpenWindow.cols )
    {
        SetWindow ( sNewWindow );
        memcpy((void *) &sOpenWindow, (void *) sNewWindow, sizeof(struct Cell_head));
    }
    else
    {
        /* The windows are identical, check current window */
        struct Cell_head sCurrentWindow;

        Rast_get_window ( &sCurrentWindow );

        if ( sNewWindow->north  != sCurrentWindow.north  || sNewWindow->south  != sCurrentWindow.south ||
             sNewWindow->east   != sCurrentWindow.east   || sNewWindow->west   != sCurrentWindow.west ||
             sNewWindow->ew_res != sCurrentWindow.ew_res || sNewWindow->ns_res != sCurrentWindow.ns_res ||
             sNewWindow->rows   != sCurrentWindow.rows   || sNewWindow->cols   != sCurrentWindow.cols
             )
        {
            SetWindow ( sNewWindow );
        }
    }

    return CE_None;
}

/************************************************************************/
/*                             IReadBlock()                             */
/*                                                                      */
/************************************************************************/

CPLErr GRASSRasterBand::IReadBlock( int /*nBlockXOff*/, int nBlockYOff,
                                    void *pImage )

{
    if ( ! this->valid ) return CE_Failure;

    // Reset window because IRasterIO could be previously called.
    if ( ResetReading ( &(((GRASSDataset *)poDS)->sCellInfo) ) != CE_None ) {
       return CE_Failure;
    }
    // open for reading
    if (hCell < 0) {
        if ( (hCell = Rast_open_old((char *) pszCellName, (char *) pszMapset)) < 0 ) {
            CPLError( CE_Failure, CPLE_AppDefined, "GRASS: Cannot open raster '%s'", pszCellName );
            return CE_Failure;
        }
    }

    if ( eDataType == GDT_Byte || eDataType == GDT_UInt16 ) {
        CELL *cbuf = Rast_allocate_c_buf();
        Rast_get_c_row ( hCell, cbuf, nBlockYOff );

        /* Reset NULLs */
        for ( int col = 0; col < nBlockXSize; col++ ) {
            if ( Rast_is_c_null_value(&(cbuf[col])) )
                cbuf[col] = (CELL) dfNoData;
        }

        GDALCopyWords ( (void *) cbuf, GDT_Int32, sizeof(CELL),
                        pImage, eDataType, GDALGetDataTypeSize(eDataType)/8,
                        nBlockXSize );

        G_free ( cbuf );
    }
    else if ( eDataType == GDT_Int32 )
    {
        Rast_get_c_row ( hCell, (CELL *) pImage, nBlockYOff );
    }
    else if ( eDataType == GDT_Float32 )
    {
        Rast_get_f_row ( hCell, (FCELL *) pImage, nBlockYOff );
    }
    else if ( eDataType == GDT_Float64 )
    {
        Rast_get_d_row ( hCell, (DCELL *) pImage, nBlockYOff );
    }

    // close to avoid confusion with other GRASS raster bands
    Rast_close( hCell );
    hCell = -1;

    return CE_None;
}

/************************************************************************/
/*                             IRasterIO()                              */
/*                                                                      */
/************************************************************************/

CPLErr GRASSRasterBand::IRasterIO ( GDALRWFlag eRWFlag,
                                   int nXOff, int nYOff, int nXSize, int nYSize,
                                   void * pData, int nBufXSize, int nBufYSize,
                                   GDALDataType eBufType,
                                   GSpacing nPixelSpace,
                                    GSpacing nLineSpace,
                                    GDALRasterIOExtraArg* /*psExtraArg*/ )
{
    /* GRASS library does that, we have only calculate and reset the region in map units
     * and if the region has changed, reopen the raster */

    /* Calculate the region */
    struct Cell_head sWindow;
    struct Cell_head *psDsWindow;

    if( eRWFlag != GF_Read ) return CE_Failure;
    if ( ! this->valid ) return CE_Failure;

    psDsWindow = &(((GRASSDataset *)poDS)->sCellInfo);

    sWindow.north = psDsWindow->north - nYOff * psDsWindow->ns_res;
    sWindow.south = sWindow.north - nYSize * psDsWindow->ns_res;
    sWindow.west = psDsWindow->west + nXOff * psDsWindow->ew_res;
    sWindow.east = sWindow.west + nXSize * psDsWindow->ew_res;
    sWindow.proj = psDsWindow->proj;
    sWindow.zone = psDsWindow->zone;

    sWindow.cols = nBufXSize;
    sWindow.rows = nBufYSize;

    /* Reset resolution */
    G_adjust_Cell_head ( &sWindow, 1, 1);

    if ( ResetReading ( &sWindow ) != CE_None )
    {
        return CE_Failure;
    }
    // open for reading
    if (hCell < 0) {
        if ( (hCell = Rast_open_old((char *) pszCellName, (char *) pszMapset)) < 0 ) {
            CPLError( CE_Failure, CPLE_AppDefined, "GRASS: Cannot open raster '%s'", pszCellName );
            return CE_Failure;
        }
    }

    /* Read Data */
    CELL  *cbuf = NULL;
    FCELL *fbuf = NULL;
    DCELL *dbuf = NULL;
    bool  direct = false;

    /* Reset space if default (0) */
    if ( nPixelSpace == 0 )
        nPixelSpace = GDALGetDataTypeSize ( eBufType ) / 8;

    if ( nLineSpace == 0 )
        nLineSpace = nBufXSize * nPixelSpace;

    if ( nGRSType == CELL_TYPE && ( !nativeNulls || eBufType != GDT_Int32 || sizeof(CELL) != 4 ||
                                    nPixelSpace != sizeof(CELL) )  )
    {
        cbuf = Rast_allocate_c_buf();
    } else if( nGRSType == FCELL_TYPE && ( eBufType != GDT_Float32 || nPixelSpace != sizeof(FCELL) ) ) {
        fbuf = Rast_allocate_f_buf();
    } else if( nGRSType == DCELL_TYPE && ( eBufType != GDT_Float64 || nPixelSpace != sizeof(DCELL) ) ) {
        dbuf = Rast_allocate_d_buf();
    } else {
        direct = true;
    }

    for ( int row = 0; row < nBufYSize; row++ ) {
        char *pnt = (char *)pData + row * nLineSpace;

        if ( nGRSType == CELL_TYPE ) {
            if ( direct ) {
                Rast_get_c_row ( hCell, (CELL *) pnt, row );
            } else {
                Rast_get_c_row ( hCell, cbuf, row );

                /* Reset NULLs */
                for ( int col = 0; col < nBufXSize; col++ ) {
                    if ( Rast_is_c_null_value(&(cbuf[col])) )
                        cbuf[col] = (CELL) dfNoData;
                }

                GDALCopyWords ( (void *) cbuf, GDT_Int32, sizeof(CELL),
                                (void *)  pnt,  eBufType, nPixelSpace,
                                nBufXSize );
            }
        } else if( nGRSType == FCELL_TYPE ) {
            if ( direct ) {
                Rast_get_f_row ( hCell, (FCELL *) pnt, row );
            } else {
                Rast_get_f_row ( hCell, fbuf, row );

                GDALCopyWords ( (void *) fbuf, GDT_Float32, sizeof(FCELL),
                                (void *)  pnt,  eBufType, nPixelSpace,
                                nBufXSize );
            }
        } else if( nGRSType == DCELL_TYPE ) {
            if ( direct ) {
                Rast_get_d_row ( hCell, (DCELL *) pnt, row );
            } else {
                Rast_get_d_row ( hCell, dbuf, row );

                GDALCopyWords ( (void *) dbuf, GDT_Float64, sizeof(DCELL),
                                (void *)  pnt,  eBufType, nPixelSpace,
                                nBufXSize );
            }
        }
    }

    if ( cbuf ) G_free ( cbuf );
    if ( fbuf ) G_free ( fbuf );
    if ( dbuf ) G_free ( dbuf );

    // close to avoid confusion with other GRASS raster bands
    Rast_close( hCell );
    hCell = -1;

    return CE_None;
}

/************************************************************************/
/*                       GetColorInterpretation()                       */
/************************************************************************/

GDALColorInterp GRASSRasterBand::GetColorInterpretation()

{
    if( poCT != NULL )
        return GCI_PaletteIndex;
    else
        return GCI_GrayIndex;
}

/************************************************************************/
/*                           GetColorTable()                            */
/************************************************************************/

GDALColorTable *GRASSRasterBand::GetColorTable()

{
    return poCT;
}

/************************************************************************/
/*                             GetMinimum()                             */
/************************************************************************/

double GRASSRasterBand::GetMinimum( int *pbSuccess )

{
    if( pbSuccess )
        *pbSuccess = bHaveMinMax;

    if( bHaveMinMax )
        return dfCellMin;

    else if( eDataType == GDT_Float32 || eDataType == GDT_Float64 )
        return -4294967295.0;
    else
        return 0;
}

/************************************************************************/
/*                             GetMaximum()                             */
/************************************************************************/

double GRASSRasterBand::GetMaximum( int *pbSuccess )

{
    if( pbSuccess )
        *pbSuccess = bHaveMinMax;

    if( bHaveMinMax )
        return dfCellMax;

    else if( eDataType == GDT_Float32 || eDataType == GDT_Float64 )
        return 4294967295.0;
    else if( eDataType == GDT_UInt32 )
        return 4294967295.0;
    else if( eDataType == GDT_UInt16 )
        return 65535;
    else
        return 255;
}

/************************************************************************/
/*                           GetNoDataValue()                           */
/************************************************************************/

double GRASSRasterBand::GetNoDataValue( int *pbSuccess )

{
    if( pbSuccess )
        *pbSuccess = TRUE;

    return dfNoData;
}

/************************************************************************/
/* ==================================================================== */
/*                             GRASSDataset                             */
/* ==================================================================== */
/************************************************************************/

/************************************************************************/
/*                            GRASSDataset()                            */
/************************************************************************/

GRASSDataset::GRASSDataset()
{
    pszProjection = NULL;

    adfGeoTransform[0] = 0.0;
    adfGeoTransform[1] = 1.0;
    adfGeoTransform[2] = 0.0;
    adfGeoTransform[3] = 0.0;
    adfGeoTransform[4] = 0.0;
    adfGeoTransform[5] = 1.0;
    pszGisdbase = NULL;
    pszLocation = NULL;
    pszElement = NULL;
}

/************************************************************************/
/*                           ~GRASSDataset()                            */
/************************************************************************/

GRASSDataset::~GRASSDataset()
{

    if ( pszGisdbase )
        G_free ( pszGisdbase );

    if ( pszLocation )
        G_free ( pszLocation );

    if ( pszElement )
        G_free ( pszElement );

    G_free( pszProjection );
}

/************************************************************************/
/*                          GetProjectionRef()                          */
/************************************************************************/

const char *GRASSDataset::_GetProjectionRef()
{
    if( pszProjection == NULL )
        return "";
    else
        return pszProjection;
}

/************************************************************************/
/*                          GetGeoTransform()                           */
/************************************************************************/

CPLErr GRASSDataset::GetGeoTransform( double * padfGeoTransform )
{
    memcpy( padfGeoTransform, adfGeoTransform, sizeof(double) * 6 );

    return CE_None;
}

/************************************************************************/
/*                            SplitPath()                               */
/* Split full path to cell or group to:                                 */
/*     gisdbase, location, mapset, element, name                        */
/* New string are allocated and should be freed when no longer needed.  */
/*                                                                      */
/* Returns: true - OK                                                   */
/*          false - failed                                              */
/************************************************************************/
bool GRASSDataset::SplitPath( char *path, char **gisdbase, char **location,
                              char **mapset, char **element, char **name )
{
    char *p;
    char *ptr[5];
    char *tmp;
    int i = 0;

    *gisdbase = NULL;
    *location = NULL;
    *mapset = NULL;
    *element = NULL;
    *name = NULL;

    if ( !path || strlen(path) == 0 )
        return false;

    tmp = G_store ( path );

    while ( (p = strrchr(tmp,'/')) != NULL  && i < 4 ) {
        *p = '\0';

        if ( strlen(p+1) == 0 ) /* repeated '/' */
            continue;

        ptr[i++] = p+1;
    }

    /* Note: empty GISDBASE == 0 is not accepted (relative path) */
    if ( i != 4 ) {
        G_free ( tmp );
        return false;
    }

    *gisdbase = G_store ( tmp );
    *location = G_store ( ptr[3] );
    *mapset   = G_store ( ptr[2] );
    *element  = G_store ( ptr[1] );
    *name     = G_store ( ptr[0] );

    G_free ( tmp );
    return true;
}

/************************************************************************/
/*                                Open()                                */
/************************************************************************/

typedef int (*GrassErrorHandler)(const char *, int);

GDALDataset *GRASSDataset::Open( GDALOpenInfo * poOpenInfo )

{
    char        *pszGisdb = NULL, *pszLoc = NULL;
    char        *pszMapset = NULL, *pszElem = NULL, *pszName = NULL;
    char        **papszCells = NULL;
    char        **papszMapsets = NULL;

/* -------------------------------------------------------------------- */
/*      Does this even look like a grass file path?                     */
/* -------------------------------------------------------------------- */
    if( strstr(poOpenInfo->pszFilename,"/cellhd/") == NULL
        && strstr(poOpenInfo->pszFilename,"/group/") == NULL )
        return NULL;

    /* Always init, if no rasters are opened G_no_gisinit resets the projection and
     * rasters in different projection may be then opened */

    // Don't use GISRC file and read/write GRASS variables (from location G_VAR_GISRC) to memory only.
    G_set_gisrc_mode ( G_GISRC_MODE_MEMORY );

    // Init GRASS libraries (required)
    G_no_gisinit();  // Doesn't check write permissions for mapset compare to G_gisinit

    // Set error function
    G_set_error_routine ( (GrassErrorHandler) Grass2CPLErrorHook );

    // GISBASE is path to the directory where GRASS is installed,
    if ( !getenv( "GISBASE" ) ) {
        static char* gisbaseEnv = NULL;
        const char *gisbase = GRASS_GISBASE;
        CPLError( CE_Warning, CPLE_AppDefined, "GRASS warning: GISBASE "
                "environment variable was not set, using:\n%s", gisbase );
        char buf[2000];
        snprintf ( buf, sizeof(buf), "GISBASE=%s", gisbase );
        buf[sizeof(buf)-1] = '\0';

        CPLFree(gisbaseEnv);
        gisbaseEnv = CPLStrdup ( buf );
        putenv( gisbaseEnv );
    }

    if ( !SplitPath( poOpenInfo->pszFilename, &pszGisdb, &pszLoc, &pszMapset,
                     &pszElem, &pszName) ) {
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Check element name                                              */
/* -------------------------------------------------------------------- */
    if ( strcmp(pszElem,"cellhd") != 0 && strcmp(pszElem,"group") != 0 ) {
        G_free(pszGisdb);
        G_free(pszLoc);
        G_free(pszMapset);
        G_free(pszElem);
        G_free(pszName);
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Set GRASS variables                                             */
/* -------------------------------------------------------------------- */

    G_setenv_nogisrc( "GISDBASE", pszGisdb );
    G_setenv_nogisrc( "LOCATION_NAME", pszLoc );
    G_setenv_nogisrc( "MAPSET", pszMapset); // group is searched only in current mapset
    G_reset_mapsets();
    G_add_mapset_to_search_path ( pszMapset );

/* -------------------------------------------------------------------- */
/*      Check if this is a valid grass cell.                            */
/* -------------------------------------------------------------------- */
    if ( strcmp(pszElem,"cellhd") == 0 ) {

        if ( G_find_file2("cell", pszName, pszMapset) == NULL ) {
            G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName);
            return NULL;
        }

        papszMapsets = CSLAddString( papszMapsets, pszMapset );
        papszCells = CSLAddString( papszCells, pszName );
    }
/* -------------------------------------------------------------------- */
/*      Check if this is a valid GRASS imagery group.                   */
/* -------------------------------------------------------------------- */
    else {
        struct Ref ref;

        I_init_group_ref( &ref );
        if ( I_get_group_ref( pszName, &ref ) == 0 ) {
            G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName);
            return NULL;
        }

        for( int iRef = 0; iRef < ref.nfiles; iRef++ )
        {
            papszCells = CSLAddString( papszCells, ref.file[iRef].name );
            papszMapsets = CSLAddString( papszMapsets, ref.file[iRef].mapset );
            G_add_mapset_to_search_path ( ref.file[iRef].mapset );
        }

        I_free_group_ref( &ref );
    }

    G_free( pszMapset );
    G_free( pszName );

/* -------------------------------------------------------------------- */
/*      Create a corresponding GDALDataset.                             */
/* -------------------------------------------------------------------- */
    GRASSDataset*poDS = new GRASSDataset();

    /* notdef: should only allow read access to an existing cell, right? */
    poDS->eAccess = poOpenInfo->eAccess;

    poDS->pszGisdbase = pszGisdb;
    poDS->pszLocation = pszLoc;
    poDS->pszElement = pszElem;

/* -------------------------------------------------------------------- */
/*      Capture some information from the file that is of interest.     */
/* -------------------------------------------------------------------- */

    Rast_get_cellhd( papszCells[0], papszMapsets[0], &(poDS->sCellInfo) );

    poDS->nRasterXSize = poDS->sCellInfo.cols;
    poDS->nRasterYSize = poDS->sCellInfo.rows;

    poDS->adfGeoTransform[0] = poDS->sCellInfo.west;
    poDS->adfGeoTransform[1] = poDS->sCellInfo.ew_res;
    poDS->adfGeoTransform[2] = 0.0;
    poDS->adfGeoTransform[3] = poDS->sCellInfo.north;
    poDS->adfGeoTransform[4] = 0.0;
    poDS->adfGeoTransform[5] = -1 * poDS->sCellInfo.ns_res;

/* -------------------------------------------------------------------- */
/*      Try to get a projection definition.                             */
/* -------------------------------------------------------------------- */
    struct Key_Value *projinfo, *projunits;

    projinfo = G_get_projinfo();
    projunits = G_get_projunits();
    poDS->pszProjection = GPJ_grass_to_wkt ( projinfo, projunits, 0, 0);
    if (projinfo) G_free_key_value(projinfo);
    if (projunits) G_free_key_value(projunits);

/* -------------------------------------------------------------------- */
/*      Create band information objects.                                */
/* -------------------------------------------------------------------- */
    for( int iBand = 0; papszCells[iBand] != NULL; iBand++ )
    {
        GRASSRasterBand *rb = new GRASSRasterBand( poDS, iBand+1, papszMapsets[iBand],
                                                                  papszCells[iBand] );

        if ( !rb->valid ) {
            CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster band %d", iBand);
            delete rb;
            delete poDS;
            return NULL;
        }

        poDS->SetBand( iBand+1, rb );
    }

    CSLDestroy(papszCells);
    CSLDestroy(papszMapsets);

/* -------------------------------------------------------------------- */
/*      Confirm the requested access is supported.                      */
/* -------------------------------------------------------------------- */
    if( poOpenInfo->eAccess == GA_Update )
    {
        delete poDS;
        CPLError( CE_Failure, CPLE_NotSupported,
                  "The GRASS driver does not support update access to existing"
                  " datasets.\n" );
        return NULL;
    }

    return poDS;
}

/************************************************************************/
/*                          GDALRegister_GRASS()                        */
/************************************************************************/

void GDALRegister_GRASS()
{
    if( !GDAL_CHECK_VERSION( "GDAL/GRASS driver" ) )
        return;

    if( GDALGetDriverByName( "GRASS" ) != NULL )
        return;

    GDALDriver *poDriver = new GDALDriver();

    poDriver->SetDescription( "GRASS" );
    poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" );
    poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "GRASS Rasters (7+)" );
    poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/raster/grass.html" );

    poDriver->pfnOpen = GRASSDataset::Open;

    GetGDALDriverManager()->RegisterDriver( poDriver );
}