File: isis3dataset.cpp

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 (4402 lines) | stat: -rw-r--r-- 168,449 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
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
/******************************************************************************
 *
 * Project:  ISIS Version 3 Driver
 * Purpose:  Implementation of ISIS3Dataset
 * Author:   Trent Hare (thare@usgs.gov)
 *           Frank Warmerdam (warmerdam@pobox.com)
 *           Even Rouault (even.rouault at spatialys.com)
 *
 * NOTE: Original code authored by Trent and placed in the public domain as
 * per US government policy.  I have (within my rights) appropriated it and
 * placed it under the following license.  This is not intended to diminish
 * Trents contribution.
 ******************************************************************************
 * Copyright (c) 2007, Frank Warmerdam <warmerdam@pobox.com>
 * Copyright (c) 2009-2010, Even Rouault <even.rouault at spatialys.com>
 * Copyright (c) 2017 Hobu Inc
 * Copyright (c) 2017, Dmitry Baryshnikov <polimax@mail.ru>
 * Copyright (c) 2017, NextGIS <info@nextgis.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 "cpl_json.h"
#include "cpl_string.h"
#include "cpl_time.h"
#include "cpl_vsi_error.h"
#include "gdal_frmts.h"
#include "gdal_proxy.h"
#include "nasakeywordhandler.h"
#include "ogrgeojsonreader.h"
#include "ogr_spatialref.h"
#include "rawdataset.h"
#include "vrtdataset.h"
#include "cpl_safemaths.hpp"

// For gethostname()
#ifdef _WIN32
#include <winsock2.h>
#else
#include <unistd.h>
#endif

#include <algorithm>
#include <map>
#include <utility>  // pair
#include <vector>

// Constants coming from ISIS3 source code
// in isis/src/base/objs/SpecialPixel/SpecialPixel.h

// There are several types of special pixels
//    *   Isis::Null Pixel has no data available
//    *   Isis::Lis Pixel was saturated on the instrument
//    *   Isis::His Pixel was saturated on the instrument
//    *   Isis::Lrs Pixel was saturated during a computation
//    *   Isis::Hrs Pixel was saturated during a computation

// 1-byte special pixel values
const unsigned char NULL1 = 0;
const unsigned char LOW_REPR_SAT1 = 0;
const unsigned char LOW_INSTR_SAT1 = 0;
const unsigned char HIGH_INSTR_SAT1 = 255;
const unsigned char HIGH_REPR_SAT1 = 255;

// 2-byte unsigned special pixel values
const unsigned short NULLU2 = 0;
const unsigned short LOW_REPR_SATU2 = 1;
const unsigned short LOW_INSTR_SATU2 = 2;
const unsigned short HIGH_INSTR_SATU2 = 65534;
const unsigned short HIGH_REPR_SATU2 = 65535;

// 2-byte signed special pixel values
const short NULL2 = -32768;
const short LOW_REPR_SAT2 = -32767;
const short LOW_INSTR_SAT2 = -32766;
const short HIGH_INSTR_SAT2 = -32765;
const short HIGH_REPR_SAT2 = -32764;

// Define 4-byte special pixel values for IEEE floating point
const float NULL4 = -3.4028226550889045e+38f;            // 0xFF7FFFFB;
const float LOW_REPR_SAT4 = -3.4028228579130005e+38f;    // 0xFF7FFFFC;
const float LOW_INSTR_SAT4 = -3.4028230607370965e+38f;   // 0xFF7FFFFD;
const float HIGH_INSTR_SAT4 = -3.4028232635611926e+38f;  // 0xFF7FFFFE;
const float HIGH_REPR_SAT4 = -3.4028234663852886e+38f;   // 0xFF7FFFFF;

// Must be large enough to hold an integer
static const char *const pszSTARTBYTE_PLACEHOLDER = "!*^STARTBYTE^*!";
// Must be large enough to hold an integer
static const char *const pszLABEL_BYTES_PLACEHOLDER = "!*^LABEL_BYTES^*!";
// Must be large enough to hold an integer
static const char *const pszHISTORY_STARTBYTE_PLACEHOLDER =
    "!*^HISTORY_STARTBYTE^*!";

/************************************************************************/
/* ==================================================================== */
/*                             ISISDataset                              */
/* ==================================================================== */
/************************************************************************/

class ISIS3Dataset final : public RawDataset
{
    friend class ISIS3RawRasterBand;
    friend class ISISTiledBand;
    friend class ISIS3WrapperRasterBand;

    class NonPixelSection
    {
      public:
        CPLString osSrcFilename;
        CPLString osDstFilename;  // empty for same file
        vsi_l_offset nSrcOffset;
        vsi_l_offset nSize;
        CPLString osPlaceHolder;  // empty if not same file
    };

    VSILFILE *m_fpLabel;               // label file (only used for writing)
    VSILFILE *m_fpImage;               // image data file. May be == fpLabel
    GDALDataset *m_poExternalDS;       // external dataset (GeoTIFF)
    bool m_bGeoTIFFAsRegularExternal;  // creation only
    bool m_bGeoTIFFInitDone;           // creation only

    CPLString m_osExternalFilename;
    bool m_bIsLabelWritten;  // creation only

    bool m_bIsTiled;
    bool m_bInitToNodata;  // creation only

    NASAKeywordHandler m_oKeywords;

    bool m_bGotTransform;
    double m_adfGeoTransform[6];

    bool m_bHasSrcNoData;  // creation only
    double m_dfSrcNoData;  // creation only

    OGRSpatialReference m_oSRS;

    // creation only variables
    CPLString m_osComment;
    CPLString m_osLatitudeType;
    CPLString m_osLongitudeDirection;
    CPLString m_osTargetName;
    bool m_bForce360;
    bool m_bWriteBoundingDegrees;
    CPLString m_osBoundingDegrees;

    CPLJSONObject m_oJSonLabel;
    CPLString m_osHistory;                              // creation only
    bool m_bUseSrcLabel;                                // creation only
    bool m_bUseSrcMapping;                              // creation only
    bool m_bUseSrcHistory;                              // creation only
    bool m_bAddGDALHistory;                             // creation only
    CPLString m_osGDALHistory;                          // creation only
    std::vector<NonPixelSection> m_aoNonPixelSections;  // creation only
    CPLJSONObject m_oSrcJSonLabel;                      // creation only
    CPLStringList m_aosISIS3MD;
    CPLStringList m_aosAdditionalFiles;
    CPLString m_osFromFilename;  // creation only

    RawBinaryLayout m_sLayout{};

    const char *GetKeyword(const char *pszPath, const char *pszDefault = "");

    double FixLong(double dfLong);
    void BuildLabel();
    void BuildHistory();
    void WriteLabel();
    void InvalidateLabel();

    static CPLString SerializeAsPDL(const CPLJSONObject &oObj);
    static void SerializeAsPDL(VSILFILE *fp, const CPLJSONObject &oObj,
                               int nDepth = 0);

  public:
    ISIS3Dataset();
    virtual ~ISIS3Dataset();

    virtual int CloseDependentDatasets() override;

    virtual CPLErr GetGeoTransform(double *padfTransform) override;
    virtual CPLErr SetGeoTransform(double *padfTransform) override;

    const OGRSpatialReference *GetSpatialRef() const override;
    CPLErr SetSpatialRef(const OGRSpatialReference *poSRS) override;

    virtual char **GetFileList() override;

    virtual char **GetMetadataDomainList() override;
    virtual char **GetMetadata(const char *pszDomain = "") override;
    virtual CPLErr SetMetadata(char **papszMD,
                               const char *pszDomain = "") override;

    bool GetRawBinaryLayout(GDALDataset::RawBinaryLayout &) override;

    static int Identify(GDALOpenInfo *);
    static GDALDataset *Open(GDALOpenInfo *);
    static GDALDataset *Create(const char *pszFilename, int nXSize, int nYSize,
                               int nBandsIn, GDALDataType eType,
                               char **papszOptions);
    static GDALDataset *CreateCopy(const char *pszFilename,
                                   GDALDataset *poSrcDS, int bStrict,
                                   char **papszOptions,
                                   GDALProgressFunc pfnProgress,
                                   void *pProgressData);
};

/************************************************************************/
/* ==================================================================== */
/*                             ISISTiledBand                            */
/* ==================================================================== */
/************************************************************************/

class ISISTiledBand final : public GDALPamRasterBand
{
    friend class ISIS3Dataset;

    VSILFILE *m_fpVSIL;
    GIntBig m_nFirstTileOffset;
    GIntBig m_nXTileOffset;
    GIntBig m_nYTileOffset;
    int m_bNativeOrder;
    bool m_bHasOffset;
    bool m_bHasScale;
    double m_dfOffset;
    double m_dfScale;
    double m_dfNoData;

  public:
    ISISTiledBand(GDALDataset *poDS, VSILFILE *fpVSIL, int nBand,
                  GDALDataType eDT, int nTileXSize, int nTileYSize,
                  GIntBig nFirstTileOffset, GIntBig nXTileOffset,
                  GIntBig nYTileOffset, int bNativeOrder);
    virtual ~ISISTiledBand()
    {
    }

    virtual CPLErr IReadBlock(int, int, void *) override;
    virtual CPLErr IWriteBlock(int, int, void *) override;

    virtual double GetOffset(int *pbSuccess = nullptr) override;
    virtual double GetScale(int *pbSuccess = nullptr) override;
    virtual CPLErr SetOffset(double dfNewOffset) override;
    virtual CPLErr SetScale(double dfNewScale) override;
    virtual double GetNoDataValue(int *pbSuccess = nullptr) override;
    virtual CPLErr SetNoDataValue(double dfNewNoData) override;

    void SetMaskBand(GDALRasterBand *poMaskBand);
};

/************************************************************************/
/* ==================================================================== */
/*                        ISIS3RawRasterBand                            */
/* ==================================================================== */
/************************************************************************/

class ISIS3RawRasterBand final : public RawRasterBand
{
    friend class ISIS3Dataset;

    bool m_bHasOffset;
    bool m_bHasScale;
    double m_dfOffset;
    double m_dfScale;
    double m_dfNoData;

  public:
    ISIS3RawRasterBand(GDALDataset *l_poDS, int l_nBand, VSILFILE *l_fpRaw,
                       vsi_l_offset l_nImgOffset, int l_nPixelOffset,
                       int l_nLineOffset, GDALDataType l_eDataType,
                       int l_bNativeOrder);
    virtual ~ISIS3RawRasterBand()
    {
    }

    virtual CPLErr IReadBlock(int, int, void *) override;
    virtual CPLErr IWriteBlock(int, int, void *) override;

    virtual CPLErr IRasterIO(GDALRWFlag, int, int, int, int, void *, int, int,
                             GDALDataType, GSpacing nPixelSpace,
                             GSpacing nLineSpace,
                             GDALRasterIOExtraArg *psExtraArg) override;

    virtual double GetOffset(int *pbSuccess = nullptr) override;
    virtual double GetScale(int *pbSuccess = nullptr) override;
    virtual CPLErr SetOffset(double dfNewOffset) override;
    virtual CPLErr SetScale(double dfNewScale) override;
    virtual double GetNoDataValue(int *pbSuccess = nullptr) override;
    virtual CPLErr SetNoDataValue(double dfNewNoData) override;

    void SetMaskBand(GDALRasterBand *poMaskBand);
};

/************************************************************************/
/* ==================================================================== */
/*                         ISIS3WrapperRasterBand                       */
/*                                                                      */
/*      proxy for bands stored in other formats.                        */
/* ==================================================================== */
/************************************************************************/
class ISIS3WrapperRasterBand final : public GDALProxyRasterBand
{
    friend class ISIS3Dataset;

    GDALRasterBand *m_poBaseBand;
    bool m_bHasOffset;
    bool m_bHasScale;
    double m_dfOffset;
    double m_dfScale;
    double m_dfNoData;

  protected:
    virtual GDALRasterBand *RefUnderlyingRasterBand() const override
    {
        return m_poBaseBand;
    }

  public:
    explicit ISIS3WrapperRasterBand(GDALRasterBand *poBaseBandIn);
    ~ISIS3WrapperRasterBand()
    {
    }

    void InitFile();

    virtual CPLErr Fill(double dfRealValue,
                        double dfImaginaryValue = 0) override;
    virtual CPLErr IWriteBlock(int, int, void *) override;

    virtual CPLErr IRasterIO(GDALRWFlag, int, int, int, int, void *, int, int,
                             GDALDataType, GSpacing nPixelSpace,
                             GSpacing nLineSpace,
                             GDALRasterIOExtraArg *psExtraArg) override;

    virtual double GetOffset(int *pbSuccess = nullptr) override;
    virtual double GetScale(int *pbSuccess = nullptr) override;
    virtual CPLErr SetOffset(double dfNewOffset) override;
    virtual CPLErr SetScale(double dfNewScale) override;
    virtual double GetNoDataValue(int *pbSuccess = nullptr) override;
    virtual CPLErr SetNoDataValue(double dfNewNoData) override;

    int GetMaskFlags() override
    {
        return nMaskFlags;
    }
    GDALRasterBand *GetMaskBand() override
    {
        return poMask;
    }
    void SetMaskBand(GDALRasterBand *poMaskBand);
};

/************************************************************************/
/* ==================================================================== */
/*                             ISISMaskBand                             */
/* ==================================================================== */

class ISISMaskBand final : public GDALRasterBand
{
    GDALRasterBand *m_poBaseBand;
    void *m_pBuffer;

  public:
    explicit ISISMaskBand(GDALRasterBand *poBaseBand);
    ~ISISMaskBand();

    virtual CPLErr IReadBlock(int, int, void *) override;
};

/************************************************************************/
/*                           ISISTiledBand()                            */
/************************************************************************/

ISISTiledBand::ISISTiledBand(GDALDataset *poDSIn, VSILFILE *fpVSILIn,
                             int nBandIn, GDALDataType eDT, int nTileXSize,
                             int nTileYSize, GIntBig nFirstTileOffsetIn,
                             GIntBig nXTileOffsetIn, GIntBig nYTileOffsetIn,
                             int bNativeOrderIn)
    : m_fpVSIL(fpVSILIn), m_nFirstTileOffset(0), m_nXTileOffset(nXTileOffsetIn),
      m_nYTileOffset(nYTileOffsetIn), m_bNativeOrder(bNativeOrderIn),
      m_bHasOffset(false), m_bHasScale(false), m_dfOffset(0.0), m_dfScale(1.0),
      m_dfNoData(0.0)
{
    poDS = poDSIn;
    nBand = nBandIn;
    eDataType = eDT;
    nBlockXSize = nTileXSize;
    nBlockYSize = nTileYSize;
    nRasterXSize = poDSIn->GetRasterXSize();
    nRasterYSize = poDSIn->GetRasterYSize();

    const int l_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, nBlockXSize);
    const int l_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, nBlockYSize);

    if (m_nXTileOffset == 0 && m_nYTileOffset == 0)
    {
        m_nXTileOffset =
            static_cast<GIntBig>(GDALGetDataTypeSizeBytes(eDT)) * nTileXSize;
        if (m_nXTileOffset > GINTBIG_MAX / nTileYSize)
        {
            CPLError(CE_Failure, CPLE_AppDefined, "Integer overflow");
            return;
        }
        m_nXTileOffset *= nTileYSize;

        if (m_nXTileOffset > GINTBIG_MAX / l_nBlocksPerRow)
        {
            CPLError(CE_Failure, CPLE_AppDefined, "Integer overflow");
            return;
        }
        m_nYTileOffset = m_nXTileOffset * l_nBlocksPerRow;
    }

    m_nFirstTileOffset = nFirstTileOffsetIn;
    if (nBand > 1)
    {
        if (m_nYTileOffset > GINTBIG_MAX / (nBand - 1) ||
            (nBand - 1) * m_nYTileOffset > GINTBIG_MAX / l_nBlocksPerColumn ||
            m_nFirstTileOffset >
                GINTBIG_MAX - (nBand - 1) * m_nYTileOffset * l_nBlocksPerColumn)
        {
            CPLError(CE_Failure, CPLE_AppDefined, "Integer overflow");
            return;
        }
        m_nFirstTileOffset += (nBand - 1) * m_nYTileOffset * l_nBlocksPerColumn;
    }
}

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

CPLErr ISISTiledBand::IReadBlock(int nXBlock, int nYBlock, void *pImage)

{
    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_osExternalFilename.empty())
    {
        if (!poGDS->m_bIsLabelWritten)
            poGDS->WriteLabel();
    }

    const GIntBig nOffset = m_nFirstTileOffset + nXBlock * m_nXTileOffset +
                            nYBlock * m_nYTileOffset;
    const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
    const size_t nBlockSize =
        static_cast<size_t>(nDTSize) * nBlockXSize * nBlockYSize;

    if (VSIFSeekL(m_fpVSIL, nOffset, SEEK_SET) != 0)
    {
        CPLError(CE_Failure, CPLE_FileIO,
                 "Failed to seek to offset %d to read tile %d,%d.",
                 static_cast<int>(nOffset), nXBlock, nYBlock);
        return CE_Failure;
    }

    if (VSIFReadL(pImage, 1, nBlockSize, m_fpVSIL) != nBlockSize)
    {
        CPLError(CE_Failure, CPLE_FileIO,
                 "Failed to read %d bytes for tile %d,%d.",
                 static_cast<int>(nBlockSize), nXBlock, nYBlock);
        return CE_Failure;
    }

    if (!m_bNativeOrder && eDataType != GDT_Byte)
        GDALSwapWords(pImage, nDTSize, nBlockXSize * nBlockYSize, nDTSize);

    return CE_None;
}

/************************************************************************/
/*                           RemapNoDataT()                             */
/************************************************************************/

template <class T>
static void RemapNoDataT(T *pBuffer, int nItems, T srcNoData, T dstNoData)
{
    for (int i = 0; i < nItems; i++)
    {
        if (pBuffer[i] == srcNoData)
            pBuffer[i] = dstNoData;
    }
}

/************************************************************************/
/*                            RemapNoData()                             */
/************************************************************************/

static void RemapNoData(GDALDataType eDataType, void *pBuffer, int nItems,
                        double dfSrcNoData, double dfDstNoData)
{
    if (eDataType == GDT_Byte)
    {
        RemapNoDataT(reinterpret_cast<GByte *>(pBuffer), nItems,
                     static_cast<GByte>(dfSrcNoData),
                     static_cast<GByte>(dfDstNoData));
    }
    else if (eDataType == GDT_UInt16)
    {
        RemapNoDataT(reinterpret_cast<GUInt16 *>(pBuffer), nItems,
                     static_cast<GUInt16>(dfSrcNoData),
                     static_cast<GUInt16>(dfDstNoData));
    }
    else if (eDataType == GDT_Int16)
    {
        RemapNoDataT(reinterpret_cast<GInt16 *>(pBuffer), nItems,
                     static_cast<GInt16>(dfSrcNoData),
                     static_cast<GInt16>(dfDstNoData));
    }
    else
    {
        CPLAssert(eDataType == GDT_Float32);
        RemapNoDataT(reinterpret_cast<float *>(pBuffer), nItems,
                     static_cast<float>(dfSrcNoData),
                     static_cast<float>(dfDstNoData));
    }
}

/**
 * Get or create CPLJSONObject.
 * @param  oParent Parent CPLJSONObject.
 * @param  osKey  Key name.
 * @return         CPLJSONObject class instance.
 */
static CPLJSONObject GetOrCreateJSONObject(CPLJSONObject &oParent,
                                           const std::string &osKey)
{
    CPLJSONObject oChild = oParent[osKey];
    if (oChild.IsValid() && oChild.GetType() != CPLJSONObject::Type::Object)
    {
        oParent.Delete(osKey);
        oChild.Deinit();
    }

    if (!oChild.IsValid())
    {
        oChild = CPLJSONObject();
        oParent.Add(osKey, oChild);
    }
    return oChild;
}

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

CPLErr ISISTiledBand::IWriteBlock(int nXBlock, int nYBlock, void *pImage)

{
    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_osExternalFilename.empty())
    {
        if (!poGDS->m_bIsLabelWritten)
            poGDS->WriteLabel();
    }

    if (poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData)
    {
        RemapNoData(eDataType, pImage, nBlockXSize * nBlockYSize,
                    poGDS->m_dfSrcNoData, m_dfNoData);
    }

    const GIntBig nOffset = m_nFirstTileOffset + nXBlock * m_nXTileOffset +
                            nYBlock * m_nYTileOffset;
    const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
    const size_t nBlockSize =
        static_cast<size_t>(nDTSize) * nBlockXSize * nBlockYSize;

    const int l_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, nBlockXSize);
    const int l_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, nBlockYSize);

    // Pad partial blocks to nodata value
    if (nXBlock == l_nBlocksPerRow - 1 && (nRasterXSize % nBlockXSize) != 0)
    {
        GByte *pabyImage = static_cast<GByte *>(pImage);
        int nXStart = nRasterXSize % nBlockXSize;
        for (int iY = 0; iY < nBlockYSize; iY++)
        {
            GDALCopyWords(&m_dfNoData, GDT_Float64, 0,
                          pabyImage + (iY * nBlockXSize + nXStart) * nDTSize,
                          eDataType, nDTSize, nBlockXSize - nXStart);
        }
    }
    if (nYBlock == l_nBlocksPerColumn - 1 && (nRasterYSize % nBlockYSize) != 0)
    {
        GByte *pabyImage = static_cast<GByte *>(pImage);
        for (int iY = nRasterYSize % nBlockYSize; iY < nBlockYSize; iY++)
        {
            GDALCopyWords(&m_dfNoData, GDT_Float64, 0,
                          pabyImage + iY * nBlockXSize * nDTSize, eDataType,
                          nDTSize, nBlockXSize);
        }
    }

    if (VSIFSeekL(m_fpVSIL, nOffset, SEEK_SET) != 0)
    {
        CPLError(CE_Failure, CPLE_FileIO,
                 "Failed to seek to offset %d to read tile %d,%d.",
                 static_cast<int>(nOffset), nXBlock, nYBlock);
        return CE_Failure;
    }

    if (!m_bNativeOrder && eDataType != GDT_Byte)
        GDALSwapWords(pImage, nDTSize, nBlockXSize * nBlockYSize, nDTSize);

    if (VSIFWriteL(pImage, 1, nBlockSize, m_fpVSIL) != nBlockSize)
    {
        CPLError(CE_Failure, CPLE_FileIO,
                 "Failed to write %d bytes for tile %d,%d.",
                 static_cast<int>(nBlockSize), nXBlock, nYBlock);
        return CE_Failure;
    }

    if (!m_bNativeOrder && eDataType != GDT_Byte)
        GDALSwapWords(pImage, nDTSize, nBlockXSize * nBlockYSize, nDTSize);

    return CE_None;
}

/************************************************************************/
/*                             SetMaskBand()                            */
/************************************************************************/

void ISISTiledBand::SetMaskBand(GDALRasterBand *poMaskBand)
{
    bOwnMask = true;
    poMask = poMaskBand;
    nMaskFlags = 0;
}

/************************************************************************/
/*                              GetOffset()                             */
/************************************************************************/

double ISISTiledBand::GetOffset(int *pbSuccess)
{
    if (pbSuccess)
        *pbSuccess = m_bHasOffset;
    return m_dfOffset;
}

/************************************************************************/
/*                              GetScale()                              */
/************************************************************************/

double ISISTiledBand::GetScale(int *pbSuccess)
{
    if (pbSuccess)
        *pbSuccess = m_bHasScale;
    return m_dfScale;
}

/************************************************************************/
/*                              SetOffset()                             */
/************************************************************************/

CPLErr ISISTiledBand::SetOffset(double dfNewOffset)
{
    m_dfOffset = dfNewOffset;
    m_bHasOffset = true;
    return CE_None;
}

/************************************************************************/
/*                              SetScale()                              */
/************************************************************************/

CPLErr ISISTiledBand::SetScale(double dfNewScale)
{
    m_dfScale = dfNewScale;
    m_bHasScale = true;
    return CE_None;
}

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

double ISISTiledBand::GetNoDataValue(int *pbSuccess)
{
    if (pbSuccess)
        *pbSuccess = true;
    return m_dfNoData;
}

/************************************************************************/
/*                           SetNoDataValue()                           */
/************************************************************************/

CPLErr ISISTiledBand::SetNoDataValue(double dfNewNoData)
{
    m_dfNoData = dfNewNoData;
    return CE_None;
}

/************************************************************************/
/*                       ISIS3RawRasterBand()                           */
/************************************************************************/

ISIS3RawRasterBand::ISIS3RawRasterBand(GDALDataset *l_poDS, int l_nBand,
                                       VSILFILE *l_fpRaw,
                                       vsi_l_offset l_nImgOffset,
                                       int l_nPixelOffset, int l_nLineOffset,
                                       GDALDataType l_eDataType,
                                       int l_bNativeOrder)
    : RawRasterBand(l_poDS, l_nBand, l_fpRaw, l_nImgOffset, l_nPixelOffset,
                    l_nLineOffset, l_eDataType, l_bNativeOrder,
                    RawRasterBand::OwnFP::NO),
      m_bHasOffset(false), m_bHasScale(false), m_dfOffset(0.0), m_dfScale(1.0),
      m_dfNoData(0.0)
{
}

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

CPLErr ISIS3RawRasterBand::IReadBlock(int nXBlock, int nYBlock, void *pImage)

{
    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_osExternalFilename.empty())
    {
        if (!poGDS->m_bIsLabelWritten)
            poGDS->WriteLabel();
    }
    return RawRasterBand::IReadBlock(nXBlock, nYBlock, pImage);
}

/************************************************************************/
/*                            IWriteBlock()                             */
/************************************************************************/

CPLErr ISIS3RawRasterBand::IWriteBlock(int nXBlock, int nYBlock, void *pImage)

{
    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_osExternalFilename.empty())
    {
        if (!poGDS->m_bIsLabelWritten)
            poGDS->WriteLabel();
    }

    if (poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData)
    {
        RemapNoData(eDataType, pImage, nBlockXSize * nBlockYSize,
                    poGDS->m_dfSrcNoData, m_dfNoData);
    }

    return RawRasterBand::IWriteBlock(nXBlock, nYBlock, pImage);
}

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

CPLErr ISIS3RawRasterBand::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)

{
    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_osExternalFilename.empty())
    {
        if (!poGDS->m_bIsLabelWritten)
            poGDS->WriteLabel();
    }
    if (eRWFlag == GF_Write && poGDS->m_bHasSrcNoData &&
        poGDS->m_dfSrcNoData != m_dfNoData)
    {
        const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
        if (eBufType == eDataType && nPixelSpace == nDTSize &&
            nLineSpace == nPixelSpace * nBufXSize)
        {
            RemapNoData(eDataType, pData, nBufXSize * nBufYSize,
                        poGDS->m_dfSrcNoData, m_dfNoData);
        }
        else
        {
            const GByte *pabySrc = reinterpret_cast<GByte *>(pData);
            GByte *pabyTemp = reinterpret_cast<GByte *>(
                VSI_MALLOC3_VERBOSE(nDTSize, nBufXSize, nBufYSize));
            for (int i = 0; i < nBufYSize; i++)
            {
                GDALCopyWords(pabySrc + i * nLineSpace, eBufType,
                              static_cast<int>(nPixelSpace),
                              pabyTemp + i * nBufXSize * nDTSize, eDataType,
                              nDTSize, nBufXSize);
            }
            RemapNoData(eDataType, pabyTemp, nBufXSize * nBufYSize,
                        poGDS->m_dfSrcNoData, m_dfNoData);
            CPLErr eErr = RawRasterBand::IRasterIO(
                eRWFlag, nXOff, nYOff, nXSize, nYSize, pabyTemp, nBufXSize,
                nBufYSize, eDataType, nDTSize, nDTSize * nBufXSize, psExtraArg);
            VSIFree(pabyTemp);
            return eErr;
        }
    }
    return RawRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
                                    pData, nBufXSize, nBufYSize, eBufType,
                                    nPixelSpace, nLineSpace, psExtraArg);
}

/************************************************************************/
/*                             SetMaskBand()                            */
/************************************************************************/

void ISIS3RawRasterBand::SetMaskBand(GDALRasterBand *poMaskBand)
{
    bOwnMask = true;
    poMask = poMaskBand;
    nMaskFlags = 0;
}

/************************************************************************/
/*                              GetOffset()                             */
/************************************************************************/

double ISIS3RawRasterBand::GetOffset(int *pbSuccess)
{
    if (pbSuccess)
        *pbSuccess = m_bHasOffset;
    return m_dfOffset;
}

/************************************************************************/
/*                              GetScale()                              */
/************************************************************************/

double ISIS3RawRasterBand::GetScale(int *pbSuccess)
{
    if (pbSuccess)
        *pbSuccess = m_bHasScale;
    return m_dfScale;
}

/************************************************************************/
/*                              SetOffset()                             */
/************************************************************************/

CPLErr ISIS3RawRasterBand::SetOffset(double dfNewOffset)
{
    m_dfOffset = dfNewOffset;
    m_bHasOffset = true;
    return CE_None;
}

/************************************************************************/
/*                              SetScale()                              */
/************************************************************************/

CPLErr ISIS3RawRasterBand::SetScale(double dfNewScale)
{
    m_dfScale = dfNewScale;
    m_bHasScale = true;
    return CE_None;
}

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

double ISIS3RawRasterBand::GetNoDataValue(int *pbSuccess)
{
    if (pbSuccess)
        *pbSuccess = true;
    return m_dfNoData;
}

/************************************************************************/
/*                           SetNoDataValue()                           */
/************************************************************************/

CPLErr ISIS3RawRasterBand::SetNoDataValue(double dfNewNoData)
{
    m_dfNoData = dfNewNoData;
    return CE_None;
}

/************************************************************************/
/*                        ISIS3WrapperRasterBand()                      */
/************************************************************************/

ISIS3WrapperRasterBand::ISIS3WrapperRasterBand(GDALRasterBand *poBaseBandIn)
    : m_poBaseBand(poBaseBandIn), m_bHasOffset(false), m_bHasScale(false),
      m_dfOffset(0.0), m_dfScale(1.0), m_dfNoData(0.0)
{
    eDataType = m_poBaseBand->GetRasterDataType();
    m_poBaseBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
}

/************************************************************************/
/*                             SetMaskBand()                            */
/************************************************************************/

void ISIS3WrapperRasterBand::SetMaskBand(GDALRasterBand *poMaskBand)
{
    bOwnMask = true;
    poMask = poMaskBand;
    nMaskFlags = 0;
}

/************************************************************************/
/*                              GetOffset()                             */
/************************************************************************/

double ISIS3WrapperRasterBand::GetOffset(int *pbSuccess)
{
    if (pbSuccess)
        *pbSuccess = m_bHasOffset;
    return m_dfOffset;
}

/************************************************************************/
/*                              GetScale()                              */
/************************************************************************/

double ISIS3WrapperRasterBand::GetScale(int *pbSuccess)
{
    if (pbSuccess)
        *pbSuccess = m_bHasScale;
    return m_dfScale;
}

/************************************************************************/
/*                              SetOffset()                             */
/************************************************************************/

CPLErr ISIS3WrapperRasterBand::SetOffset(double dfNewOffset)
{
    m_dfOffset = dfNewOffset;
    m_bHasOffset = true;

    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_poExternalDS && eAccess == GA_Update)
        poGDS->m_poExternalDS->GetRasterBand(nBand)->SetOffset(dfNewOffset);

    return CE_None;
}

/************************************************************************/
/*                              SetScale()                              */
/************************************************************************/

CPLErr ISIS3WrapperRasterBand::SetScale(double dfNewScale)
{
    m_dfScale = dfNewScale;
    m_bHasScale = true;

    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_poExternalDS && eAccess == GA_Update)
        poGDS->m_poExternalDS->GetRasterBand(nBand)->SetScale(dfNewScale);

    return CE_None;
}

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

double ISIS3WrapperRasterBand::GetNoDataValue(int *pbSuccess)
{
    if (pbSuccess)
        *pbSuccess = true;
    return m_dfNoData;
}

/************************************************************************/
/*                           SetNoDataValue()                           */
/************************************************************************/

CPLErr ISIS3WrapperRasterBand::SetNoDataValue(double dfNewNoData)
{
    m_dfNoData = dfNewNoData;

    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_poExternalDS && eAccess == GA_Update)
        poGDS->m_poExternalDS->GetRasterBand(nBand)->SetNoDataValue(
            dfNewNoData);

    return CE_None;
}

/************************************************************************/
/*                              InitFile()                              */
/************************************************************************/

void ISIS3WrapperRasterBand::InitFile()
{
    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_bGeoTIFFAsRegularExternal && !poGDS->m_bGeoTIFFInitDone)
    {
        poGDS->m_bGeoTIFFInitDone = true;

        const int nBands = poGDS->GetRasterCount();
        // We need to make sure that blocks are written in the right order
        for (int i = 0; i < nBands; i++)
        {
            poGDS->m_poExternalDS->GetRasterBand(i + 1)->Fill(m_dfNoData);
        }
        poGDS->m_poExternalDS->FlushCache(false);

        // Check that blocks are effectively written in expected order.
        const int nBlockSizeBytes =
            nBlockXSize * nBlockYSize * GDALGetDataTypeSizeBytes(eDataType);

        GIntBig nLastOffset = 0;
        bool bGoOn = true;
        const int l_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, nBlockXSize);
        const int l_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, nBlockYSize);
        for (int i = 0; i < nBands && bGoOn; i++)
        {
            for (int y = 0; y < l_nBlocksPerColumn && bGoOn; y++)
            {
                for (int x = 0; x < l_nBlocksPerRow && bGoOn; x++)
                {
                    const char *pszBlockOffset =
                        poGDS->m_poExternalDS->GetRasterBand(i + 1)
                            ->GetMetadataItem(
                                CPLSPrintf("BLOCK_OFFSET_%d_%d", x, y), "TIFF");
                    if (pszBlockOffset)
                    {
                        GIntBig nOffset = CPLAtoGIntBig(pszBlockOffset);
                        if (i != 0 || x != 0 || y != 0)
                        {
                            if (nOffset != nLastOffset + nBlockSizeBytes)
                            {
                                CPLError(CE_Warning, CPLE_AppDefined,
                                         "Block %d,%d band %d not at expected "
                                         "offset",
                                         x, y, i + 1);
                                bGoOn = false;
                                poGDS->m_bGeoTIFFAsRegularExternal = false;
                            }
                        }
                        nLastOffset = nOffset;
                    }
                    else
                    {
                        CPLError(CE_Warning, CPLE_AppDefined,
                                 "Block %d,%d band %d not at expected "
                                 "offset",
                                 x, y, i + 1);
                        bGoOn = false;
                        poGDS->m_bGeoTIFFAsRegularExternal = false;
                    }
                }
            }
        }
    }
}

/************************************************************************/
/*                               Fill()                                 */
/************************************************************************/

CPLErr ISIS3WrapperRasterBand::Fill(double dfRealValue, double dfImaginaryValue)
{
    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData == dfRealValue)
    {
        dfRealValue = m_dfNoData;
    }
    if (poGDS->m_bGeoTIFFAsRegularExternal && !poGDS->m_bGeoTIFFInitDone)
    {
        InitFile();
    }

    return GDALProxyRasterBand::Fill(dfRealValue, dfImaginaryValue);
}

/************************************************************************/
/*                             IWriteBlock()                             */
/************************************************************************/

CPLErr ISIS3WrapperRasterBand::IWriteBlock(int nXBlock, int nYBlock,
                                           void *pImage)

{
    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData)
    {
        RemapNoData(eDataType, pImage, nBlockXSize * nBlockYSize,
                    poGDS->m_dfSrcNoData, m_dfNoData);
    }
    if (poGDS->m_bGeoTIFFAsRegularExternal && !poGDS->m_bGeoTIFFInitDone)
    {
        InitFile();
    }

    return GDALProxyRasterBand::IWriteBlock(nXBlock, nYBlock, pImage);
}

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

CPLErr ISIS3WrapperRasterBand::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)

{
    ISIS3Dataset *poGDS = reinterpret_cast<ISIS3Dataset *>(poDS);
    if (eRWFlag == GF_Write && poGDS->m_bGeoTIFFAsRegularExternal &&
        !poGDS->m_bGeoTIFFInitDone)
    {
        InitFile();
    }
    if (eRWFlag == GF_Write && poGDS->m_bHasSrcNoData &&
        poGDS->m_dfSrcNoData != m_dfNoData)
    {
        const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
        if (eBufType == eDataType && nPixelSpace == nDTSize &&
            nLineSpace == nPixelSpace * nBufXSize)
        {
            RemapNoData(eDataType, pData, nBufXSize * nBufYSize,
                        poGDS->m_dfSrcNoData, m_dfNoData);
        }
        else
        {
            const GByte *pabySrc = reinterpret_cast<GByte *>(pData);
            GByte *pabyTemp = reinterpret_cast<GByte *>(
                VSI_MALLOC3_VERBOSE(nDTSize, nBufXSize, nBufYSize));
            for (int i = 0; i < nBufYSize; i++)
            {
                GDALCopyWords(pabySrc + i * nLineSpace, eBufType,
                              static_cast<int>(nPixelSpace),
                              pabyTemp + i * nBufXSize * nDTSize, eDataType,
                              nDTSize, nBufXSize);
            }
            RemapNoData(eDataType, pabyTemp, nBufXSize * nBufYSize,
                        poGDS->m_dfSrcNoData, m_dfNoData);
            CPLErr eErr = GDALProxyRasterBand::IRasterIO(
                eRWFlag, nXOff, nYOff, nXSize, nYSize, pabyTemp, nBufXSize,
                nBufYSize, eDataType, nDTSize, nDTSize * nBufXSize, psExtraArg);
            VSIFree(pabyTemp);
            return eErr;
        }
    }
    return GDALProxyRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
                                          pData, nBufXSize, nBufYSize, eBufType,
                                          nPixelSpace, nLineSpace, psExtraArg);
}

/************************************************************************/
/*                            ISISMaskBand()                            */
/************************************************************************/

ISISMaskBand::ISISMaskBand(GDALRasterBand *poBaseBand)
    : m_poBaseBand(poBaseBand), m_pBuffer(nullptr)
{
    eDataType = GDT_Byte;
    poBaseBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
    nRasterXSize = poBaseBand->GetXSize();
    nRasterYSize = poBaseBand->GetYSize();
}

/************************************************************************/
/*                           ~ISISMaskBand()                            */
/************************************************************************/

ISISMaskBand::~ISISMaskBand()
{
    VSIFree(m_pBuffer);
}

/************************************************************************/
/*                             FillMask()                               */
/************************************************************************/

template <class T>
static void FillMask(void *pvBuffer, GByte *pabyDst, int nReqXSize,
                     int nReqYSize, int nBlockXSize, T NULL_VAL, T LOW_REPR_SAT,
                     T LOW_INSTR_SAT, T HIGH_INSTR_SAT, T HIGH_REPR_SAT)
{
    const T *pSrc = static_cast<T *>(pvBuffer);
    for (int y = 0; y < nReqYSize; y++)
    {
        for (int x = 0; x < nReqXSize; x++)
        {
            const T nSrc = pSrc[y * nBlockXSize + x];
            if (nSrc == NULL_VAL || nSrc == LOW_REPR_SAT ||
                nSrc == LOW_INSTR_SAT || nSrc == HIGH_INSTR_SAT ||
                nSrc == HIGH_REPR_SAT)
            {
                pabyDst[y * nBlockXSize + x] = 0;
            }
            else
            {
                pabyDst[y * nBlockXSize + x] = 255;
            }
        }
    }
}

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

CPLErr ISISMaskBand::IReadBlock(int nXBlock, int nYBlock, void *pImage)

{
    const GDALDataType eSrcDT = m_poBaseBand->GetRasterDataType();
    const int nSrcDTSize = GDALGetDataTypeSizeBytes(eSrcDT);
    if (m_pBuffer == nullptr)
    {
        m_pBuffer = VSI_MALLOC3_VERBOSE(nBlockXSize, nBlockYSize, nSrcDTSize);
        if (m_pBuffer == nullptr)
            return CE_Failure;
    }

    int nXOff = nXBlock * nBlockXSize;
    int nReqXSize = nBlockXSize;
    if (nXOff + nReqXSize > nRasterXSize)
        nReqXSize = nRasterXSize - nXOff;
    int nYOff = nYBlock * nBlockYSize;
    int nReqYSize = nBlockYSize;
    if (nYOff + nReqYSize > nRasterYSize)
        nReqYSize = nRasterYSize - nYOff;

    if (m_poBaseBand->RasterIO(GF_Read, nXOff, nYOff, nReqXSize, nReqYSize,
                               m_pBuffer, nReqXSize, nReqYSize, eSrcDT,
                               nSrcDTSize, nSrcDTSize * nBlockXSize,
                               nullptr) != CE_None)
    {
        return CE_Failure;
    }

    GByte *pabyDst = static_cast<GByte *>(pImage);
    if (eSrcDT == GDT_Byte)
    {
        FillMask<GByte>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize,
                        NULL1, LOW_REPR_SAT1, LOW_INSTR_SAT1, HIGH_INSTR_SAT1,
                        HIGH_REPR_SAT1);
    }
    else if (eSrcDT == GDT_UInt16)
    {
        FillMask<GUInt16>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize,
                          NULLU2, LOW_REPR_SATU2, LOW_INSTR_SATU2,
                          HIGH_INSTR_SATU2, HIGH_REPR_SATU2);
    }
    else if (eSrcDT == GDT_Int16)
    {
        FillMask<GInt16>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize,
                         NULL2, LOW_REPR_SAT2, LOW_INSTR_SAT2, HIGH_INSTR_SAT2,
                         HIGH_REPR_SAT2);
    }
    else
    {
        CPLAssert(eSrcDT == GDT_Float32);
        FillMask<float>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize,
                        NULL4, LOW_REPR_SAT4, LOW_INSTR_SAT4, HIGH_INSTR_SAT4,
                        HIGH_REPR_SAT4);
    }

    return CE_None;
}

/************************************************************************/
/*                            ISIS3Dataset()                            */
/************************************************************************/

ISIS3Dataset::ISIS3Dataset()
    : m_fpLabel(nullptr), m_fpImage(nullptr), m_poExternalDS(nullptr),
      m_bGeoTIFFAsRegularExternal(false), m_bGeoTIFFInitDone(true),
      m_bIsLabelWritten(true), m_bIsTiled(false), m_bInitToNodata(false),
      m_bGotTransform(false), m_bHasSrcNoData(false), m_dfSrcNoData(0.0),
      m_bForce360(false), m_bWriteBoundingDegrees(true), m_bUseSrcLabel(true),
      m_bUseSrcMapping(false), m_bUseSrcHistory(true), m_bAddGDALHistory(true)
{
    m_oKeywords.SetStripSurroundingQuotes(true);
    m_adfGeoTransform[0] = 0.0;
    m_adfGeoTransform[1] = 1.0;
    m_adfGeoTransform[2] = 0.0;
    m_adfGeoTransform[3] = 0.0;
    m_adfGeoTransform[4] = 0.0;
    m_adfGeoTransform[5] = 1.0;

    // Deinit JSON objects
    m_oJSonLabel.Deinit();
    m_oSrcJSonLabel.Deinit();
}

/************************************************************************/
/*                           ~ISIS3Dataset()                            */
/************************************************************************/

ISIS3Dataset::~ISIS3Dataset()

{
    if (!m_bIsLabelWritten)
        WriteLabel();
    if (m_poExternalDS && m_bGeoTIFFAsRegularExternal && !m_bGeoTIFFInitDone)
    {
        reinterpret_cast<ISIS3WrapperRasterBand *>(GetRasterBand(1))
            ->InitFile();
    }
    ISIS3Dataset::FlushCache(true);
    if (m_fpLabel != nullptr)
        VSIFCloseL(m_fpLabel);
    if (m_fpImage != nullptr && m_fpImage != m_fpLabel)
        VSIFCloseL(m_fpImage);

    ISIS3Dataset::CloseDependentDatasets();
}

/************************************************************************/
/*                        CloseDependentDatasets()                      */
/************************************************************************/

int ISIS3Dataset::CloseDependentDatasets()
{
    int bHasDroppedRef = GDALPamDataset::CloseDependentDatasets();

    if (m_poExternalDS)
    {
        bHasDroppedRef = FALSE;
        delete m_poExternalDS;
        m_poExternalDS = nullptr;
    }

    for (int iBand = 0; iBand < nBands; iBand++)
    {
        delete papoBands[iBand];
    }
    nBands = 0;

    return bHasDroppedRef;
}

/************************************************************************/
/*                            GetFileList()                             */
/************************************************************************/

char **ISIS3Dataset::GetFileList()

{
    char **papszFileList = GDALPamDataset::GetFileList();

    if (!m_osExternalFilename.empty())
        papszFileList = CSLAddString(papszFileList, m_osExternalFilename);
    for (int i = 0; i < m_aosAdditionalFiles.Count(); ++i)
    {
        if (CSLFindString(papszFileList, m_aosAdditionalFiles[i]) < 0)
        {
            papszFileList =
                CSLAddString(papszFileList, m_aosAdditionalFiles[i]);
        }
    }

    return papszFileList;
}

/************************************************************************/
/*                           GetSpatialRef()                            */
/************************************************************************/

const OGRSpatialReference *ISIS3Dataset::GetSpatialRef() const

{
    if (!m_oSRS.IsEmpty())
        return &m_oSRS;

    return GDALPamDataset::GetSpatialRef();
}

/************************************************************************/
/*                           SetSpatialRef()                            */
/************************************************************************/

CPLErr ISIS3Dataset::SetSpatialRef(const OGRSpatialReference *poSRS)
{
    if (eAccess == GA_ReadOnly)
        return GDALPamDataset::SetSpatialRef(poSRS);
    if (poSRS)
        m_oSRS = *poSRS;
    else
        m_oSRS.Clear();
    if (m_poExternalDS)
        m_poExternalDS->SetSpatialRef(poSRS);
    InvalidateLabel();
    return CE_None;
}

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

CPLErr ISIS3Dataset::GetGeoTransform(double *padfTransform)

{
    if (m_bGotTransform)
    {
        memcpy(padfTransform, m_adfGeoTransform, sizeof(double) * 6);
        return CE_None;
    }

    return GDALPamDataset::GetGeoTransform(padfTransform);
}

/************************************************************************/
/*                          SetGeoTransform()                           */
/************************************************************************/

CPLErr ISIS3Dataset::SetGeoTransform(double *padfTransform)

{
    if (eAccess == GA_ReadOnly)
        return GDALPamDataset::SetGeoTransform(padfTransform);
    if (padfTransform[1] <= 0.0 || padfTransform[1] != -padfTransform[5] ||
        padfTransform[2] != 0.0 || padfTransform[4] != 0.0)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "Only north-up geotransform with square pixels supported");
        return CE_Failure;
    }
    m_bGotTransform = true;
    memcpy(m_adfGeoTransform, padfTransform, sizeof(double) * 6);
    if (m_poExternalDS)
        m_poExternalDS->SetGeoTransform(padfTransform);
    InvalidateLabel();
    return CE_None;
}

/************************************************************************/
/*                      GetMetadataDomainList()                         */
/************************************************************************/

char **ISIS3Dataset::GetMetadataDomainList()
{
    return BuildMetadataDomainList(nullptr, FALSE, "", "json:ISIS3", nullptr);
}

/************************************************************************/
/*                             GetMetadata()                            */
/************************************************************************/

char **ISIS3Dataset::GetMetadata(const char *pszDomain)
{
    if (pszDomain != nullptr && EQUAL(pszDomain, "json:ISIS3"))
    {
        if (m_aosISIS3MD.empty())
        {
            if (eAccess == GA_Update && !m_oJSonLabel.IsValid())
            {
                BuildLabel();
            }
            CPLAssert(m_oJSonLabel.IsValid());
            const CPLString osJson =
                m_oJSonLabel.Format(CPLJSONObject::PrettyFormat::Pretty);
            m_aosISIS3MD.InsertString(0, osJson.c_str());
        }
        return m_aosISIS3MD.List();
    }
    return GDALPamDataset::GetMetadata(pszDomain);
}

/************************************************************************/
/*                           InvalidateLabel()                          */
/************************************************************************/

void ISIS3Dataset::InvalidateLabel()
{
    m_oJSonLabel.Deinit();
    m_aosISIS3MD.Clear();
}

/************************************************************************/
/*                             SetMetadata()                            */
/************************************************************************/

CPLErr ISIS3Dataset::SetMetadata(char **papszMD, const char *pszDomain)
{
    if (m_bUseSrcLabel && eAccess == GA_Update && pszDomain != nullptr &&
        EQUAL(pszDomain, "json:ISIS3"))
    {
        m_oSrcJSonLabel.Deinit();
        InvalidateLabel();
        if (papszMD != nullptr && papszMD[0] != nullptr)
        {
            CPLJSONDocument oJSONDocument;
            const GByte *pabyData = reinterpret_cast<const GByte *>(papszMD[0]);
            if (!oJSONDocument.LoadMemory(pabyData))
            {
                return CE_Failure;
            }

            m_oSrcJSonLabel = oJSONDocument.GetRoot();
            if (!m_oSrcJSonLabel.IsValid())
            {
                return CE_Failure;
            }
        }
        return CE_None;
    }
    return GDALPamDataset::SetMetadata(papszMD, pszDomain);
}

/************************************************************************/
/*                              Identify()                              */
/************************************************************************/
int ISIS3Dataset::Identify(GDALOpenInfo *poOpenInfo)

{
    if (poOpenInfo->fpL != nullptr && poOpenInfo->pabyHeader != nullptr &&
        strstr((const char *)poOpenInfo->pabyHeader, "IsisCube") != nullptr)
        return TRUE;

    return FALSE;
}

/************************************************************************/
/*                        GetRawBinaryLayout()                          */
/************************************************************************/

bool ISIS3Dataset::GetRawBinaryLayout(GDALDataset::RawBinaryLayout &sLayout)
{
    if (m_sLayout.osRawFilename.empty())
        return false;
    sLayout = m_sLayout;
    return true;
}

/************************************************************************/
/*                           GetValueAndUnits()                         */
/************************************************************************/

static void GetValueAndUnits(const CPLJSONObject &obj,
                             std::vector<double> &adfValues,
                             std::vector<std::string> &aosUnits,
                             int nExpectedVals)
{
    if (obj.GetType() == CPLJSONObject::Type::Integer ||
        obj.GetType() == CPLJSONObject::Type::Double)
    {
        adfValues.push_back(obj.ToDouble());
    }
    else if (obj.GetType() == CPLJSONObject::Type::Object)
    {
        auto oValue = obj.GetObj("value");
        auto oUnit = obj.GetObj("unit");
        if (oValue.IsValid() &&
            (oValue.GetType() == CPLJSONObject::Type::Integer ||
             oValue.GetType() == CPLJSONObject::Type::Double ||
             oValue.GetType() == CPLJSONObject::Type::Array) &&
            oUnit.IsValid() && oUnit.GetType() == CPLJSONObject::Type::String)
        {
            if (oValue.GetType() == CPLJSONObject::Type::Array)
            {
                GetValueAndUnits(oValue, adfValues, aosUnits, nExpectedVals);
            }
            else
            {
                adfValues.push_back(oValue.ToDouble());
            }
            aosUnits.push_back(oUnit.ToString());
        }
    }
    else if (obj.GetType() == CPLJSONObject::Type::Array)
    {
        auto oArray = obj.ToArray();
        if (oArray.Size() == nExpectedVals)
        {
            for (int i = 0; i < nExpectedVals; i++)
            {
                if (oArray[i].GetType() == CPLJSONObject::Type::Integer ||
                    oArray[i].GetType() == CPLJSONObject::Type::Double)
                {
                    adfValues.push_back(oArray[i].ToDouble());
                }
                else
                {
                    adfValues.clear();
                    return;
                }
            }
        }
    }
}

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

GDALDataset *ISIS3Dataset::Open(GDALOpenInfo *poOpenInfo)

{
    /* -------------------------------------------------------------------- */
    /*      Does this look like a CUBE dataset?                             */
    /* -------------------------------------------------------------------- */
    if (!Identify(poOpenInfo))
        return nullptr;

    /* -------------------------------------------------------------------- */
    /*      Open the file using the large file API.                         */
    /* -------------------------------------------------------------------- */
    ISIS3Dataset *poDS = new ISIS3Dataset();

    if (!poDS->m_oKeywords.Ingest(poOpenInfo->fpL, 0))
    {
        VSIFCloseL(poOpenInfo->fpL);
        poOpenInfo->fpL = nullptr;
        delete poDS;
        return nullptr;
    }
    poDS->m_oJSonLabel = poDS->m_oKeywords.GetJsonObject();
    poDS->m_oJSonLabel.Add("_filename", poOpenInfo->pszFilename);

    // Find additional files from the label
    for (const CPLJSONObject &oObj : poDS->m_oJSonLabel.GetChildren())
    {
        if (oObj.GetType() == CPLJSONObject::Type::Object)
        {
            CPLString osContainerName = oObj.GetName();
            CPLJSONObject oContainerName = oObj.GetObj("_container_name");
            if (oContainerName.GetType() == CPLJSONObject::Type::String)
            {
                osContainerName = oContainerName.ToString();
            }

            CPLJSONObject oFilename = oObj.GetObj("^" + osContainerName);
            if (oFilename.GetType() == CPLJSONObject::Type::String)
            {
                VSIStatBufL sStat;
                CPLString osFilename(
                    CPLFormFilename(CPLGetPath(poOpenInfo->pszFilename),
                                    oFilename.ToString().c_str(), nullptr));
                if (VSIStatL(osFilename, &sStat) == 0)
                {
                    poDS->m_aosAdditionalFiles.AddString(osFilename);
                }
                else
                {
                    CPLDebug("ISIS3", "File %s referenced but not foud",
                             osFilename.c_str());
                }
            }
        }
    }

    VSIFCloseL(poOpenInfo->fpL);
    poOpenInfo->fpL = nullptr;

    /* -------------------------------------------------------------------- */
    /* Assume user is pointing to label (i.e. .lbl) file for detached option */
    /* -------------------------------------------------------------------- */
    //  Image can be inline or detached and point to an image name
    //  the Format can be Tiled or Raw
    //  Object = Core
    //      StartByte   = 65537
    //      Format      = Tile
    //      TileSamples = 128
    //      TileLines   = 128
    // OR-----
    //  Object = Core
    //      StartByte = 1
    //      ^Core     = r0200357_detatched.cub
    //      Format    = BandSequential
    // OR-----
    //  Object = Core
    //      StartByte = 1
    //      ^Core     = r0200357_detached_tiled.cub
    //      Format      = Tile
    //      TileSamples = 128
    //      TileLines   = 128
    // OR-----
    //  Object = Core
    //      StartByte = 1
    //      ^Core     = some.tif
    //      Format    = GeoTIFF

    /* -------------------------------------------------------------------- */
    /*      What file contains the actual data?                             */
    /* -------------------------------------------------------------------- */
    const char *pszCore = poDS->GetKeyword("IsisCube.Core.^Core");
    CPLString osQubeFile;

    if (EQUAL(pszCore, ""))
        osQubeFile = poOpenInfo->pszFilename;
    else
    {
        CPLString osPath = CPLGetPath(poOpenInfo->pszFilename);
        osQubeFile = CPLFormFilename(osPath, pszCore, nullptr);
        poDS->m_osExternalFilename = osQubeFile;
    }

    /* -------------------------------------------------------------------- */
    /*      Check if file an ISIS3 header file?  Read a few lines of text   */
    /*      searching for something starting with nrows or ncols.           */
    /* -------------------------------------------------------------------- */

    /*************   Skipbytes     *****************************/
    int nSkipBytes = atoi(poDS->GetKeyword("IsisCube.Core.StartByte", "1"));
    if (nSkipBytes <= 1)
        nSkipBytes = 0;
    else
        nSkipBytes -= 1;

    /*******   Grab format type (BandSequential, Tiled)  *******/
    CPLString osFormat = poDS->GetKeyword("IsisCube.Core.Format");

    int tileSizeX = 0;
    int tileSizeY = 0;

    if (EQUAL(osFormat, "Tile"))
    {
        poDS->m_bIsTiled = true;
        /******* Get Tile Sizes *********/
        tileSizeX = atoi(poDS->GetKeyword("IsisCube.Core.TileSamples"));
        tileSizeY = atoi(poDS->GetKeyword("IsisCube.Core.TileLines"));
        if (tileSizeX <= 0 || tileSizeY <= 0)
        {
            CPLError(CE_Failure, CPLE_OpenFailed,
                     "Wrong tile dimensions : %d x %d", tileSizeX, tileSizeY);
            delete poDS;
            return nullptr;
        }
    }
    else if (!EQUAL(osFormat, "BandSequential") && !EQUAL(osFormat, "GeoTIFF"))
    {
        CPLError(CE_Failure, CPLE_OpenFailed, "%s format not supported.",
                 osFormat.c_str());
        delete poDS;
        return nullptr;
    }

    /***********   Grab samples lines band ************/
    const int nCols =
        atoi(poDS->GetKeyword("IsisCube.Core.Dimensions.Samples"));
    const int nRows = atoi(poDS->GetKeyword("IsisCube.Core.Dimensions.Lines"));
    const int nBands = atoi(poDS->GetKeyword("IsisCube.Core.Dimensions.Bands"));

    /****** Grab format type - ISIS3 only supports 8,U16,S16,32 *****/
    GDALDataType eDataType = GDT_Byte;
    double dfNoData = 0.0;

    const char *itype = poDS->GetKeyword("IsisCube.Core.Pixels.Type");
    if (EQUAL(itype, "UnsignedByte"))
    {
        eDataType = GDT_Byte;
        dfNoData = NULL1;
    }
    else if (EQUAL(itype, "UnsignedWord"))
    {
        eDataType = GDT_UInt16;
        dfNoData = NULLU2;
    }
    else if (EQUAL(itype, "SignedWord"))
    {
        eDataType = GDT_Int16;
        dfNoData = NULL2;
    }
    else if (EQUAL(itype, "Real") || EQUAL(itype, ""))
    {
        eDataType = GDT_Float32;
        dfNoData = NULL4;
    }
    else
    {
        CPLError(CE_Failure, CPLE_OpenFailed, "%s pixel type not supported.",
                 itype);
        delete poDS;
        return nullptr;
    }

    /***********   Grab samples lines band ************/

    // default to MSB
    const bool bIsLSB =
        EQUAL(poDS->GetKeyword("IsisCube.Core.Pixels.ByteOrder"), "Lsb");

    /***********   Grab Cellsize ************/
    double dfXDim = 1.0;
    double dfYDim = 1.0;

    const char *pszRes = poDS->GetKeyword("IsisCube.Mapping.PixelResolution");
    if (strlen(pszRes) > 0)
    {
        dfXDim = CPLAtof(pszRes); /* values are in meters */
        dfYDim = -CPLAtof(pszRes);
    }

    /***********   Grab UpperLeftCornerY ************/
    double dfULYMap = 0.5;

    const char *pszULY = poDS->GetKeyword("IsisCube.Mapping.UpperLeftCornerY");
    if (strlen(pszULY) > 0)
    {
        dfULYMap = CPLAtof(pszULY);
    }

    /***********   Grab UpperLeftCornerX ************/
    double dfULXMap = 0.5;

    const char *pszULX = poDS->GetKeyword("IsisCube.Mapping.UpperLeftCornerX");
    if (strlen(pszULX) > 0)
    {
        dfULXMap = CPLAtof(pszULX);
    }

    /***********  Grab TARGET_NAME  ************/
    /**** This is the planets name i.e. Mars ***/
    const char *target_name = poDS->GetKeyword("IsisCube.Mapping.TargetName");

#ifdef notdef
    const double dfLongitudeMulFactor =
        EQUAL(poDS->GetKeyword("IsisCube.Mapping.LongitudeDirection",
                               "PositiveEast"),
              "PositiveEast")
            ? 1
            : -1;
#else
    const double dfLongitudeMulFactor = 1;
#endif

    /***********   Grab MAP_PROJECTION_TYPE ************/
    const char *map_proj_name =
        poDS->GetKeyword("IsisCube.Mapping.ProjectionName");

    /***********   Grab SEMI-MAJOR ************/
    const double semi_major =
        CPLAtof(poDS->GetKeyword("IsisCube.Mapping.EquatorialRadius"));

    /***********   Grab semi-minor ************/
    const double semi_minor =
        CPLAtof(poDS->GetKeyword("IsisCube.Mapping.PolarRadius"));

    /***********   Grab CENTER_LAT ************/
    const double center_lat =
        CPLAtof(poDS->GetKeyword("IsisCube.Mapping.CenterLatitude"));

    /***********   Grab CENTER_LON ************/
    const double center_lon =
        CPLAtof(poDS->GetKeyword("IsisCube.Mapping.CenterLongitude")) *
        dfLongitudeMulFactor;

    /***********   Grab 1st std parallel ************/
    const double first_std_parallel =
        CPLAtof(poDS->GetKeyword("IsisCube.Mapping.FirstStandardParallel"));

    /***********   Grab 2nd std parallel ************/
    const double second_std_parallel =
        CPLAtof(poDS->GetKeyword("IsisCube.Mapping.SecondStandardParallel"));

    /***********   Grab scaleFactor ************/
    const double scaleFactor =
        CPLAtof(poDS->GetKeyword("IsisCube.Mapping.scaleFactor", "1.0"));

    /*** grab      LatitudeType = Planetographic ****/
    // Need to further study how ocentric/ographic will effect the gdal library
    // So far we will use this fact to define a sphere or ellipse for some
    // projections

    // Frank - may need to talk this over
    bool bIsGeographic = true;
    if (EQUAL(poDS->GetKeyword("IsisCube.Mapping.LatitudeType"),
              "Planetocentric"))
        bIsGeographic = false;

        // Set oSRS projection and parameters
        // ############################################################
        // ISIS3 Projection types
        //   Equirectangular
        //   LambertConformal
        //   Mercator
        //   ObliqueCylindrical
        //   Orthographic
        //   PolarStereographic
        //   SimpleCylindrical
        //   Sinusoidal
        //   TransverseMercator

#ifdef DEBUG
    CPLDebug("ISIS3", "using projection %s", map_proj_name);
#endif

    OGRSpatialReference oSRS;
    bool bProjectionSet = true;

    if ((EQUAL(map_proj_name, "Equirectangular")) ||
        (EQUAL(map_proj_name, "SimpleCylindrical")))
    {
        oSRS.SetEquirectangular2(0.0, center_lon, center_lat, 0, 0);
    }
    else if (EQUAL(map_proj_name, "Orthographic"))
    {
        oSRS.SetOrthographic(center_lat, center_lon, 0, 0);
    }
    else if (EQUAL(map_proj_name, "Sinusoidal"))
    {
        oSRS.SetSinusoidal(center_lon, 0, 0);
    }
    else if (EQUAL(map_proj_name, "Mercator"))
    {
        oSRS.SetMercator(center_lat, center_lon, scaleFactor, 0, 0);
    }
    else if (EQUAL(map_proj_name, "PolarStereographic"))
    {
        oSRS.SetPS(center_lat, center_lon, scaleFactor, 0, 0);
    }
    else if (EQUAL(map_proj_name, "TransverseMercator"))
    {
        oSRS.SetTM(center_lat, center_lon, scaleFactor, 0, 0);
    }
    else if (EQUAL(map_proj_name, "LambertConformal"))
    {
        oSRS.SetLCC(first_std_parallel, second_std_parallel, center_lat,
                    center_lon, 0, 0);
    }
    else if (EQUAL(map_proj_name, "PointPerspective"))
    {
        // Distance parameter is the distance to the center of the body, and is
        // given in km
        const double distance =
            CPLAtof(poDS->GetKeyword("IsisCube.Mapping.Distance")) * 1000.0;
        const double height_above_ground = distance - semi_major;
        oSRS.SetVerticalPerspective(center_lat, center_lon, 0,
                                    height_above_ground, 0, 0);
    }
    else if (EQUAL(map_proj_name, "ObliqueCylindrical"))
    {
        const double poleLatitude =
            CPLAtof(poDS->GetKeyword("IsisCube.Mapping.PoleLatitude"));
        const double poleLongitude =
            CPLAtof(poDS->GetKeyword("IsisCube.Mapping.PoleLongitude")) *
            dfLongitudeMulFactor;
        const double poleRotation =
            CPLAtof(poDS->GetKeyword("IsisCube.Mapping.PoleRotation"));
        CPLString oProj4String;
        // ISIS3 rotated pole doesn't use the same conventions than PROJ ob_tran
        // Compare the sign difference in
        // https://github.com/USGS-Astrogeology/ISIS3/blob/3.8.0/isis/src/base/objs/ObliqueCylindrical/ObliqueCylindrical.cpp#L244
        // and
        // https://github.com/OSGeo/PROJ/blob/6.2/src/projections/ob_tran.cpp#L34
        // They can be compensated by modifying the poleLatitude to
        // 180-poleLatitude There's also a sign difference for the poleRotation
        // parameter The existence of those different conventions is
        // acknowledged in
        // https://pds-imaging.jpl.nasa.gov/documentation/Cassini_BIDRSIS.PDF in
        // the middle of page 10
        oProj4String.Printf("+proj=ob_tran +o_proj=eqc +o_lon_p=%.18g "
                            "+o_lat_p=%.18g +lon_0=%.18g",
                            -poleRotation, 180 - poleLatitude, poleLongitude);
        oSRS.SetFromUserInput(oProj4String);
    }
    else
    {
        CPLDebug("ISIS3",
                 "Dataset projection %s is not supported. Continuing...",
                 map_proj_name);
        bProjectionSet = false;
    }

    if (bProjectionSet)
    {
        // Create projection name, i.e. MERCATOR MARS and set as ProjCS keyword
        CPLString osProjTargetName(map_proj_name);
        osProjTargetName += " ";
        osProjTargetName += target_name;
        oSRS.SetProjCS(osProjTargetName);  // set ProjCS keyword

        // The geographic/geocentric name will be the same basic name as the
        // body name 'GCS' = Geographic/Geocentric Coordinate System
        CPLString osGeogName("GCS_");
        osGeogName += target_name;

        // The datum name will be the same basic name as the planet
        CPLString osDatumName("D_");
        osDatumName += target_name;

        CPLString osSphereName(target_name);
        // strcat(osSphereName, "_IAU_IAG");  //Might not be IAU defined so
        // don't add

        // calculate inverse flattening from major and minor axis: 1/f = a/(a-b)
        double iflattening = 0.0;
        if ((semi_major - semi_minor) < 0.0000001)
            iflattening = 0;
        else
            iflattening = semi_major / (semi_major - semi_minor);

        // Set the body size but take into consideration which proj is being
        // used to help w/ proj4 compatibility The use of a Sphere, polar radius
        // or ellipse here is based on how ISIS does it internally
        if (((EQUAL(map_proj_name, "Stereographic") &&
              (fabs(center_lat) == 90))) ||
            (EQUAL(map_proj_name, "PolarStereographic")))
        {
            if (bIsGeographic)
            {
                // Geograpraphic, so set an ellipse
                oSRS.SetGeogCS(osGeogName, osDatumName, osSphereName,
                               semi_major, iflattening, "Reference_Meridian",
                               0.0);
            }
            else
            {
                // Geocentric, so force a sphere using the semi-minor axis. I
                // hope...
                osSphereName += "_polarRadius";
                oSRS.SetGeogCS(osGeogName, osDatumName, osSphereName,
                               semi_minor, 0.0, "Reference_Meridian", 0.0);
            }
        }
        else if ((EQUAL(map_proj_name, "SimpleCylindrical")) ||
                 (EQUAL(map_proj_name, "Orthographic")) ||
                 (EQUAL(map_proj_name, "Stereographic")) ||
                 (EQUAL(map_proj_name, "Sinusoidal")) ||
                 (EQUAL(map_proj_name, "PointPerspective")))
        {
            // ISIS uses the spherical equation for these projections
            // so force a sphere.
            oSRS.SetGeogCS(osGeogName, osDatumName, osSphereName, semi_major,
                           0.0, "Reference_Meridian", 0.0);
        }
        else if (EQUAL(map_proj_name, "Equirectangular"))
        {
            // Calculate localRadius using ISIS3 simple elliptical method
            //   not the more standard Radius of Curvature method
            // PI = 4 * atan(1);
            const double radLat = center_lat * M_PI / 180;  // in radians
            const double meanRadius = sqrt(pow(semi_minor * cos(radLat), 2) +
                                           pow(semi_major * sin(radLat), 2));
            const double localRadius =
                (meanRadius == 0.0) ? 0.0
                                    : semi_major * semi_minor / meanRadius;
            osSphereName += "_localRadius";
            oSRS.SetGeogCS(osGeogName, osDatumName, osSphereName, localRadius,
                           0.0, "Reference_Meridian", 0.0);
        }
        else
        {
            // All other projections: Mercator, Transverse Mercator, Lambert
            // Conformal, etc. Geographic, so set an ellipse
            if (bIsGeographic)
            {
                oSRS.SetGeogCS(osGeogName, osDatumName, osSphereName,
                               semi_major, iflattening, "Reference_Meridian",
                               0.0);
            }
            else
            {
                // Geocentric, so force a sphere. I hope...
                oSRS.SetGeogCS(osGeogName, osDatumName, osSphereName,
                               semi_major, 0.0, "Reference_Meridian", 0.0);
            }
        }

        // translate back into a projection string.
        poDS->m_oSRS = oSRS;
        poDS->m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    }

    /* END ISIS3 Label Read */
    /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

    /* -------------------------------------------------------------------- */
    /*      Did we get the required keywords?  If not we return with        */
    /*      this never having been considered to be a match. This isn't     */
    /*      an error!                                                       */
    /* -------------------------------------------------------------------- */
    if (!GDALCheckDatasetDimensions(nCols, nRows) ||
        !GDALCheckBandCount(nBands, false))
    {
        delete poDS;
        return nullptr;
    }

    /* -------------------------------------------------------------------- */
    /*      Capture some information from the file that is of interest.     */
    /* -------------------------------------------------------------------- */
    poDS->nRasterXSize = nCols;
    poDS->nRasterYSize = nRows;

    /* -------------------------------------------------------------------- */
    /*      Open target binary file.                                        */
    /* -------------------------------------------------------------------- */
    if (EQUAL(osFormat, "GeoTIFF"))
    {
        if (nSkipBytes != 0)
        {
            CPLError(CE_Warning, CPLE_NotSupported,
                     "Ignoring StartByte=%d for format=GeoTIFF",
                     1 + nSkipBytes);
        }
        if (osQubeFile == poOpenInfo->pszFilename)
        {
            CPLError(CE_Failure, CPLE_AppDefined, "A ^Core file must be set");
            delete poDS;
            return nullptr;
        }
        poDS->m_poExternalDS = reinterpret_cast<GDALDataset *>(
            GDALOpen(osQubeFile, poOpenInfo->eAccess));
        if (poDS->m_poExternalDS == nullptr)
        {
            delete poDS;
            return nullptr;
        }
        if (poDS->m_poExternalDS->GetRasterXSize() != poDS->nRasterXSize ||
            poDS->m_poExternalDS->GetRasterYSize() != poDS->nRasterYSize ||
            poDS->m_poExternalDS->GetRasterCount() != nBands ||
            poDS->m_poExternalDS->GetRasterBand(1)->GetRasterDataType() !=
                eDataType)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "%s has incompatible characteristics with the ones "
                     "declared in the label.",
                     osQubeFile.c_str());
            delete poDS;
            return nullptr;
        }
    }
    else
    {
        if (poOpenInfo->eAccess == GA_ReadOnly)
            poDS->m_fpImage = VSIFOpenL(osQubeFile, "r");
        else
            poDS->m_fpImage = VSIFOpenL(osQubeFile, "r+");

        if (poDS->m_fpImage == nullptr)
        {
            CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open %s: %s.",
                     osQubeFile.c_str(), VSIStrerror(errno));
            delete poDS;
            return nullptr;
        }

        // Sanity checks in case the external raw file appears to be a
        // TIFF file
        if (EQUAL(CPLGetExtension(osQubeFile), "tif"))
        {
            GDALDataset *poTIF_DS = reinterpret_cast<GDALDataset *>(
                GDALOpen(osQubeFile, GA_ReadOnly));
            if (poTIF_DS)
            {
                bool bWarned = false;
                if (poTIF_DS->GetRasterXSize() != poDS->nRasterXSize ||
                    poTIF_DS->GetRasterYSize() != poDS->nRasterYSize ||
                    poTIF_DS->GetRasterCount() != nBands ||
                    poTIF_DS->GetRasterBand(1)->GetRasterDataType() !=
                        eDataType ||
                    poTIF_DS->GetMetadataItem("COMPRESSION",
                                              "IMAGE_STRUCTURE") != nullptr)
                {
                    bWarned = true;
                    CPLError(
                        CE_Warning, CPLE_AppDefined,
                        "%s has incompatible characteristics with the ones "
                        "declared in the label.",
                        osQubeFile.c_str());
                }
                int nBlockXSize = 1, nBlockYSize = 1;
                poTIF_DS->GetRasterBand(1)->GetBlockSize(&nBlockXSize,
                                                         &nBlockYSize);
                if ((poDS->m_bIsTiled &&
                     (nBlockXSize != tileSizeX || nBlockYSize != tileSizeY)) ||
                    (!poDS->m_bIsTiled && (nBlockXSize != nCols ||
                                           (nBands > 1 && nBlockYSize != 1))))
                {
                    if (!bWarned)
                    {
                        bWarned = true;
                        CPLError(
                            CE_Warning, CPLE_AppDefined,
                            "%s has incompatible characteristics with the ones "
                            "declared in the label.",
                            osQubeFile.c_str());
                    }
                }
                // to please Clang Static Analyzer
                nBlockXSize = std::max(1, nBlockXSize);
                nBlockYSize = std::max(1, nBlockYSize);

                // Check that blocks are effectively written in expected order.
                const int nBlockSizeBytes = nBlockXSize * nBlockYSize *
                                            GDALGetDataTypeSizeBytes(eDataType);
                bool bGoOn = !bWarned;
                const int l_nBlocksPerRow = DIV_ROUND_UP(nCols, nBlockXSize);
                const int l_nBlocksPerColumn = DIV_ROUND_UP(nRows, nBlockYSize);
                int nBlockNo = 0;
                for (int i = 0; i < nBands && bGoOn; i++)
                {
                    for (int y = 0; y < l_nBlocksPerColumn && bGoOn; y++)
                    {
                        for (int x = 0; x < l_nBlocksPerRow && bGoOn; x++)
                        {
                            const char *pszBlockOffset =
                                poTIF_DS->GetRasterBand(i + 1)->GetMetadataItem(
                                    CPLSPrintf("BLOCK_OFFSET_%d_%d", x, y),
                                    "TIFF");
                            if (pszBlockOffset)
                            {
                                GIntBig nOffset = CPLAtoGIntBig(pszBlockOffset);
                                if (nOffset !=
                                    nSkipBytes + nBlockNo * nBlockSizeBytes)
                                {
                                    // bWarned = true;
                                    CPLError(CE_Warning, CPLE_AppDefined,
                                             "%s has incompatible "
                                             "characteristics with the ones "
                                             "declared in the label.",
                                             osQubeFile.c_str());
                                    bGoOn = false;
                                }
                            }
                            nBlockNo++;
                        }
                    }
                }

                delete poTIF_DS;
            }
        }
    }

    poDS->eAccess = poOpenInfo->eAccess;

    /* -------------------------------------------------------------------- */
    /*      Compute the line offset.                                        */
    /* -------------------------------------------------------------------- */
    int nLineOffset = 0;
    int nPixelOffset = 0;
    vsi_l_offset nBandOffset = 0;

    if (EQUAL(osFormat, "BandSequential"))
    {
        const int nItemSize = GDALGetDataTypeSizeBytes(eDataType);
        nPixelOffset = nItemSize;
        try
        {
            nLineOffset = (CPLSM(nPixelOffset) * CPLSM(nCols)).v();
        }
        catch (const CPLSafeIntOverflow &)
        {
            delete poDS;
            return nullptr;
        }
        nBandOffset = static_cast<vsi_l_offset>(nLineOffset) * nRows;

        poDS->m_sLayout.osRawFilename = osQubeFile;
        if (nBands > 1)
            poDS->m_sLayout.eInterleaving = RawBinaryLayout::Interleaving::BSQ;
        poDS->m_sLayout.eDataType = eDataType;
        poDS->m_sLayout.bLittleEndianOrder = bIsLSB;
        poDS->m_sLayout.nImageOffset = nSkipBytes;
        poDS->m_sLayout.nPixelOffset = nPixelOffset;
        poDS->m_sLayout.nLineOffset = nLineOffset;
        poDS->m_sLayout.nBandOffset = static_cast<GIntBig>(nBandOffset);
    }
    /* else Tiled or external */

    /* -------------------------------------------------------------------- */
    /*      Extract BandBin info.                                           */
    /* -------------------------------------------------------------------- */
    std::vector<std::string> aosBandNames;
    std::vector<std::string> aosBandUnits;
    std::vector<double> adfWavelengths;
    std::vector<std::string> aosWavelengthsUnit;
    std::vector<double> adfBandwidth;
    std::vector<std::string> aosBandwidthUnit;
    const auto oBandBin = poDS->m_oJSonLabel.GetObj("IsisCube/BandBin");
    if (oBandBin.IsValid() && oBandBin.GetType() == CPLJSONObject::Type::Object)
    {
        for (const auto &child : oBandBin.GetChildren())
        {
            if (CPLString(child.GetName()).ifind("name") != std::string::npos)
            {
                // Use "name" in priority
                if (EQUAL(child.GetName().c_str(), "name"))
                {
                    aosBandNames.clear();
                }
                else if (!aosBandNames.empty())
                {
                    continue;
                }

                if (child.GetType() == CPLJSONObject::Type::String &&
                    nBands == 1)
                {
                    aosBandNames.push_back(child.ToString());
                }
                else if (child.GetType() == CPLJSONObject::Type::Array)
                {
                    auto oArray = child.ToArray();
                    if (oArray.Size() == nBands)
                    {
                        for (int i = 0; i < nBands; i++)
                        {
                            if (oArray[i].GetType() ==
                                CPLJSONObject::Type::String)
                            {
                                aosBandNames.push_back(oArray[i].ToString());
                            }
                            else
                            {
                                aosBandNames.clear();
                                break;
                            }
                        }
                    }
                }
            }
            else if (EQUAL(child.GetName().c_str(), "BandSuffixUnit") &&
                     child.GetType() == CPLJSONObject::Type::Array)
            {
                auto oArray = child.ToArray();
                if (oArray.Size() == nBands)
                {
                    for (int i = 0; i < nBands; i++)
                    {
                        if (oArray[i].GetType() == CPLJSONObject::Type::String)
                        {
                            aosBandUnits.push_back(oArray[i].ToString());
                        }
                        else
                        {
                            aosBandUnits.clear();
                            break;
                        }
                    }
                }
            }
            else if (EQUAL(child.GetName().c_str(), "BandBinCenter") ||
                     EQUAL(child.GetName().c_str(), "Center"))
            {
                GetValueAndUnits(child, adfWavelengths, aosWavelengthsUnit,
                                 nBands);
            }
            else if (EQUAL(child.GetName().c_str(), "BandBinUnit") &&
                     child.GetType() == CPLJSONObject::Type::String)
            {
                CPLString unit(child.ToString());
                if (STARTS_WITH_CI(unit, "micromet") || EQUAL(unit, "um") ||
                    STARTS_WITH_CI(unit, "nanomet") || EQUAL(unit, "nm"))
                {
                    aosWavelengthsUnit.push_back(child.ToString());
                }
            }
            else if (EQUAL(child.GetName().c_str(), "Width"))
            {
                GetValueAndUnits(child, adfBandwidth, aosBandwidthUnit, nBands);
            }
        }

        if (!adfWavelengths.empty() && aosWavelengthsUnit.size() == 1)
        {
            for (int i = 1; i < nBands; i++)
            {
                aosWavelengthsUnit.push_back(aosWavelengthsUnit[0]);
            }
        }
        if (!adfBandwidth.empty() && aosBandwidthUnit.size() == 1)
        {
            for (int i = 1; i < nBands; i++)
            {
                aosBandwidthUnit.push_back(aosBandwidthUnit[0]);
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Create band information objects.                                */
/* -------------------------------------------------------------------- */
#ifdef CPL_LSB
    const bool bNativeOrder = bIsLSB;
#else
    const bool bNativeOrder = !bIsLSB;
#endif

    for (int i = 0; i < nBands; i++)
    {
        GDALRasterBand *poBand = nullptr;

        if (poDS->m_poExternalDS != nullptr)
        {
            ISIS3WrapperRasterBand *poISISBand = new ISIS3WrapperRasterBand(
                poDS->m_poExternalDS->GetRasterBand(i + 1));
            poBand = poISISBand;
            poDS->SetBand(i + 1, poBand);

            poISISBand->SetMaskBand(new ISISMaskBand(poISISBand));
        }
        else if (poDS->m_bIsTiled)
        {
            CPLErrorReset();
            ISISTiledBand *poISISBand = new ISISTiledBand(
                poDS, poDS->m_fpImage, i + 1, eDataType, tileSizeX, tileSizeY,
                nSkipBytes, 0, 0, bNativeOrder);
            if (CPLGetLastErrorType() != CE_None)
            {
                delete poISISBand;
                delete poDS;
                return nullptr;
            }
            poBand = poISISBand;
            poDS->SetBand(i + 1, poBand);

            poISISBand->SetMaskBand(new ISISMaskBand(poISISBand));
        }
        else
        {
            ISIS3RawRasterBand *poISISBand = new ISIS3RawRasterBand(
                poDS, i + 1, poDS->m_fpImage, nSkipBytes + nBandOffset * i,
                nPixelOffset, nLineOffset, eDataType, bNativeOrder);

            poBand = poISISBand;
            poDS->SetBand(i + 1, poBand);

            poISISBand->SetMaskBand(new ISISMaskBand(poISISBand));
        }

        if (i < static_cast<int>(aosBandNames.size()))
        {
            poBand->SetDescription(aosBandNames[i].c_str());
        }
        if (i < static_cast<int>(adfWavelengths.size()) &&
            i < static_cast<int>(aosWavelengthsUnit.size()))
        {
            poBand->SetMetadataItem("WAVELENGTH",
                                    CPLSPrintf("%f", adfWavelengths[i]));
            poBand->SetMetadataItem("WAVELENGTH_UNIT",
                                    aosWavelengthsUnit[i].c_str());
            if (i < static_cast<int>(adfBandwidth.size()) &&
                i < static_cast<int>(aosBandwidthUnit.size()))
            {
                poBand->SetMetadataItem("BANDWIDTH",
                                        CPLSPrintf("%f", adfBandwidth[i]));
                poBand->SetMetadataItem("BANDWIDTH_UNIT",
                                        aosBandwidthUnit[i].c_str());
            }
        }
        if (i < static_cast<int>(aosBandUnits.size()))
        {
            poBand->SetUnitType(aosBandUnits[i].c_str());
        }

        poBand->SetNoDataValue(dfNoData);

        // Set offset/scale values.
        const double dfOffset =
            CPLAtofM(poDS->GetKeyword("IsisCube.Core.Pixels.Base", "0.0"));
        const double dfScale = CPLAtofM(
            poDS->GetKeyword("IsisCube.Core.Pixels.Multiplier", "1.0"));
        if (dfOffset != 0.0 || dfScale != 1.0)
        {
            poBand->SetOffset(dfOffset);
            poBand->SetScale(dfScale);
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Check for a .prj file. For ISIS3 I would like to keep this in   */
    /* -------------------------------------------------------------------- */
    const CPLString osPath = CPLGetPath(poOpenInfo->pszFilename);
    const CPLString osName = CPLGetBasename(poOpenInfo->pszFilename);
    const char *pszPrjFile = CPLFormCIFilename(osPath, osName, "prj");

    VSILFILE *fp = VSIFOpenL(pszPrjFile, "r");
    if (fp != nullptr)
    {
        VSIFCloseL(fp);

        char **papszLines = CSLLoad(pszPrjFile);

        OGRSpatialReference oSRS2;
        if (oSRS2.importFromESRI(papszLines) == OGRERR_NONE)
        {
            poDS->m_aosAdditionalFiles.AddString(pszPrjFile);
            poDS->m_oSRS = oSRS2;
            poDS->m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
        }

        CSLDestroy(papszLines);
    }

    if (dfULXMap != 0.5 || dfULYMap != 0.5 || dfXDim != 1.0 || dfYDim != 1.0)
    {
        poDS->m_bGotTransform = true;
        poDS->m_adfGeoTransform[0] = dfULXMap;
        poDS->m_adfGeoTransform[1] = dfXDim;
        poDS->m_adfGeoTransform[2] = 0.0;
        poDS->m_adfGeoTransform[3] = dfULYMap;
        poDS->m_adfGeoTransform[4] = 0.0;
        poDS->m_adfGeoTransform[5] = dfYDim;
    }

    if (!poDS->m_bGotTransform)
    {
        poDS->m_bGotTransform = CPL_TO_BOOL(GDALReadWorldFile(
            poOpenInfo->pszFilename, "cbw", poDS->m_adfGeoTransform));
        if (poDS->m_bGotTransform)
        {
            poDS->m_aosAdditionalFiles.AddString(
                CPLResetExtension(poOpenInfo->pszFilename, "cbw"));
        }
    }

    if (!poDS->m_bGotTransform)
    {
        poDS->m_bGotTransform = CPL_TO_BOOL(GDALReadWorldFile(
            poOpenInfo->pszFilename, "wld", poDS->m_adfGeoTransform));
        if (poDS->m_bGotTransform)
        {
            poDS->m_aosAdditionalFiles.AddString(
                CPLResetExtension(poOpenInfo->pszFilename, "wld"));
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Initialize any PAM information.                                 */
    /* -------------------------------------------------------------------- */
    poDS->SetDescription(poOpenInfo->pszFilename);
    poDS->TryLoadXML();

    /* -------------------------------------------------------------------- */
    /*      Check for overviews.                                            */
    /* -------------------------------------------------------------------- */
    poDS->oOvManager.Initialize(poDS, poOpenInfo->pszFilename);

    return poDS;
}

/************************************************************************/
/*                             GetKeyword()                             */
/************************************************************************/

const char *ISIS3Dataset::GetKeyword(const char *pszPath,
                                     const char *pszDefault)

{
    return m_oKeywords.GetKeyword(pszPath, pszDefault);
}

/************************************************************************/
/*                              FixLong()                               */
/************************************************************************/

double ISIS3Dataset::FixLong(double dfLong)
{
    if (m_osLongitudeDirection == "PositiveWest")
        dfLong = -dfLong;
    if (m_bForce360 && dfLong < 0)
        dfLong += 360.0;
    return dfLong;
}

/************************************************************************/
/*                           BuildLabel()                               */
/************************************************************************/

void ISIS3Dataset::BuildLabel()
{
    CPLJSONObject oLabel = m_oSrcJSonLabel;
    if (!oLabel.IsValid())
    {
        oLabel = CPLJSONObject();
    }
    // If we have a source label, then edit it directly
    CPLJSONObject oIsisCube = GetOrCreateJSONObject(oLabel, "IsisCube");
    oIsisCube.Set("_type", "object");

    if (!m_osComment.empty())
        oIsisCube.Set("_comment", m_osComment);

    CPLJSONObject oCore = GetOrCreateJSONObject(oIsisCube, "Core");
    if (oCore.GetType() != CPLJSONObject::Type::Object)
    {
        oIsisCube.Delete("Core");
        oCore = CPLJSONObject();
        oIsisCube.Add("Core", oCore);
    }
    oCore.Set("_type", "object");

    if (!m_osExternalFilename.empty())
    {
        if (m_poExternalDS && m_bGeoTIFFAsRegularExternal)
        {
            if (!m_bGeoTIFFInitDone)
            {
                reinterpret_cast<ISIS3WrapperRasterBand *>(GetRasterBand(1))
                    ->InitFile();
            }

            const char *pszOffset =
                m_poExternalDS->GetRasterBand(1)->GetMetadataItem(
                    "BLOCK_OFFSET_0_0", "TIFF");
            if (pszOffset)
            {
                oCore.Set("StartByte", 1 + atoi(pszOffset));
            }
            else
            {
                // Shouldn't happen normally
                CPLError(CE_Warning, CPLE_AppDefined,
                         "Missing BLOCK_OFFSET_0_0");
                m_bGeoTIFFAsRegularExternal = false;
                oCore.Set("StartByte", 1);
            }
        }
        else
        {
            oCore.Set("StartByte", 1);
        }
        if (!m_osExternalFilename.empty())
        {
            const CPLString osExternalFilename =
                CPLGetFilename(m_osExternalFilename);
            oCore.Set("^Core", osExternalFilename);
        }
    }
    else
    {
        oCore.Set("StartByte", pszSTARTBYTE_PLACEHOLDER);
        oCore.Delete("^Core");
    }

    if (m_poExternalDS && !m_bGeoTIFFAsRegularExternal)
    {
        oCore.Set("Format", "GeoTIFF");
        oCore.Delete("TileSamples");
        oCore.Delete("TileLines");
    }
    else if (m_bIsTiled)
    {
        oCore.Set("Format", "Tile");
        int nBlockXSize = 1, nBlockYSize = 1;
        GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
        oCore.Set("TileSamples", nBlockXSize);
        oCore.Set("TileLines", nBlockYSize);
    }
    else
    {
        oCore.Set("Format", "BandSequential");
        oCore.Delete("TileSamples");
        oCore.Delete("TileLines");
    }

    CPLJSONObject oDimensions = GetOrCreateJSONObject(oCore, "Dimensions");
    oDimensions.Set("_type", "group");
    oDimensions.Set("Samples", nRasterXSize);
    oDimensions.Set("Lines", nRasterYSize);
    oDimensions.Set("Bands", nBands);

    CPLJSONObject oPixels = GetOrCreateJSONObject(oCore, "Pixels");
    oPixels.Set("_type", "group");
    const GDALDataType eDT = GetRasterBand(1)->GetRasterDataType();
    oPixels.Set("Type", (eDT == GDT_Byte)     ? "UnsignedByte"
                        : (eDT == GDT_UInt16) ? "UnsignedWord"
                        : (eDT == GDT_Int16)  ? "SignedWord"
                                              : "Real");

    oPixels.Set("ByteOrder", "Lsb");
    oPixels.Set("Base", GetRasterBand(1)->GetOffset());
    oPixels.Set("Multiplier", GetRasterBand(1)->GetScale());

    const OGRSpatialReference &oSRS = m_oSRS;

    if (!m_bUseSrcMapping)
    {
        oIsisCube.Delete("Mapping");
    }

    CPLJSONObject oMapping = GetOrCreateJSONObject(oIsisCube, "Mapping");
    if (m_bUseSrcMapping && oMapping.IsValid() &&
        oMapping.GetType() == CPLJSONObject::Type::Object)
    {
        if (!m_osTargetName.empty())
            oMapping.Set("TargetName", m_osTargetName);
        if (!m_osLatitudeType.empty())
            oMapping.Set("LatitudeType", m_osLatitudeType);
        if (!m_osLongitudeDirection.empty())
            oMapping.Set("LongitudeDirection", m_osLongitudeDirection);
    }
    else if (!m_bUseSrcMapping && !m_oSRS.IsEmpty())
    {
        oMapping.Add("_type", "group");

        if (oSRS.IsProjected() || oSRS.IsGeographic())
        {
            const char *pszDatum = oSRS.GetAttrValue("DATUM");
            CPLString osTargetName(m_osTargetName);
            if (osTargetName.empty())
            {
                if (pszDatum && STARTS_WITH(pszDatum, "D_"))
                {
                    osTargetName = pszDatum + 2;
                }
                else if (pszDatum)
                {
                    osTargetName = pszDatum;
                }
            }
            if (!osTargetName.empty())
                oMapping.Add("TargetName", osTargetName);

            oMapping.Add("EquatorialRadius/value", oSRS.GetSemiMajor());
            oMapping.Add("EquatorialRadius/unit", "meters");
            oMapping.Add("PolarRadius/value", oSRS.GetSemiMinor());
            oMapping.Add("PolarRadius/unit", "meters");

            if (!m_osLatitudeType.empty())
                oMapping.Add("LatitudeType", m_osLatitudeType);
            else
                oMapping.Add("LatitudeType", "Planetocentric");

            if (!m_osLongitudeDirection.empty())
                oMapping.Add("LongitudeDirection", m_osLongitudeDirection);
            else
                oMapping.Add("LongitudeDirection", "PositiveEast");

            double adfX[4] = {0};
            double adfY[4] = {0};
            bool bLongLatCorners = false;
            if (m_bGotTransform)
            {
                for (int i = 0; i < 4; i++)
                {
                    adfX[i] = m_adfGeoTransform[0] +
                              (i % 2) * nRasterXSize * m_adfGeoTransform[1];
                    adfY[i] = m_adfGeoTransform[3] +
                              ((i == 0 || i == 3) ? 0 : 1) * nRasterYSize *
                                  m_adfGeoTransform[5];
                }
                if (oSRS.IsGeographic())
                {
                    bLongLatCorners = true;
                }
                else
                {
                    OGRSpatialReference *poSRSLongLat = oSRS.CloneGeogCS();
                    if (poSRSLongLat)
                    {
                        poSRSLongLat->SetAxisMappingStrategy(
                            OAMS_TRADITIONAL_GIS_ORDER);
                        OGRCoordinateTransformation *poCT =
                            OGRCreateCoordinateTransformation(&oSRS,
                                                              poSRSLongLat);
                        if (poCT)
                        {
                            if (poCT->Transform(4, adfX, adfY))
                            {
                                bLongLatCorners = true;
                            }
                            delete poCT;
                        }
                        delete poSRSLongLat;
                    }
                }
            }
            if (bLongLatCorners)
            {
                for (int i = 0; i < 4; i++)
                {
                    adfX[i] = FixLong(adfX[i]);
                }
            }

            if (bLongLatCorners &&
                (m_bForce360 || adfX[0] < -180.0 || adfX[3] > 180.0))
            {
                oMapping.Add("LongitudeDomain", 360);
            }
            else
            {
                oMapping.Add("LongitudeDomain", 180);
            }

            if (m_bWriteBoundingDegrees && !m_osBoundingDegrees.empty())
            {
                char **papszTokens =
                    CSLTokenizeString2(m_osBoundingDegrees, ",", 0);
                if (CSLCount(papszTokens) == 4)
                {
                    oMapping.Add("MinimumLatitude", CPLAtof(papszTokens[1]));
                    oMapping.Add("MinimumLongitude", CPLAtof(papszTokens[0]));
                    oMapping.Add("MaximumLatitude", CPLAtof(papszTokens[3]));
                    oMapping.Add("MaximumLongitude", CPLAtof(papszTokens[2]));
                }
                CSLDestroy(papszTokens);
            }
            else if (m_bWriteBoundingDegrees && bLongLatCorners)
            {
                oMapping.Add("MinimumLatitude",
                             std::min(std::min(adfY[0], adfY[1]),
                                      std::min(adfY[2], adfY[3])));
                oMapping.Add("MinimumLongitude",
                             std::min(std::min(adfX[0], adfX[1]),
                                      std::min(adfX[2], adfX[3])));
                oMapping.Add("MaximumLatitude",
                             std::max(std::max(adfY[0], adfY[1]),
                                      std::max(adfY[2], adfY[3])));
                oMapping.Add("MaximumLongitude",
                             std::max(std::max(adfX[0], adfX[1]),
                                      std::max(adfX[2], adfX[3])));
            }

            const char *pszProjection = oSRS.GetAttrValue("PROJECTION");
            if (pszProjection == nullptr)
            {
                oMapping.Add("ProjectionName", "SimpleCylindrical");
                oMapping.Add("CenterLongitude", 0.0);
                oMapping.Add("CenterLatitude", 0.0);
                oMapping.Add("CenterLatitudeRadius", oSRS.GetSemiMajor());
            }
            else if (EQUAL(pszProjection, SRS_PT_EQUIRECTANGULAR))
            {
                oMapping.Add("ProjectionName", "Equirectangular");
                if (oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0) != 0.0)
                {
                    CPLError(CE_Warning, CPLE_NotSupported,
                             "Ignoring %s. Only 0 value supported",
                             SRS_PP_LATITUDE_OF_ORIGIN);
                }
                oMapping.Add("CenterLongitude",
                             FixLong(oSRS.GetNormProjParm(
                                 SRS_PP_CENTRAL_MERIDIAN, 0.0)));
                const double dfCenterLat =
                    oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, 0.0);
                oMapping.Add("CenterLatitude", dfCenterLat);

                // in radians
                const double radLat = dfCenterLat * M_PI / 180;
                const double semi_major = oSRS.GetSemiMajor();
                const double semi_minor = oSRS.GetSemiMinor();
                const double localRadius =
                    semi_major * semi_minor /
                    sqrt(pow(semi_minor * cos(radLat), 2) +
                         pow(semi_major * sin(radLat), 2));
                oMapping.Add("CenterLatitudeRadius", localRadius);
            }

            else if (EQUAL(pszProjection, SRS_PT_ORTHOGRAPHIC))
            {
                oMapping.Add("ProjectionName", "Orthographic");
                oMapping.Add("CenterLongitude",
                             FixLong(oSRS.GetNormProjParm(
                                 SRS_PP_CENTRAL_MERIDIAN, 0.0)));
                oMapping.Add(
                    "CenterLatitude",
                    oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0));
            }

            else if (EQUAL(pszProjection, SRS_PT_SINUSOIDAL))
            {
                oMapping.Add("ProjectionName", "Sinusoidal");
                oMapping.Add("CenterLongitude",
                             FixLong(oSRS.GetNormProjParm(
                                 SRS_PP_LONGITUDE_OF_CENTER, 0.0)));
            }

            else if (EQUAL(pszProjection, SRS_PT_MERCATOR_1SP))
            {
                oMapping.Add("ProjectionName", "Mercator");
                oMapping.Add("CenterLongitude",
                             FixLong(oSRS.GetNormProjParm(
                                 SRS_PP_CENTRAL_MERIDIAN, 0.0)));
                oMapping.Add(
                    "CenterLatitude",
                    oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0));
                oMapping.Add("scaleFactor",
                             oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0));
            }

            else if (EQUAL(pszProjection, SRS_PT_POLAR_STEREOGRAPHIC))
            {
                oMapping.Add("ProjectionName", "PolarStereographic");
                oMapping.Add("CenterLongitude",
                             FixLong(oSRS.GetNormProjParm(
                                 SRS_PP_CENTRAL_MERIDIAN, 0.0)));
                oMapping.Add(
                    "CenterLatitude",
                    oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0));
                oMapping.Add("scaleFactor",
                             oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0));
            }

            else if (EQUAL(pszProjection, SRS_PT_TRANSVERSE_MERCATOR))
            {
                oMapping.Add("ProjectionName", "TransverseMercator");
                oMapping.Add("CenterLongitude",
                             FixLong(oSRS.GetNormProjParm(
                                 SRS_PP_CENTRAL_MERIDIAN, 0.0)));
                oMapping.Add(
                    "CenterLatitude",
                    oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0));
                oMapping.Add("scaleFactor",
                             oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0));
            }

            else if (EQUAL(pszProjection, SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP))
            {
                oMapping.Add("ProjectionName", "LambertConformal");
                oMapping.Add("CenterLongitude",
                             FixLong(oSRS.GetNormProjParm(
                                 SRS_PP_CENTRAL_MERIDIAN, 0.0)));
                oMapping.Add(
                    "CenterLatitude",
                    oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0));
                oMapping.Add(
                    "FirstStandardParallel",
                    oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, 0.0));
                oMapping.Add(
                    "SecondStandardParallel",
                    oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_2, 0.0));
            }

            else if (EQUAL(pszProjection,
                           "Vertical Perspective"))  // PROJ 7 required
            {
                oMapping.Add("ProjectionName", "PointPerspective");
                oMapping.Add("CenterLongitude",
                             FixLong(oSRS.GetNormProjParm(
                                 "Longitude of topocentric origin", 0.0)));
                oMapping.Add("CenterLatitude",
                             oSRS.GetNormProjParm(
                                 "Latitude of topocentric origin", 0.0));
                // ISIS3 value is the distance from center of ellipsoid, in km
                oMapping.Add("Distance",
                             (oSRS.GetNormProjParm("Viewpoint height", 0.0) +
                              oSRS.GetSemiMajor()) /
                                 1000.0);
            }

            else if (EQUAL(pszProjection, "custom_proj4"))
            {
                const char *pszProj4 =
                    oSRS.GetExtension("PROJCS", "PROJ4", nullptr);
                if (pszProj4 && strstr(pszProj4, "+proj=ob_tran") &&
                    strstr(pszProj4, "+o_proj=eqc"))
                {
                    const auto FetchParam =
                        [](const char *pszProj4Str, const char *pszKey)
                    {
                        CPLString needle;
                        needle.Printf("+%s=", pszKey);
                        const char *pszVal =
                            strstr(pszProj4Str, needle.c_str());
                        if (pszVal)
                            return CPLAtof(pszVal + needle.size());
                        return 0.0;
                    };

                    double dfLonP = FetchParam(pszProj4, "o_lon_p");
                    double dfLatP = FetchParam(pszProj4, "o_lat_p");
                    double dfLon0 = FetchParam(pszProj4, "lon_0");
                    double dfPoleRotation = -dfLonP;
                    double dfPoleLatitude = 180 - dfLatP;
                    double dfPoleLongitude = dfLon0;
                    oMapping.Add("ProjectionName", "ObliqueCylindrical");
                    oMapping.Add("PoleLatitude", dfPoleLatitude);
                    oMapping.Add("PoleLongitude", FixLong(dfPoleLongitude));
                    oMapping.Add("PoleRotation", dfPoleRotation);
                }
                else
                {
                    CPLError(CE_Warning, CPLE_NotSupported,
                             "Projection %s not supported", pszProjection);
                }
            }
            else
            {
                CPLError(CE_Warning, CPLE_NotSupported,
                         "Projection %s not supported", pszProjection);
            }

            if (oMapping["ProjectionName"].IsValid())
            {
                if (oSRS.GetNormProjParm(SRS_PP_FALSE_EASTING, 0.0) != 0.0)
                {
                    CPLError(CE_Warning, CPLE_NotSupported,
                             "Ignoring %s. Only 0 value supported",
                             SRS_PP_FALSE_EASTING);
                }
                if (oSRS.GetNormProjParm(SRS_PP_FALSE_NORTHING, 0.0) != 0.0)
                {
                    CPLError(CE_Warning, CPLE_AppDefined,
                             "Ignoring %s. Only 0 value supported",
                             SRS_PP_FALSE_NORTHING);
                }
            }
        }
        else
        {
            CPLError(CE_Warning, CPLE_NotSupported, "SRS not supported");
        }
    }

    if (!m_bUseSrcMapping && m_bGotTransform)
    {
        oMapping.Add("_type", "group");

        const double dfDegToMeter = oSRS.GetSemiMajor() * M_PI / 180.0;
        if (!m_oSRS.IsEmpty() && oSRS.IsProjected())
        {
            const double dfLinearUnits = oSRS.GetLinearUnits();
            // Maybe we should deal differently with non meter units ?
            const double dfRes = m_adfGeoTransform[1] * dfLinearUnits;
            const double dfScale = dfDegToMeter / dfRes;
            oMapping.Add("UpperLeftCornerX", m_adfGeoTransform[0]);
            oMapping.Add("UpperLeftCornerY", m_adfGeoTransform[3]);
            oMapping.Add("PixelResolution/value", dfRes);
            oMapping.Add("PixelResolution/unit", "meters/pixel");
            oMapping.Add("Scale/value", dfScale);
            oMapping.Add("Scale/unit", "pixels/degree");
        }
        else if (!m_oSRS.IsEmpty() && oSRS.IsGeographic())
        {
            const double dfScale = 1.0 / m_adfGeoTransform[1];
            const double dfRes = m_adfGeoTransform[1] * dfDegToMeter;
            oMapping.Add("UpperLeftCornerX",
                         m_adfGeoTransform[0] * dfDegToMeter);
            oMapping.Add("UpperLeftCornerY",
                         m_adfGeoTransform[3] * dfDegToMeter);
            oMapping.Add("PixelResolution/value", dfRes);
            oMapping.Add("PixelResolution/unit", "meters/pixel");
            oMapping.Add("Scale/value", dfScale);
            oMapping.Add("Scale/unit", "pixels/degree");
        }
        else
        {
            oMapping.Add("UpperLeftCornerX", m_adfGeoTransform[0]);
            oMapping.Add("UpperLeftCornerY", m_adfGeoTransform[3]);
            oMapping.Add("PixelResolution", m_adfGeoTransform[1]);
        }
    }

    CPLJSONObject oLabelLabel = GetOrCreateJSONObject(oLabel, "Label");
    oLabelLabel.Set("_type", "object");
    oLabelLabel.Set("Bytes", pszLABEL_BYTES_PLACEHOLDER);

    // Deal with History object
    BuildHistory();

    oLabel.Delete("History");
    if (!m_osHistory.empty())
    {
        CPLJSONObject oHistory;
        oHistory.Add("_type", "object");
        oHistory.Add("Name", "IsisCube");
        if (m_osExternalFilename.empty())
            oHistory.Add("StartByte", pszHISTORY_STARTBYTE_PLACEHOLDER);
        else
            oHistory.Add("StartByte", 1);
        oHistory.Add("Bytes", static_cast<GIntBig>(m_osHistory.size()));
        if (!m_osExternalFilename.empty())
        {
            CPLString osFilename(CPLGetBasename(GetDescription()));
            osFilename += ".History.IsisCube";
            oHistory.Add("^History", osFilename);
        }
        oLabel.Add("History", oHistory);
    }

    // Deal with other objects that have StartByte & Bytes
    m_aoNonPixelSections.clear();
    if (m_oSrcJSonLabel.IsValid())
    {
        CPLString osLabelSrcFilename;
        CPLJSONObject oFilename = oLabel["_filename"];
        if (oFilename.GetType() == CPLJSONObject::Type::String)
        {
            osLabelSrcFilename = oFilename.ToString();
        }

        for (CPLJSONObject &oObj : oLabel.GetChildren())
        {
            CPLString osKey = oObj.GetName();
            if (osKey == "History")
            {
                continue;
            }

            CPLJSONObject oBytes = oObj.GetObj("Bytes");
            if (oBytes.GetType() != CPLJSONObject::Type::Integer ||
                oBytes.ToInteger() <= 0)
            {
                continue;
            }

            CPLJSONObject oStartByte = oObj.GetObj("StartByte");
            if (oStartByte.GetType() != CPLJSONObject::Type::Integer ||
                oStartByte.ToInteger() <= 0)
            {
                continue;
            }

            if (osLabelSrcFilename.empty())
            {
                CPLError(CE_Warning, CPLE_AppDefined,
                         "Cannot find _filename attribute in "
                         "source ISIS3 metadata. Removing object "
                         "%s from the label.",
                         osKey.c_str());
                oLabel.Delete(osKey);
                continue;
            }

            NonPixelSection oSection;
            oSection.osSrcFilename = osLabelSrcFilename;
            oSection.nSrcOffset =
                static_cast<vsi_l_offset>(oObj.GetInteger("StartByte")) - 1U;
            oSection.nSize =
                static_cast<vsi_l_offset>(oObj.GetInteger("Bytes"));

            CPLString osName;
            CPLJSONObject oName = oObj.GetObj("Name");
            if (oName.GetType() == CPLJSONObject::Type::String)
            {
                osName = oName.ToString();
            }

            CPLString osContainerName(osKey);
            CPLJSONObject oContainerName = oObj.GetObj("_container_name");
            if (oContainerName.GetType() == CPLJSONObject::Type::String)
            {
                osContainerName = oContainerName.ToString();
            }

            const CPLString osKeyFilename("^" + osContainerName);
            CPLJSONObject oFilenameCap = oObj.GetObj(osKeyFilename);
            if (oFilenameCap.GetType() == CPLJSONObject::Type::String)
            {
                VSIStatBufL sStat;
                const CPLString osSrcFilename(
                    CPLFormFilename(CPLGetPath(osLabelSrcFilename),
                                    oFilenameCap.ToString().c_str(), nullptr));
                if (VSIStatL(osSrcFilename, &sStat) == 0)
                {
                    oSection.osSrcFilename = osSrcFilename;
                }
                else
                {
                    CPLError(CE_Warning, CPLE_AppDefined,
                             "Object %s points to %s, which does "
                             "not exist. Removing this section "
                             "from the label",
                             osKey.c_str(), osSrcFilename.c_str());
                    oLabel.Delete(osKey);
                    continue;
                }
            }

            if (!m_osExternalFilename.empty())
            {
                oObj.Set("StartByte", 1);
            }
            else
            {
                CPLString osPlaceHolder;
                osPlaceHolder.Printf(
                    "!*^PLACEHOLDER_%d_STARTBYTE^*!",
                    static_cast<int>(m_aoNonPixelSections.size()) + 1);
                oObj.Set("StartByte", osPlaceHolder);
                oSection.osPlaceHolder = osPlaceHolder;
            }

            if (!m_osExternalFilename.empty())
            {
                CPLString osDstFilename(CPLGetBasename(GetDescription()));
                osDstFilename += ".";
                osDstFilename += osContainerName;
                if (!osName.empty())
                {
                    osDstFilename += ".";
                    osDstFilename += osName;
                }

                oSection.osDstFilename = CPLFormFilename(
                    CPLGetPath(GetDescription()), osDstFilename, nullptr);

                oObj.Set(osKeyFilename, osDstFilename);
            }
            else
            {
                oObj.Delete(osKeyFilename);
            }

            m_aoNonPixelSections.push_back(oSection);
        }
    }
    m_oJSonLabel = oLabel;
}

/************************************************************************/
/*                         BuildHistory()                               */
/************************************************************************/

void ISIS3Dataset::BuildHistory()
{
    CPLString osHistory;

    if (m_oSrcJSonLabel.IsValid() && m_bUseSrcHistory)
    {
        vsi_l_offset nHistoryOffset = 0;
        int nHistorySize = 0;
        CPLString osSrcFilename;

        CPLJSONObject oFilename = m_oSrcJSonLabel["_filename"];
        if (oFilename.GetType() == CPLJSONObject::Type::String)
        {
            osSrcFilename = oFilename.ToString();
        }
        CPLString osHistoryFilename(osSrcFilename);
        CPLJSONObject oHistory = m_oSrcJSonLabel["History"];
        if (oHistory.GetType() == CPLJSONObject::Type::Object)
        {
            CPLJSONObject oHistoryFilename = oHistory["^History"];
            if (oHistoryFilename.GetType() == CPLJSONObject::Type::String)
            {
                osHistoryFilename = CPLFormFilename(
                    CPLGetPath(osSrcFilename),
                    oHistoryFilename.ToString().c_str(), nullptr);
            }

            CPLJSONObject oStartByte = oHistory["StartByte"];
            if (oStartByte.GetType() == CPLJSONObject::Type::Integer)
            {
                if (oStartByte.ToInteger() > 0)
                {
                    nHistoryOffset =
                        static_cast<vsi_l_offset>(oStartByte.ToInteger()) - 1U;
                }
            }

            CPLJSONObject oBytes = oHistory["Bytes"];
            if (oBytes.GetType() == CPLJSONObject::Type::Integer)
            {
                nHistorySize = static_cast<int>(oBytes.ToInteger());
            }
        }

        if (osHistoryFilename.empty())
        {
            CPLDebug("ISIS3", "Cannot find filename for source history");
        }
        else if (nHistorySize <= 0 || nHistorySize > 1000000)
        {
            CPLDebug("ISIS3", "Invalid or missing value for History.Bytes "
                              "for source history");
        }
        else
        {
            VSILFILE *fpHistory = VSIFOpenL(osHistoryFilename, "rb");
            if (fpHistory != nullptr)
            {
                VSIFSeekL(fpHistory, nHistoryOffset, SEEK_SET);
                osHistory.resize(nHistorySize);
                if (VSIFReadL(&osHistory[0], nHistorySize, 1, fpHistory) != 1)
                {
                    CPLError(CE_Warning, CPLE_FileIO,
                             "Cannot read %d bytes at offset " CPL_FRMT_GUIB
                             "of %s: history will not be preserved",
                             nHistorySize, nHistoryOffset,
                             osHistoryFilename.c_str());
                    osHistory.clear();
                }
                VSIFCloseL(fpHistory);
            }
            else
            {
                CPLError(CE_Warning, CPLE_FileIO,
                         "Cannot open %s: history will not be preserved",
                         osHistoryFilename.c_str());
            }
        }
    }

    if (m_bAddGDALHistory && !m_osGDALHistory.empty())
    {
        if (!osHistory.empty())
            osHistory += "\n";
        osHistory += m_osGDALHistory;
    }
    else if (m_bAddGDALHistory)
    {
        if (!osHistory.empty())
            osHistory += "\n";

        CPLJSONObject oHistoryObj;
        char szFullFilename[2048] = {0};
        if (!CPLGetExecPath(szFullFilename, sizeof(szFullFilename) - 1))
            strcpy(szFullFilename, "unknown_program");
        const CPLString osProgram(CPLGetBasename(szFullFilename));
        const CPLString osPath(CPLGetPath(szFullFilename));

        CPLJSONObject oObj;
        oHistoryObj.Add(osProgram, oObj);

        oObj.Add("_type", "object");
        oObj.Add("GdalVersion", GDALVersionInfo("RELEASE_NAME"));
        if (osPath != ".")
            oObj.Add("ProgramPath", osPath);
        time_t nCurTime = time(nullptr);
        if (nCurTime != -1)
        {
            struct tm mytm;
            CPLUnixTimeToYMDHMS(nCurTime, &mytm);
            oObj.Add("ExecutionDateTime",
                     CPLSPrintf("%04d-%02d-%02dT%02d:%02d:%02d",
                                mytm.tm_year + 1900, mytm.tm_mon + 1,
                                mytm.tm_mday, mytm.tm_hour, mytm.tm_min,
                                mytm.tm_sec));
        }
        char szHostname[256] = {0};
        if (gethostname(szHostname, sizeof(szHostname) - 1) == 0)
        {
            oObj.Add("HostName", std::string(szHostname));
        }
        const char *pszUsername = CPLGetConfigOption("USERNAME", nullptr);
        if (pszUsername == nullptr)
            pszUsername = CPLGetConfigOption("USER", nullptr);
        if (pszUsername != nullptr)
        {
            oObj.Add("UserName", pszUsername);
        }
        oObj.Add("Description", "GDAL conversion");

        CPLJSONObject oUserParameters;
        oObj.Add("UserParameters", oUserParameters);

        oUserParameters.Add("_type", "group");
        if (!m_osFromFilename.empty())
        {
            const CPLString osFromFilename = CPLGetFilename(m_osFromFilename);
            oUserParameters.Add("FROM", osFromFilename);
        }
        if (nullptr != GetDescription())
        {
            const CPLString osToFileName = CPLGetFilename(GetDescription());
            oUserParameters.Add("TO", osToFileName);
        }
        if (m_bForce360)
            oUserParameters.Add("Force_360", "true");

        osHistory += SerializeAsPDL(oHistoryObj);
    }

    m_osHistory = osHistory;
}

/************************************************************************/
/*                           WriteLabel()                               */
/************************************************************************/

void ISIS3Dataset::WriteLabel()
{
    m_bIsLabelWritten = true;

    if (!m_oJSonLabel.IsValid())
        BuildLabel();

    // Serialize label
    CPLString osLabel(SerializeAsPDL(m_oJSonLabel));
    osLabel += "End\n";
    if (m_osExternalFilename.empty() && osLabel.size() < 65536)
    {
        // In-line labels have conventionally a minimize size of 65536 bytes
        // See #2741
        osLabel.resize(65536);
    }
    char *pszLabel = &osLabel[0];
    const int nLabelSize = static_cast<int>(osLabel.size());

    // Hack back StartByte value
    {
        char *pszStartByte = strstr(pszLabel, pszSTARTBYTE_PLACEHOLDER);
        if (pszStartByte != nullptr)
        {
            const char *pszOffset = CPLSPrintf("%d", 1 + nLabelSize);
            memcpy(pszStartByte, pszOffset, strlen(pszOffset));
            memset(pszStartByte + strlen(pszOffset), ' ',
                   strlen(pszSTARTBYTE_PLACEHOLDER) - strlen(pszOffset));
        }
    }

    // Hack back Label.Bytes value
    {
        char *pszLabelBytes = strstr(pszLabel, pszLABEL_BYTES_PLACEHOLDER);
        if (pszLabelBytes != nullptr)
        {
            const char *pszBytes = CPLSPrintf("%d", nLabelSize);
            memcpy(pszLabelBytes, pszBytes, strlen(pszBytes));
            memset(pszLabelBytes + strlen(pszBytes), ' ',
                   strlen(pszLABEL_BYTES_PLACEHOLDER) - strlen(pszBytes));
        }
    }

    const GDALDataType eType = GetRasterBand(1)->GetRasterDataType();
    const int nDTSize = GDALGetDataTypeSizeBytes(eType);
    vsi_l_offset nImagePixels = 0;
    if (m_poExternalDS == nullptr)
    {
        if (m_bIsTiled)
        {
            int nBlockXSize = 1, nBlockYSize = 1;
            GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
            nImagePixels = static_cast<vsi_l_offset>(nBlockXSize) *
                           nBlockYSize * nBands *
                           DIV_ROUND_UP(nRasterXSize, nBlockXSize) *
                           DIV_ROUND_UP(nRasterYSize, nBlockYSize);
        }
        else
        {
            nImagePixels =
                static_cast<vsi_l_offset>(nRasterXSize) * nRasterYSize * nBands;
        }
    }

    // Hack back History.StartBytes value
    char *pszHistoryStartBytes =
        strstr(pszLabel, pszHISTORY_STARTBYTE_PLACEHOLDER);

    vsi_l_offset nHistoryOffset = 0;
    vsi_l_offset nLastOffset = 0;
    if (pszHistoryStartBytes != nullptr)
    {
        CPLAssert(m_osExternalFilename.empty());
        nHistoryOffset = nLabelSize + nImagePixels * nDTSize;
        nLastOffset = nHistoryOffset + m_osHistory.size();
        const char *pszStartByte =
            CPLSPrintf(CPL_FRMT_GUIB, nHistoryOffset + 1);
        CPLAssert(strlen(pszStartByte) <
                  strlen(pszHISTORY_STARTBYTE_PLACEHOLDER));
        memcpy(pszHistoryStartBytes, pszStartByte, strlen(pszStartByte));
        memset(pszHistoryStartBytes + strlen(pszStartByte), ' ',
               strlen(pszHISTORY_STARTBYTE_PLACEHOLDER) - strlen(pszStartByte));
    }

    // Replace placeholders in other sections
    for (size_t i = 0; i < m_aoNonPixelSections.size(); ++i)
    {
        if (!m_aoNonPixelSections[i].osPlaceHolder.empty())
        {
            char *pszPlaceHolder =
                strstr(pszLabel, m_aoNonPixelSections[i].osPlaceHolder.c_str());
            CPLAssert(pszPlaceHolder != nullptr);
            const char *pszStartByte =
                CPLSPrintf(CPL_FRMT_GUIB, nLastOffset + 1);
            nLastOffset += m_aoNonPixelSections[i].nSize;
            CPLAssert(strlen(pszStartByte) <
                      m_aoNonPixelSections[i].osPlaceHolder.size());

            memcpy(pszPlaceHolder, pszStartByte, strlen(pszStartByte));
            memset(pszPlaceHolder + strlen(pszStartByte), ' ',
                   m_aoNonPixelSections[i].osPlaceHolder.size() -
                       strlen(pszStartByte));
        }
    }

    // Write to final file
    VSIFSeekL(m_fpLabel, 0, SEEK_SET);
    VSIFWriteL(pszLabel, 1, osLabel.size(), m_fpLabel);

    if (m_osExternalFilename.empty())
    {
        // Update image offset in bands
        if (m_bIsTiled)
        {
            for (int i = 0; i < nBands; i++)
            {
                ISISTiledBand *poBand =
                    reinterpret_cast<ISISTiledBand *>(GetRasterBand(i + 1));
                poBand->m_nFirstTileOffset += nLabelSize;
            }
        }
        else
        {
            for (int i = 0; i < nBands; i++)
            {
                ISIS3RawRasterBand *poBand =
                    reinterpret_cast<ISIS3RawRasterBand *>(
                        GetRasterBand(i + 1));
                poBand->nImgOffset += nLabelSize;
            }
        }
    }

    if (m_bInitToNodata)
    {
        // Initialize the image to nodata
        const double dfNoData = GetRasterBand(1)->GetNoDataValue();
        if (dfNoData == 0.0)
        {
            VSIFTruncateL(m_fpImage,
                          VSIFTellL(m_fpImage) + nImagePixels * nDTSize);
        }
        else if (nDTSize != 0)  // to make Coverity not warn about div by 0
        {
            const int nPageSize = 4096;  // Must be multiple of 4 since
                                         // Float32 is the largest type
            CPLAssert((nPageSize % nDTSize) == 0);
            const int nMaxPerPage = nPageSize / nDTSize;
            GByte *pabyTemp = static_cast<GByte *>(CPLMalloc(nPageSize));
            GDALCopyWords(&dfNoData, GDT_Float64, 0, pabyTemp, eType, nDTSize,
                          nMaxPerPage);
#ifdef CPL_MSB
            GDALSwapWords(pabyTemp, nDTSize, nMaxPerPage, nDTSize);
#endif
            for (vsi_l_offset i = 0; i < nImagePixels; i += nMaxPerPage)
            {
                int n;
                if (i + nMaxPerPage <= nImagePixels)
                    n = nMaxPerPage;
                else
                    n = static_cast<int>(nImagePixels - i);
                if (VSIFWriteL(pabyTemp, n * nDTSize, 1, m_fpImage) != 1)
                {
                    CPLError(CE_Failure, CPLE_FileIO,
                             "Cannot initialize imagery to null");
                    break;
                }
            }

            CPLFree(pabyTemp);
        }
    }

    // Write history
    if (!m_osHistory.empty())
    {
        if (m_osExternalFilename.empty())
        {
            VSIFSeekL(m_fpLabel, nHistoryOffset, SEEK_SET);
            VSIFWriteL(m_osHistory.c_str(), 1, m_osHistory.size(), m_fpLabel);
        }
        else
        {
            CPLString osFilename(CPLGetBasename(GetDescription()));
            osFilename += ".History.IsisCube";
            osFilename = CPLFormFilename(CPLGetPath(GetDescription()),
                                         osFilename, nullptr);
            VSILFILE *fp = VSIFOpenL(osFilename, "wb");
            if (fp)
            {
                m_aosAdditionalFiles.AddString(osFilename);

                VSIFWriteL(m_osHistory.c_str(), 1, m_osHistory.size(), fp);
                VSIFCloseL(fp);
            }
            else
            {
                CPLError(CE_Warning, CPLE_FileIO, "Cannot write %s",
                         osFilename.c_str());
            }
        }
    }

    // Write other non pixel sections
    for (size_t i = 0; i < m_aoNonPixelSections.size(); ++i)
    {
        VSILFILE *fpSrc =
            VSIFOpenL(m_aoNonPixelSections[i].osSrcFilename, "rb");
        if (fpSrc == nullptr)
        {
            CPLError(CE_Warning, CPLE_FileIO, "Cannot open %s",
                     m_aoNonPixelSections[i].osSrcFilename.c_str());
            continue;
        }

        VSILFILE *fpDest = m_fpLabel;
        if (!m_aoNonPixelSections[i].osDstFilename.empty())
        {
            fpDest = VSIFOpenL(m_aoNonPixelSections[i].osDstFilename, "wb");
            if (fpDest == nullptr)
            {
                CPLError(CE_Warning, CPLE_FileIO, "Cannot create %s",
                         m_aoNonPixelSections[i].osDstFilename.c_str());
                VSIFCloseL(fpSrc);
                continue;
            }

            m_aosAdditionalFiles.AddString(
                m_aoNonPixelSections[i].osDstFilename);
        }

        VSIFSeekL(fpSrc, m_aoNonPixelSections[i].nSrcOffset, SEEK_SET);
        GByte abyBuffer[4096];
        vsi_l_offset nRemaining = m_aoNonPixelSections[i].nSize;
        while (nRemaining)
        {
            size_t nToRead = 4096;
            if (nRemaining < nToRead)
                nToRead = static_cast<size_t>(nRemaining);
            size_t nRead = VSIFReadL(abyBuffer, 1, nToRead, fpSrc);
            if (nRead != nToRead)
            {
                CPLError(CE_Warning, CPLE_FileIO,
                         "Could not read " CPL_FRMT_GUIB " bytes from %s",
                         m_aoNonPixelSections[i].nSize,
                         m_aoNonPixelSections[i].osSrcFilename.c_str());
                break;
            }
            VSIFWriteL(abyBuffer, 1, nRead, fpDest);
            nRemaining -= nRead;
        }

        VSIFCloseL(fpSrc);
        if (fpDest != m_fpLabel)
            VSIFCloseL(fpDest);
    }
}

/************************************************************************/
/*                      SerializeAsPDL()                                */
/************************************************************************/

CPLString ISIS3Dataset::SerializeAsPDL(const CPLJSONObject &oObj)
{
    CPLString osTmpFile(
        CPLSPrintf("/vsimem/isis3_%p", oObj.GetInternalHandle()));
    VSILFILE *fpTmp = VSIFOpenL(osTmpFile, "wb+");
    SerializeAsPDL(fpTmp, oObj);
    VSIFCloseL(fpTmp);
    CPLString osContent(reinterpret_cast<char *>(
        VSIGetMemFileBuffer(osTmpFile, nullptr, FALSE)));
    VSIUnlink(osTmpFile);
    return osContent;
}

/************************************************************************/
/*                      SerializeAsPDL()                                */
/************************************************************************/

void ISIS3Dataset::SerializeAsPDL(VSILFILE *fp, const CPLJSONObject &oObj,
                                  int nDepth)
{
    CPLString osIndentation;
    for (int i = 0; i < nDepth; i++)
        osIndentation += "  ";
    const size_t WIDTH = 79;

    std::vector<CPLJSONObject> aoChildren = oObj.GetChildren();
    size_t nMaxKeyLength = 0;
    for (const CPLJSONObject &oChild : aoChildren)
    {
        const CPLString osKey = oChild.GetName();
        if (EQUAL(osKey, "_type") || EQUAL(osKey, "_container_name") ||
            EQUAL(osKey, "_filename"))
        {
            continue;
        }

        const auto eType = oChild.GetType();
        if (eType == CPLJSONObject::Type::String ||
            eType == CPLJSONObject::Type::Integer ||
            eType == CPLJSONObject::Type::Double ||
            eType == CPLJSONObject::Type::Array)
        {
            if (osKey.size() > nMaxKeyLength)
            {
                nMaxKeyLength = osKey.size();
            }
        }
        else if (eType == CPLJSONObject::Type::Object)
        {
            CPLJSONObject oValue = oChild.GetObj("value");
            CPLJSONObject oUnit = oChild.GetObj("unit");
            if (oValue.IsValid() &&
                oUnit.GetType() == CPLJSONObject::Type::String)
            {
                if (osKey.size() > nMaxKeyLength)
                {
                    nMaxKeyLength = osKey.size();
                }
            }
        }
    }

    for (const CPLJSONObject &oChild : aoChildren)
    {
        const CPLString osKey = oChild.GetName();
        if (EQUAL(osKey, "_type") || EQUAL(osKey, "_container_name") ||
            EQUAL(osKey, "_filename"))
        {
            continue;
        }
        if (STARTS_WITH(osKey, "_comment"))
        {
            if (oChild.GetType() == CPLJSONObject::Type::String)
            {
                VSIFPrintfL(fp, "#%s\n", oChild.ToString().c_str());
            }
            continue;
        }
        CPLString osPadding;
        size_t nLen = osKey.size();
        if (nLen < nMaxKeyLength)
        {
            osPadding.append(nMaxKeyLength - nLen, ' ');
        }

        const auto eType = oChild.GetType();
        if (eType == CPLJSONObject::Type::Object)
        {
            CPLJSONObject oType = oChild.GetObj("_type");
            CPLJSONObject oContainerName = oChild.GetObj("_container_name");
            CPLString osContainerName = osKey;
            if (oContainerName.GetType() == CPLJSONObject::Type::String)
            {
                osContainerName = oContainerName.ToString();
            }
            if (oType.GetType() == CPLJSONObject::Type::String)
            {
                const CPLString osType = oType.ToString();
                if (EQUAL(osType, "Object"))
                {
                    if (nDepth == 0 && VSIFTellL(fp) != 0)
                        VSIFPrintfL(fp, "\n");
                    VSIFPrintfL(fp, "%sObject = %s\n", osIndentation.c_str(),
                                osContainerName.c_str());
                    SerializeAsPDL(fp, oChild, nDepth + 1);
                    VSIFPrintfL(fp, "%sEnd_Object\n", osIndentation.c_str());
                }
                else if (EQUAL(osType, "Group"))
                {
                    VSIFPrintfL(fp, "\n");
                    VSIFPrintfL(fp, "%sGroup = %s\n", osIndentation.c_str(),
                                osContainerName.c_str());
                    SerializeAsPDL(fp, oChild, nDepth + 1);
                    VSIFPrintfL(fp, "%sEnd_Group\n", osIndentation.c_str());
                }
            }
            else
            {
                CPLJSONObject oValue = oChild.GetObj("value");
                CPLJSONObject oUnit = oChild.GetObj("unit");
                if (oValue.IsValid() &&
                    oUnit.GetType() == CPLJSONObject::Type::String)
                {
                    const CPLString osUnit = oUnit.ToString();
                    const auto eValueType = oValue.GetType();
                    if (eValueType == CPLJSONObject::Type::Integer)
                    {
                        VSIFPrintfL(fp, "%s%s%s = %d <%s>\n",
                                    osIndentation.c_str(), osKey.c_str(),
                                    osPadding.c_str(), oValue.ToInteger(),
                                    osUnit.c_str());
                    }
                    else if (eValueType == CPLJSONObject::Type::Double)
                    {
                        const double dfVal = oValue.ToDouble();
                        if (dfVal >= INT_MIN && dfVal <= INT_MAX &&
                            static_cast<int>(dfVal) == dfVal)
                        {
                            VSIFPrintfL(fp, "%s%s%s = %d.0 <%s>\n",
                                        osIndentation.c_str(), osKey.c_str(),
                                        osPadding.c_str(),
                                        static_cast<int>(dfVal),
                                        osUnit.c_str());
                        }
                        else
                        {
                            VSIFPrintfL(fp, "%s%s%s = %.18g <%s>\n",
                                        osIndentation.c_str(), osKey.c_str(),
                                        osPadding.c_str(), dfVal,
                                        osUnit.c_str());
                        }
                    }
                }
            }
        }
        else if (eType == CPLJSONObject::Type::String)
        {
            CPLString osVal = oChild.ToString();
            const char *pszVal = osVal.c_str();
            if (pszVal[0] == '\0' || strchr(pszVal, ' ') ||
                strstr(pszVal, "\\n") || strstr(pszVal, "\\r"))
            {
                osVal.replaceAll("\\n", "\n");
                osVal.replaceAll("\\r", "\r");
                VSIFPrintfL(fp, "%s%s%s = \"%s\"\n", osIndentation.c_str(),
                            osKey.c_str(), osPadding.c_str(), osVal.c_str());
            }
            else
            {
                if (osIndentation.size() + osKey.size() + osPadding.size() +
                            strlen(" = ") + strlen(pszVal) >
                        WIDTH &&
                    osIndentation.size() + osKey.size() + osPadding.size() +
                            strlen(" = ") <
                        WIDTH)
                {
                    size_t nFirstPos = osIndentation.size() + osKey.size() +
                                       osPadding.size() + strlen(" = ");
                    VSIFPrintfL(fp, "%s%s%s = ", osIndentation.c_str(),
                                osKey.c_str(), osPadding.c_str());
                    size_t nCurPos = nFirstPos;
                    for (int j = 0; pszVal[j] != '\0'; j++)
                    {
                        nCurPos++;
                        if (nCurPos == WIDTH && pszVal[j + 1] != '\0')
                        {
                            VSIFPrintfL(fp, "-\n");
                            for (size_t k = 0; k < nFirstPos; k++)
                            {
                                const char chSpace = ' ';
                                VSIFWriteL(&chSpace, 1, 1, fp);
                            }
                            nCurPos = nFirstPos + 1;
                        }
                        VSIFWriteL(&pszVal[j], 1, 1, fp);
                    }
                    VSIFPrintfL(fp, "\n");
                }
                else
                {
                    VSIFPrintfL(fp, "%s%s%s = %s\n", osIndentation.c_str(),
                                osKey.c_str(), osPadding.c_str(), pszVal);
                }
            }
        }
        else if (eType == CPLJSONObject::Type::Integer)
        {
            const int nVal = oChild.ToInteger();
            VSIFPrintfL(fp, "%s%s%s = %d\n", osIndentation.c_str(),
                        osKey.c_str(), osPadding.c_str(), nVal);
        }
        else if (eType == CPLJSONObject::Type::Double)
        {
            const double dfVal = oChild.ToDouble();
            if (dfVal >= INT_MIN && dfVal <= INT_MAX &&
                static_cast<int>(dfVal) == dfVal)
            {
                VSIFPrintfL(fp, "%s%s%s = %d.0\n", osIndentation.c_str(),
                            osKey.c_str(), osPadding.c_str(),
                            static_cast<int>(dfVal));
            }
            else
            {
                VSIFPrintfL(fp, "%s%s%s = %.18g\n", osIndentation.c_str(),
                            osKey.c_str(), osPadding.c_str(), dfVal);
            }
        }
        else if (eType == CPLJSONObject::Type::Array)
        {
            CPLJSONArray oArrayItem(oChild);
            const int nLength = oArrayItem.Size();
            size_t nFirstPos = osIndentation.size() + osKey.size() +
                               osPadding.size() + strlen(" = (");
            VSIFPrintfL(fp, "%s%s%s = (", osIndentation.c_str(), osKey.c_str(),
                        osPadding.c_str());
            size_t nCurPos = nFirstPos;
            for (int idx = 0; idx < nLength; idx++)
            {
                CPLJSONObject oItem = oArrayItem[idx];
                const auto eArrayItemType = oItem.GetType();
                if (eArrayItemType == CPLJSONObject::Type::String)
                {
                    CPLString osVal = oItem.ToString();
                    const char *pszVal = osVal.c_str();
                    if (pszVal[0] == '\0' || strchr(pszVal, ' ') ||
                        strstr(pszVal, "\\n") || strstr(pszVal, "\\r"))
                    {
                        osVal.replaceAll("\\n", "\n");
                        osVal.replaceAll("\\r", "\r");
                        VSIFPrintfL(fp, "\"%s\"", osVal.c_str());
                    }
                    else if (nFirstPos < WIDTH &&
                             nCurPos + strlen(pszVal) > WIDTH)
                    {
                        if (idx > 0)
                        {
                            VSIFPrintfL(fp, "\n");
                            for (size_t j = 0; j < nFirstPos; j++)
                            {
                                const char chSpace = ' ';
                                VSIFWriteL(&chSpace, 1, 1, fp);
                            }
                            nCurPos = nFirstPos;
                        }

                        for (int j = 0; pszVal[j] != '\0'; j++)
                        {
                            nCurPos++;
                            if (nCurPos == WIDTH && pszVal[j + 1] != '\0')
                            {
                                VSIFPrintfL(fp, "-\n");
                                for (size_t k = 0; k < nFirstPos; k++)
                                {
                                    const char chSpace = ' ';
                                    VSIFWriteL(&chSpace, 1, 1, fp);
                                }
                                nCurPos = nFirstPos + 1;
                            }
                            VSIFWriteL(&pszVal[j], 1, 1, fp);
                        }
                    }
                    else
                    {
                        VSIFPrintfL(fp, "%s", pszVal);
                        nCurPos += strlen(pszVal);
                    }
                }
                else if (eArrayItemType == CPLJSONObject::Type::Integer)
                {
                    const int nVal = oItem.ToInteger();
                    const char *pszVal = CPLSPrintf("%d", nVal);
                    const size_t nValLen = strlen(pszVal);
                    if (nFirstPos < WIDTH && idx > 0 &&
                        nCurPos + nValLen > WIDTH)
                    {
                        VSIFPrintfL(fp, "\n");
                        for (size_t j = 0; j < nFirstPos; j++)
                        {
                            const char chSpace = ' ';
                            VSIFWriteL(&chSpace, 1, 1, fp);
                        }
                        nCurPos = nFirstPos;
                    }
                    VSIFPrintfL(fp, "%d", nVal);
                    nCurPos += nValLen;
                }
                else if (eArrayItemType == CPLJSONObject::Type::Double)
                {
                    const double dfVal = oItem.ToDouble();
                    CPLString osVal;
                    if (dfVal >= INT_MIN && dfVal <= INT_MAX &&
                        static_cast<int>(dfVal) == dfVal)
                    {
                        osVal = CPLSPrintf("%d.0", static_cast<int>(dfVal));
                    }
                    else
                    {
                        osVal = CPLSPrintf("%.18g", dfVal);
                    }
                    const size_t nValLen = osVal.size();
                    if (nFirstPos < WIDTH && idx > 0 &&
                        nCurPos + nValLen > WIDTH)
                    {
                        VSIFPrintfL(fp, "\n");
                        for (size_t j = 0; j < nFirstPos; j++)
                        {
                            const char chSpace = ' ';
                            VSIFWriteL(&chSpace, 1, 1, fp);
                        }
                        nCurPos = nFirstPos;
                    }
                    VSIFPrintfL(fp, "%s", osVal.c_str());
                    nCurPos += nValLen;
                }
                if (idx < nLength - 1)
                {
                    VSIFPrintfL(fp, ", ");
                    nCurPos += 2;
                }
            }
            VSIFPrintfL(fp, ")\n");
        }
    }
}

/************************************************************************/
/*                           Create()                                   */
/************************************************************************/

GDALDataset *ISIS3Dataset::Create(const char *pszFilename, int nXSize,
                                  int nYSize, int nBandsIn, GDALDataType eType,
                                  char **papszOptions)
{
    if (eType != GDT_Byte && eType != GDT_UInt16 && eType != GDT_Int16 &&
        eType != GDT_Float32)
    {
        CPLError(CE_Failure, CPLE_NotSupported, "Unsupported data type");
        return nullptr;
    }
    if (nBandsIn == 0 || nBandsIn > 32767)
    {
        CPLError(CE_Failure, CPLE_NotSupported, "Unsupported band count");
        return nullptr;
    }

    const char *pszDataLocation =
        CSLFetchNameValueDef(papszOptions, "DATA_LOCATION", "LABEL");
    const bool bIsTiled = CPLFetchBool(papszOptions, "TILED", false);
    const int nBlockXSize = std::max(
        1, atoi(CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", "256")));
    const int nBlockYSize = std::max(
        1, atoi(CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", "256")));
    if (!EQUAL(pszDataLocation, "LABEL") &&
        !EQUAL(CPLGetExtension(pszFilename), "LBL"))
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "For DATA_LOCATION=%s, "
                 "the main filename should have a .lbl extension",
                 pszDataLocation);
        return nullptr;
    }

    VSILFILE *fp = VSIFOpenExL(pszFilename, "wb", true);
    if (fp == nullptr)
    {
        CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s: %s", pszFilename,
                 VSIGetLastErrorMsg());
        return nullptr;
    }
    VSILFILE *fpImage = nullptr;
    CPLString osExternalFilename;
    GDALDataset *poExternalDS = nullptr;
    bool bGeoTIFFAsRegularExternal = false;
    if (EQUAL(pszDataLocation, "EXTERNAL"))
    {
        osExternalFilename =
            CSLFetchNameValueDef(papszOptions, "EXTERNAL_FILENAME",
                                 CPLResetExtension(pszFilename, "cub"));
        fpImage = VSIFOpenExL(osExternalFilename, "wb", true);
        if (fpImage == nullptr)
        {
            CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s: %s",
                     osExternalFilename.c_str(), VSIGetLastErrorMsg());
            VSIFCloseL(fp);
            return nullptr;
        }
    }
    else if (EQUAL(pszDataLocation, "GEOTIFF"))
    {
        osExternalFilename =
            CSLFetchNameValueDef(papszOptions, "EXTERNAL_FILENAME",
                                 CPLResetExtension(pszFilename, "tif"));
        GDALDriver *poDrv =
            static_cast<GDALDriver *>(GDALGetDriverByName("GTiff"));
        if (poDrv == nullptr)
        {
            CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GTiff driver");
            VSIFCloseL(fp);
            return nullptr;
        }
        char **papszGTiffOptions = nullptr;
        papszGTiffOptions =
            CSLSetNameValue(papszGTiffOptions, "ENDIANNESS", "LITTLE");
        if (bIsTiled)
        {
            papszGTiffOptions =
                CSLSetNameValue(papszGTiffOptions, "TILED", "YES");
            papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "BLOCKXSIZE",
                                                CPLSPrintf("%d", nBlockXSize));
            papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "BLOCKYSIZE",
                                                CPLSPrintf("%d", nBlockYSize));
        }
        const char *pszGTiffOptions =
            CSLFetchNameValueDef(papszOptions, "GEOTIFF_OPTIONS", "");
        char **papszTokens = CSLTokenizeString2(pszGTiffOptions, ",", 0);
        for (int i = 0; papszTokens[i] != nullptr; i++)
        {
            papszGTiffOptions = CSLAddString(papszGTiffOptions, papszTokens[i]);
        }
        CSLDestroy(papszTokens);

        // If the user didn't specify any compression and
        // GEOTIFF_AS_REGULAR_EXTERNAL is set (or unspecified), then the
        // GeoTIFF file can be seen as a regular external raw file, provided
        // we make some provision on its organization.
        if (CSLFetchNameValue(papszGTiffOptions, "COMPRESS") == nullptr &&
            CPLFetchBool(papszOptions, "GEOTIFF_AS_REGULAR_EXTERNAL", true))
        {
            bGeoTIFFAsRegularExternal = true;
            papszGTiffOptions =
                CSLSetNameValue(papszGTiffOptions, "INTERLEAVE", "BAND");
            // Will make sure that our blocks at nodata are not optimized
            // away but indeed well written
            papszGTiffOptions = CSLSetNameValue(
                papszGTiffOptions, "@WRITE_EMPTY_TILES_SYNCHRONOUSLY", "YES");
            if (!bIsTiled && nBandsIn > 1)
            {
                papszGTiffOptions =
                    CSLSetNameValue(papszGTiffOptions, "BLOCKYSIZE", "1");
            }
        }

        poExternalDS = poDrv->Create(osExternalFilename, nXSize, nYSize,
                                     nBandsIn, eType, papszGTiffOptions);
        CSLDestroy(papszGTiffOptions);
        if (poExternalDS == nullptr)
        {
            CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s",
                     osExternalFilename.c_str());
            VSIFCloseL(fp);
            return nullptr;
        }
    }

    ISIS3Dataset *poDS = new ISIS3Dataset();
    poDS->SetDescription(pszFilename);
    poDS->eAccess = GA_Update;
    poDS->nRasterXSize = nXSize;
    poDS->nRasterYSize = nYSize;
    poDS->m_osExternalFilename = osExternalFilename;
    poDS->m_poExternalDS = poExternalDS;
    poDS->m_bGeoTIFFAsRegularExternal = bGeoTIFFAsRegularExternal;
    if (bGeoTIFFAsRegularExternal)
        poDS->m_bGeoTIFFInitDone = false;
    poDS->m_fpLabel = fp;
    poDS->m_fpImage = fpImage ? fpImage : fp;
    poDS->m_bIsLabelWritten = false;
    poDS->m_bIsTiled = bIsTiled;
    poDS->m_bInitToNodata = (poDS->m_poExternalDS == nullptr);
    poDS->m_osComment = CSLFetchNameValueDef(papszOptions, "COMMENT", "");
    poDS->m_osLatitudeType =
        CSLFetchNameValueDef(papszOptions, "LATITUDE_TYPE", "");
    poDS->m_osLongitudeDirection =
        CSLFetchNameValueDef(papszOptions, "LONGITUDE_DIRECTION", "");
    poDS->m_osTargetName =
        CSLFetchNameValueDef(papszOptions, "TARGET_NAME", "");
    poDS->m_bForce360 = CPLFetchBool(papszOptions, "FORCE_360", false);
    poDS->m_bWriteBoundingDegrees =
        CPLFetchBool(papszOptions, "WRITE_BOUNDING_DEGREES", true);
    poDS->m_osBoundingDegrees =
        CSLFetchNameValueDef(papszOptions, "BOUNDING_DEGREES", "");
    poDS->m_bUseSrcLabel = CPLFetchBool(papszOptions, "USE_SRC_LABEL", true);
    poDS->m_bUseSrcMapping =
        CPLFetchBool(papszOptions, "USE_SRC_MAPPING", false);
    poDS->m_bUseSrcHistory =
        CPLFetchBool(papszOptions, "USE_SRC_HISTORY", true);
    poDS->m_bAddGDALHistory =
        CPLFetchBool(papszOptions, "ADD_GDAL_HISTORY", true);
    if (poDS->m_bAddGDALHistory)
    {
        poDS->m_osGDALHistory =
            CSLFetchNameValueDef(papszOptions, "GDAL_HISTORY", "");
    }
    const double dfNoData = (eType == GDT_Byte)     ? NULL1
                            : (eType == GDT_UInt16) ? NULLU2
                            : (eType == GDT_Int16)
                                ? NULL2
                                :
                                /*(eType == GDT_Float32) ?*/ NULL4;

    for (int i = 0; i < nBandsIn; i++)
    {
        GDALRasterBand *poBand = nullptr;

        if (poDS->m_poExternalDS != nullptr)
        {
            ISIS3WrapperRasterBand *poISISBand = new ISIS3WrapperRasterBand(
                poDS->m_poExternalDS->GetRasterBand(i + 1));
            poBand = poISISBand;
        }
        else if (bIsTiled)
        {
            ISISTiledBand *poISISBand = new ISISTiledBand(
                poDS, poDS->m_fpImage, i + 1, eType, nBlockXSize, nBlockYSize,
                0,  // nSkipBytes, to be hacked
                // afterwards for in-label imagery
                0, 0, CPL_IS_LSB);

            poBand = poISISBand;
        }
        else
        {
            const int nPixelOffset = GDALGetDataTypeSizeBytes(eType);
            const int nLineOffset = nPixelOffset * nXSize;
            const vsi_l_offset nBandOffset =
                static_cast<vsi_l_offset>(nLineOffset) * nYSize;
            ISIS3RawRasterBand *poISISBand = new ISIS3RawRasterBand(
                poDS, i + 1, poDS->m_fpImage,
                nBandOffset * i,  // nImgOffset, to be
                // hacked afterwards for in-label imagery
                nPixelOffset, nLineOffset, eType, CPL_IS_LSB);

            poBand = poISISBand;
        }
        poDS->SetBand(i + 1, poBand);
        poBand->SetNoDataValue(dfNoData);
    }

    return poDS;
}

/************************************************************************/
/*                      GetUnderlyingDataset()                          */
/************************************************************************/

static GDALDataset *GetUnderlyingDataset(GDALDataset *poSrcDS)
{
    if (poSrcDS->GetDriver() != nullptr &&
        poSrcDS->GetDriver() == GDALGetDriverByName("VRT"))
    {
        VRTDataset *poVRTDS = reinterpret_cast<VRTDataset *>(poSrcDS);
        poSrcDS = poVRTDS->GetSingleSimpleSource();
    }

    return poSrcDS;
}

/************************************************************************/
/*                            CreateCopy()                              */
/************************************************************************/

GDALDataset *ISIS3Dataset::CreateCopy(const char *pszFilename,
                                      GDALDataset *poSrcDS, int /*bStrict*/,
                                      char **papszOptions,
                                      GDALProgressFunc pfnProgress,
                                      void *pProgressData)
{
    const char *pszDataLocation =
        CSLFetchNameValueDef(papszOptions, "DATA_LOCATION", "LABEL");
    GDALDataset *poSrcUnderlyingDS = GetUnderlyingDataset(poSrcDS);
    if (poSrcUnderlyingDS == nullptr)
        poSrcUnderlyingDS = poSrcDS;
    if (EQUAL(pszDataLocation, "GEOTIFF") &&
        strcmp(poSrcUnderlyingDS->GetDescription(),
               CSLFetchNameValueDef(papszOptions, "EXTERNAL_FILENAME",
                                    CPLResetExtension(pszFilename, "tif"))) ==
            0)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "Output file has same name as input file");
        return nullptr;
    }
    if (poSrcDS->GetRasterCount() == 0)
    {
        CPLError(CE_Failure, CPLE_NotSupported, "Unsupported band count");
        return nullptr;
    }

    const int nXSize = poSrcDS->GetRasterXSize();
    const int nYSize = poSrcDS->GetRasterYSize();
    const int nBands = poSrcDS->GetRasterCount();
    GDALDataType eType = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    ISIS3Dataset *poDS = reinterpret_cast<ISIS3Dataset *>(
        Create(pszFilename, nXSize, nYSize, nBands, eType, papszOptions));
    if (poDS == nullptr)
        return nullptr;
    poDS->m_osFromFilename = poSrcUnderlyingDS->GetDescription();

    double adfGeoTransform[6] = {0.0};
    if (poSrcDS->GetGeoTransform(adfGeoTransform) == CE_None &&
        (adfGeoTransform[0] != 0.0 || adfGeoTransform[1] != 1.0 ||
         adfGeoTransform[2] != 0.0 || adfGeoTransform[3] != 0.0 ||
         adfGeoTransform[4] != 0.0 || adfGeoTransform[5] != 1.0))
    {
        poDS->SetGeoTransform(adfGeoTransform);
    }

    auto poSrcSRS = poSrcDS->GetSpatialRef();
    if (poSrcSRS)
    {
        poDS->SetSpatialRef(poSrcSRS);
    }

    for (int i = 1; i <= nBands; i++)
    {
        const double dfOffset = poSrcDS->GetRasterBand(i)->GetOffset();
        if (dfOffset != 0.0)
            poDS->GetRasterBand(i)->SetOffset(dfOffset);

        const double dfScale = poSrcDS->GetRasterBand(i)->GetScale();
        if (dfScale != 1.0)
            poDS->GetRasterBand(i)->SetScale(dfScale);
    }

    // Do we need to remap nodata ?
    int bHasNoData = FALSE;
    poDS->m_dfSrcNoData =
        poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    poDS->m_bHasSrcNoData = CPL_TO_BOOL(bHasNoData);

    if (poDS->m_bUseSrcLabel)
    {
        char **papszMD_ISIS3 = poSrcDS->GetMetadata("json:ISIS3");
        if (papszMD_ISIS3 != nullptr)
        {
            poDS->SetMetadata(papszMD_ISIS3, "json:ISIS3");
        }
    }

    // We don't need to initialize the imagery as we are going to copy it
    // completely
    poDS->m_bInitToNodata = false;
    CPLErr eErr = GDALDatasetCopyWholeRaster(poSrcDS, poDS, nullptr,
                                             pfnProgress, pProgressData);
    poDS->FlushCache(false);
    poDS->m_bHasSrcNoData = false;
    if (eErr != CE_None)
    {
        delete poDS;
        return nullptr;
    }

    return poDS;
}

/************************************************************************/
/*                         GDALRegister_ISIS3()                         */
/************************************************************************/

void GDALRegister_ISIS3()

{
    if (GDALGetDriverByName("ISIS3") != nullptr)
        return;

    GDALDriver *poDriver = new GDALDriver();

    poDriver->SetDescription("ISIS3");
    poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
    poDriver->SetMetadataItem(GDAL_DMD_LONGNAME,
                              "USGS Astrogeology ISIS cube (Version 3)");
    poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/isis3.html");
    poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
    poDriver->SetMetadataItem(GDAL_DMD_EXTENSIONS, "lbl cub");
    poDriver->SetMetadataItem(GDAL_DMD_CREATIONDATATYPES,
                              "Byte UInt16 Int16 Float32");
    poDriver->SetMetadataItem(GDAL_DMD_OPENOPTIONLIST, "<OpenOptionList/>");
    poDriver->SetMetadataItem(
        GDAL_DMD_CREATIONOPTIONLIST,
        "<CreationOptionList>"
        "  <Option name='DATA_LOCATION' type='string-select' "
        "description='Location of pixel data' default='LABEL'>"
        "     <Value>LABEL</Value>"
        "     <Value>EXTERNAL</Value>"
        "     <Value>GEOTIFF</Value>"
        "  </Option>"
        "  <Option name='GEOTIFF_AS_REGULAR_EXTERNAL' type='boolean' "
        "description='Whether the GeoTIFF file, if uncompressed, should be "
        "registered as a regular raw file' default='YES'/>"
        "  <Option name='GEOTIFF_OPTIONS' type='string' "
        "description='Comma separated list of KEY=VALUE tuples to forward "
        "to the GeoTIFF driver'/>"
        "  <Option name='EXTERNAL_FILENAME' type='string' "
        "description='Override default external filename. "
        "Only for DATA_LOCATION=EXTERNAL or GEOTIFF'/>"
        "  <Option name='TILED' type='boolean' "
        "description='Whether the pixel data should be tiled' default='NO'/>"
        "  <Option name='BLOCKXSIZE' type='int' "
        "description='Tile width' default='256'/>"
        "  <Option name='BLOCKYSIZE' type='int' "
        "description='Tile height' default='256'/>"
        "  <Option name='COMMENT' type='string' "
        "description='Comment to add into the label'/>"
        "  <Option name='LATITUDE_TYPE' type='string-select' "
        "description='Value of Mapping.LatitudeType' default='Planetocentric'>"
        "     <Value>Planetocentric</Value>"
        "     <Value>Planetographic</Value>"
        "  </Option>"
        "  <Option name='LONGITUDE_DIRECTION' type='string-select' "
        "description='Value of Mapping.LongitudeDirection' "
        "default='PositiveEast'>"
        "     <Value>PositiveEast</Value>"
        "     <Value>PositiveWest</Value>"
        "  </Option>"
        "  <Option name='TARGET_NAME' type='string' description='Value of "
        "Mapping.TargetName'/>"
        "  <Option name='FORCE_360' type='boolean' "
        "description='Whether to force longitudes in [0,360] range' "
        "default='NO'/>"
        "  <Option name='WRITE_BOUNDING_DEGREES' type='boolean' "
        "description='Whether to write Min/MaximumLong/Latitude values' "
        "default='YES'/>"
        "  <Option name='BOUNDING_DEGREES' type='string' "
        "description='Manually set bounding box with the syntax "
        "min_long,min_lat,max_long,max_lat'/>"
        "  <Option name='USE_SRC_LABEL' type='boolean' "
        "description='Whether to use source label in ISIS3 to ISIS3 "
        "conversions' "
        "default='YES'/>"
        "  <Option name='USE_SRC_MAPPING' type='boolean' "
        "description='Whether to use Mapping group from source label in "
        "ISIS3 to ISIS3 conversions' "
        "default='NO'/>"
        "  <Option name='USE_SRC_HISTORY' type='boolean' "
        "description='Whether to use content pointed by the History object in "
        "ISIS3 to ISIS3 conversions' "
        "default='YES'/>"
        "  <Option name='ADD_GDAL_HISTORY' type='boolean' "
        "description='Whether to add GDAL specific history in the content "
        "pointed "
        "by the History object in "
        "ISIS3 to ISIS3 conversions' "
        "default='YES'/>"
        "  <Option name='GDAL_HISTORY' type='string' "
        "description='Manually defined GDAL history. Must be formatted as "
        "ISIS3 "
        "PDL. If not specified, it is automatically composed.'/>"
        "</CreationOptionList>");

    poDriver->pfnOpen = ISIS3Dataset::Open;
    poDriver->pfnIdentify = ISIS3Dataset::Identify;
    poDriver->pfnCreate = ISIS3Dataset::Create;
    poDriver->pfnCreateCopy = ISIS3Dataset::CreateCopy;

    GetGDALDriverManager()->RegisterDriver(poDriver);
}