File: gridlib.c

package info (click to toggle)
gdal 3.6.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 89,664 kB
  • sloc: cpp: 1,136,033; ansic: 197,355; python: 35,910; java: 5,511; xml: 4,011; sh: 3,950; cs: 2,443; yacc: 1,047; makefile: 288
file content (1202 lines) | stat: -rw-r--r-- 43,114 bytes parent folder | download
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
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
/******************************************************************************
 * $Id$
 *
 * Project:  Arc/Info Binary Grid Translator
 * Purpose:  Grid file reading code.
 * Author:   Frank Warmerdam, warmerdam@pobox.com
 *
 ******************************************************************************
 * Copyright (c) 1999, Frank Warmerdam
 * Copyright (c) 2007-2010, 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 "aigrid.h"

CPL_INLINE static void CPL_IGNORE_RET_VAL_INT(CPL_UNUSED int unused)
{
}

/************************************************************************/
/*                    AIGProcessRaw32bitFloatBlock()                    */
/*                                                                      */
/*      Process a block using ``00'' (32 bit) raw format.               */
/************************************************************************/

static CPLErr AIGProcessRaw32BitFloatBlock(GByte *pabyCur, int nDataSize,
                                           int nMin, int nBlockXSize,
                                           int nBlockYSize, float *pafData)

{
    int i;

    (void)nMin;
    if (nDataSize < nBlockXSize * nBlockYSize * 4)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Block too small");
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Collect raw data.                                               */
    /* -------------------------------------------------------------------- */
    for (i = 0; i < nBlockXSize * nBlockYSize; i++)
    {
        float fWork;

#ifdef CPL_LSB
        ((GByte *)&fWork)[3] = *(pabyCur++);
        ((GByte *)&fWork)[2] = *(pabyCur++);
        ((GByte *)&fWork)[1] = *(pabyCur++);
        ((GByte *)&fWork)[0] = *(pabyCur++);
#else
        ((GByte *)&fWork)[0] = *(pabyCur++);
        ((GByte *)&fWork)[1] = *(pabyCur++);
        ((GByte *)&fWork)[2] = *(pabyCur++);
        ((GByte *)&fWork)[3] = *(pabyCur++);
#endif

        pafData[i] = fWork;
    }

    return (CE_None);
}

/************************************************************************/
/*                      AIGProcessIntConstBlock()                       */
/*                                                                      */
/*      Process a block using ``00'' constant 32bit integer format.     */
/************************************************************************/

static CPLErr AIGProcessIntConstBlock(GByte *pabyCur, int nDataSize, int nMin,
                                      int nBlockXSize, int nBlockYSize,
                                      GInt32 *panData)

{
    int i;

    (void)pabyCur;
    (void)nDataSize;

    /* -------------------------------------------------------------------- */
    /*	Apply constant min value.					*/
    /* -------------------------------------------------------------------- */
    for (i = 0; i < nBlockXSize * nBlockYSize; i++)
        panData[i] = nMin;

    return (CE_None);
}

/************************************************************************/
/*                         AIGRolloverSignedAdd()                       */
/************************************************************************/

CPL_NOSANITIZE_UNSIGNED_INT_OVERFLOW
static GInt32 AIGRolloverSignedAdd(GInt32 a, GInt32 b)
{
    // Not really portable as assumes complement to 2 representation
    // but AIG assumes typical unsigned rollover on signed
    // integer operations.
    GInt32 res;
    GUInt32 resUnsigned = (GUInt32)(a) + (GUInt32)(b);
    memcpy(&res, &resUnsigned, sizeof(res));
    return res;
}

/************************************************************************/
/*                         AIGProcess32bitRawBlock()                    */
/*                                                                      */
/*      Process a block using ``20'' (thirty two bit) raw format.        */
/************************************************************************/

static CPLErr AIGProcessRaw32BitBlock(GByte *pabyCur, int nDataSize, int nMin,
                                      int nBlockXSize, int nBlockYSize,
                                      GInt32 *panData)

{
    int i;

    if (nDataSize < nBlockXSize * nBlockYSize * 4)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Block too small");
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Collect raw data.                                               */
    /* -------------------------------------------------------------------- */
    for (i = 0; i < nBlockXSize * nBlockYSize; i++)
    {
        memcpy(panData + i, pabyCur, 4);
        panData[i] = CPL_MSBWORD32(panData[i]);
        panData[i] = AIGRolloverSignedAdd(panData[i], nMin);
        pabyCur += 4;
    }

    return (CE_None);
}

/************************************************************************/
/*                         AIGProcess16bitRawBlock()                    */
/*                                                                      */
/*      Process a block using ``10'' (sixteen bit) raw format.          */
/************************************************************************/

static CPLErr AIGProcessRaw16BitBlock(GByte *pabyCur, int nDataSize, int nMin,
                                      int nBlockXSize, int nBlockYSize,
                                      GInt32 *panData)

{
    int i;

    if (nDataSize < nBlockXSize * nBlockYSize * 2)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Block too small");
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Collect raw data.                                               */
    /* -------------------------------------------------------------------- */
    for (i = 0; i < nBlockXSize * nBlockYSize; i++)
    {
        panData[i] = AIGRolloverSignedAdd(pabyCur[0] * 256 + pabyCur[1], nMin);
        pabyCur += 2;
    }

    return (CE_None);
}

/************************************************************************/
/*                         AIGProcess4BitRawBlock()                     */
/*                                                                      */
/*      Process a block using ``08'' raw format.                        */
/************************************************************************/

static CPLErr AIGProcessRaw4BitBlock(GByte *pabyCur, int nDataSize, int nMin,
                                     int nBlockXSize, int nBlockYSize,
                                     GInt32 *panData)

{
    int i;

    if (nDataSize < (nBlockXSize * nBlockYSize + 1) / 2)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Block too small");
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Collect raw data.                                               */
    /* -------------------------------------------------------------------- */
    for (i = 0; i < nBlockXSize * nBlockYSize; i++)
    {
        if (i % 2 == 0)
            panData[i] = AIGRolloverSignedAdd((*(pabyCur)&0xf0) >> 4, nMin);
        else
            panData[i] = AIGRolloverSignedAdd(*(pabyCur++) & 0xf, nMin);
    }

    return (CE_None);
}

/************************************************************************/
/*                       AIGProcess1BitRawBlock()                       */
/*                                                                      */
/*      Process a block using ``0x01'' raw format.                      */
/************************************************************************/

static CPLErr AIGProcessRaw1BitBlock(GByte *pabyCur, int nDataSize, int nMin,
                                     int nBlockXSize, int nBlockYSize,
                                     GInt32 *panData)

{
    int i;

    if (nDataSize < (nBlockXSize * nBlockYSize + 7) / 8)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Block too small");
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Collect raw data.                                               */
    /* -------------------------------------------------------------------- */
    for (i = 0; i < nBlockXSize * nBlockYSize; i++)
    {
        if (pabyCur[i >> 3] & (0x80 >> (i & 0x7)))
            panData[i] = AIGRolloverSignedAdd(1, nMin);
        else
            panData[i] = 0 + nMin;
    }

    return (CE_None);
}

/************************************************************************/
/*                         AIGProcessRawBlock()                         */
/*                                                                      */
/*      Process a block using ``08'' raw format.                        */
/************************************************************************/

static CPLErr AIGProcessRawBlock(GByte *pabyCur, int nDataSize, int nMin,
                                 int nBlockXSize, int nBlockYSize,
                                 GInt32 *panData)

{
    int i;

    if (nDataSize < nBlockXSize * nBlockYSize)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Block too small");
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Collect raw data.                                               */
    /* -------------------------------------------------------------------- */
    for (i = 0; i < nBlockXSize * nBlockYSize; i++)
    {
        panData[i] = AIGRolloverSignedAdd(*(pabyCur++), nMin);
    }

    return (CE_None);
}

/************************************************************************/
/*                         AIGProcessFFBlock()                          */
/*                                                                      */
/*      Process a type 0xFF (CCITT RLE) compressed block.               */
/************************************************************************/

static CPLErr AIGProcessFFBlock(GByte *pabyCur, int nDataSize, int nMin,
                                int nBlockXSize, int nBlockYSize,
                                GInt32 *panData)

{
    /* -------------------------------------------------------------------- */
    /*      Convert CCITT compress bitstream into 1bit raw data.            */
    /* -------------------------------------------------------------------- */
    CPLErr eErr;
    int i, nDstBytes = (nBlockXSize * nBlockYSize + 7) / 8;
    unsigned char *pabyIntermediate;

    pabyIntermediate = (unsigned char *)VSI_MALLOC_VERBOSE(nDstBytes);
    if (pabyIntermediate == NULL)
    {
        return CE_Failure;
    }

    eErr = DecompressCCITTRLETile(pabyCur, nDataSize, pabyIntermediate,
                                  nDstBytes, nBlockXSize, nBlockYSize);
    if (eErr != CE_None)
    {
        CPLFree(pabyIntermediate);
        return eErr;
    }

    /* -------------------------------------------------------------------- */
    /*      Convert the bit buffer into 32bit integers and account for      */
    /*      nMin.                                                           */
    /* -------------------------------------------------------------------- */
    for (i = 0; i < nBlockXSize * nBlockYSize; i++)
    {
        if (pabyIntermediate[i >> 3] & (0x80 >> (i & 0x7)))
            panData[i] = AIGRolloverSignedAdd(nMin, 1);
        else
            panData[i] = nMin;
    }

    CPLFree(pabyIntermediate);

    return (CE_None);
}

/************************************************************************/
/*                          AIGProcessBlock()                           */
/*                                                                      */
/*      Process a block using ``D7'', ``E0'' or ``DF'' compression.     */
/************************************************************************/

static CPLErr AIGProcessBlock(GByte *pabyCur, int nDataSize, int nMin,
                              int nMagic, int nBlockXSize, int nBlockYSize,
                              GInt32 *panData)

{
    int nTotPixels, nPixels;
    int i;

    /* ==================================================================== */
    /*     Process runs till we are done.                                  */
    /* ==================================================================== */
    nTotPixels = nBlockXSize * nBlockYSize;
    nPixels = 0;

    while (nPixels < nTotPixels && nDataSize > 0)
    {
        int nMarker = *(pabyCur++);

        nDataSize--;

        /* --------------------------------------------------------------------
         */
        /*      Repeat data - four byte data block (0xE0) */
        /* --------------------------------------------------------------------
         */
        if (nMagic == 0xE0)
        {
            GInt32 nValue;

            if (nMarker + nPixels > nTotPixels)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Run too long in AIGProcessBlock, needed %d values, "
                         "got %d.",
                         nTotPixels - nPixels, nMarker);
                return CE_Failure;
            }

            if (nDataSize < 4)
            {
                CPLError(CE_Failure, CPLE_AppDefined, "Block too small");
                return CE_Failure;
            }

            nValue = 0;
            memcpy(&nValue, pabyCur, 4);
            pabyCur += 4;
            nDataSize -= 4;

            nValue = CPL_MSBWORD32(nValue);
            nValue = AIGRolloverSignedAdd(nValue, nMin);
            for (i = 0; i < nMarker; i++)
                panData[nPixels++] = nValue;
        }

        /* --------------------------------------------------------------------
         */
        /*      Repeat data - two byte data block (0xF0) */
        /* --------------------------------------------------------------------
         */
        else if (nMagic == 0xF0)
        {
            GInt32 nValue;

            if (nMarker + nPixels > nTotPixels)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Run too long in AIGProcessBlock, needed %d values, "
                         "got %d.",
                         nTotPixels - nPixels, nMarker);
                return CE_Failure;
            }

            if (nDataSize < 2)
            {
                CPLError(CE_Failure, CPLE_AppDefined, "Block too small");
                return CE_Failure;
            }

            nValue = AIGRolloverSignedAdd(pabyCur[0] * 256 + pabyCur[1], nMin);
            pabyCur += 2;
            nDataSize -= 2;

            for (i = 0; i < nMarker; i++)
                panData[nPixels++] = nValue;
        }

        /* --------------------------------------------------------------------
         */
        /*      Repeat data - one byte data block (0xFC) */
        /* --------------------------------------------------------------------
         */
        else if (nMagic == 0xFC || nMagic == 0xF8)
        {
            GInt32 nValue;

            if (nMarker + nPixels > nTotPixels)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Run too long in AIGProcessBlock, needed %d values, "
                         "got %d.",
                         nTotPixels - nPixels, nMarker);
                return CE_Failure;
            }

            if (nDataSize < 1)
            {
                CPLError(CE_Failure, CPLE_AppDefined, "Block too small");
                return CE_Failure;
            }

            nValue = AIGRolloverSignedAdd(*(pabyCur++), nMin);
            nDataSize--;

            for (i = 0; i < nMarker; i++)
                panData[nPixels++] = nValue;
        }

        /* --------------------------------------------------------------------
         */
        /*      Repeat data - no actual data, just assign minimum (0xDF) */
        /* --------------------------------------------------------------------
         */
        else if (nMagic == 0xDF && nMarker < 128)
        {
            if (nMarker + nPixels > nTotPixels)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Run too long in AIGProcessBlock, needed %d values, "
                         "got %d.",
                         nTotPixels - nPixels, nMarker);
                return CE_Failure;
            }

            for (i = 0; i < nMarker; i++)
                panData[nPixels++] = nMin;
        }

        /* --------------------------------------------------------------------
         */
        /*      Literal data (0xD7): 8bit values. */
        /* --------------------------------------------------------------------
         */
        else if (nMagic == 0xD7 && nMarker < 128)
        {
            if (nMarker + nPixels > nTotPixels)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Run too long in AIGProcessBlock, needed %d values, "
                         "got %d.",
                         nTotPixels - nPixels, nMarker);
                return CE_Failure;
            }

            while (nMarker > 0 && nDataSize > 0)
            {
                panData[nPixels++] = AIGRolloverSignedAdd(*(pabyCur++), nMin);
                nMarker--;
                nDataSize--;
            }
        }

        /* --------------------------------------------------------------------
         */
        /*      Literal data (0xCF): 16 bit values. */
        /* --------------------------------------------------------------------
         */
        else if (nMagic == 0xCF && nMarker < 128)
        {
            GInt32 nValue;

            if (nMarker + nPixels > nTotPixels)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Run too long in AIGProcessBlock, needed %d values, "
                         "got %d.",
                         nTotPixels - nPixels, nMarker);
                return CE_Failure;
            }

            while (nMarker > 0 && nDataSize >= 2)
            {
                nValue =
                    AIGRolloverSignedAdd(pabyCur[0] * 256 + pabyCur[1], nMin);
                panData[nPixels++] = nValue;
                pabyCur += 2;

                nMarker--;
                nDataSize -= 2;
            }
        }

        /* --------------------------------------------------------------------
         */
        /*      Nodata repeat */
        /* --------------------------------------------------------------------
         */
        else if (nMarker > 128)
        {
            nMarker = 256 - nMarker;

            if (nMarker + nPixels > nTotPixels)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Run too long in AIGProcessBlock, needed %d values, "
                         "got %d.",
                         nTotPixels - nPixels, nMarker);
                return CE_Failure;
            }

            while (nMarker > 0)
            {
                panData[nPixels++] = ESRI_GRID_NO_DATA;
                nMarker--;
            }
        }

        else
        {
            return CE_Failure;
        }
    }

    if (nPixels < nTotPixels || nDataSize < 0)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Ran out of data processing block with nMagic=%d.", nMagic);
        return CE_Failure;
    }

    return CE_None;
}

/************************************************************************/
/*                            AIGReadBlock()                            */
/*                                                                      */
/*      Read a single block of integer grid data.                       */
/************************************************************************/

CPLErr AIGReadBlock(VSILFILE *fp, GUInt32 nBlockOffset, int nBlockSize,
                    int nBlockXSize, int nBlockYSize, GInt32 *panData,
                    int nCellType, int bCompressed)

{
    GByte *pabyRaw, *pabyCur;
    CPLErr eErr;
    int i, nMagic, nMinSize = 0, nDataSize;
    GInt32 nMin = 0;

    /* -------------------------------------------------------------------- */
    /*      If the block has zero size it is all dummies.                   */
    /* -------------------------------------------------------------------- */
    if (nBlockSize == 0)
    {
        for (i = 0; i < nBlockXSize * nBlockYSize; i++)
            panData[i] = ESRI_GRID_NO_DATA;

        return (CE_None);
    }

    /* -------------------------------------------------------------------- */
    /*      Read the block into memory.                                     */
    /* -------------------------------------------------------------------- */
    if (nBlockSize <= 0 || nBlockSize > 65535 * 2)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Invalid block size : %d",
                 nBlockSize);
        return CE_Failure;
    }

    pabyRaw = (GByte *)VSIMalloc(nBlockSize + 2);
    if (pabyRaw == NULL)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Cannot allocate memory for block");
        return CE_Failure;
    }

    if (VSIFSeekL(fp, nBlockOffset, SEEK_SET) != 0 ||
        VSIFReadL(pabyRaw, nBlockSize + 2, 1, fp) != 1)
    {
        memset(panData, 0, nBlockXSize * nBlockYSize * 4);
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Read of %d bytes from offset %d for grid block failed.",
                 nBlockSize + 2, nBlockOffset);
        CPLFree(pabyRaw);
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Verify the block size.                                          */
    /* -------------------------------------------------------------------- */
    if (nBlockSize != (pabyRaw[0] * 256 + pabyRaw[1]) * 2)
    {
        memset(panData, 0, nBlockXSize * nBlockYSize * 4);
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Block is corrupt, block size was %d, but expected to be %d.",
                 (pabyRaw[0] * 256 + pabyRaw[1]) * 2, nBlockSize);
        CPLFree(pabyRaw);
        return CE_Failure;
    }

    nDataSize = nBlockSize;

    /* -------------------------------------------------------------------- */
    /*      Handle float files and uncompressed integer files directly.     */
    /* -------------------------------------------------------------------- */
    if (nCellType == AIG_CELLTYPE_FLOAT)
    {
        AIGProcessRaw32BitFloatBlock(pabyRaw + 2, nDataSize, 0, nBlockXSize,
                                     nBlockYSize, (float *)panData);
        CPLFree(pabyRaw);

        return CE_None;
    }

    if (nCellType == AIG_CELLTYPE_INT && !bCompressed)
    {
        AIGProcessRaw32BitBlock(pabyRaw + 2, nDataSize, nMin, nBlockXSize,
                                nBlockYSize, panData);
        CPLFree(pabyRaw);
        return CE_None;
    }

    /* -------------------------------------------------------------------- */
    /*      Collect minimum value.                                          */
    /* -------------------------------------------------------------------- */

    /* The first 2 bytes that give the block size are not included in nDataSize
     */
    /* and have already been safely read */
    pabyCur = pabyRaw + 2;

    /* Need at least 2 byte to read the nMinSize and the nMagic */
    if (nDataSize < 2)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Corrupt block. Need 2 bytes to read nMagic and nMinSize, "
                 "only %d available",
                 nDataSize);
        CPLFree(pabyRaw);
        return CE_Failure;
    }
    nMagic = pabyCur[0];
    nMinSize = pabyCur[1];
    pabyCur += 2;
    nDataSize -= 2;

    /* Need at least nMinSize bytes to read the nMin value */
    if (nDataSize < nMinSize)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Corrupt block. Need %d bytes to read nMin. Only %d available",
                 nMinSize, nDataSize);
        CPLFree(pabyRaw);
        return CE_Failure;
    }

    if (nMinSize > 4)
    {
        memset(panData, 0, nBlockXSize * nBlockYSize * 4);
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Corrupt 'minsize' of %d in block header.  Read aborted.",
                 nMinSize);
        CPLFree(pabyRaw);
        return CE_Failure;
    }

    if (nMinSize == 4)
    {
        memcpy(&nMin, pabyCur, 4);
        nMin = CPL_MSBWORD32(nMin);
        pabyCur += 4;
    }
    else
    {
        nMin = 0;
        for (i = 0; i < nMinSize; i++)
        {
            nMin = nMin * 256 + *pabyCur;
            pabyCur++;
        }

        /* If nMinSize = 0, then we might have only 4 bytes in pabyRaw */
        /* don't try to read the 5th one then */
        if (nMinSize != 0 && pabyRaw[4] > 127)
        {
            if (nMinSize == 2)
                nMin = nMin - 65536;
            else if (nMinSize == 1)
                nMin = nMin - 256;
            else if (nMinSize == 3)
                nMin = nMin - 256 * 256 * 256;
        }
    }

    nDataSize -= nMinSize;

    /* -------------------------------------------------------------------- */
    /*	Call an appropriate handler depending on magic code.		*/
    /* -------------------------------------------------------------------- */
    eErr = CE_None;
    if (nMagic == 0x08)
    {
        AIGProcessRawBlock(pabyCur, nDataSize, nMin, nBlockXSize, nBlockYSize,
                           panData);
    }
    else if (nMagic == 0x04)
    {
        AIGProcessRaw4BitBlock(pabyCur, nDataSize, nMin, nBlockXSize,
                               nBlockYSize, panData);
    }
    else if (nMagic == 0x01)
    {
        AIGProcessRaw1BitBlock(pabyCur, nDataSize, nMin, nBlockXSize,
                               nBlockYSize, panData);
    }
    else if (nMagic == 0x00)
    {
        AIGProcessIntConstBlock(pabyCur, nDataSize, nMin, nBlockXSize,
                                nBlockYSize, panData);
    }
    else if (nMagic == 0x10)
    {
        AIGProcessRaw16BitBlock(pabyCur, nDataSize, nMin, nBlockXSize,
                                nBlockYSize, panData);
    }
    else if (nMagic == 0x20)
    {
        AIGProcessRaw32BitBlock(pabyCur, nDataSize, nMin, nBlockXSize,
                                nBlockYSize, panData);
    }
    else if (nMagic == 0xFF)
    {
        eErr = AIGProcessFFBlock(pabyCur, nDataSize, nMin, nBlockXSize,
                                 nBlockYSize, panData);
    }
    else
    {
        eErr = AIGProcessBlock(pabyCur, nDataSize, nMin, nMagic, nBlockXSize,
                               nBlockYSize, panData);

        if (eErr == CE_Failure)
        {
            static int bHasWarned = FALSE;

            for (i = 0; i < nBlockXSize * nBlockYSize; i++)
                panData[i] = ESRI_GRID_NO_DATA;

            if (!bHasWarned)
            {
                CPLError(CE_Warning, CPLE_AppDefined,
                         "Unsupported Arc/Info Binary Grid tile of type 0x%X"
                         " encountered.\n"
                         "This and subsequent unsupported tile types set to"
                         " no data value.\n",
                         nMagic);
                bHasWarned = TRUE;
            }
        }
    }

    CPLFree(pabyRaw);

    return eErr;
}

/************************************************************************/
/*                           AIGReadHeader()                            */
/*                                                                      */
/*      Read the hdr.adf file, and populate the given info structure    */
/*      appropriately.                                                  */
/************************************************************************/

CPLErr AIGReadHeader(const char *pszCoverName, AIGInfo_t *psInfo)

{
    char *pszHDRFilename;
    VSILFILE *fp;
    GByte abyData[308];
    const size_t nHDRFilenameLen = strlen(pszCoverName) + 30;

    /* -------------------------------------------------------------------- */
    /*      Open the file hdr.adf file.                                     */
    /* -------------------------------------------------------------------- */
    pszHDRFilename = (char *)CPLMalloc(nHDRFilenameLen);
    snprintf(pszHDRFilename, nHDRFilenameLen, "%s/hdr.adf", pszCoverName);

    fp = AIGLLOpen(pszHDRFilename, "rb");

    if (fp == NULL)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Failed to open grid header file:\n%s\n", pszHDRFilename);

        CPLFree(pszHDRFilename);
        return (CE_Failure);
    }

    CPLFree(pszHDRFilename);

    /* -------------------------------------------------------------------- */
    /*      Read the whole file (we expect it to always be 308 bytes        */
    /*      long.                                                           */
    /* -------------------------------------------------------------------- */

    if (VSIFReadL(abyData, 1, 308, fp) != 308)
    {
        CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
        return (CE_Failure);
    }

    CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));

    /* -------------------------------------------------------------------- */
    /*      Read the block size information.                                */
    /* -------------------------------------------------------------------- */
    memcpy(&(psInfo->nCellType), abyData + 16, 4);
    memcpy(&(psInfo->bCompressed), abyData + 20, 4);
    memcpy(&(psInfo->nBlocksPerRow), abyData + 288, 4);
    memcpy(&(psInfo->nBlocksPerColumn), abyData + 292, 4);
    memcpy(&(psInfo->nBlockXSize), abyData + 296, 4);
    memcpy(&(psInfo->nBlockYSize), abyData + 304, 4);
    memcpy(&(psInfo->dfCellSizeX), abyData + 256, 8);
    memcpy(&(psInfo->dfCellSizeY), abyData + 264, 8);

#ifdef CPL_LSB
    psInfo->nCellType = CPL_SWAP32(psInfo->nCellType);
    psInfo->bCompressed = CPL_SWAP32(psInfo->bCompressed);
    psInfo->nBlocksPerRow = CPL_SWAP32(psInfo->nBlocksPerRow);
    psInfo->nBlocksPerColumn = CPL_SWAP32(psInfo->nBlocksPerColumn);
    psInfo->nBlockXSize = CPL_SWAP32(psInfo->nBlockXSize);
    psInfo->nBlockYSize = CPL_SWAP32(psInfo->nBlockYSize);
    CPL_SWAPDOUBLE(&(psInfo->dfCellSizeX));
    CPL_SWAPDOUBLE(&(psInfo->dfCellSizeY));
#endif

    psInfo->bCompressed = !psInfo->bCompressed;

    return (CE_None);
}

/************************************************************************/
/*                         AIGReadBlockIndex()                          */
/*                                                                      */
/*      Read the w001001x.adf file, and populate the given info         */
/*      structure with the block offsets, and sizes.                    */
/************************************************************************/

CPLErr AIGReadBlockIndex(AIGInfo_t *psInfo, AIGTileInfo *psTInfo,
                         const char *pszBasename)

{
    char *pszHDRFilename;
    VSILFILE *fp;
    int i;
    GUInt32 nValue, nLength;
    GUInt32 *panIndex;
    GByte abyHeader[8];
    const size_t nHDRFilenameLen = strlen(psInfo->pszCoverName) + 40;

    /* -------------------------------------------------------------------- */
    /*      Open the file hdr.adf file.                                     */
    /* -------------------------------------------------------------------- */
    pszHDRFilename = (char *)CPLMalloc(nHDRFilenameLen);
    snprintf(pszHDRFilename, nHDRFilenameLen, "%s/%sx.adf",
             psInfo->pszCoverName, pszBasename);

    fp = AIGLLOpen(pszHDRFilename, "rb");

    if (fp == NULL)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Failed to open grid block index file:\n%s\n", pszHDRFilename);

        CPLFree(pszHDRFilename);
        return (CE_Failure);
    }

    CPLFree(pszHDRFilename);

    /* -------------------------------------------------------------------- */
    /*      Verify the magic number.  This is often corrupted by CR/LF      */
    /*      translation.                                                    */
    /* -------------------------------------------------------------------- */
    if (VSIFReadL(abyHeader, 1, 8, fp) != 8)
    {
        CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
        return CE_Failure;
    }
    if (abyHeader[3] == 0x0D && abyHeader[4] == 0x0A)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "w001001x.adf file header has been corrupted by unix to dos "
                 "text conversion.");
        CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
        return CE_Failure;
    }

    if (abyHeader[0] != 0x00 || abyHeader[1] != 0x00 || abyHeader[2] != 0x27 ||
        abyHeader[3] != 0x0A || abyHeader[4] != 0xFF || abyHeader[5] != 0xFF)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "w001001x.adf file header magic number is corrupt.");
        CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Get the file length (in 2 byte shorts)                          */
    /* -------------------------------------------------------------------- */
    if (VSIFSeekL(fp, 24, SEEK_SET) != 0 || VSIFReadL(&nValue, 1, 4, fp) != 4)
    {
        CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
        return CE_Failure;
    }

    nValue = CPL_MSBWORD32(nValue);
    if (nValue > INT_MAX)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "AIGReadBlockIndex: Bad length");
        CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
        return CE_Failure;
    }
    nLength = nValue * 2;
    if (nLength <= 100)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "AIGReadBlockIndex: Bad length");
        CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Allocate buffer, and read the file (from beyond the header)     */
    /*      into the buffer.                                                */
    /* -------------------------------------------------------------------- */
    psTInfo->nBlocks = (nLength - 100) / 8;
    if (psTInfo->nBlocks >= 1000000)
    {
        // Avoid excessive memory consumption.
        vsi_l_offset nFileSize;
        VSIFSeekL(fp, 0, SEEK_END);
        nFileSize = VSIFTellL(fp);
        if (nFileSize < 100 ||
            (vsi_l_offset)psTInfo->nBlocks > (nFileSize - 100) / 8)
        {
            CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
            return CE_Failure;
        }
    }
    panIndex = (GUInt32 *)VSI_MALLOC2_VERBOSE(psTInfo->nBlocks, 8);
    if (panIndex == NULL)
    {
        CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
        return CE_Failure;
    }
    if (VSIFSeekL(fp, 100, SEEK_SET) != 0 ||
        (int)VSIFReadL(panIndex, 8, psTInfo->nBlocks, fp) != psTInfo->nBlocks)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "AIGReadBlockIndex: Cannot read block info");
        CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
        CPLFree(panIndex);
        return CE_Failure;
    }

    CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));

    /* -------------------------------------------------------------------- */
    /*	Allocate AIGInfo block info arrays.				*/
    /* -------------------------------------------------------------------- */
    psTInfo->panBlockOffset =
        (GUInt32 *)VSI_MALLOC2_VERBOSE(4, psTInfo->nBlocks);
    psTInfo->panBlockSize = (int *)VSI_MALLOC2_VERBOSE(4, psTInfo->nBlocks);
    if (psTInfo->panBlockOffset == NULL || psTInfo->panBlockSize == NULL)
    {
        CPLFree(psTInfo->panBlockOffset);
        CPLFree(psTInfo->panBlockSize);
        psTInfo->panBlockOffset = NULL;
        psTInfo->panBlockSize = NULL;
        CPLFree(panIndex);
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Populate the block information.                                 */
    /* -------------------------------------------------------------------- */
    for (i = 0; i < psTInfo->nBlocks; i++)
    {
        GUInt32 nVal;

        nVal = CPL_MSBWORD32(panIndex[i * 2]);
        if (nVal >= INT_MAX)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "AIGReadBlockIndex: Bad offset for block %d", i);
            CPLFree(psTInfo->panBlockOffset);
            CPLFree(psTInfo->panBlockSize);
            psTInfo->panBlockOffset = NULL;
            psTInfo->panBlockSize = NULL;
            CPLFree(panIndex);
            return CE_Failure;
        }
        psTInfo->panBlockOffset[i] = nVal * 2;

        nVal = CPL_MSBWORD32(panIndex[i * 2 + 1]);
        if (nVal >= INT_MAX / 2)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "AIGReadBlockIndex: Bad size for block %d", i);
            CPLFree(psTInfo->panBlockOffset);
            CPLFree(psTInfo->panBlockSize);
            psTInfo->panBlockOffset = NULL;
            psTInfo->panBlockSize = NULL;
            CPLFree(panIndex);
            return CE_Failure;
        }
        psTInfo->panBlockSize[i] = nVal * 2;
    }

    CPLFree(panIndex);

    return (CE_None);
}

/************************************************************************/
/*                           AIGReadBounds()                            */
/*                                                                      */
/*      Read the dblbnd.adf file for the georeferenced bounds.          */
/************************************************************************/

CPLErr AIGReadBounds(const char *pszCoverName, AIGInfo_t *psInfo)

{
    char *pszHDRFilename;
    VSILFILE *fp;
    double adfBound[4];
    const size_t nHDRFilenameLen = strlen(pszCoverName) + 40;

    /* -------------------------------------------------------------------- */
    /*      Open the file dblbnd.adf file.                                  */
    /* -------------------------------------------------------------------- */
    pszHDRFilename = (char *)CPLMalloc(nHDRFilenameLen);
    snprintf(pszHDRFilename, nHDRFilenameLen, "%s/dblbnd.adf", pszCoverName);

    fp = AIGLLOpen(pszHDRFilename, "rb");

    if (fp == NULL)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Failed to open grid bounds file:\n%s\n", pszHDRFilename);

        CPLFree(pszHDRFilename);
        return (CE_Failure);
    }

    CPLFree(pszHDRFilename);

    /* -------------------------------------------------------------------- */
    /*      Get the contents - four doubles.                                */
    /* -------------------------------------------------------------------- */
    if (VSIFReadL(adfBound, 1, 32, fp) != 32)
    {
        CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));
        return CE_Failure;
    }

    CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));

#ifdef CPL_LSB
    CPL_SWAPDOUBLE(adfBound + 0);
    CPL_SWAPDOUBLE(adfBound + 1);
    CPL_SWAPDOUBLE(adfBound + 2);
    CPL_SWAPDOUBLE(adfBound + 3);
#endif

    psInfo->dfLLX = adfBound[0];
    psInfo->dfLLY = adfBound[1];
    psInfo->dfURX = adfBound[2];
    psInfo->dfURY = adfBound[3];

    return (CE_None);
}

/************************************************************************/
/*                         AIGReadStatistics()                          */
/*                                                                      */
/*      Read the sta.adf file for the layer statistics.                 */
/************************************************************************/

CPLErr AIGReadStatistics(const char *pszCoverName, AIGInfo_t *psInfo)

{
    char *pszHDRFilename;
    VSILFILE *fp;
    double adfStats[4];
    const size_t nHDRFilenameLen = strlen(pszCoverName) + 40;
    size_t nRead;

    psInfo->dfMin = 0.0;
    psInfo->dfMax = 0.0;
    psInfo->dfMean = 0.0;
    psInfo->dfStdDev = -1.0;

    /* -------------------------------------------------------------------- */
    /*      Open the file sta.adf file.                                     */
    /* -------------------------------------------------------------------- */
    pszHDRFilename = (char *)CPLMalloc(nHDRFilenameLen);
    snprintf(pszHDRFilename, nHDRFilenameLen, "%s/sta.adf", pszCoverName);

    fp = AIGLLOpen(pszHDRFilename, "rb");

    if (fp == NULL)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Failed to open grid statistics file:\n%s\n", pszHDRFilename);

        CPLFree(pszHDRFilename);
        return (CE_Failure);
    }

    /* -------------------------------------------------------------------- */
    /*      Get the contents - 3 or 4 doubles.                              */
    /* -------------------------------------------------------------------- */
    nRead = VSIFReadL(adfStats, 1, 32, fp);

    CPL_IGNORE_RET_VAL_INT(VSIFCloseL(fp));

    if (nRead == 32)
    {
#ifdef CPL_LSB
        CPL_SWAPDOUBLE(adfStats + 0);
        CPL_SWAPDOUBLE(adfStats + 1);
        CPL_SWAPDOUBLE(adfStats + 2);
        CPL_SWAPDOUBLE(adfStats + 3);
#endif

        psInfo->dfMin = adfStats[0];
        psInfo->dfMax = adfStats[1];
        psInfo->dfMean = adfStats[2];
        psInfo->dfStdDev = adfStats[3];
    }
    else if (nRead == 24)
    {
        /* See dataset at https://trac.osgeo.org/gdal/ticket/6633 */
        /* In that case, we have only min, max and mean, in LSB ordering */
        CPL_LSBPTR64(adfStats + 0);
        CPL_LSBPTR64(adfStats + 1);
        CPL_LSBPTR64(adfStats + 2);

        psInfo->dfMin = adfStats[0];
        psInfo->dfMax = adfStats[1];
        psInfo->dfMean = adfStats[2];
    }
    else
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Wrong content for %s",
                 pszHDRFilename);
        CPLFree(pszHDRFilename);
        return CE_Failure;
    }

    CPLFree(pszHDRFilename);
    return CE_None;
}