File: gdalwarp_lib.cpp

package info (click to toggle)
gdal 3.12.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 92,292 kB
  • sloc: cpp: 1,223,498; ansic: 206,434; python: 26,278; java: 6,001; xml: 4,769; sh: 3,855; cs: 2,513; yacc: 1,306; makefile: 214
file content (6603 lines) | stat: -rw-r--r-- 262,789 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
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
/******************************************************************************
 *
 * Project:  High Performance Image Reprojector
 * Purpose:  Test program for high performance warper API.
 * Author:   Frank Warmerdam <warmerdam@pobox.com>
 *
 ******************************************************************************
 * Copyright (c) 2002, i3 - information integration and imaging
 *                          Fort Collins, CO
 * Copyright (c) 2007-2015, Even Rouault <even dot rouault at spatialys.com>
 * Copyright (c) 2015, Faza Mahamood
 *
 * SPDX-License-Identifier: MIT
 ****************************************************************************/

#include "cpl_port.h"
#include "gdal_utils.h"
#include "gdal_utils_priv.h"
#include "gdalargumentparser.h"

#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <algorithm>
#include <array>
#include <limits>
#include <set>
#include <utility>
#include <vector>

// Suppress deprecation warning for GDALOpenVerticalShiftGrid and
// GDALApplyVerticalShiftGrid
#ifndef CPL_WARN_DEPRECATED_GDALOpenVerticalShiftGrid
#define CPL_WARN_DEPRECATED_GDALOpenVerticalShiftGrid(x)
#define CPL_WARN_DEPRECATED_GDALApplyVerticalShiftGrid(x)
#endif

#include "commonutils.h"
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_progress.h"
#include "cpl_string.h"
#include "gdal.h"
#include "gdal_alg.h"
#include "gdal_alg_priv.h"
#include "gdal_priv.h"
#include "gdalwarper.h"
#include "ogr_api.h"
#include "ogr_core.h"
#include "ogr_geometry.h"
#include "ogr_spatialref.h"
#include "ogr_srs_api.h"
#include "ogr_proj_p.h"
#include "ogrct_priv.h"
#include "ogrsf_frmts.h"
#include "vrtdataset.h"
#include "../frmts/gtiff/cogdriver.h"

#if PROJ_VERSION_MAJOR > 6 || PROJ_VERSION_MINOR >= 3
#define USE_PROJ_BASED_VERTICAL_SHIFT_METHOD
#endif

/************************************************************************/
/*                        GDALWarpAppOptions                            */
/************************************************************************/

/** Options for use with GDALWarp(). GDALWarpAppOptions* must be allocated and
 * freed with GDALWarpAppOptionsNew() and GDALWarpAppOptionsFree() respectively.
 */
struct GDALWarpAppOptions
{
    /*! Raw program arguments */
    CPLStringList aosArgs{};

    /*! set georeferenced extents of output file to be created (in target SRS by
       default, or in the SRS specified with pszTE_SRS) */
    double dfMinX = 0;
    double dfMinY = 0;
    double dfMaxX = 0;
    double dfMaxY = 0;

    /*! the SRS in which to interpret the coordinates given in
       GDALWarpAppOptions::dfMinX, GDALWarpAppOptions::dfMinY,
       GDALWarpAppOptions::dfMaxX and GDALWarpAppOptions::dfMaxY. The SRS may be
       any of the usual GDAL/OGR forms, complete WKT, PROJ.4, EPSG:n or a file
       containing the WKT. It is a convenience e.g. when knowing the output
       coordinates in a geodetic long/lat SRS, but still wanting a result in a
       projected coordinate system. */
    std::string osTE_SRS{};

    /*! set output file resolution (in target georeferenced units) */
    double dfXRes = 0;
    double dfYRes = 0;

    /*! whether target pixels should have dfXRes == dfYRes */
    bool bSquarePixels = false;

    /*! align the coordinates of the extent of the output file to the values of
       the GDALWarpAppOptions::dfXRes and GDALWarpAppOptions::dfYRes, such that
       the aligned extent includes the minimum extent. */
    bool bTargetAlignedPixels = false;

    /*! set output file size in pixels and lines. If
       GDALWarpAppOptions::nForcePixels or GDALWarpAppOptions::nForceLines is
       set to 0, the other dimension will be guessed from the computed
       resolution. Note that GDALWarpAppOptions::nForcePixels and
        GDALWarpAppOptions::nForceLines cannot be used with
       GDALWarpAppOptions::dfXRes and GDALWarpAppOptions::dfYRes. */
    int nForcePixels = 0;
    int nForceLines = 0;

    /*! allow or suppress progress monitor and other non-error output */
    bool bQuiet = true;

    /*! the progress function to use */
    GDALProgressFunc pfnProgress = GDALDummyProgress;

    /*! pointer to the progress data variable */
    void *pProgressData = nullptr;

    /*! creates an output alpha band to identify nodata (unset/transparent)
       pixels when set to true */
    bool bEnableDstAlpha = false;

    /*! forces the last band of an input file to be considered as alpha band. */
    bool bEnableSrcAlpha = false;

    /*! Prevent a source alpha band from being considered as such */
    bool bDisableSrcAlpha = false;

    /*! output format. Use the short format name. */
    std::string osFormat{};

    bool bCreateOutput = false;

    /*! list of warp options. ("NAME1=VALUE1","NAME2=VALUE2",...). The
        GDALWarpOptions::aosWarpOptions docs show all options. */
    CPLStringList aosWarpOptions{};

    double dfErrorThreshold = -1;

    /*! the amount of memory (in megabytes) that the warp API is allowed
        to use for caching. */
    double dfWarpMemoryLimit = 0;

    /*! list of create options for the output format driver. See format
        specific documentation for legal creation options for each format. */
    CPLStringList aosCreateOptions{};

    /*! the data type of the output bands */
    GDALDataType eOutputType = GDT_Unknown;

    /*! working pixel data type. The data type of pixels in the source
        image and destination image buffers. */
    GDALDataType eWorkingType = GDT_Unknown;

    /*! the resampling method. Available methods are: near, bilinear,
        cubic, cubicspline, lanczos, average, mode, max, min, med,
        q1, q3, sum */
    GDALResampleAlg eResampleAlg = GRA_NearestNeighbour;

    /*! whether -r was specified */
    bool bResampleAlgSpecifiedByUser = false;

    /*! nodata masking values for input bands (different values can be supplied
        for each band). ("value1 value2 ..."). Masked values will not be used
        in interpolation. Use a value of "None" to ignore intrinsic nodata
        settings on the source dataset. */
    std::string osSrcNodata{};

    /*! nodata values for output bands (different values can be supplied for
        each band). ("value1 value2 ..."). New files will be initialized to
        this value and if possible the nodata value will be recorded in the
        output file. Use a value of "None" to ensure that nodata is not defined.
        If this argument is not used then nodata values will be copied from
        the source dataset. */
    std::string osDstNodata{};

    /*! use multithreaded warping implementation. Multiple threads will be used
        to process chunks of image and perform input/output operation
       simultaneously. */
    bool bMulti = false;

    /*! list of transformer options suitable to pass to
       GDALCreateGenImgProjTransformer2().
        ("NAME1=VALUE1","NAME2=VALUE2",...) */
    CPLStringList aosTransformerOptions{};

    /*! enable use of a blend cutline from a vector dataset name or a WKT
     * geometry
     */
    std::string osCutlineDSNameOrWKT{};

    /*! cutline SRS */
    std::string osCutlineSRS{};

    /*! the named layer to be selected from the cutline datasource */
    std::string osCLayer{};

    /*! restrict desired cutline features based on attribute query */
    std::string osCWHERE{};

    /*! SQL query to select the cutline features instead of from a layer
        with osCLayer */
    std::string osCSQL{};

    /*! crop the extent of the target dataset to the extent of the cutline */
    bool bCropToCutline = false;

    /*! copy dataset and band metadata will be copied from the first source
       dataset. Items that differ between source datasets will be set "*" (see
       GDALWarpAppOptions::pszMDConflictValue) */
    bool bCopyMetadata = true;

    /*! copy band information from the first source dataset */
    bool bCopyBandInfo = true;

    /*! value to set metadata items that conflict between source datasets
       (default is "*"). Use "" to remove conflicting items. */
    std::string osMDConflictValue = "*";

    /*! set the color interpretation of the bands of the target dataset from the
     * source dataset */
    bool bSetColorInterpretation = false;

    /*! overview level of source files to be used */
    int nOvLevel = OVR_LEVEL_AUTO;

    /*! Whether to enable vertical shift adjustment */
    bool bVShift = false;

    /*! Whether to disable vertical shift adjustment */
    bool bNoVShift = false;

    /*! Source bands */
    std::vector<int> anSrcBands{};

    /*! Destination bands */
    std::vector<int> anDstBands{};

    /*! Used when using a temporary TIFF file while warping */
    bool bDeleteOutputFileOnceCreated = false;
};

static CPLErr
LoadCutline(const std::string &osCutlineDSNameOrWKT, const std::string &osSRS,
            const std::string &oszCLayer, const std::string &osCWHERE,
            const std::string &osCSQL, OGRGeometryH *phCutlineRet);
static CPLErr TransformCutlineToSource(GDALDataset *poSrcDS,
                                       OGRGeometry *poCutline,
                                       char ***ppapszWarpOptions,
                                       CSLConstList papszTO);

static GDALDatasetH GDALWarpCreateOutput(
    int nSrcCount, GDALDatasetH *pahSrcDS, const char *pszFilename,
    const char *pszFormat, char **papszTO, CSLConstList papszCreateOptions,
    GDALDataType eDT, GDALTransformerArgUniquePtr &hTransformArg,
    bool bSetColorInterpretation, GDALWarpAppOptions *psOptions,
    bool bUpdateTransformerWithDestGT);

static void RemoveConflictingMetadata(GDALMajorObjectH hObj,
                                      CSLConstList papszMetadata,
                                      const char *pszValueConflict);

static double GetAverageSegmentLength(const OGRGeometry *poGeom)
{
    if (!poGeom)
        return 0;
    switch (wkbFlatten(poGeom->getGeometryType()))
    {
        case wkbLineString:
        {
            const auto *poLS = poGeom->toLineString();
            double dfSum = 0;
            const int nPoints = poLS->getNumPoints();
            if (nPoints == 0)
                return 0;
            for (int i = 0; i < nPoints - 1; i++)
            {
                double dfX1 = poLS->getX(i);
                double dfY1 = poLS->getY(i);
                double dfX2 = poLS->getX(i + 1);
                double dfY2 = poLS->getY(i + 1);
                double dfDX = dfX2 - dfX1;
                double dfDY = dfY2 - dfY1;
                dfSum += sqrt(dfDX * dfDX + dfDY * dfDY);
            }
            return dfSum / nPoints;
        }

        case wkbPolygon:
        {
            if (poGeom->IsEmpty())
                return 0;
            double dfSum = 0;
            for (const auto *poLS : poGeom->toPolygon())
            {
                dfSum += GetAverageSegmentLength(poLS);
            }
            return dfSum / (1 + poGeom->toPolygon()->getNumInteriorRings());
        }

        case wkbMultiPolygon:
        case wkbMultiLineString:
        case wkbGeometryCollection:
        {
            if (poGeom->IsEmpty())
                return 0;
            double dfSum = 0;
            for (const auto *poSubGeom : poGeom->toGeometryCollection())
            {
                dfSum += GetAverageSegmentLength(poSubGeom);
            }
            return dfSum / poGeom->toGeometryCollection()->getNumGeometries();
        }

        default:
            return 0;
    }
}

/************************************************************************/
/*                          FetchSrcMethod()                            */
/************************************************************************/

static const char *FetchSrcMethod(CSLConstList papszTO,
                                  const char *pszDefault = nullptr)
{
    const char *pszMethod = CSLFetchNameValue(papszTO, "SRC_METHOD");
    if (!pszMethod)
        pszMethod = CSLFetchNameValueDef(papszTO, "METHOD", pszDefault);
    return pszMethod;
}

static const char *FetchSrcMethod(const CPLStringList &aosTO,
                                  const char *pszDefault = nullptr)
{
    const char *pszMethod = aosTO.FetchNameValue("SRC_METHOD");
    if (!pszMethod)
        pszMethod = aosTO.FetchNameValueDef("METHOD", pszDefault);
    return pszMethod;
}

/************************************************************************/
/*                          GetSrcDSProjection()                        */
/*                                                                      */
/* Takes into account SRC_SRS transformer option in priority, and then  */
/* dataset characteristics as well as the METHOD transformer            */
/* option to determine the source SRS.                                  */
/************************************************************************/

static CPLString GetSrcDSProjection(GDALDatasetH hDS, CSLConstList papszTO)
{
    const char *pszProjection = CSLFetchNameValue(papszTO, "SRC_SRS");
    if (pszProjection != nullptr || hDS == nullptr)
    {
        return pszProjection ? pszProjection : "";
    }

    const char *pszMethod = FetchSrcMethod(papszTO);
    char **papszMD = nullptr;
    const OGRSpatialReferenceH hSRS = GDALGetSpatialRef(hDS);
    const char *pszGeolocationDataset =
        CSLFetchNameValueDef(papszTO, "SRC_GEOLOC_ARRAY",
                             CSLFetchNameValue(papszTO, "GEOLOC_ARRAY"));
    if (pszGeolocationDataset != nullptr &&
        (pszMethod == nullptr || EQUAL(pszMethod, "GEOLOC_ARRAY")))
    {
        auto aosMD =
            GDALCreateGeolocationMetadata(hDS, pszGeolocationDataset, true);
        pszProjection = aosMD.FetchNameValue("SRS");
        if (pszProjection)
            return pszProjection;  // return in this scope so that aosMD is
                                   // still valid
    }
    else if (hSRS && (pszMethod == nullptr || EQUAL(pszMethod, "GEOTRANSFORM")))
    {
        char *pszWKT = nullptr;
        {
            CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
            if (OSRExportToWkt(hSRS, &pszWKT) != OGRERR_NONE)
            {
                CPLFree(pszWKT);
                pszWKT = nullptr;
                const char *const apszOptions[] = {"FORMAT=WKT2", nullptr};
                OSRExportToWktEx(hSRS, &pszWKT, apszOptions);
            }
        }
        CPLString osWKT = pszWKT ? pszWKT : "";
        CPLFree(pszWKT);
        return osWKT;
    }
    else if (GDALGetGCPProjection(hDS) != nullptr &&
             strlen(GDALGetGCPProjection(hDS)) > 0 &&
             GDALGetGCPCount(hDS) > 1 &&
             (pszMethod == nullptr || STARTS_WITH_CI(pszMethod, "GCP_")))
    {
        pszProjection = GDALGetGCPProjection(hDS);
    }
    else if (GDALGetMetadata(hDS, "RPC") != nullptr &&
             (pszMethod == nullptr || EQUAL(pszMethod, "RPC")))
    {
        pszProjection = SRS_WKT_WGS84_LAT_LONG;
    }
    else if ((papszMD = GDALGetMetadata(hDS, "GEOLOCATION")) != nullptr &&
             (pszMethod == nullptr || EQUAL(pszMethod, "GEOLOC_ARRAY")))
    {
        pszProjection = CSLFetchNameValue(papszMD, "SRS");
    }
    return pszProjection ? pszProjection : "";
}

/************************************************************************/
/*                      CreateCTCutlineToSrc()                          */
/************************************************************************/

static std::unique_ptr<OGRCoordinateTransformation> CreateCTCutlineToSrc(
    const OGRSpatialReference *poRasterSRS, const OGRSpatialReference *poDstSRS,
    const OGRSpatialReference *poCutlineSRS, CSLConstList papszTO)
{
    const OGRSpatialReference *poCutlineOrTargetSRS =
        poCutlineSRS ? poCutlineSRS : poDstSRS;
    std::unique_ptr<OGRCoordinateTransformation> poCTCutlineToSrc;
    if (poCutlineOrTargetSRS && poRasterSRS &&
        !poCutlineOrTargetSRS->IsSame(poRasterSRS))
    {
        OGRCoordinateTransformationOptions oOptions;
        // If the cutline SRS is the same as the target SRS and there is
        // an explicit -ct between the source SRS and the target SRS, then
        // use it in the reverse way to transform from the cutline SRS to
        // the source SRS.
        if (poDstSRS && poCutlineOrTargetSRS->IsSame(poDstSRS))
        {
            const char *pszCT =
                CSLFetchNameValue(papszTO, "COORDINATE_OPERATION");
            if (pszCT)
            {
                oOptions.SetCoordinateOperation(pszCT, /* bInverse = */ true);
            }
        }
        poCTCutlineToSrc.reset(OGRCreateCoordinateTransformation(
            poCutlineOrTargetSRS, poRasterSRS, oOptions));
    }
    return poCTCutlineToSrc;
}

/************************************************************************/
/*                           CropToCutline()                            */
/************************************************************************/

static CPLErr CropToCutline(const OGRGeometry *poCutline, CSLConstList papszTO,
                            CSLConstList papszWarpOptions, int nSrcCount,
                            GDALDatasetH *pahSrcDS, double &dfMinX,
                            double &dfMinY, double &dfMaxX, double &dfMaxY,
                            const GDALWarpAppOptions *psOptions)
{
    // We could possibly directly reproject from cutline SRS to target SRS,
    // but when applying the cutline, it is reprojected to source raster image
    // space using the source SRS. To be consistent, we reproject
    // the cutline from cutline SRS to source SRS and then from source SRS to
    // target SRS.
    const OGRSpatialReference *poCutlineSRS = poCutline->getSpatialReference();
    const char *pszThisTargetSRS = CSLFetchNameValue(papszTO, "DST_SRS");
    std::unique_ptr<OGRSpatialReference> poSrcSRS;
    std::unique_ptr<OGRSpatialReference> poDstSRS;

    const CPLString osThisSourceSRS =
        GetSrcDSProjection(nSrcCount > 0 ? pahSrcDS[0] : nullptr, papszTO);
    if (!osThisSourceSRS.empty())
    {
        poSrcSRS = std::make_unique<OGRSpatialReference>();
        poSrcSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
        if (poSrcSRS->SetFromUserInput(osThisSourceSRS) != OGRERR_NONE)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Cannot compute bounding box of cutline.");
            return CE_Failure;
        }
    }
    else if (!pszThisTargetSRS && !poCutlineSRS)
    {
        OGREnvelope sEnvelope;
        poCutline->getEnvelope(&sEnvelope);

        dfMinX = sEnvelope.MinX;
        dfMinY = sEnvelope.MinY;
        dfMaxX = sEnvelope.MaxX;
        dfMaxY = sEnvelope.MaxY;

        return CE_None;
    }
    else
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Cannot compute bounding box of cutline. Cannot find "
                 "source SRS");
        return CE_Failure;
    }

    if (pszThisTargetSRS)
    {
        poDstSRS = std::make_unique<OGRSpatialReference>();
        poDstSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
        if (poDstSRS->SetFromUserInput(pszThisTargetSRS) != OGRERR_NONE)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Cannot compute bounding box of cutline.");
            return CE_Failure;
        }
    }
    else
    {
        poDstSRS.reset(poSrcSRS->Clone());
    }

    auto poCutlineGeom = std::unique_ptr<OGRGeometry>(poCutline->clone());
    auto poCTCutlineToSrc = CreateCTCutlineToSrc(poSrcSRS.get(), poDstSRS.get(),
                                                 poCutlineSRS, papszTO);

    std::unique_ptr<OGRCoordinateTransformation> poCTSrcToDst;
    if (!poSrcSRS->IsSame(poDstSRS.get()))
    {
        poCTSrcToDst.reset(
            OGRCreateCoordinateTransformation(poSrcSRS.get(), poDstSRS.get()));
    }

    // Reproject cutline to target SRS, by doing intermediate vertex
    // densification in source SRS.
    if (poCTSrcToDst || poCTCutlineToSrc)
    {
        OGREnvelope sLastEnvelope, sCurEnvelope;
        std::unique_ptr<OGRGeometry> poTransformedGeom;
        auto poGeomInSrcSRS =
            std::unique_ptr<OGRGeometry>(poCutlineGeom->clone());
        if (poCTCutlineToSrc)
        {
            poGeomInSrcSRS.reset(OGRGeometryFactory::transformWithOptions(
                poGeomInSrcSRS.get(), poCTCutlineToSrc.get(), nullptr));
            if (!poGeomInSrcSRS)
                return CE_Failure;
        }

        // Do not use a smaller epsilon, otherwise it could cause useless
        // segmentization (https://github.com/OSGeo/gdal/issues/4826)
        constexpr double epsilon = 1e-10;
        for (int nIter = 0; nIter < 10; nIter++)
        {
            poTransformedGeom.reset(poGeomInSrcSRS->clone());
            if (poCTSrcToDst)
            {
                poTransformedGeom.reset(
                    OGRGeometryFactory::transformWithOptions(
                        poTransformedGeom.get(), poCTSrcToDst.get(), nullptr));
                if (!poTransformedGeom)
                    return CE_Failure;
            }
            poTransformedGeom->getEnvelope(&sCurEnvelope);
            if (nIter > 0 || !poCTSrcToDst)
            {
                if (std::abs(sCurEnvelope.MinX - sLastEnvelope.MinX) <=
                        epsilon *
                            std::abs(sCurEnvelope.MinX + sLastEnvelope.MinX) &&
                    std::abs(sCurEnvelope.MinY - sLastEnvelope.MinY) <=
                        epsilon *
                            std::abs(sCurEnvelope.MinY + sLastEnvelope.MinY) &&
                    std::abs(sCurEnvelope.MaxX - sLastEnvelope.MaxX) <=
                        epsilon *
                            std::abs(sCurEnvelope.MaxX + sLastEnvelope.MaxX) &&
                    std::abs(sCurEnvelope.MaxY - sLastEnvelope.MaxY) <=
                        epsilon *
                            std::abs(sCurEnvelope.MaxY + sLastEnvelope.MaxY))
                {
                    break;
                }
            }
            double dfAverageSegmentLength =
                GetAverageSegmentLength(poGeomInSrcSRS.get());
            poGeomInSrcSRS->segmentize(dfAverageSegmentLength / 4);

            sLastEnvelope = sCurEnvelope;
        }

        poCutlineGeom = std::move(poTransformedGeom);
    }

    OGREnvelope sEnvelope;
    poCutlineGeom->getEnvelope(&sEnvelope);

    dfMinX = sEnvelope.MinX;
    dfMinY = sEnvelope.MinY;
    dfMaxX = sEnvelope.MaxX;
    dfMaxY = sEnvelope.MaxY;
    if (!poCTSrcToDst && nSrcCount > 0 && psOptions->dfXRes == 0.0 &&
        psOptions->dfYRes == 0.0)
    {
        // No raster reprojection: stick on exact pixel boundaries of the source
        // to preserve resolution and avoid resampling
        double adfGT[6];
        if (GDALGetGeoTransform(pahSrcDS[0], adfGT) == CE_None)
        {
            // We allow for a relative error in coordinates up to 0.1% of the
            // pixel size for rounding purposes.
            constexpr double REL_EPS_PIXEL = 1e-3;
            if (CPLFetchBool(papszWarpOptions, "CUTLINE_ALL_TOUCHED", false))
            {
                // All touched ? Then make the extent a bit larger than the
                // cutline envelope
                dfMinX = adfGT[0] +
                         floor((dfMinX - adfGT[0]) / adfGT[1] + REL_EPS_PIXEL) *
                             adfGT[1];
                dfMinY = adfGT[3] +
                         ceil((dfMinY - adfGT[3]) / adfGT[5] - REL_EPS_PIXEL) *
                             adfGT[5];
                dfMaxX = adfGT[0] +
                         ceil((dfMaxX - adfGT[0]) / adfGT[1] - REL_EPS_PIXEL) *
                             adfGT[1];
                dfMaxY = adfGT[3] +
                         floor((dfMaxY - adfGT[3]) / adfGT[5] + REL_EPS_PIXEL) *
                             adfGT[5];
            }
            else
            {
                // Otherwise, make it a bit smaller
                dfMinX = adfGT[0] +
                         ceil((dfMinX - adfGT[0]) / adfGT[1] - REL_EPS_PIXEL) *
                             adfGT[1];
                dfMinY = adfGT[3] +
                         floor((dfMinY - adfGT[3]) / adfGT[5] + REL_EPS_PIXEL) *
                             adfGT[5];
                dfMaxX = adfGT[0] +
                         floor((dfMaxX - adfGT[0]) / adfGT[1] + REL_EPS_PIXEL) *
                             adfGT[1];
                dfMaxY = adfGT[3] +
                         ceil((dfMaxY - adfGT[3]) / adfGT[5] - REL_EPS_PIXEL) *
                             adfGT[5];
            }
        }
    }

    return CE_None;
}

#ifdef USE_PROJ_BASED_VERTICAL_SHIFT_METHOD

static bool MustApplyVerticalShift(GDALDatasetH hWrkSrcDS,
                                   const GDALWarpAppOptions *psOptions,
                                   OGRSpatialReference &oSRSSrc,
                                   OGRSpatialReference &oSRSDst,
                                   bool &bSrcHasVertAxis, bool &bDstHasVertAxis)
{
    bool bApplyVShift = psOptions->bVShift;

    // Check if we must do vertical shift grid transform
    const char *pszSrcWKT =
        psOptions->aosTransformerOptions.FetchNameValue("SRC_SRS");
    if (pszSrcWKT)
        oSRSSrc.SetFromUserInput(pszSrcWKT);
    else
    {
        auto hSRS = GDALGetSpatialRef(hWrkSrcDS);
        if (hSRS)
            oSRSSrc = *(OGRSpatialReference::FromHandle(hSRS));
        else
            return false;
    }

    const char *pszDstWKT =
        psOptions->aosTransformerOptions.FetchNameValue("DST_SRS");
    if (pszDstWKT)
        oSRSDst.SetFromUserInput(pszDstWKT);
    else
        return false;

    if (oSRSSrc.IsSame(&oSRSDst))
        return false;

    bSrcHasVertAxis = oSRSSrc.IsCompound() ||
                      ((oSRSSrc.IsProjected() || oSRSSrc.IsGeographic()) &&
                       oSRSSrc.GetAxesCount() == 3);

    bDstHasVertAxis = oSRSDst.IsCompound() ||
                      ((oSRSDst.IsProjected() || oSRSDst.IsGeographic()) &&
                       oSRSDst.GetAxesCount() == 3);

    if ((GDALGetRasterCount(hWrkSrcDS) == 1 || psOptions->bVShift) &&
        (bSrcHasVertAxis || bDstHasVertAxis))
    {
        bApplyVShift = true;
    }
    return bApplyVShift;
}

/************************************************************************/
/*                      ApplyVerticalShift()                            */
/************************************************************************/

static bool ApplyVerticalShift(GDALDatasetH hWrkSrcDS,
                               const GDALWarpAppOptions *psOptions,
                               GDALWarpOptions *psWO)
{
    if (psOptions->bVShift)
    {
        psWO->papszWarpOptions = CSLSetNameValue(psWO->papszWarpOptions,
                                                 "APPLY_VERTICAL_SHIFT", "YES");
    }

    OGRSpatialReference oSRSSrc;
    OGRSpatialReference oSRSDst;
    bool bSrcHasVertAxis = false;
    bool bDstHasVertAxis = false;
    bool bApplyVShift =
        MustApplyVerticalShift(hWrkSrcDS, psOptions, oSRSSrc, oSRSDst,
                               bSrcHasVertAxis, bDstHasVertAxis);

    if ((GDALGetRasterCount(hWrkSrcDS) == 1 || psOptions->bVShift) &&
        (bSrcHasVertAxis || bDstHasVertAxis))
    {
        bApplyVShift = true;
        psWO->papszWarpOptions = CSLSetNameValue(psWO->papszWarpOptions,
                                                 "APPLY_VERTICAL_SHIFT", "YES");

        if (CSLFetchNameValue(psWO->papszWarpOptions,
                              "MULT_FACTOR_VERTICAL_SHIFT") == nullptr)
        {
            // Select how to go from input dataset units to meters
            double dfToMeterSrc = 1.0;
            const char *pszUnit =
                GDALGetRasterUnitType(GDALGetRasterBand(hWrkSrcDS, 1));

            double dfToMeterSrcAxis = 1.0;
            if (bSrcHasVertAxis)
            {
                oSRSSrc.GetAxis(nullptr, 2, nullptr, &dfToMeterSrcAxis);
            }

            if (pszUnit && (EQUAL(pszUnit, "m") || EQUAL(pszUnit, "meter") ||
                            EQUAL(pszUnit, "metre")))
            {
            }
            else if (pszUnit &&
                     (EQUAL(pszUnit, "ft") || EQUAL(pszUnit, "foot")))
            {
                dfToMeterSrc = CPLAtof(SRS_UL_FOOT_CONV);
            }
            else if (pszUnit && (EQUAL(pszUnit, "US survey foot")))
            {
                dfToMeterSrc = CPLAtof(SRS_UL_US_FOOT_CONV);
            }
            else if (pszUnit && !EQUAL(pszUnit, ""))
            {
                if (bSrcHasVertAxis)
                {
                    dfToMeterSrc = dfToMeterSrcAxis;
                }
                else
                {
                    CPLError(CE_Warning, CPLE_AppDefined,
                             "Unknown units=%s. Assuming metre.", pszUnit);
                }
            }
            else
            {
                if (bSrcHasVertAxis)
                    oSRSSrc.GetAxis(nullptr, 2, nullptr, &dfToMeterSrc);
            }

            double dfToMeterDst = 1.0;
            if (bDstHasVertAxis)
                oSRSDst.GetAxis(nullptr, 2, nullptr, &dfToMeterDst);

            if (dfToMeterSrc > 0 && dfToMeterDst > 0)
            {
                const double dfMultFactorVerticalShift =
                    dfToMeterSrc / dfToMeterDst;
                CPLDebug("WARP", "Applying MULT_FACTOR_VERTICAL_SHIFT=%.18g",
                         dfMultFactorVerticalShift);
                psWO->papszWarpOptions = CSLSetNameValue(
                    psWO->papszWarpOptions, "MULT_FACTOR_VERTICAL_SHIFT",
                    CPLSPrintf("%.18g", dfMultFactorVerticalShift));

                const double dfMultFactorVerticalShiftPipeline =
                    dfToMeterSrcAxis / dfToMeterDst;
                CPLDebug("WARP",
                         "Applying MULT_FACTOR_VERTICAL_SHIFT_PIPELINE=%.18g",
                         dfMultFactorVerticalShiftPipeline);
                psWO->papszWarpOptions = CSLSetNameValue(
                    psWO->papszWarpOptions,
                    "MULT_FACTOR_VERTICAL_SHIFT_PIPELINE",
                    CPLSPrintf("%.18g", dfMultFactorVerticalShiftPipeline));
            }
        }
    }

    return bApplyVShift;
}

#else

/************************************************************************/
/*                      ApplyVerticalShiftGrid()                        */
/************************************************************************/

static GDALDatasetH ApplyVerticalShiftGrid(GDALDatasetH hWrkSrcDS,
                                           const GDALWarpAppOptions *psOptions,
                                           GDALDatasetH hVRTDS,
                                           bool &bErrorOccurredOut)
{
    bErrorOccurredOut = false;
    // Check if we must do vertical shift grid transform
    OGRSpatialReference oSRSSrc;
    OGRSpatialReference oSRSDst;
    const char *pszSrcWKT =
        psOptions->aosTransformerOptions.FetchNameValue("SRC_SRS");
    if (pszSrcWKT)
        oSRSSrc.SetFromUserInput(pszSrcWKT);
    else
    {
        auto hSRS = GDALGetSpatialRef(hWrkSrcDS);
        if (hSRS)
            oSRSSrc = *(OGRSpatialReference::FromHandle(hSRS));
    }

    const char *pszDstWKT =
        psOptions->aosTransformerOptions.FetchNameValue("DST_SRS");
    if (pszDstWKT)
        oSRSDst.SetFromUserInput(pszDstWKT);

    double adfGT[6] = {};
    if (GDALGetRasterCount(hWrkSrcDS) == 1 &&
        GDALGetGeoTransform(hWrkSrcDS, adfGT) == CE_None &&
        !oSRSSrc.IsEmpty() && !oSRSDst.IsEmpty())
    {
        if ((oSRSSrc.IsCompound() ||
             (oSRSSrc.IsGeographic() && oSRSSrc.GetAxesCount() == 3)) ||
            (oSRSDst.IsCompound() ||
             (oSRSDst.IsGeographic() && oSRSDst.GetAxesCount() == 3)))
        {
            const char *pszSrcProj4Geoids =
                oSRSSrc.GetExtension("VERT_DATUM", "PROJ4_GRIDS");
            const char *pszDstProj4Geoids =
                oSRSDst.GetExtension("VERT_DATUM", "PROJ4_GRIDS");

            if (oSRSSrc.IsCompound() && pszSrcProj4Geoids == nullptr)
            {
                CPLDebug("GDALWARP", "Source SRS is a compound CRS but lacks "
                                     "+geoidgrids");
            }

            if (oSRSDst.IsCompound() && pszDstProj4Geoids == nullptr)
            {
                CPLDebug("GDALWARP", "Target SRS is a compound CRS but lacks "
                                     "+geoidgrids");
            }

            if (pszSrcProj4Geoids != nullptr && pszDstProj4Geoids != nullptr &&
                EQUAL(pszSrcProj4Geoids, pszDstProj4Geoids))
            {
                pszSrcProj4Geoids = nullptr;
                pszDstProj4Geoids = nullptr;
            }

            // Select how to go from input dataset units to meters
            const char *pszUnit =
                GDALGetRasterUnitType(GDALGetRasterBand(hWrkSrcDS, 1));
            double dfToMeterSrc = 1.0;
            if (pszUnit && (EQUAL(pszUnit, "m") || EQUAL(pszUnit, "meter") ||
                            EQUAL(pszUnit, "metre")))
            {
            }
            else if (pszUnit &&
                     (EQUAL(pszUnit, "ft") || EQUAL(pszUnit, "foot")))
            {
                dfToMeterSrc = CPLAtof(SRS_UL_FOOT_CONV);
            }
            else if (pszUnit && (EQUAL(pszUnit, "US survey foot")))
            {
                dfToMeterSrc = CPLAtof(SRS_UL_US_FOOT_CONV);
            }
            else
            {
                if (pszUnit && !EQUAL(pszUnit, ""))
                {
                    CPLError(CE_Warning, CPLE_AppDefined, "Unknown units=%s",
                             pszUnit);
                }
                if (oSRSSrc.IsCompound())
                {
                    dfToMeterSrc = oSRSSrc.GetTargetLinearUnits("VERT_CS");
                }
                else if (oSRSSrc.IsProjected())
                {
                    dfToMeterSrc = oSRSSrc.GetLinearUnits();
                }
            }

            double dfToMeterDst = 1.0;
            if (oSRSDst.IsCompound())
            {
                dfToMeterDst = oSRSDst.GetTargetLinearUnits("VERT_CS");
            }
            else if (oSRSDst.IsProjected())
            {
                dfToMeterDst = oSRSDst.GetLinearUnits();
            }

            char **papszOptions = nullptr;
            if (psOptions->eOutputType != GDT_Unknown)
            {
                papszOptions = CSLSetNameValue(
                    papszOptions, "DATATYPE",
                    GDALGetDataTypeName(psOptions->eOutputType));
            }
            papszOptions =
                CSLSetNameValue(papszOptions, "ERROR_ON_MISSING_VERT_SHIFT",
                                psOptions->aosTransformerOptions.FetchNameValue(
                                    "ERROR_ON_MISSING_VERT_SHIFT"));
            papszOptions = CSLSetNameValue(papszOptions, "SRC_SRS", pszSrcWKT);

            if (pszSrcProj4Geoids != nullptr)
            {
                int bError = FALSE;
                GDALDatasetH hGridDataset =
                    GDALOpenVerticalShiftGrid(pszSrcProj4Geoids, &bError);
                if (bError && hGridDataset == nullptr)
                {
                    CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s.",
                             pszSrcProj4Geoids);
                    bErrorOccurredOut = true;
                    CSLDestroy(papszOptions);
                    return hWrkSrcDS;
                }
                else if (hGridDataset != nullptr)
                {
                    // Transform from source vertical datum to WGS84
                    GDALDatasetH hTmpDS = GDALApplyVerticalShiftGrid(
                        hWrkSrcDS, hGridDataset, FALSE, dfToMeterSrc, 1.0,
                        papszOptions);
                    GDALReleaseDataset(hGridDataset);
                    if (hTmpDS == nullptr)
                    {
                        bErrorOccurredOut = true;
                        CSLDestroy(papszOptions);
                        return hWrkSrcDS;
                    }
                    else
                    {
                        if (hVRTDS)
                        {
                            CPLError(
                                CE_Failure, CPLE_NotSupported,
                                "Warping to VRT with vertical transformation "
                                "not supported with PROJ < 6.3");
                            bErrorOccurredOut = true;
                            CSLDestroy(papszOptions);
                            return hWrkSrcDS;
                        }

                        CPLDebug("GDALWARP",
                                 "Adjusting source dataset "
                                 "with source vertical datum using %s",
                                 pszSrcProj4Geoids);
                        GDALReleaseDataset(hWrkSrcDS);
                        hWrkSrcDS = hTmpDS;
                        dfToMeterSrc = 1.0;
                    }
                }
            }

            if (pszDstProj4Geoids != nullptr)
            {
                int bError = FALSE;
                GDALDatasetH hGridDataset =
                    GDALOpenVerticalShiftGrid(pszDstProj4Geoids, &bError);
                if (bError && hGridDataset == nullptr)
                {
                    CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s.",
                             pszDstProj4Geoids);
                    bErrorOccurredOut = true;
                    CSLDestroy(papszOptions);
                    return hWrkSrcDS;
                }
                else if (hGridDataset != nullptr)
                {
                    // Transform from WGS84 to target vertical datum
                    GDALDatasetH hTmpDS = GDALApplyVerticalShiftGrid(
                        hWrkSrcDS, hGridDataset, TRUE, dfToMeterSrc,
                        dfToMeterDst, papszOptions);
                    GDALReleaseDataset(hGridDataset);
                    if (hTmpDS == nullptr)
                    {
                        bErrorOccurredOut = true;
                        CSLDestroy(papszOptions);
                        return hWrkSrcDS;
                    }
                    else
                    {
                        if (hVRTDS)
                        {
                            CPLError(
                                CE_Failure, CPLE_NotSupported,
                                "Warping to VRT with vertical transformation "
                                "not supported with PROJ < 6.3");
                            bErrorOccurredOut = true;
                            CSLDestroy(papszOptions);
                            return hWrkSrcDS;
                        }

                        CPLDebug("GDALWARP",
                                 "Adjusting source dataset "
                                 "with target vertical datum using %s",
                                 pszDstProj4Geoids);
                        GDALReleaseDataset(hWrkSrcDS);
                        hWrkSrcDS = hTmpDS;
                    }
                }
            }

            CSLDestroy(papszOptions);
        }
    }
    return hWrkSrcDS;
}

#endif

/************************************************************************/
/*                        CanUseBuildVRT()                              */
/************************************************************************/

static bool CanUseBuildVRT(int nSrcCount, GDALDatasetH *pahSrcDS)
{

    bool bCanUseBuildVRT = true;
    std::vector<std::array<double, 4>> aoExtents;
    bool bSrcHasAlpha = false;
    int nPrevBandCount = 0;
    OGRSpatialReference oSRSPrev;
    double dfLastResX = 0;
    double dfLastResY = 0;
    for (int i = 0; i < nSrcCount; i++)
    {
        double adfGT[6];
        auto hSrcDS = pahSrcDS[i];
        if (EQUAL(GDALGetDescription(hSrcDS), ""))
        {
            bCanUseBuildVRT = false;
            break;
        }
        if (GDALGetGeoTransform(hSrcDS, adfGT) != CE_None || adfGT[2] != 0 ||
            adfGT[4] != 0 || adfGT[5] > 0)
        {
            bCanUseBuildVRT = false;
            break;
        }
        const double dfMinX = adfGT[0];
        const double dfMinY = adfGT[3] + GDALGetRasterYSize(hSrcDS) * adfGT[5];
        const double dfMaxX = adfGT[0] + GDALGetRasterXSize(hSrcDS) * adfGT[1];
        const double dfMaxY = adfGT[3];
        const int nBands = GDALGetRasterCount(hSrcDS);
        if (nBands > 1 && GDALGetRasterColorInterpretation(GDALGetRasterBand(
                              hSrcDS, nBands)) == GCI_AlphaBand)
        {
            bSrcHasAlpha = true;
        }
        aoExtents.emplace_back(
            std::array<double, 4>{{dfMinX, dfMinY, dfMaxX, dfMaxY}});
        const auto poSRS = GDALDataset::FromHandle(hSrcDS)->GetSpatialRef();
        if (i == 0)
        {
            nPrevBandCount = nBands;
            if (poSRS)
                oSRSPrev = *poSRS;
            dfLastResX = adfGT[1];
            dfLastResY = adfGT[5];
        }
        else
        {
            if (nPrevBandCount != nBands)
            {
                bCanUseBuildVRT = false;
                break;
            }
            if (poSRS == nullptr && !oSRSPrev.IsEmpty())
            {
                bCanUseBuildVRT = false;
                break;
            }
            if (poSRS != nullptr &&
                (oSRSPrev.IsEmpty() || !poSRS->IsSame(&oSRSPrev)))
            {
                bCanUseBuildVRT = false;
                break;
            }
            if (dfLastResX != adfGT[1] || dfLastResY != adfGT[5])
            {
                bCanUseBuildVRT = false;
                break;
            }
        }
    }
    if (bSrcHasAlpha && bCanUseBuildVRT)
    {
        // Quadratic performance loop. If that happens to be an issue,
        // we might need to build a quad tree
        for (size_t i = 0; i < aoExtents.size(); i++)
        {
            const double dfMinX = aoExtents[i][0];
            const double dfMinY = aoExtents[i][1];
            const double dfMaxX = aoExtents[i][2];
            const double dfMaxY = aoExtents[i][3];
            for (size_t j = i + 1; j < aoExtents.size(); j++)
            {
                const double dfOtherMinX = aoExtents[j][0];
                const double dfOtherMinY = aoExtents[j][1];
                const double dfOtherMaxX = aoExtents[j][2];
                const double dfOtherMaxY = aoExtents[j][3];
                if (dfMinX < dfOtherMaxX && dfOtherMinX < dfMaxX &&
                    dfMinY < dfOtherMaxY && dfOtherMinY < dfMaxY)
                {
                    bCanUseBuildVRT = false;
                    break;
                }
            }
            if (!bCanUseBuildVRT)
                break;
        }
    }
    return bCanUseBuildVRT;
}

#ifdef HAVE_TIFF

/************************************************************************/
/*                      DealWithCOGOptions()                            */
/************************************************************************/

static bool DealWithCOGOptions(CPLStringList &aosCreateOptions, int nSrcCount,
                               GDALDatasetH *pahSrcDS,
                               GDALWarpAppOptions *psOptions,
                               GDALTransformerArgUniquePtr &hUniqueTransformArg)
{
    const auto SetDstSRS = [psOptions](const std::string &osTargetSRS)
    {
        const char *pszExistingDstSRS =
            psOptions->aosTransformerOptions.FetchNameValue("DST_SRS");
        if (pszExistingDstSRS)
        {
            OGRSpatialReference oSRS1;
            oSRS1.SetFromUserInput(pszExistingDstSRS);
            OGRSpatialReference oSRS2;
            oSRS2.SetFromUserInput(osTargetSRS.c_str());
            if (!oSRS1.IsSame(&oSRS2))
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Target SRS implied by COG creation options is not "
                         "the same as the one specified by -t_srs");
                return false;
            }
        }
        psOptions->aosTransformerOptions.SetNameValue("DST_SRS",
                                                      osTargetSRS.c_str());
        return true;
    };

    CPLString osTargetSRS;
    if (COGGetTargetSRS(aosCreateOptions.List(), osTargetSRS))
    {
        if (!SetDstSRS(osTargetSRS))
            return false;
    }

    if (!(psOptions->dfMinX == 0 && psOptions->dfMinY == 0 &&
          psOptions->dfMaxX == 0 && psOptions->dfMaxY == 0 &&
          psOptions->dfXRes == 0 && psOptions->dfYRes == 0 &&
          psOptions->nForcePixels == 0 && psOptions->nForceLines == 0))
    {
        if (!psOptions->bResampleAlgSpecifiedByUser && nSrcCount > 0)
        {
            GDALGetWarpResampleAlg(
                COGGetResampling(GDALDataset::FromHandle(pahSrcDS[0]),
                                 aosCreateOptions.List())
                    .c_str(),
                psOptions->eResampleAlg);
        }
        return true;
    }

    GDALWarpAppOptions oClonedOptions(*psOptions);
    oClonedOptions.bQuiet = true;
    const CPLString osTmpFilename(
        VSIMemGenerateHiddenFilename("gdalwarp_tmp.tif"));
    CPLStringList aosTmpGTiffCreateOptions;
    aosTmpGTiffCreateOptions.SetNameValue("SPARSE_OK", "YES");
    aosTmpGTiffCreateOptions.SetNameValue("TILED", "YES");
    aosTmpGTiffCreateOptions.SetNameValue("BLOCKXSIZE", "4096");
    aosTmpGTiffCreateOptions.SetNameValue("BLOCKYSIZE", "4096");
    auto hTmpDS = GDALWarpCreateOutput(
        nSrcCount, pahSrcDS, osTmpFilename, "GTiff",
        oClonedOptions.aosTransformerOptions.List(),
        aosTmpGTiffCreateOptions.List(), oClonedOptions.eOutputType,
        hUniqueTransformArg, false, &oClonedOptions,
        /* bUpdateTransformerWithDestGT = */ false);
    if (hTmpDS == nullptr)
    {
        return false;
    }

    CPLString osResampling;
    int nXSize = 0;
    int nYSize = 0;
    double dfMinX = 0;
    double dfMinY = 0;
    double dfMaxX = 0;
    double dfMaxY = 0;
    bool bRet = true;
    if (COGGetWarpingCharacteristics(GDALDataset::FromHandle(hTmpDS),
                                     aosCreateOptions.List(), osResampling,
                                     osTargetSRS, nXSize, nYSize, dfMinX,
                                     dfMinY, dfMaxX, dfMaxY))
    {
        if (!psOptions->bResampleAlgSpecifiedByUser)
            GDALGetWarpResampleAlg(osResampling, psOptions->eResampleAlg);
        psOptions->dfMinX = dfMinX;
        psOptions->dfMinY = dfMinY;
        psOptions->dfMaxX = dfMaxX;
        psOptions->dfMaxY = dfMaxY;
        psOptions->nForcePixels = nXSize;
        psOptions->nForceLines = nYSize;
        COGRemoveWarpingOptions(aosCreateOptions);
    }
    GDALClose(hTmpDS);
    VSIUnlink(osTmpFilename);
    return bRet;
}

#endif

/************************************************************************/
/*                      GDALWarpIndirect()                              */
/************************************************************************/

static GDALDatasetH
GDALWarpDirect(const char *pszDest, GDALDatasetH hDstDS, int nSrcCount,
               GDALDatasetH *pahSrcDS,
               GDALTransformerArgUniquePtr hUniqueTransformArg,
               GDALWarpAppOptions *psOptions, int *pbUsageError);

static int CPL_STDCALL myScaledProgress(double dfProgress, const char *,
                                        void *pProgressData)
{
    return GDALScaledProgress(dfProgress, nullptr, pProgressData);
}

static GDALDatasetH GDALWarpIndirect(const char *pszDest, GDALDriverH hDriver,
                                     int nSrcCount, GDALDatasetH *pahSrcDS,
                                     GDALWarpAppOptions *psOptions,
                                     int *pbUsageError)
{
    CPLStringList aosCreateOptions(psOptions->aosCreateOptions);
    psOptions->aosCreateOptions.Clear();

    // Do not use a warped VRT input for COG output, because that would cause
    // warping to be done both during overview computation and creation of
    // full resolution image. Better materialize a temporary GTiff a bit later
    // in that method.
    if (nSrcCount == 1 && !EQUAL(psOptions->osFormat.c_str(), "COG"))
    {
        psOptions->osFormat = "VRT";
        auto pfnProgress = psOptions->pfnProgress;
        psOptions->pfnProgress = GDALDummyProgress;
        auto pProgressData = psOptions->pProgressData;
        psOptions->pProgressData = nullptr;

        auto hTmpDS = GDALWarpDirect("", nullptr, nSrcCount, pahSrcDS, nullptr,
                                     psOptions, pbUsageError);
        if (hTmpDS)
        {
            auto hRet = GDALCreateCopy(hDriver, pszDest, hTmpDS, FALSE,
                                       aosCreateOptions.List(), pfnProgress,
                                       pProgressData);
            GDALClose(hTmpDS);
            return hRet;
        }
        return nullptr;
    }

    // Detect a pure mosaicing situation where a BuildVRT approach is
    // sufficient.
    GDALDatasetH hTmpDS = nullptr;
    if (psOptions->aosTransformerOptions.empty() &&
        psOptions->eOutputType == GDT_Unknown && psOptions->dfMinX == 0 &&
        psOptions->dfMinY == 0 && psOptions->dfMaxX == 0 &&
        psOptions->dfMaxY == 0 && psOptions->dfXRes == 0 &&
        psOptions->dfYRes == 0 && psOptions->nForcePixels == 0 &&
        psOptions->nForceLines == 0 &&
        psOptions->osCutlineDSNameOrWKT.empty() &&
        CanUseBuildVRT(nSrcCount, pahSrcDS))
    {
        CPLStringList aosArgv;
        const int nBands = GDALGetRasterCount(pahSrcDS[0]);
        if ((nBands == 1 ||
             (nBands > 1 && GDALGetRasterColorInterpretation(GDALGetRasterBand(
                                pahSrcDS[0], nBands)) != GCI_AlphaBand)) &&
            (psOptions->bEnableDstAlpha
#ifdef HAVE_TIFF
             || (EQUAL(psOptions->osFormat.c_str(), "COG") &&
                 COGHasWarpingOptions(aosCreateOptions.List()) &&
                 CPLTestBool(
                     aosCreateOptions.FetchNameValueDef("ADD_ALPHA", "YES")))
#endif
                 ))
        {
            aosArgv.AddString("-addalpha");
        }
        auto psBuildVRTOptions =
            GDALBuildVRTOptionsNew(aosArgv.List(), nullptr);
        hTmpDS = GDALBuildVRT("", nSrcCount, pahSrcDS, nullptr,
                              psBuildVRTOptions, nullptr);
        GDALBuildVRTOptionsFree(psBuildVRTOptions);
    }
    auto pfnProgress = psOptions->pfnProgress;
    auto pProgressData = psOptions->pProgressData;
    CPLString osTmpFilename;
    double dfStartPctCreateCopy = 0.0;
    if (hTmpDS == nullptr)
    {
        GDALTransformerArgUniquePtr hUniqueTransformArg;
#ifdef HAVE_TIFF
        // Special processing for COG output. As some of its options do
        // on-the-fly reprojection, take them into account now, and remove them
        // from the COG creation stage.
        if (EQUAL(psOptions->osFormat.c_str(), "COG") &&
            !DealWithCOGOptions(aosCreateOptions, nSrcCount, pahSrcDS,
                                psOptions, hUniqueTransformArg))
        {
            return nullptr;
        }
#endif

        // Materialize a temporary GeoTIFF with the result of the warp
        psOptions->osFormat = "GTiff";
        psOptions->aosCreateOptions.AddString("SPARSE_OK=YES");
        psOptions->aosCreateOptions.AddString("COMPRESS=LZW");
        psOptions->aosCreateOptions.AddString("TILED=YES");
        psOptions->aosCreateOptions.AddString("BIGTIFF=YES");
        psOptions->pfnProgress = myScaledProgress;
        dfStartPctCreateCopy = 2. / 3;
        psOptions->pProgressData = GDALCreateScaledProgress(
            0, dfStartPctCreateCopy, pfnProgress, pProgressData);
        psOptions->bDeleteOutputFileOnceCreated = true;
        osTmpFilename = CPLGenerateTempFilenameSafe(CPLGetFilename(pszDest));
        hTmpDS = GDALWarpDirect(osTmpFilename, nullptr, nSrcCount, pahSrcDS,
                                std::move(hUniqueTransformArg), psOptions,
                                pbUsageError);
        GDALDestroyScaledProgress(psOptions->pProgressData);
        psOptions->pfnProgress = nullptr;
        psOptions->pProgressData = nullptr;
    }
    if (hTmpDS)
    {
        auto pScaledProgressData = GDALCreateScaledProgress(
            dfStartPctCreateCopy, 1.0, pfnProgress, pProgressData);
        auto hRet = GDALCreateCopy(hDriver, pszDest, hTmpDS, FALSE,
                                   aosCreateOptions.List(), myScaledProgress,
                                   pScaledProgressData);
        GDALDestroyScaledProgress(pScaledProgressData);
        GDALClose(hTmpDS);
        VSIStatBufL sStat;
        if (!osTmpFilename.empty() &&
            VSIStatL(osTmpFilename.c_str(), &sStat) == 0)
        {
            GDALDeleteDataset(GDALGetDriverByName("GTiff"), osTmpFilename);
        }
        return hRet;
    }
    return nullptr;
}

/************************************************************************/
/*                             GDALWarp()                               */
/************************************************************************/

/**
 * Image reprojection and warping function.
 *
 * This is the equivalent of the <a href="/programs/gdalwarp.html">gdalwarp</a>
 * utility.
 *
 * GDALWarpAppOptions* must be allocated and freed with GDALWarpAppOptionsNew()
 * and GDALWarpAppOptionsFree() respectively.
 * pszDest and hDstDS cannot be used at the same time.
 *
 * @param pszDest the destination dataset path or NULL.
 * @param hDstDS the destination dataset or NULL.
 * @param nSrcCount the number of input datasets.
 * @param pahSrcDS the list of input datasets. For practical purposes, the type
 * of this argument should be considered as "const GDALDatasetH* const*", that
 * is neither the array nor its values are mutated by this function.
 * @param psOptionsIn the options struct returned by GDALWarpAppOptionsNew() or
 * NULL.
 * @param pbUsageError pointer to a integer output variable to store if any
 * usage error has occurred, or NULL.
 * @return the output dataset (new dataset that must be closed using
 * GDALClose(), or hDstDS if not NULL) or NULL in case of error. If the output
 * format is a VRT dataset, then the returned VRT dataset has a reference to
 * pahSrcDS[0]. Hence pahSrcDS[0] should be closed after the returned dataset
 * if using GDALClose().
 * A safer alternative is to use GDALReleaseDataset() instead of using
 * GDALClose(), in which case you can close datasets in any order.
 *
 * @since GDAL 2.1
 */

GDALDatasetH GDALWarp(const char *pszDest, GDALDatasetH hDstDS, int nSrcCount,
                      GDALDatasetH *pahSrcDS,
                      const GDALWarpAppOptions *psOptionsIn, int *pbUsageError)
{
    CPLErrorReset();

    for (int i = 0; i < nSrcCount; i++)
    {
        if (!pahSrcDS[i])
            return nullptr;
    }

    GDALWarpAppOptions oOptionsTmp;
    if (psOptionsIn)
        oOptionsTmp = *psOptionsIn;
    GDALWarpAppOptions *psOptions = &oOptionsTmp;

    if (hDstDS == nullptr)
    {
        if (psOptions->osFormat.empty())
        {
            psOptions->osFormat = GetOutputDriverForRaster(pszDest);
            if (psOptions->osFormat.empty())
            {
                return nullptr;
            }
        }

        auto hDriver = GDALGetDriverByName(psOptions->osFormat.c_str());
        if (hDriver != nullptr &&
            GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATE, nullptr) ==
                nullptr &&
            GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATECOPY, nullptr) !=
                nullptr)
        {
            auto ret = GDALWarpIndirect(pszDest, hDriver, nSrcCount, pahSrcDS,
                                        psOptions, pbUsageError);
            return ret;
        }
    }

    auto ret = GDALWarpDirect(pszDest, hDstDS, nSrcCount, pahSrcDS, nullptr,
                              psOptions, pbUsageError);

    return ret;
}

/************************************************************************/
/*                    UseTEAndTSAndTRConsistently()                     */
/************************************************************************/

static bool UseTEAndTSAndTRConsistently(const GDALWarpAppOptions *psOptions)
{
    // We normally don't allow -te, -ts and -tr together, unless they are all
    // consistent. The interest of this is to use the -tr values to produce
    // exact pixel size, rather than inferring it from -te and -ts

    // Constant and logic to be kept in sync with cogdriver.cpp
    constexpr double RELATIVE_ERROR_RES_SHARED_BY_COG_AND_GDALWARP = 1e-8;
    return psOptions->nForcePixels != 0 && psOptions->nForceLines != 0 &&
           psOptions->dfXRes != 0 && psOptions->dfYRes != 0 &&
           !(psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
             psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0) &&
           fabs((psOptions->dfMaxX - psOptions->dfMinX) / psOptions->dfXRes -
                psOptions->nForcePixels) <=
               RELATIVE_ERROR_RES_SHARED_BY_COG_AND_GDALWARP &&
           fabs((psOptions->dfMaxY - psOptions->dfMinY) / psOptions->dfYRes -
                psOptions->nForceLines) <=
               RELATIVE_ERROR_RES_SHARED_BY_COG_AND_GDALWARP;
}

/************************************************************************/
/*                            CheckOptions()                            */
/************************************************************************/

static bool CheckOptions(const char *pszDest, GDALDatasetH hDstDS,
                         int nSrcCount, GDALDatasetH *pahSrcDS,
                         GDALWarpAppOptions *psOptions, bool &bVRT,
                         int *pbUsageError)
{

    if (hDstDS)
    {
        if (psOptions->bCreateOutput == true)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "All options related to creation ignored in update mode");
            psOptions->bCreateOutput = false;
        }
    }

    if ((psOptions->osFormat.empty() &&
         EQUAL(CPLGetExtensionSafe(pszDest).c_str(), "VRT")) ||
        (EQUAL(psOptions->osFormat.c_str(), "VRT")))
    {
        if (hDstDS != nullptr)
        {
            CPLError(CE_Warning, CPLE_NotSupported,
                     "VRT output not compatible with existing dataset.");
            return false;
        }

        bVRT = true;

        if (nSrcCount > 1)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "gdalwarp -of VRT just takes into account "
                     "the first source dataset.\nIf all source datasets "
                     "are in the same projection, try making a mosaic of\n"
                     "them with gdalbuildvrt, and use the resulting "
                     "VRT file as the input of\ngdalwarp -of VRT.");
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Check that incompatible options are not used                    */
    /* -------------------------------------------------------------------- */

    if ((psOptions->nForcePixels != 0 || psOptions->nForceLines != 0) &&
        (psOptions->dfXRes != 0 && psOptions->dfYRes != 0) &&
        !UseTEAndTSAndTRConsistently(psOptions))
    {
        CPLError(CE_Failure, CPLE_IllegalArg,
                 "-tr and -ts options cannot be used at the same time.");
        if (pbUsageError)
            *pbUsageError = TRUE;
        return false;
    }

    if (psOptions->bTargetAlignedPixels && psOptions->dfXRes == 0 &&
        psOptions->dfYRes == 0)
    {
        CPLError(CE_Failure, CPLE_IllegalArg,
                 "-tap option cannot be used without using -tr.");
        if (pbUsageError)
            *pbUsageError = TRUE;
        return false;
    }

    if (!psOptions->bQuiet &&
        !(psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
          psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0))
    {
        if (psOptions->dfMinX >= psOptions->dfMaxX)
            CPLError(CE_Warning, CPLE_AppDefined,
                     "-te values have minx >= maxx. This will result in a "
                     "horizontally flipped image.");
        if (psOptions->dfMinY >= psOptions->dfMaxY)
            CPLError(CE_Warning, CPLE_AppDefined,
                     "-te values have miny >= maxy. This will result in a "
                     "vertically flipped image.");
    }

    if (psOptions->dfErrorThreshold < 0)
    {
        // By default, use approximate transformer unless RPC_DEM is specified
        if (psOptions->aosTransformerOptions.FetchNameValue("RPC_DEM") !=
            nullptr)
            psOptions->dfErrorThreshold = 0.0;
        else
            psOptions->dfErrorThreshold = 0.125;
    }

    /* -------------------------------------------------------------------- */
    /*      -te_srs option                                                  */
    /* -------------------------------------------------------------------- */
    if (!psOptions->osTE_SRS.empty())
    {
        if (psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
            psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "-te_srs ignored since -te is not specified.");
        }
        else
        {
            OGRSpatialReference oSRSIn;
            oSRSIn.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
            oSRSIn.SetFromUserInput(psOptions->osTE_SRS.c_str());
            OGRSpatialReference oSRSDS;
            oSRSDS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
            bool bOK = false;
            if (psOptions->aosTransformerOptions.FetchNameValue("DST_SRS") !=
                nullptr)
            {
                oSRSDS.SetFromUserInput(
                    psOptions->aosTransformerOptions.FetchNameValue("DST_SRS"));
                bOK = true;
            }
            else if (psOptions->aosTransformerOptions.FetchNameValue(
                         "SRC_SRS") != nullptr)
            {
                oSRSDS.SetFromUserInput(
                    psOptions->aosTransformerOptions.FetchNameValue("SRC_SRS"));
                bOK = true;
            }
            else if (nSrcCount)
            {
                const auto poSrcSRS =
                    GDALDataset::FromHandle(pahSrcDS[0])->GetSpatialRef();
                if (poSrcSRS)
                {
                    oSRSDS = *poSrcSRS;
                    bOK = true;
                }
            }
            if (!bOK)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "-te_srs ignored since none of -t_srs, -s_srs is "
                         "specified or the input dataset has no projection.");
                return false;
            }
            if (!oSRSIn.IsSame(&oSRSDS))
            {
                double dfWestLongitudeDeg = 0.0;
                double dfSouthLatitudeDeg = 0.0;
                double dfEastLongitudeDeg = 0.0;
                double dfNorthLatitudeDeg = 0.0;

                OGRCoordinateTransformationOptions options;
                if (GDALComputeAreaOfInterest(
                        &oSRSIn, psOptions->dfMinX, psOptions->dfMinY,
                        psOptions->dfMaxX, psOptions->dfMaxY,
                        dfWestLongitudeDeg, dfSouthLatitudeDeg,
                        dfEastLongitudeDeg, dfNorthLatitudeDeg))
                {
                    options.SetAreaOfInterest(
                        dfWestLongitudeDeg, dfSouthLatitudeDeg,
                        dfEastLongitudeDeg, dfNorthLatitudeDeg);
                }
                auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
                    OGRCreateCoordinateTransformation(&oSRSIn, &oSRSDS,
                                                      options));
                constexpr int DENSIFY_PTS = 21;
                if (!(poCT && poCT->TransformBounds(
                                  psOptions->dfMinX, psOptions->dfMinY,
                                  psOptions->dfMaxX, psOptions->dfMaxY,
                                  &(psOptions->dfMinX), &(psOptions->dfMinY),
                                  &(psOptions->dfMaxX), &(psOptions->dfMaxY),
                                  DENSIFY_PTS)))
                {
                    CPLError(CE_Failure, CPLE_AppDefined,
                             "-te_srs ignored since coordinate transformation "
                             "failed.");
                    return false;
                }
            }
        }
    }
    return true;
}

/************************************************************************/
/*                       ProcessCutlineOptions()                        */
/************************************************************************/

static bool ProcessCutlineOptions(int nSrcCount, GDALDatasetH *pahSrcDS,
                                  GDALWarpAppOptions *psOptions,
                                  std::unique_ptr<OGRGeometry> &poCutline)
{
    if (!psOptions->osCutlineDSNameOrWKT.empty())
    {
        CPLErr eError;
        OGRGeometryH hCutline = nullptr;
        eError = LoadCutline(psOptions->osCutlineDSNameOrWKT,
                             psOptions->osCutlineSRS, psOptions->osCLayer,
                             psOptions->osCWHERE, psOptions->osCSQL, &hCutline);
        poCutline.reset(OGRGeometry::FromHandle(hCutline));
        if (eError == CE_Failure)
        {
            return false;
        }
    }

    if (psOptions->bCropToCutline && poCutline)
    {
        CPLErr eError;
        eError = CropToCutline(poCutline.get(),
                               psOptions->aosTransformerOptions.List(),
                               psOptions->aosWarpOptions.List(), nSrcCount,
                               pahSrcDS, psOptions->dfMinX, psOptions->dfMinY,
                               psOptions->dfMaxX, psOptions->dfMaxY, psOptions);
        if (eError == CE_Failure)
        {
            return false;
        }
    }

    const char *pszWarpThreads =
        psOptions->aosWarpOptions.FetchNameValue("NUM_THREADS");
    if (pszWarpThreads != nullptr)
    {
        /* Used by TPS transformer to parallelize direct and inverse matrix
         * computation */
        psOptions->aosTransformerOptions.SetNameValue("NUM_THREADS",
                                                      pszWarpThreads);
    }

    return true;
}

/************************************************************************/
/*                            CreateOutput()                            */
/************************************************************************/

static GDALDatasetH
CreateOutput(const char *pszDest, int nSrcCount, GDALDatasetH *pahSrcDS,
             GDALWarpAppOptions *psOptions, const bool bInitDestSetByUser,
             GDALTransformerArgUniquePtr &hUniqueTransformArg)
{
    if (nSrcCount == 1 && !psOptions->bDisableSrcAlpha)
    {
        if (GDALGetRasterCount(pahSrcDS[0]) > 0 &&
            GDALGetRasterColorInterpretation(GDALGetRasterBand(
                pahSrcDS[0], GDALGetRasterCount(pahSrcDS[0]))) == GCI_AlphaBand)
        {
            psOptions->bEnableSrcAlpha = true;
            psOptions->bEnableDstAlpha = true;
            if (!psOptions->bQuiet)
                printf("Using band %d of source image as alpha.\n",
                       GDALGetRasterCount(pahSrcDS[0]));
        }
    }

    auto hDstDS = GDALWarpCreateOutput(
        nSrcCount, pahSrcDS, pszDest, psOptions->osFormat.c_str(),
        psOptions->aosTransformerOptions.List(),
        psOptions->aosCreateOptions.List(), psOptions->eOutputType,
        hUniqueTransformArg, psOptions->bSetColorInterpretation, psOptions,
        /* bUpdateTransformerWithDestGT = */ true);
    if (hDstDS == nullptr)
    {
        return nullptr;
    }
    psOptions->bCreateOutput = true;

    if (!bInitDestSetByUser)
    {
        if (psOptions->osDstNodata.empty())
        {
            psOptions->aosWarpOptions.SetNameValue("INIT_DEST", "0");
        }
        else
        {
            psOptions->aosWarpOptions.SetNameValue("INIT_DEST", "NO_DATA");
        }
    }

    return hDstDS;
}

/************************************************************************/
/*                    EditISIS3ForMetadataChanges()                     */
/************************************************************************/

static std::string
EditISIS3ForMetadataChanges(const char *pszJSON,
                            const GDALWarpAppOptions *psOptions)
{
    CPLJSONDocument oJSONDocument;
    if (!oJSONDocument.LoadMemory(pszJSON))
    {
        return std::string();
    }

    auto oRoot = oJSONDocument.GetRoot();
    if (!oRoot.IsValid())
    {
        return std::string();
    }

    auto oGDALHistory = oRoot.GetObj("GDALHistory");
    if (!oGDALHistory.IsValid())
    {
        oGDALHistory = CPLJSONObject();
        oRoot.Add("GDALHistory", oGDALHistory);
    }
    oGDALHistory["_type"] = "object";

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

    oGDALHistory["GdalVersion"] = GDALVersionInfo("RELEASE_NAME");
    oGDALHistory["Program"] = osProgram;
    if (osPath != ".")
        oGDALHistory["ProgramPath"] = osPath;

    std::string osArgs;
    for (const char *pszArg : psOptions->aosArgs)
    {
        if (!osArgs.empty())
            osArgs += ' ';
        osArgs += pszArg;
    }
    oGDALHistory["ProgramArguments"] = osArgs;

    oGDALHistory.Add(
        "Comment",
        "Part of that metadata might be invalid due to a reprojection "
        "operation having been performed by GDAL tools");

    return oRoot.Format(CPLJSONObject::PrettyFormat::Pretty);
}

/************************************************************************/
/*                           ProcessMetadata()                          */
/************************************************************************/

static void ProcessMetadata(int iSrc, GDALDatasetH hSrcDS, GDALDatasetH hDstDS,
                            const GDALWarpAppOptions *psOptions,
                            const bool bEnableDstAlpha)
{
    if (psOptions->bCopyMetadata)
    {
        const char *pszSrcInfo = nullptr;
        GDALRasterBandH hSrcBand = nullptr;
        GDALRasterBandH hDstBand = nullptr;

        /* copy metadata from first dataset */
        if (iSrc == 0)
        {
            CPLDebug(
                "WARP",
                "Copying metadata from first source to destination dataset");
            /* copy dataset-level metadata */
            char **papszMetadata = GDALGetMetadata(hSrcDS, nullptr);

            char **papszMetadataNew = nullptr;
            for (int i = 0;
                 papszMetadata != nullptr && papszMetadata[i] != nullptr; i++)
            {
                // Do not preserve NODATA_VALUES when the output includes an
                // alpha band
                if (bEnableDstAlpha &&
                    STARTS_WITH_CI(papszMetadata[i], "NODATA_VALUES="))
                {
                    continue;
                }
                // Do not preserve the CACHE_PATH from the WMS driver
                if (STARTS_WITH_CI(papszMetadata[i], "CACHE_PATH="))
                {
                    continue;
                }

                papszMetadataNew =
                    CSLAddString(papszMetadataNew, papszMetadata[i]);
            }

            if (CSLCount(papszMetadataNew) > 0)
            {
                if (GDALSetMetadata(hDstDS, papszMetadataNew, nullptr) !=
                    CE_None)
                    CPLError(CE_Warning, CPLE_AppDefined,
                             "error copying metadata to destination dataset.");
            }

            CSLDestroy(papszMetadataNew);

            /* ISIS3 -> ISIS3 special case */
            if (EQUAL(psOptions->osFormat.c_str(), "ISIS3") ||
                EQUAL(psOptions->osFormat.c_str(), "PDS4") ||
                EQUAL(psOptions->osFormat.c_str(), "GTIFF") ||
                EQUAL(psOptions->osFormat.c_str(), "COG"))
            {
                char **papszMD_ISIS3 = GDALGetMetadata(hSrcDS, "json:ISIS3");
                if (papszMD_ISIS3 != nullptr && papszMD_ISIS3[0])
                {
                    std::string osJSON = papszMD_ISIS3[0];
                    osJSON =
                        EditISIS3ForMetadataChanges(osJSON.c_str(), psOptions);
                    if (!osJSON.empty())
                    {
                        char *apszMD[] = {osJSON.data(), nullptr};
                        GDALSetMetadata(hDstDS, apszMD, "json:ISIS3");
                    }
                }
            }
            else if (EQUAL(psOptions->osFormat.c_str(), "PDS4"))
            {
                char **papszMD_PDS4 = GDALGetMetadata(hSrcDS, "xml:PDS4");
                if (papszMD_PDS4 != nullptr)
                    GDALSetMetadata(hDstDS, papszMD_PDS4, "xml:PDS4");
            }
            else if (EQUAL(psOptions->osFormat.c_str(), "VICAR"))
            {
                char **papszMD_VICAR = GDALGetMetadata(hSrcDS, "json:VICAR");
                if (papszMD_VICAR != nullptr)
                    GDALSetMetadata(hDstDS, papszMD_VICAR, "json:VICAR");
            }

            /* copy band-level metadata and other info */
            if (GDALGetRasterCount(hSrcDS) == GDALGetRasterCount(hDstDS))
            {
                for (int iBand = 0; iBand < GDALGetRasterCount(hSrcDS); iBand++)
                {
                    hSrcBand = GDALGetRasterBand(hSrcDS, iBand + 1);
                    hDstBand = GDALGetRasterBand(hDstDS, iBand + 1);
                    /* copy metadata, except stats (#5319) */
                    papszMetadata = GDALGetMetadata(hSrcBand, nullptr);
                    if (CSLCount(papszMetadata) > 0)
                    {
                        // GDALSetMetadata( hDstBand, papszMetadata, NULL );
                        papszMetadataNew = nullptr;
                        for (int i = 0; papszMetadata != nullptr &&
                                        papszMetadata[i] != nullptr;
                             i++)
                        {
                            if (!STARTS_WITH(papszMetadata[i], "STATISTICS_"))
                                papszMetadataNew = CSLAddString(
                                    papszMetadataNew, papszMetadata[i]);
                        }
                        GDALSetMetadata(hDstBand, papszMetadataNew, nullptr);
                        CSLDestroy(papszMetadataNew);
                    }
                    /* copy other info (Description, Unit Type) - what else? */
                    if (psOptions->bCopyBandInfo)
                    {
                        pszSrcInfo = GDALGetDescription(hSrcBand);
                        if (pszSrcInfo != nullptr && strlen(pszSrcInfo) > 0)
                            GDALSetDescription(hDstBand, pszSrcInfo);
                        pszSrcInfo = GDALGetRasterUnitType(hSrcBand);
                        if (pszSrcInfo != nullptr && strlen(pszSrcInfo) > 0)
                            GDALSetRasterUnitType(hDstBand, pszSrcInfo);
                    }
                }
            }
        }
        /* remove metadata that conflicts between datasets */
        else
        {
            CPLDebug("WARP",
                     "Removing conflicting metadata from destination dataset "
                     "(source #%d)",
                     iSrc);
            /* remove conflicting dataset-level metadata */
            RemoveConflictingMetadata(hDstDS, GDALGetMetadata(hSrcDS, nullptr),
                                      psOptions->osMDConflictValue.c_str());

            /* remove conflicting copy band-level metadata and other info */
            if (GDALGetRasterCount(hSrcDS) == GDALGetRasterCount(hDstDS))
            {
                for (int iBand = 0; iBand < GDALGetRasterCount(hSrcDS); iBand++)
                {
                    hSrcBand = GDALGetRasterBand(hSrcDS, iBand + 1);
                    hDstBand = GDALGetRasterBand(hDstDS, iBand + 1);
                    /* remove conflicting metadata */
                    RemoveConflictingMetadata(
                        hDstBand, GDALGetMetadata(hSrcBand, nullptr),
                        psOptions->osMDConflictValue.c_str());
                    /* remove conflicting info */
                    if (psOptions->bCopyBandInfo)
                    {
                        pszSrcInfo = GDALGetDescription(hSrcBand);
                        const char *pszDstInfo = GDALGetDescription(hDstBand);
                        if (!(pszSrcInfo != nullptr && strlen(pszSrcInfo) > 0 &&
                              pszDstInfo != nullptr && strlen(pszDstInfo) > 0 &&
                              EQUAL(pszSrcInfo, pszDstInfo)))
                            GDALSetDescription(hDstBand, "");
                        pszSrcInfo = GDALGetRasterUnitType(hSrcBand);
                        pszDstInfo = GDALGetRasterUnitType(hDstBand);
                        if (!(pszSrcInfo != nullptr && strlen(pszSrcInfo) > 0 &&
                              pszDstInfo != nullptr && strlen(pszDstInfo) > 0 &&
                              EQUAL(pszSrcInfo, pszDstInfo)))
                            GDALSetRasterUnitType(hDstBand, "");
                    }
                }
            }
        }
    }
}

/************************************************************************/
/*                             SetupNoData()                            */
/************************************************************************/

static CPLErr SetupNoData(const char *pszDest, int iSrc, GDALDatasetH hSrcDS,
                          GDALDatasetH hWrkSrcDS, GDALDatasetH hDstDS,
                          GDALWarpOptions *psWO, GDALWarpAppOptions *psOptions,
                          const bool bEnableDstAlpha,
                          const bool bInitDestSetByUser)
{
    if (!psOptions->osSrcNodata.empty() &&
        !EQUAL(psOptions->osSrcNodata.c_str(), "none"))
    {
        CPLStringList aosTokens(
            CSLTokenizeString(psOptions->osSrcNodata.c_str()));
        const int nTokenCount = aosTokens.Count();

        psWO->padfSrcNoDataReal =
            static_cast<double *>(CPLMalloc(psWO->nBandCount * sizeof(double)));
        psWO->padfSrcNoDataImag = nullptr;

        for (int i = 0; i < psWO->nBandCount; i++)
        {
            if (i < nTokenCount)
            {
                double dfNoDataReal;
                double dfNoDataImag;

                if (CPLStringToComplex(aosTokens[i], &dfNoDataReal,
                                       &dfNoDataImag) != CE_None)
                {
                    CPLError(CE_Failure, CPLE_AppDefined,
                             "Error parsing srcnodata for band %d", i + 1);
                    return CE_Failure;
                }

                psWO->padfSrcNoDataReal[i] =
                    GDALAdjustNoDataCloseToFloatMax(dfNoDataReal);

                if (strchr(aosTokens[i], 'i') != nullptr)
                {
                    if (psWO->padfSrcNoDataImag == nullptr)
                    {
                        psWO->padfSrcNoDataImag = static_cast<double *>(
                            CPLCalloc(psWO->nBandCount, sizeof(double)));
                    }
                    psWO->padfSrcNoDataImag[i] =
                        GDALAdjustNoDataCloseToFloatMax(dfNoDataImag);
                }
            }
            else
            {
                psWO->padfSrcNoDataReal[i] = psWO->padfSrcNoDataReal[i - 1];
                if (psWO->padfSrcNoDataImag != nullptr)
                {
                    psWO->padfSrcNoDataImag[i] = psWO->padfSrcNoDataImag[i - 1];
                }
            }
        }

        if (psWO->nBandCount > 1 &&
            CSLFetchNameValue(psWO->papszWarpOptions, "UNIFIED_SRC_NODATA") ==
                nullptr)
        {
            CPLDebug("WARP", "Set UNIFIED_SRC_NODATA=YES");
            psWO->papszWarpOptions = CSLSetNameValue(
                psWO->papszWarpOptions, "UNIFIED_SRC_NODATA", "YES");
        }
    }

    /* -------------------------------------------------------------------- */
    /*      If -srcnodata was not specified, but the data has nodata        */
    /*      values, use them.                                               */
    /* -------------------------------------------------------------------- */
    if (psOptions->osSrcNodata.empty())
    {
        int bHaveNodata = FALSE;
        double dfReal = 0.0;

        for (int i = 0; !bHaveNodata && i < psWO->nBandCount; i++)
        {
            GDALRasterBandH hBand =
                GDALGetRasterBand(hWrkSrcDS, psWO->panSrcBands[i]);
            dfReal = GDALGetRasterNoDataValue(hBand, &bHaveNodata);
        }

        if (bHaveNodata)
        {
            if (!psOptions->bQuiet)
            {
                if (std::isnan(dfReal))
                    printf("Using internal nodata values (e.g. nan) for image "
                           "%s.\n",
                           GDALGetDescription(hSrcDS));
                else
                    printf("Using internal nodata values (e.g. %g) for image "
                           "%s.\n",
                           dfReal, GDALGetDescription(hSrcDS));
            }
            psWO->padfSrcNoDataReal = static_cast<double *>(
                CPLMalloc(psWO->nBandCount * sizeof(double)));

            for (int i = 0; i < psWO->nBandCount; i++)
            {
                GDALRasterBandH hBand =
                    GDALGetRasterBand(hWrkSrcDS, psWO->panSrcBands[i]);

                dfReal = GDALGetRasterNoDataValue(hBand, &bHaveNodata);

                if (bHaveNodata)
                {
                    psWO->padfSrcNoDataReal[i] = dfReal;
                }
                else
                {
                    psWO->padfSrcNoDataReal[i] = -123456.789;
                }
            }
        }
    }

    /* -------------------------------------------------------------------- */
    /*      If the output dataset was created, and we have a destination    */
    /*      nodata value, go through marking the bands with the information.*/
    /* -------------------------------------------------------------------- */
    if (!psOptions->osDstNodata.empty() &&
        !EQUAL(psOptions->osDstNodata.c_str(), "none"))
    {
        CPLStringList aosTokens(
            CSLTokenizeString(psOptions->osDstNodata.c_str()));
        const int nTokenCount = aosTokens.Count();
        bool bDstNoDataNone = true;

        psWO->padfDstNoDataReal =
            static_cast<double *>(CPLMalloc(psWO->nBandCount * sizeof(double)));
        psWO->padfDstNoDataImag =
            static_cast<double *>(CPLMalloc(psWO->nBandCount * sizeof(double)));

        for (int i = 0; i < psWO->nBandCount; i++)
        {
            psWO->padfDstNoDataReal[i] = -1.1e20;
            psWO->padfDstNoDataImag[i] = 0.0;

            if (i < nTokenCount)
            {
                if (aosTokens[i] != nullptr && EQUAL(aosTokens[i], "none"))
                {
                    CPLDebug("WARP", "dstnodata of band %d not set", i);
                    bDstNoDataNone = true;
                    continue;
                }
                else if (aosTokens[i] ==
                         nullptr)  // this should not happen, but just in case
                {
                    CPLError(CE_Failure, CPLE_AppDefined,
                             "Error parsing dstnodata arg #%d", i);
                    bDstNoDataNone = true;
                    continue;
                }

                if (CPLStringToComplex(aosTokens[i],
                                       psWO->padfDstNoDataReal + i,
                                       psWO->padfDstNoDataImag + i) != CE_None)
                {

                    CPLError(CE_Failure, CPLE_AppDefined,
                             "Error parsing dstnodata for band %d", i + 1);
                    return CE_Failure;
                }

                psWO->padfDstNoDataReal[i] =
                    GDALAdjustNoDataCloseToFloatMax(psWO->padfDstNoDataReal[i]);
                psWO->padfDstNoDataImag[i] =
                    GDALAdjustNoDataCloseToFloatMax(psWO->padfDstNoDataImag[i]);
                bDstNoDataNone = false;
                CPLDebug("WARP", "dstnodata of band %d set to %f", i,
                         psWO->padfDstNoDataReal[i]);
            }
            else
            {
                if (!bDstNoDataNone)
                {
                    psWO->padfDstNoDataReal[i] = psWO->padfDstNoDataReal[i - 1];
                    psWO->padfDstNoDataImag[i] = psWO->padfDstNoDataImag[i - 1];
                    CPLDebug("WARP",
                             "dstnodata of band %d set from previous band", i);
                }
                else
                {
                    CPLDebug("WARP", "dstnodata value of band %d not set", i);
                    continue;
                }
            }

            GDALRasterBandH hBand =
                GDALGetRasterBand(hDstDS, psWO->panDstBands[i]);
            int bClamped = FALSE;
            int bRounded = FALSE;
            psWO->padfDstNoDataReal[i] = GDALAdjustValueToDataType(
                GDALGetRasterDataType(hBand), psWO->padfDstNoDataReal[i],
                &bClamped, &bRounded);

            if (bClamped)
            {
                CPLError(
                    CE_Warning, CPLE_AppDefined,
                    "for band %d, destination nodata value has been clamped "
                    "to %.0f, the original value being out of range.",
                    psWO->panDstBands[i], psWO->padfDstNoDataReal[i]);
            }
            else if (bRounded)
            {
                CPLError(
                    CE_Warning, CPLE_AppDefined,
                    "for band %d, destination nodata value has been rounded "
                    "to %.0f, %s being an integer datatype.",
                    psWO->panDstBands[i], psWO->padfDstNoDataReal[i],
                    GDALGetDataTypeName(GDALGetRasterDataType(hBand)));
            }

            if (psOptions->bCreateOutput && iSrc == 0)
            {
                GDALSetRasterNoDataValue(
                    GDALGetRasterBand(hDstDS, psWO->panDstBands[i]),
                    psWO->padfDstNoDataReal[i]);
            }
        }
    }

    /* check if the output dataset has already nodata */
    if (psOptions->osDstNodata.empty())
    {
        int bHaveNodataAll = TRUE;
        for (int i = 0; i < psWO->nBandCount; i++)
        {
            GDALRasterBandH hBand =
                GDALGetRasterBand(hDstDS, psWO->panDstBands[i]);
            int bHaveNodata = FALSE;
            GDALGetRasterNoDataValue(hBand, &bHaveNodata);
            bHaveNodataAll &= bHaveNodata;
        }
        if (bHaveNodataAll)
        {
            psWO->padfDstNoDataReal = static_cast<double *>(
                CPLMalloc(psWO->nBandCount * sizeof(double)));
            for (int i = 0; i < psWO->nBandCount; i++)
            {
                GDALRasterBandH hBand =
                    GDALGetRasterBand(hDstDS, psWO->panDstBands[i]);
                int bHaveNodata = FALSE;
                psWO->padfDstNoDataReal[i] =
                    GDALGetRasterNoDataValue(hBand, &bHaveNodata);
                CPLDebug("WARP", "band=%d dstNoData=%f", i,
                         psWO->padfDstNoDataReal[i]);
            }
        }
    }

    // If creating a new file that has default nodata value,
    // try to override the default output nodata values with the source ones.
    if (psOptions->osDstNodata.empty() && psWO->padfSrcNoDataReal != nullptr &&
        psWO->padfDstNoDataReal != nullptr && psOptions->bCreateOutput &&
        iSrc == 0 && !bEnableDstAlpha)
    {
        for (int i = 0; i < psWO->nBandCount; i++)
        {
            GDALRasterBandH hBand =
                GDALGetRasterBand(hDstDS, psWO->panDstBands[i]);
            int bHaveNodata = FALSE;
            CPLPushErrorHandler(CPLQuietErrorHandler);
            bool bRedefinedOK =
                (GDALSetRasterNoDataValue(hBand, psWO->padfSrcNoDataReal[i]) ==
                     CE_None &&
                 GDALGetRasterNoDataValue(hBand, &bHaveNodata) ==
                     psWO->padfSrcNoDataReal[i] &&
                 bHaveNodata);
            CPLPopErrorHandler();
            if (bRedefinedOK)
            {
                if (i == 0 && !psOptions->bQuiet)
                    printf("Copying nodata values from source %s "
                           "to destination %s.\n",
                           GDALGetDescription(hSrcDS), pszDest);
                psWO->padfDstNoDataReal[i] = psWO->padfSrcNoDataReal[i];

                if (i == 0 && !bInitDestSetByUser)
                {
                    /* As we didn't know at the beginning if there was source
                     * nodata */
                    /* we have initialized INIT_DEST=0. Override this with
                     * NO_DATA now */
                    psWO->papszWarpOptions = CSLSetNameValue(
                        psWO->papszWarpOptions, "INIT_DEST", "NO_DATA");
                }
            }
            else
            {
                break;
            }
        }
    }

    /* else try to fill dstNoData from source bands, unless -dstalpha is
     * specified */
    else if (psOptions->osDstNodata.empty() &&
             psWO->padfSrcNoDataReal != nullptr &&
             psWO->padfDstNoDataReal == nullptr && !bEnableDstAlpha)
    {
        psWO->padfDstNoDataReal =
            static_cast<double *>(CPLMalloc(psWO->nBandCount * sizeof(double)));

        if (psWO->padfSrcNoDataImag != nullptr)
        {
            psWO->padfDstNoDataImag = static_cast<double *>(
                CPLMalloc(psWO->nBandCount * sizeof(double)));
        }

        if (!psOptions->bQuiet)
            printf("Copying nodata values from source %s to destination %s.\n",
                   GDALGetDescription(hSrcDS), pszDest);

        for (int i = 0; i < psWO->nBandCount; i++)
        {
            psWO->padfDstNoDataReal[i] = psWO->padfSrcNoDataReal[i];
            if (psWO->padfSrcNoDataImag != nullptr)
            {
                psWO->padfDstNoDataImag[i] = psWO->padfSrcNoDataImag[i];
            }
            CPLDebug("WARP", "srcNoData=%f dstNoData=%f",
                     psWO->padfSrcNoDataReal[i], psWO->padfDstNoDataReal[i]);

            if (psOptions->bCreateOutput && iSrc == 0)
            {
                CPLDebug("WARP",
                         "calling GDALSetRasterNoDataValue() for band#%d", i);
                GDALSetRasterNoDataValue(
                    GDALGetRasterBand(hDstDS, psWO->panDstBands[i]),
                    psWO->padfDstNoDataReal[i]);
            }
        }

        if (psOptions->bCreateOutput && !bInitDestSetByUser && iSrc == 0)
        {
            /* As we didn't know at the beginning if there was source nodata */
            /* we have initialized INIT_DEST=0. Override this with NO_DATA now
             */
            psWO->papszWarpOptions =
                CSLSetNameValue(psWO->papszWarpOptions, "INIT_DEST", "NO_DATA");
        }
    }

    return CE_None;
}

/************************************************************************/
/*                         SetupSkipNoSource()                          */
/************************************************************************/

static void SetupSkipNoSource(int iSrc, GDALDatasetH hDstDS,
                              GDALWarpOptions *psWO,
                              GDALWarpAppOptions *psOptions)
{
    if (psOptions->bCreateOutput && iSrc == 0 &&
        CSLFetchNameValue(psWO->papszWarpOptions, "SKIP_NOSOURCE") == nullptr &&
        CSLFetchNameValue(psWO->papszWarpOptions, "STREAMABLE_OUTPUT") ==
            nullptr &&
        // This white list of drivers could potentially be extended.
        (EQUAL(psOptions->osFormat.c_str(), "MEM") ||
         EQUAL(psOptions->osFormat.c_str(), "GTiff") ||
         EQUAL(psOptions->osFormat.c_str(), "GPKG")))
    {
        // We can enable the optimization only if the user didn't specify
        // a INIT_DEST value that would contradict the destination nodata.

        bool bOKRegardingInitDest = false;
        const char *pszInitDest =
            CSLFetchNameValue(psWO->papszWarpOptions, "INIT_DEST");
        if (pszInitDest == nullptr || EQUAL(pszInitDest, "NO_DATA"))
        {
            bOKRegardingInitDest = true;

            // The MEM driver will return non-initialized blocks at 0
            // so make sure that the nodata value is 0.
            if (EQUAL(psOptions->osFormat.c_str(), "MEM"))
            {
                for (int i = 0; i < GDALGetRasterCount(hDstDS); i++)
                {
                    int bHasNoData = false;
                    double dfDstNoDataVal = GDALGetRasterNoDataValue(
                        GDALGetRasterBand(hDstDS, i + 1), &bHasNoData);
                    if (bHasNoData && dfDstNoDataVal != 0.0)
                    {
                        bOKRegardingInitDest = false;
                        break;
                    }
                }
            }
        }
        else
        {
            char **papszTokensInitDest = CSLTokenizeString(pszInitDest);
            const int nTokenCountInitDest = CSLCount(papszTokensInitDest);
            if (nTokenCountInitDest == 1 ||
                nTokenCountInitDest == GDALGetRasterCount(hDstDS))
            {
                bOKRegardingInitDest = true;
                for (int i = 0; i < GDALGetRasterCount(hDstDS); i++)
                {
                    double dfInitVal = GDALAdjustNoDataCloseToFloatMax(
                        CPLAtofM(papszTokensInitDest[std::min(
                            i, nTokenCountInitDest - 1)]));
                    int bHasNoData = false;
                    double dfDstNoDataVal = GDALGetRasterNoDataValue(
                        GDALGetRasterBand(hDstDS, i + 1), &bHasNoData);
                    if (!((bHasNoData && dfInitVal == dfDstNoDataVal) ||
                          (!bHasNoData && dfInitVal == 0.0)))
                    {
                        bOKRegardingInitDest = false;
                        break;
                    }
                    if (EQUAL(psOptions->osFormat.c_str(), "MEM") &&
                        bHasNoData && dfDstNoDataVal != 0.0)
                    {
                        bOKRegardingInitDest = false;
                        break;
                    }
                }
            }
            CSLDestroy(papszTokensInitDest);
        }

        if (bOKRegardingInitDest)
        {
            CPLDebug("GDALWARP", "Defining SKIP_NOSOURCE=YES");
            psWO->papszWarpOptions =
                CSLSetNameValue(psWO->papszWarpOptions, "SKIP_NOSOURCE", "YES");
        }
    }
}

/************************************************************************/
/*                     AdjustOutputExtentForRPC()                       */
/************************************************************************/

/** Returns false if there's no intersection between source extent defined
 * by RPC and target extent.
 */
static bool AdjustOutputExtentForRPC(GDALDatasetH hSrcDS, GDALDatasetH hDstDS,
                                     GDALTransformerFunc pfnTransformer,
                                     void *hTransformArg, GDALWarpOptions *psWO,
                                     GDALWarpAppOptions *psOptions,
                                     int &nWarpDstXOff, int &nWarpDstYOff,
                                     int &nWarpDstXSize, int &nWarpDstYSize)
{
    if (CPLTestBool(CSLFetchNameValueDef(psWO->papszWarpOptions,
                                         "SKIP_NOSOURCE", "NO")) &&
        GDALGetMetadata(hSrcDS, "RPC") != nullptr &&
        EQUAL(FetchSrcMethod(psOptions->aosTransformerOptions, "RPC"), "RPC") &&
        CPLTestBool(
            CPLGetConfigOption("RESTRICT_OUTPUT_DATASET_UPDATE", "YES")))
    {
        double adfSuggestedGeoTransform[6];
        double adfExtent[4];
        int nPixels, nLines;
        if (GDALSuggestedWarpOutput2(hSrcDS, pfnTransformer, hTransformArg,
                                     adfSuggestedGeoTransform, &nPixels,
                                     &nLines, adfExtent, 0) == CE_None)
        {
            const double dfMinX = adfExtent[0];
            const double dfMinY = adfExtent[1];
            const double dfMaxX = adfExtent[2];
            const double dfMaxY = adfExtent[3];
            const double dfThreshold = static_cast<double>(INT_MAX) / 2;
            if (std::fabs(dfMinX) < dfThreshold &&
                std::fabs(dfMinY) < dfThreshold &&
                std::fabs(dfMaxX) < dfThreshold &&
                std::fabs(dfMaxY) < dfThreshold)
            {
                const int nPadding = 5;
                nWarpDstXOff =
                    std::max(nWarpDstXOff,
                             static_cast<int>(std::floor(dfMinX)) - nPadding);
                nWarpDstYOff =
                    std::max(nWarpDstYOff,
                             static_cast<int>(std::floor(dfMinY)) - nPadding);
                nWarpDstXSize = std::min(nWarpDstXSize - nWarpDstXOff,
                                         static_cast<int>(std::ceil(dfMaxX)) +
                                             nPadding - nWarpDstXOff);
                nWarpDstYSize = std::min(nWarpDstYSize - nWarpDstYOff,
                                         static_cast<int>(std::ceil(dfMaxY)) +
                                             nPadding - nWarpDstYOff);
                if (nWarpDstXSize <= 0 || nWarpDstYSize <= 0)
                {
                    CPLDebug("WARP",
                             "No intersection between source extent defined "
                             "by RPC and target extent");
                    return false;
                }
                if (nWarpDstXOff != 0 || nWarpDstYOff != 0 ||
                    nWarpDstXSize != GDALGetRasterXSize(hDstDS) ||
                    nWarpDstYSize != GDALGetRasterYSize(hDstDS))
                {
                    CPLDebug("WARP",
                             "Restricting warping to output dataset window "
                             "%d,%d,%dx%d",
                             nWarpDstXOff, nWarpDstYOff, nWarpDstXSize,
                             nWarpDstYSize);
                }
            }
        }
    }
    return true;
}

/************************************************************************/
/*                           GDALWarpDirect()                           */
/************************************************************************/

static GDALDatasetH
GDALWarpDirect(const char *pszDest, GDALDatasetH hDstDS, int nSrcCount,
               GDALDatasetH *pahSrcDS,
               GDALTransformerArgUniquePtr hUniqueTransformArg,
               GDALWarpAppOptions *psOptions, int *pbUsageError)
{
    CPLErrorReset();
    if (pszDest == nullptr && hDstDS == nullptr)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "pszDest == NULL && hDstDS == NULL");

        if (pbUsageError)
            *pbUsageError = TRUE;
        return nullptr;
    }
    if (pszDest == nullptr)
        pszDest = GDALGetDescription(hDstDS);

#ifdef DEBUG
    GDALDataset *poDstDS = GDALDataset::FromHandle(hDstDS);
    const int nExpectedRefCountAtEnd =
        (poDstDS != nullptr) ? poDstDS->GetRefCount() : 1;
    (void)nExpectedRefCountAtEnd;
#endif
    const bool bDropDstDSRef = (hDstDS != nullptr);
    if (hDstDS != nullptr)
        GDALReferenceDataset(hDstDS);

#if defined(USE_PROJ_BASED_VERTICAL_SHIFT_METHOD)
    if (psOptions->bNoVShift)
    {
        psOptions->aosTransformerOptions.SetNameValue("@STRIP_VERT_CS", "YES");
    }
    else if (nSrcCount)
    {
        bool bSrcHasVertAxis = false;
        bool bDstHasVertAxis = false;
        OGRSpatialReference oSRSSrc;
        OGRSpatialReference oSRSDst;

        if (MustApplyVerticalShift(pahSrcDS[0], psOptions, oSRSSrc, oSRSDst,
                                   bSrcHasVertAxis, bDstHasVertAxis))
        {
            psOptions->aosTransformerOptions.SetNameValue("PROMOTE_TO_3D",
                                                          "YES");
        }
    }
#else
    psOptions->aosTransformerOptions.SetNameValue("@STRIP_VERT_CS", "YES");
#endif

    bool bVRT = false;
    if (!CheckOptions(pszDest, hDstDS, nSrcCount, pahSrcDS, psOptions, bVRT,
                      pbUsageError))
    {
        return nullptr;
    }

    /* -------------------------------------------------------------------- */
    /*      If we have a cutline datasource read it and attach it in the    */
    /*      warp options.                                                   */
    /* -------------------------------------------------------------------- */
    std::unique_ptr<OGRGeometry> poCutline;
    if (!ProcessCutlineOptions(nSrcCount, pahSrcDS, psOptions, poCutline))
    {
        return nullptr;
    }

    /* -------------------------------------------------------------------- */
    /*      If the target dataset does not exist, we need to create it.     */
    /* -------------------------------------------------------------------- */
    const bool bInitDestSetByUser =
        (psOptions->aosWarpOptions.FetchNameValue("INIT_DEST") != nullptr);

    const bool bFigureoutCorrespondingWindow =
        (hDstDS != nullptr) ||
        (((psOptions->nForcePixels != 0 && psOptions->nForceLines != 0) ||
          (psOptions->dfXRes != 0 && psOptions->dfYRes != 0)) &&
         !(psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
           psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0));

    const char *pszMethod = FetchSrcMethod(psOptions->aosTransformerOptions);
    if (pszMethod && EQUAL(pszMethod, "GCP_TPS") &&
        psOptions->dfErrorThreshold > 0 &&
        !psOptions->aosTransformerOptions.FetchNameValue(
            "SRC_APPROX_ERROR_IN_PIXEL"))
    {
        psOptions->aosTransformerOptions.SetNameValue(
            "SRC_APPROX_ERROR_IN_PIXEL",
            CPLSPrintf("%g", psOptions->dfErrorThreshold));
    }

    if (hDstDS == nullptr)
    {
        hDstDS = CreateOutput(pszDest, nSrcCount, pahSrcDS, psOptions,
                              bInitDestSetByUser, hUniqueTransformArg);
        if (!hDstDS)
        {
            return nullptr;
        }
#ifdef DEBUG
        // Do not remove this if the #ifdef DEBUG before is still there !
        poDstDS = GDALDataset::FromHandle(hDstDS);
        CPL_IGNORE_RET_VAL(poDstDS);
#endif
    }
    else
    {
        if (psOptions->aosWarpOptions.FetchNameValue("SKIP_NOSOURCE") ==
            nullptr)
        {
            CPLDebug("GDALWARP", "Defining SKIP_NOSOURCE=YES");
            psOptions->aosWarpOptions.SetNameValue("SKIP_NOSOURCE", "YES");
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Detect if output has alpha channel.                             */
    /* -------------------------------------------------------------------- */
    bool bEnableDstAlpha = psOptions->bEnableDstAlpha;
    if (!bEnableDstAlpha && GDALGetRasterCount(hDstDS) &&
        GDALGetRasterColorInterpretation(GDALGetRasterBand(
            hDstDS, GDALGetRasterCount(hDstDS))) == GCI_AlphaBand &&
        !psOptions->bDisableSrcAlpha)
    {
        if (!psOptions->bQuiet)
            printf("Using band %d of destination image as alpha.\n",
                   GDALGetRasterCount(hDstDS));

        bEnableDstAlpha = true;
    }

    /* -------------------------------------------------------------------- */
    /*      Create global progress function.                                */
    /* -------------------------------------------------------------------- */
    struct Progress
    {
        GDALProgressFunc pfnExternalProgress;
        void *pExternalProgressData;
        int iSrc;
        int nSrcCount;
        GDALDatasetH *pahSrcDS;

        int Do(double dfComplete)
        {
            CPLString osMsg;
            osMsg.Printf("Processing %s [%d/%d]",
                         CPLGetFilename(GDALGetDescription(pahSrcDS[iSrc])),
                         iSrc + 1, nSrcCount);
            return pfnExternalProgress((iSrc + dfComplete) / nSrcCount,
                                       osMsg.c_str(), pExternalProgressData);
        }

        static int CPL_STDCALL ProgressFunc(double dfComplete, const char *,
                                            void *pThis)
        {
            return static_cast<Progress *>(pThis)->Do(dfComplete);
        }
    };

    Progress oProgress;
    oProgress.pfnExternalProgress = psOptions->pfnProgress;
    oProgress.pExternalProgressData = psOptions->pProgressData;
    oProgress.nSrcCount = nSrcCount;
    oProgress.pahSrcDS = pahSrcDS;

    /* -------------------------------------------------------------------- */
    /*      Loop over all source files, processing each in turn.            */
    /* -------------------------------------------------------------------- */
    bool bHasGotErr = false;
    for (int iSrc = 0; iSrc < nSrcCount; iSrc++)
    {
        GDALDatasetH hSrcDS;

        /* --------------------------------------------------------------------
         */
        /*      Open this file. */
        /* --------------------------------------------------------------------
         */
        hSrcDS = pahSrcDS[iSrc];
        oProgress.iSrc = iSrc;

        /* --------------------------------------------------------------------
         */
        /*      Check that there's at least one raster band */
        /* --------------------------------------------------------------------
         */
        if (GDALGetRasterCount(hSrcDS) == 0)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Input file %s has no raster bands.",
                     GDALGetDescription(hSrcDS));
            GDALReleaseDataset(hDstDS);
            return nullptr;
        }

        /* --------------------------------------------------------------------
         */
        /*      Do we have a source alpha band? */
        /* --------------------------------------------------------------------
         */
        bool bEnableSrcAlpha = psOptions->bEnableSrcAlpha;
        if (GDALGetRasterColorInterpretation(GDALGetRasterBand(
                hSrcDS, GDALGetRasterCount(hSrcDS))) == GCI_AlphaBand &&
            !bEnableSrcAlpha && !psOptions->bDisableSrcAlpha)
        {
            bEnableSrcAlpha = true;
            if (!psOptions->bQuiet)
                printf("Using band %d of source image as alpha.\n",
                       GDALGetRasterCount(hSrcDS));
        }

        /* --------------------------------------------------------------------
         */
        /*      Get the metadata of the first source DS and copy it to the */
        /*      destination DS. Copy Band-level metadata and other info, only */
        /*      if source and destination band count are equal. Any values that
         */
        /*      conflict between source datasets are set to pszMDConflictValue.
         */
        /* --------------------------------------------------------------------
         */
        ProcessMetadata(iSrc, hSrcDS, hDstDS, psOptions, bEnableDstAlpha);

        /* --------------------------------------------------------------------
         */
        /*      Warns if the file has a color table and something more */
        /*      complicated than nearest neighbour resampling is asked */
        /* --------------------------------------------------------------------
         */

        if (psOptions->eResampleAlg != GRA_NearestNeighbour &&
            psOptions->eResampleAlg != GRA_Mode &&
            GDALGetRasterColorTable(GDALGetRasterBand(hSrcDS, 1)) != nullptr)
        {
            if (!psOptions->bQuiet)
                CPLError(
                    CE_Warning, CPLE_AppDefined,
                    "Input file %s has a color table, which will likely lead "
                    "to "
                    "bad results when using a resampling method other than "
                    "nearest neighbour or mode. Converting the dataset prior "
                    "to 24/32 bit "
                    "is advised.",
                    GDALGetDescription(hSrcDS));
        }

        // For RPC warping add a few extra source pixels by default
        // (probably mostly needed in the RPC DEM case)
        if (iSrc == 0 && (GDALGetMetadata(hSrcDS, "RPC") != nullptr &&
                          (pszMethod == nullptr || EQUAL(pszMethod, "RPC"))))
        {
            if (!psOptions->aosWarpOptions.FetchNameValue("SOURCE_EXTRA"))
            {
                CPLDebug(
                    "WARP",
                    "Set SOURCE_EXTRA=5 warping options due to RPC warping");
                psOptions->aosWarpOptions.SetNameValue("SOURCE_EXTRA", "5");
            }

            if (!psOptions->aosWarpOptions.FetchNameValue("SAMPLE_STEPS") &&
                !psOptions->aosWarpOptions.FetchNameValue("SAMPLE_GRID") &&
                psOptions->aosTransformerOptions.FetchNameValue("RPC_DEM"))
            {
                CPLDebug("WARP", "Set SAMPLE_STEPS=ALL warping options due to "
                                 "RPC DEM warping");
                psOptions->aosWarpOptions.SetNameValue("SAMPLE_STEPS", "ALL");
            }
        }
        // Also do the same for GCP TPS warping, e.g. to solve use case of
        // https://github.com/OSGeo/gdal/issues/12736
        else if (iSrc == 0 &&
                 (GDALGetGCPCount(hSrcDS) > 0 &&
                  (pszMethod == nullptr || EQUAL(pszMethod, "TPS"))))
        {
            if (!psOptions->aosWarpOptions.FetchNameValue("SOURCE_EXTRA"))
            {
                CPLDebug(
                    "WARP",
                    "Set SOURCE_EXTRA=5 warping options due to TPS warping");
            }
        }

        /* --------------------------------------------------------------------
         */
        /*      Create a transformation object from the source to */
        /*      destination coordinate system. */
        /* --------------------------------------------------------------------
         */
        GDALTransformerArgUniquePtr hTransformArg;
        if (hUniqueTransformArg)
            hTransformArg = std::move(hUniqueTransformArg);
        else
        {
            hTransformArg.reset(GDALCreateGenImgProjTransformer2(
                hSrcDS, hDstDS, psOptions->aosTransformerOptions.List()));
            if (hTransformArg == nullptr)
            {
                GDALReleaseDataset(hDstDS);
                return nullptr;
            }
        }

        GDALTransformerFunc pfnTransformer = GDALGenImgProjTransform;

        // Check if transformation is inversible
        {
            double dfX = GDALGetRasterXSize(hDstDS) / 2.0;
            double dfY = GDALGetRasterYSize(hDstDS) / 2.0;
            double dfZ = 0;
            int bSuccess = false;
            const auto nErrorCounterBefore = CPLGetErrorCounter();
            pfnTransformer(hTransformArg.get(), TRUE, 1, &dfX, &dfY, &dfZ,
                           &bSuccess);
            if (!bSuccess && CPLGetErrorCounter() > nErrorCounterBefore &&
                strstr(CPLGetLastErrorMsg(), "No inverse operation"))
            {
                GDALReleaseDataset(hDstDS);
                return nullptr;
            }
        }

        /* --------------------------------------------------------------------
         */
        /*      Determine if we must work with the full-resolution source */
        /*      dataset, or one of its overview level. */
        /* --------------------------------------------------------------------
         */
        GDALDataset *poSrcDS = static_cast<GDALDataset *>(hSrcDS);
        GDALDataset *poSrcOvrDS = nullptr;
        int nOvCount = poSrcDS->GetRasterBand(1)->GetOverviewCount();
        if (psOptions->nOvLevel <= OVR_LEVEL_AUTO && nOvCount > 0)
        {
            double dfTargetRatio = 0;
            double dfTargetRatioX = 0;
            double dfTargetRatioY = 0;

            if (bFigureoutCorrespondingWindow)
            {
                // If the user has explicitly set the target bounds and
                // resolution, or we're updating an existing file, then figure
                // out which source window corresponds to the target raster.
                constexpr int nPointsOneDim = 10;
                constexpr int nPoints = nPointsOneDim * nPointsOneDim;
                std::vector<double> adfX(nPoints);
                std::vector<double> adfY(nPoints);
                std::vector<double> adfZ(nPoints);
                const int nDstXSize = GDALGetRasterXSize(hDstDS);
                const int nDstYSize = GDALGetRasterYSize(hDstDS);
                int iPoint = 0;
                for (int iX = 0; iX < nPointsOneDim; ++iX)
                {
                    for (int iY = 0; iY < nPointsOneDim; ++iY)
                    {
                        adfX[iPoint] = nDstXSize * static_cast<double>(iX) /
                                       (nPointsOneDim - 1);
                        adfY[iPoint] = nDstYSize * static_cast<double>(iY) /
                                       (nPointsOneDim - 1);
                        iPoint++;
                    }
                }
                std::vector<int> abSuccess(nPoints);
                pfnTransformer(hTransformArg.get(), TRUE, nPoints, &adfX[0],
                               &adfY[0], &adfZ[0], &abSuccess[0]);

                double dfMinSrcX = std::numeric_limits<double>::infinity();
                double dfMaxSrcX = -std::numeric_limits<double>::infinity();
                double dfMinSrcY = std::numeric_limits<double>::infinity();
                double dfMaxSrcY = -std::numeric_limits<double>::infinity();
                for (int i = 0; i < nPoints; i++)
                {
                    if (abSuccess[i])
                    {
                        dfMinSrcX = std::min(dfMinSrcX, adfX[i]);
                        dfMaxSrcX = std::max(dfMaxSrcX, adfX[i]);
                        dfMinSrcY = std::min(dfMinSrcY, adfY[i]);
                        dfMaxSrcY = std::max(dfMaxSrcY, adfY[i]);
                    }
                }
                if (dfMaxSrcX > dfMinSrcX)
                {
                    dfTargetRatioX =
                        (dfMaxSrcX - dfMinSrcX) / GDALGetRasterXSize(hDstDS);
                }
                if (dfMaxSrcY > dfMinSrcY)
                {
                    dfTargetRatioY =
                        (dfMaxSrcY - dfMinSrcY) / GDALGetRasterYSize(hDstDS);
                }
                // take the minimum of these ratios #7019
                dfTargetRatio = std::min(dfTargetRatioX, dfTargetRatioY);
            }
            else
            {
                /* Compute what the "natural" output resolution (in pixels)
                 * would be for this */
                /* input dataset */
                double adfSuggestedGeoTransform[6];
                int nPixels, nLines;
                if (GDALSuggestedWarpOutput(
                        hSrcDS, pfnTransformer, hTransformArg.get(),
                        adfSuggestedGeoTransform, &nPixels, &nLines) == CE_None)
                {
                    dfTargetRatio = 1.0 / adfSuggestedGeoTransform[1];
                }
            }

            if (dfTargetRatio > 1.0)
            {
                // Note: keep this logic for overview selection in sync between
                // gdalwarp_lib.cpp and rasterio.cpp
                const char *pszOversampligThreshold = CPLGetConfigOption(
                    "GDALWARP_OVERSAMPLING_THRESHOLD", nullptr);
                const double dfOversamplingThreshold =
                    pszOversampligThreshold ? CPLAtof(pszOversampligThreshold)
                                            : 1.0;

                int iBestOvr = -1;
                double dfBestRatio = 0;
                for (int iOvr = -1; iOvr < nOvCount; iOvr++)
                {
                    const double dfOvrRatio =
                        iOvr < 0
                            ? 1.0
                            : static_cast<double>(poSrcDS->GetRasterXSize()) /
                                  poSrcDS->GetRasterBand(1)
                                      ->GetOverview(iOvr)
                                      ->GetXSize();

                    // Is it nearly the requested factor and better (lower) than
                    // the current best factor?
                    // Use an epsilon because of numerical instability.
                    constexpr double EPSILON = 1e-1;
                    if (dfOvrRatio >=
                            dfTargetRatio * dfOversamplingThreshold + EPSILON ||
                        dfOvrRatio <= dfBestRatio)
                    {
                        continue;
                    }

                    iBestOvr = iOvr;
                    dfBestRatio = dfOvrRatio;
                    if (std::abs(dfTargetRatio - dfOvrRatio) < EPSILON)
                    {
                        break;
                    }
                }
                const int iOvr =
                    iBestOvr + (psOptions->nOvLevel - OVR_LEVEL_AUTO);
                if (iOvr >= 0)
                {
                    CPLDebug("WARP", "Selecting overview level %d for %s", iOvr,
                             GDALGetDescription(hSrcDS));
                    poSrcOvrDS =
                        GDALCreateOverviewDataset(poSrcDS, iOvr,
                                                  /* bThisLevelOnly = */ false);
                }
            }
        }
        else if (psOptions->nOvLevel >= 0)
        {
            poSrcOvrDS = GDALCreateOverviewDataset(poSrcDS, psOptions->nOvLevel,
                                                   /* bThisLevelOnly = */ true);
            if (poSrcOvrDS == nullptr)
            {
                if (!psOptions->bQuiet)
                {
                    CPLError(CE_Warning, CPLE_AppDefined,
                             "cannot get overview level %d for "
                             "dataset %s. Defaulting to level %d",
                             psOptions->nOvLevel, GDALGetDescription(hSrcDS),
                             nOvCount - 1);
                }
                if (nOvCount > 0)
                    poSrcOvrDS =
                        GDALCreateOverviewDataset(poSrcDS, nOvCount - 1,
                                                  /* bThisLevelOnly = */ false);
            }
            else
            {
                CPLDebug("WARP", "Selecting overview level %d for %s",
                         psOptions->nOvLevel, GDALGetDescription(hSrcDS));
            }
        }

        if (poSrcOvrDS == nullptr)
            GDALReferenceDataset(hSrcDS);

        GDALDatasetH hWrkSrcDS =
            poSrcOvrDS ? static_cast<GDALDatasetH>(poSrcOvrDS) : hSrcDS;

#if !defined(USE_PROJ_BASED_VERTICAL_SHIFT_METHOD)
        if (!psOptions->bNoVShift)
        {
            bool bErrorOccurred = false;
            hWrkSrcDS = ApplyVerticalShiftGrid(
                hWrkSrcDS, psOptions, bVRT ? hDstDS : nullptr, bErrorOccurred);
            if (bErrorOccurred)
            {
                GDALReleaseDataset(hWrkSrcDS);
                GDALReleaseDataset(hDstDS);
                return nullptr;
            }
        }
#endif

        /* --------------------------------------------------------------------
         */
        /*      Clear temporary INIT_DEST settings after the first image. */
        /* --------------------------------------------------------------------
         */
        if (psOptions->bCreateOutput && iSrc == 1)
            psOptions->aosWarpOptions.SetNameValue("INIT_DEST", nullptr);

        /* --------------------------------------------------------------------
         */
        /*      Define SKIP_NOSOURCE after the first image (since
         * initialization*/
        /*      has already be done). */
        /* --------------------------------------------------------------------
         */
        if (iSrc == 1 && psOptions->aosWarpOptions.FetchNameValue(
                             "SKIP_NOSOURCE") == nullptr)
        {
            CPLDebug("GDALWARP", "Defining SKIP_NOSOURCE=YES");
            psOptions->aosWarpOptions.SetNameValue("SKIP_NOSOURCE", "YES");
        }

        /* --------------------------------------------------------------------
         */
        /*      Setup warp options. */
        /* --------------------------------------------------------------------
         */
        std::unique_ptr<GDALWarpOptions, decltype(&GDALDestroyWarpOptions)>
            psWO(GDALCreateWarpOptions(), GDALDestroyWarpOptions);

        psWO->papszWarpOptions = CSLDuplicate(psOptions->aosWarpOptions.List());
        psWO->eWorkingDataType = psOptions->eWorkingType;

        psWO->eResampleAlg = psOptions->eResampleAlg;

        psWO->hSrcDS = hWrkSrcDS;
        psWO->hDstDS = hDstDS;

        if (!bVRT)
        {
            if (psOptions->pfnProgress == GDALDummyProgress)
            {
                psWO->pfnProgress = GDALDummyProgress;
                psWO->pProgressArg = nullptr;
            }
            else
            {
                psWO->pfnProgress = Progress::ProgressFunc;
                psWO->pProgressArg = &oProgress;
            }
        }

        if (psOptions->dfWarpMemoryLimit != 0.0)
            psWO->dfWarpMemoryLimit = psOptions->dfWarpMemoryLimit;

        /* --------------------------------------------------------------------
         */
        /*      Setup band mapping. */
        /* --------------------------------------------------------------------
         */
        if (psOptions->anSrcBands.empty())
        {
            if (bEnableSrcAlpha)
                psWO->nBandCount = GDALGetRasterCount(hWrkSrcDS) - 1;
            else
                psWO->nBandCount = GDALGetRasterCount(hWrkSrcDS);
        }
        else
        {
            psWO->nBandCount = static_cast<int>(psOptions->anSrcBands.size());
        }

        const int nNeededDstBands =
            psWO->nBandCount + (bEnableDstAlpha ? 1 : 0);
        if (nNeededDstBands > GDALGetRasterCount(hDstDS))
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Destination dataset has %d bands, but at least %d "
                     "are needed",
                     GDALGetRasterCount(hDstDS), nNeededDstBands);
            GDALReleaseDataset(hWrkSrcDS);
            GDALReleaseDataset(hDstDS);
            return nullptr;
        }

        psWO->panSrcBands =
            static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
        psWO->panDstBands =
            static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
        if (psOptions->anSrcBands.empty())
        {
            for (int i = 0; i < psWO->nBandCount; i++)
            {
                psWO->panSrcBands[i] = i + 1;
                psWO->panDstBands[i] = i + 1;
            }
        }
        else
        {
            for (int i = 0; i < psWO->nBandCount; i++)
            {
                if (psOptions->anSrcBands[i] <= 0 ||
                    psOptions->anSrcBands[i] > GDALGetRasterCount(hSrcDS))
                {
                    CPLError(CE_Failure, CPLE_AppDefined,
                             "-srcband[%d] = %d is invalid", i,
                             psOptions->anSrcBands[i]);
                    GDALReleaseDataset(hWrkSrcDS);
                    GDALReleaseDataset(hDstDS);
                    return nullptr;
                }
                if (psOptions->anDstBands[i] <= 0 ||
                    psOptions->anDstBands[i] > GDALGetRasterCount(hDstDS))
                {
                    CPLError(CE_Failure, CPLE_AppDefined,
                             "-dstband[%d] = %d is invalid", i,
                             psOptions->anDstBands[i]);
                    GDALReleaseDataset(hWrkSrcDS);
                    GDALReleaseDataset(hDstDS);
                    return nullptr;
                }
                psWO->panSrcBands[i] = psOptions->anSrcBands[i];
                psWO->panDstBands[i] = psOptions->anDstBands[i];
            }
        }

        /* --------------------------------------------------------------------
         */
        /*      Setup alpha bands used if any. */
        /* --------------------------------------------------------------------
         */
        if (bEnableSrcAlpha)
            psWO->nSrcAlphaBand = GDALGetRasterCount(hWrkSrcDS);

        if (bEnableDstAlpha)
        {
            if (psOptions->anSrcBands.empty())
                psWO->nDstAlphaBand = GDALGetRasterCount(hDstDS);
            else
                psWO->nDstAlphaBand =
                    static_cast<int>(psOptions->anDstBands.size()) + 1;
        }

        /* ------------------------------------------------------------------ */
        /*      Setup NODATA options.                                         */
        /* ------------------------------------------------------------------ */
        if (SetupNoData(pszDest, iSrc, hSrcDS, hWrkSrcDS, hDstDS, psWO.get(),
                        psOptions, bEnableDstAlpha,
                        bInitDestSetByUser) != CE_None)
        {
            GDALReleaseDataset(hWrkSrcDS);
            GDALReleaseDataset(hDstDS);
            return nullptr;
        }

        oProgress.Do(0);

        /* --------------------------------------------------------------------
         */
        /*      For the first source image of a newly created dataset, decide */
        /*      if we can safely enable SKIP_NOSOURCE optimization. */
        /* --------------------------------------------------------------------
         */
        SetupSkipNoSource(iSrc, hDstDS, psWO.get(), psOptions);

        /* --------------------------------------------------------------------
         */
        /*      In some cases, RPC evaluation can find valid input pixel for */
        /*      output pixels that are outside the footprint of the source */
        /*      dataset, so limit the area we update in the target dataset from
         */
        /*      the suggested warp output (only in cases where
         * SKIP_NOSOURCE=YES) */
        /* --------------------------------------------------------------------
         */
        int nWarpDstXOff = 0;
        int nWarpDstYOff = 0;
        int nWarpDstXSize = GDALGetRasterXSize(hDstDS);
        int nWarpDstYSize = GDALGetRasterYSize(hDstDS);

        if (!AdjustOutputExtentForRPC(hSrcDS, hDstDS, pfnTransformer,
                                      hTransformArg.get(), psWO.get(),
                                      psOptions, nWarpDstXOff, nWarpDstYOff,
                                      nWarpDstXSize, nWarpDstYSize))
        {
            GDALReleaseDataset(hWrkSrcDS);
            continue;
        }

        /* We need to recreate the transform when operating on an overview */
        if (poSrcOvrDS != nullptr)
        {
            hTransformArg.reset(GDALCreateGenImgProjTransformer2(
                hWrkSrcDS, hDstDS, psOptions->aosTransformerOptions.List()));
        }

        bool bUseApproxTransformer = psOptions->dfErrorThreshold != 0.0;
#ifdef USE_PROJ_BASED_VERTICAL_SHIFT_METHOD
        if (!psOptions->bNoVShift)
        {
            // Can modify psWO->papszWarpOptions
            if (ApplyVerticalShift(hWrkSrcDS, psOptions, psWO.get()))
            {
                bUseApproxTransformer = false;
            }
        }
#endif

        /* --------------------------------------------------------------------
         */
        /*      Warp the transformer with a linear approximator unless the */
        /*      acceptable error is zero. */
        /* --------------------------------------------------------------------
         */
        if (bUseApproxTransformer)
        {
            hTransformArg.reset(GDALCreateApproxTransformer(
                GDALGenImgProjTransform, hTransformArg.release(),
                psOptions->dfErrorThreshold));
            pfnTransformer = GDALApproxTransform;
            GDALApproxTransformerOwnsSubtransformer(hTransformArg.get(), TRUE);
        }

        /* --------------------------------------------------------------------
         */
        /*      If we have a cutline, transform it into the source */
        /*      pixel/line coordinate system and insert into warp options. */
        /* --------------------------------------------------------------------
         */
        if (poCutline)
        {
            CPLErr eError;
            eError = TransformCutlineToSource(
                GDALDataset::FromHandle(hWrkSrcDS), poCutline.get(),
                &(psWO->papszWarpOptions),
                psOptions->aosTransformerOptions.List());
            if (eError == CE_Failure)
            {
                GDALReleaseDataset(hWrkSrcDS);
                GDALReleaseDataset(hDstDS);
                return nullptr;
            }
        }

        /* --------------------------------------------------------------------
         */
        /*      If we are producing VRT output, then just initialize it with */
        /*      the warp options and write out now rather than proceeding */
        /*      with the operations. */
        /* --------------------------------------------------------------------
         */
        if (bVRT)
        {
            GDALSetMetadataItem(hDstDS, "SrcOvrLevel",
                                CPLSPrintf("%d", psOptions->nOvLevel), nullptr);

            // In case of success, hDstDS has become the owner of hTransformArg
            // so we need to release it
            psWO->pfnTransformer = pfnTransformer;
            psWO->pTransformerArg = hTransformArg.release();
            CPLErr eErr = GDALInitializeWarpedVRT(hDstDS, psWO.get());
            if (eErr != CE_None)
            {
                // In case of error, reacquire psWO->pTransformerArg
                hTransformArg.reset(psWO->pTransformerArg);
            }
            GDALReleaseDataset(hWrkSrcDS);
            if (eErr != CE_None)
            {
                GDALReleaseDataset(hDstDS);
                return nullptr;
            }

            if (!EQUAL(pszDest, ""))
            {
                const bool bWasFailureBefore =
                    (CPLGetLastErrorType() == CE_Failure);
                GDALFlushCache(hDstDS);
                if (!bWasFailureBefore && CPLGetLastErrorType() == CE_Failure)
                {
                    GDALReleaseDataset(hDstDS);
                    hDstDS = nullptr;
                }
            }

            if (hDstDS)
                oProgress.Do(1);

            return hDstDS;
        }

        /* --------------------------------------------------------------------
         */
        /*      Initialize and execute the warp. */
        /* --------------------------------------------------------------------
         */
        GDALWarpOperation oWO;

        if (oWO.Initialize(psWO.get(), pfnTransformer,
                           std::move(hTransformArg)) == CE_None)
        {
            CPLErr eErr;
            if (psOptions->bMulti)
                eErr = oWO.ChunkAndWarpMulti(nWarpDstXOff, nWarpDstYOff,
                                             nWarpDstXSize, nWarpDstYSize);
            else
                eErr = oWO.ChunkAndWarpImage(nWarpDstXOff, nWarpDstYOff,
                                             nWarpDstXSize, nWarpDstYSize);
            if (eErr != CE_None)
                bHasGotErr = true;
        }
        else
        {
            bHasGotErr = true;
        }

        /* --------------------------------------------------------------------
         */
        /*      Cleanup */
        /* --------------------------------------------------------------------
         */
        GDALReleaseDataset(hWrkSrcDS);
    }

    /* -------------------------------------------------------------------- */
    /*      Final Cleanup.                                                  */
    /* -------------------------------------------------------------------- */
    const bool bWasFailureBefore = (CPLGetLastErrorType() == CE_Failure);
    GDALFlushCache(hDstDS);
    if (!bWasFailureBefore && CPLGetLastErrorType() == CE_Failure)
    {
        bHasGotErr = true;
    }

    if (bHasGotErr || bDropDstDSRef)
        GDALReleaseDataset(hDstDS);

#ifdef DEBUG
    if (!bHasGotErr || bDropDstDSRef)
    {
        CPLAssert(poDstDS->GetRefCount() == nExpectedRefCountAtEnd);
    }
#endif

    return bHasGotErr ? nullptr : hDstDS;
}

/************************************************************************/
/*                          ValidateCutline()                           */
/*  Same as OGR_G_IsValid() except that it processes polygon per polygon*/
/*  without paying attention to MultiPolygon specific validity rules.   */
/************************************************************************/

static bool ValidateCutline(const OGRGeometry *poGeom, bool bVerbose)
{
    const OGRwkbGeometryType eType = wkbFlatten(poGeom->getGeometryType());
    if (eType == wkbMultiPolygon)
    {
        for (const auto *poSubGeom : *(poGeom->toMultiPolygon()))
        {
            if (!ValidateCutline(poSubGeom, bVerbose))
                return false;
        }
    }
    else if (eType == wkbPolygon)
    {
        if (OGRGeometryFactory::haveGEOS() && !poGeom->IsValid())
        {
            if (!bVerbose)
                return false;

            char *pszWKT = nullptr;
            poGeom->exportToWkt(&pszWKT);
            CPLDebug("GDALWARP", "WKT = \"%s\"", pszWKT ? pszWKT : "(null)");
            const char *pszFile =
                CPLGetConfigOption("GDALWARP_DUMP_WKT_TO_FILE", nullptr);
            if (pszFile && pszWKT)
            {
                FILE *f =
                    EQUAL(pszFile, "stderr") ? stderr : fopen(pszFile, "wb");
                if (f)
                {
                    fprintf(f, "id,WKT\n");
                    fprintf(f, "1,\"%s\"\n", pszWKT);
                    if (!EQUAL(pszFile, "stderr"))
                        fclose(f);
                }
            }
            CPLFree(pszWKT);

            if (CPLTestBool(
                    CPLGetConfigOption("GDALWARP_IGNORE_BAD_CUTLINE", "NO")))
                CPLError(CE_Warning, CPLE_AppDefined,
                         "Cutline polygon is invalid.");
            else
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Cutline polygon is invalid.");
                return false;
            }
        }
    }
    else
    {
        if (bVerbose)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Cutline not of polygon type.");
        }
        return false;
    }

    return true;
}

/************************************************************************/
/*                            LoadCutline()                             */
/*                                                                      */
/*      Load blend cutline from OGR datasource.                         */
/************************************************************************/

static CPLErr LoadCutline(const std::string &osCutlineDSNameOrWKT,
                          const std::string &osSRS, const std::string &osCLayer,
                          const std::string &osCWHERE,
                          const std::string &osCSQL, OGRGeometryH *phCutlineRet)

{
    if (STARTS_WITH_CI(osCutlineDSNameOrWKT.c_str(), "POLYGON(") ||
        STARTS_WITH_CI(osCutlineDSNameOrWKT.c_str(), "POLYGON (") ||
        STARTS_WITH_CI(osCutlineDSNameOrWKT.c_str(), "MULTIPOLYGON(") ||
        STARTS_WITH_CI(osCutlineDSNameOrWKT.c_str(), "MULTIPOLYGON ("))
    {
        std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSRS;
        if (!osSRS.empty())
        {
            poSRS.reset(new OGRSpatialReference());
            poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
            poSRS->SetFromUserInput(osSRS.c_str());
        }

        auto [poGeom, _] = OGRGeometryFactory::createFromWkt(
            osCutlineDSNameOrWKT.c_str(), poSRS.get());
        *phCutlineRet = OGRGeometry::ToHandle(poGeom.release());
        return *phCutlineRet ? CE_None : CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Open source vector dataset.                                     */
    /* -------------------------------------------------------------------- */
    auto poDS = std::unique_ptr<GDALDataset>(
        GDALDataset::Open(osCutlineDSNameOrWKT.c_str(), GDAL_OF_VECTOR));
    if (poDS == nullptr)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s.",
                 osCutlineDSNameOrWKT.c_str());
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Get the source layer                                            */
    /* -------------------------------------------------------------------- */
    OGRLayer *poLayer = nullptr;

    if (!osCSQL.empty())
        poLayer = poDS->ExecuteSQL(osCSQL.c_str(), nullptr, nullptr);
    else if (!osCLayer.empty())
        poLayer = poDS->GetLayerByName(osCLayer.c_str());
    else
        poLayer = poDS->GetLayer(0);

    if (poLayer == nullptr)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Failed to identify source layer from datasource.");
        return CE_Failure;
    }

    /* -------------------------------------------------------------------- */
    /*      Apply WHERE clause if there is one.                             */
    /* -------------------------------------------------------------------- */
    if (!osCWHERE.empty())
        poLayer->SetAttributeFilter(osCWHERE.c_str());

    /* -------------------------------------------------------------------- */
    /*      Collect the geometries from this layer, and build list of       */
    /*      burn values.                                                    */
    /* -------------------------------------------------------------------- */
    auto poMultiPolygon = std::make_unique<OGRMultiPolygon>();

    for (auto &&poFeature : poLayer)
    {
        auto poGeom = std::unique_ptr<OGRGeometry>(poFeature->StealGeometry());
        if (poGeom == nullptr)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Cutline feature without a geometry.");
            goto error;
        }

        if (!ValidateCutline(poGeom.get(), true))
        {
            goto error;
        }

        OGRwkbGeometryType eType = wkbFlatten(poGeom->getGeometryType());

        if (eType == wkbPolygon)
            poMultiPolygon->addGeometry(std::move(poGeom));
        else if (eType == wkbMultiPolygon)
        {
            for (const auto *poSubGeom : poGeom->toMultiPolygon())
            {
                poMultiPolygon->addGeometry(poSubGeom);
            }
        }
    }

    if (poMultiPolygon->IsEmpty())
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Did not get any cutline features.");
        goto error;
    }

    /* -------------------------------------------------------------------- */
    /*      Ensure the coordinate system gets set on the geometry.          */
    /* -------------------------------------------------------------------- */
    if (!osSRS.empty())
    {
        std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSRS(
            new OGRSpatialReference());
        poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
        poSRS->SetFromUserInput(osSRS.c_str());
        poMultiPolygon->assignSpatialReference(poSRS.get());
    }
    else
    {
        poMultiPolygon->assignSpatialReference(poLayer->GetSpatialRef());
    }

    *phCutlineRet = OGRGeometry::ToHandle(poMultiPolygon.release());

    /* -------------------------------------------------------------------- */
    /*      Cleanup                                                         */
    /* -------------------------------------------------------------------- */
    if (!osCSQL.empty())
        poDS->ReleaseResultSet(poLayer);

    return CE_None;

error:
    if (!osCSQL.empty())
        poDS->ReleaseResultSet(poLayer);

    return CE_Failure;
}

/************************************************************************/
/*                        GDALWarpCreateOutput()                        */
/*                                                                      */
/*      Create the output file based on various command line options,   */
/*      and the input file.                                             */
/*      If there's just one source file, then hUniqueTransformArg will  */
/*      be set in order them to be reused by main function. This saves  */
/*      transform recomputation, which can be expensive in the -tps case*/
/************************************************************************/

static GDALDatasetH GDALWarpCreateOutput(
    int nSrcCount, GDALDatasetH *pahSrcDS, const char *pszFilename,
    const char *pszFormat, char **papszTO, CSLConstList papszCreateOptions,
    GDALDataType eDT, GDALTransformerArgUniquePtr &hUniqueTransformArg,
    bool bSetColorInterpretation, GDALWarpAppOptions *psOptions,
    bool bUpdateTransformerWithDestGT)

{
    GDALDriverH hDriver;
    GDALDatasetH hDstDS;
    GDALRasterAttributeTableH hRAT = nullptr;
    double dfWrkMinX = 0, dfWrkMaxX = 0, dfWrkMinY = 0, dfWrkMaxY = 0;
    double dfWrkResX = 0, dfWrkResY = 0;
    int nDstBandCount = 0;
    std::vector<GDALColorInterp> apeColorInterpretations;
    bool bVRT = false;

    if (EQUAL(pszFormat, "VRT"))
        bVRT = true;

    // Special case for geographic to Mercator (typically EPSG:4326 to EPSG:3857)
    // where latitudes close to 90 go to infinity
    // We clamp latitudes between ~ -85 and ~ 85 degrees.
    const char *pszDstSRS = CSLFetchNameValue(papszTO, "DST_SRS");
    if (nSrcCount == 1 && pszDstSRS && psOptions->dfMinX == 0.0 &&
        psOptions->dfMinY == 0.0 && psOptions->dfMaxX == 0.0 &&
        psOptions->dfMaxY == 0.0)
    {
        auto hSrcDS = pahSrcDS[0];
        const auto osSrcSRS = GetSrcDSProjection(pahSrcDS[0], papszTO);
        OGRSpatialReference oSrcSRS;
        oSrcSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
        oSrcSRS.SetFromUserInput(osSrcSRS.c_str());
        OGRSpatialReference oDstSRS;
        oDstSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
        oDstSRS.SetFromUserInput(pszDstSRS);
        const char *pszProjection = oDstSRS.GetAttrValue("PROJECTION");
        const char *pszMethod = FetchSrcMethod(papszTO);
        double adfSrcGT[6] = {0};
        // This MAX_LAT values is equivalent to the semi_major_axis * PI
        // easting/northing value only for EPSG:3857, but it is also quite
        // reasonable for other Mercator projections
        constexpr double MAX_LAT = 85.0511287798066;
        constexpr double EPS = 1e-3;
        const auto GetMinLon = [&adfSrcGT]() { return adfSrcGT[0]; };
        const auto GetMaxLon = [&adfSrcGT, hSrcDS]()
        { return adfSrcGT[0] + adfSrcGT[1] * GDALGetRasterXSize(hSrcDS); };
        const auto GetMinLat = [&adfSrcGT, hSrcDS]()
        { return adfSrcGT[3] + adfSrcGT[5] * GDALGetRasterYSize(hSrcDS); };
        const auto GetMaxLat = [&adfSrcGT]() { return adfSrcGT[3]; };
        if (oSrcSRS.IsGeographic() && !oSrcSRS.IsDerivedGeographic() &&
            pszProjection && EQUAL(pszProjection, SRS_PT_MERCATOR_1SP) &&
            oDstSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0) == 0 &&
            (pszMethod == nullptr || EQUAL(pszMethod, "GEOTRANSFORM")) &&
            CSLFetchNameValue(papszTO, "COORDINATE_OPERATION") == nullptr &&
            CSLFetchNameValue(papszTO, "SRC_METHOD") == nullptr &&
            CSLFetchNameValue(papszTO, "DST_METHOD") == nullptr &&
            GDALGetGeoTransform(hSrcDS, adfSrcGT) == CE_None &&
            adfSrcGT[2] == 0 && adfSrcGT[4] == 0 && adfSrcGT[5] < 0 &&
            GetMinLon() >= -180 - EPS && GetMaxLon() <= 180 + EPS &&
            ((GetMaxLat() > MAX_LAT && GetMinLat() < MAX_LAT) ||
             (GetMaxLat() > -MAX_LAT && GetMinLat() < -MAX_LAT)) &&
            GDALGetMetadata(hSrcDS, "GEOLOC_ARRAY") == nullptr &&
            GDALGetMetadata(hSrcDS, "RPC") == nullptr)
        {
            auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
                OGRCreateCoordinateTransformation(&oSrcSRS, &oDstSRS));
            if (poCT)
            {
                double xLL = std::max(GetMinLon(), -180.0);
                double yLL = std::max(GetMinLat(), -MAX_LAT);
                double xUR = std::min(GetMaxLon(), 180.0);
                double yUR = std::min(GetMaxLat(), MAX_LAT);
                if (poCT->Transform(1, &xLL, &yLL) &&
                    poCT->Transform(1, &xUR, &yUR))
                {
                    psOptions->dfMinX = xLL;
                    psOptions->dfMinY = yLL;
                    psOptions->dfMaxX = xUR;
                    psOptions->dfMaxY = yUR;
                    CPLError(CE_Warning, CPLE_AppDefined,
                             "Clamping output bounds to (%f,%f) -> (%f, %f)",
                             psOptions->dfMinX, psOptions->dfMinY,
                             psOptions->dfMaxX, psOptions->dfMaxY);
                }
            }
        }
    }

    /* If (-ts and -te) or (-tr and -te) are specified, we don't need to compute
     * the suggested output extent */
    const bool bNeedsSuggestedWarpOutput =
        !(((psOptions->nForcePixels != 0 && psOptions->nForceLines != 0) ||
           (psOptions->dfXRes != 0 && psOptions->dfYRes != 0)) &&
          !(psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
            psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0));

    // If -te is specified, not not -tr and -ts
    const bool bKnownTargetExtentButNotResolution =
        !(psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
          psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0) &&
        psOptions->nForcePixels == 0 && psOptions->nForceLines == 0 &&
        psOptions->dfXRes == 0 && psOptions->dfYRes == 0;

    /* -------------------------------------------------------------------- */
    /*      Find the output driver.                                         */
    /* -------------------------------------------------------------------- */
    hDriver = GDALGetDriverByName(pszFormat);
    if (hDriver == nullptr ||
        (GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATE, nullptr) == nullptr &&
         GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATECOPY, nullptr) ==
             nullptr))
    {
        auto poMissingDriver =
            GetGDALDriverManager()->GetHiddenDriverByName(pszFormat);
        if (poMissingDriver)
        {
            const std::string msg =
                GDALGetMessageAboutMissingPluginDriver(poMissingDriver);
            printf("Output driver `%s' not found but is known. However plugin "
                   "%s\n",
                   pszFormat, msg.c_str());
            return nullptr;
        }

        printf("Output driver `%s' not recognised or does not support\n",
               pszFormat);
        printf("direct output file creation or CreateCopy. "
               "The following format drivers are eligible for warp output:\n");

        for (int iDr = 0; iDr < GDALGetDriverCount(); iDr++)
        {
            hDriver = GDALGetDriver(iDr);

            if (GDALGetMetadataItem(hDriver, GDAL_DCAP_RASTER, nullptr) !=
                    nullptr &&
                (GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATE, nullptr) !=
                     nullptr ||
                 GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATECOPY, nullptr) !=
                     nullptr))
            {
                printf("  %s: %s\n", GDALGetDriverShortName(hDriver),
                       GDALGetDriverLongName(hDriver));
            }
        }
        printf("\n");
        return nullptr;
    }

    /* -------------------------------------------------------------------- */
    /*      For virtual output files, we have to set a special subclass     */
    /*      of dataset to create.                                           */
    /* -------------------------------------------------------------------- */
    CPLStringList aosCreateOptions(CSLDuplicate(papszCreateOptions));
    if (bVRT)
        aosCreateOptions.SetNameValue("SUBCLASS", "VRTWarpedDataset");

    /* -------------------------------------------------------------------- */
    /*      Loop over all input files to collect extents.                   */
    /* -------------------------------------------------------------------- */
    CPLString osThisTargetSRS;
    {
        const char *pszThisTargetSRS = CSLFetchNameValue(papszTO, "DST_SRS");
        if (pszThisTargetSRS != nullptr)
            osThisTargetSRS = pszThisTargetSRS;
    }

    CPLStringList aoTOList(papszTO, FALSE);

    double dfResFromSourceAndTargetExtent =
        std::numeric_limits<double>::infinity();

    /* -------------------------------------------------------------------- */
    /*      Establish list of files of output dataset if it already exists. */
    /* -------------------------------------------------------------------- */
    std::set<std::string> oSetExistingDestFiles;
    {
        CPLPushErrorHandler(CPLQuietErrorHandler);
        const char *const apszAllowedDrivers[] = {pszFormat, nullptr};
        auto poExistingOutputDS = std::unique_ptr<GDALDataset>(
            GDALDataset::Open(pszFilename, GDAL_OF_RASTER, apszAllowedDrivers));
        if (poExistingOutputDS)
        {
            for (const char *pszFilenameInList :
                 CPLStringList(poExistingOutputDS->GetFileList()))
            {
                oSetExistingDestFiles.insert(
                    CPLString(pszFilenameInList).replaceAll('\\', '/'));
            }
        }
        CPLPopErrorHandler();
    }
    std::set<std::string> oSetExistingDestFilesFoundInSource;
    std::unique_ptr<GDALColorTable> poCT;

    for (int iSrc = 0; iSrc < nSrcCount; iSrc++)
    {
        /* --------------------------------------------------------------------
         */
        /*      Check that there's at least one raster band */
        /* --------------------------------------------------------------------
         */
        GDALDatasetH hSrcDS = pahSrcDS[iSrc];
        if (GDALGetRasterCount(hSrcDS) == 0)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Input file %s has no raster bands.",
                     GDALGetDescription(hSrcDS));
            return nullptr;
        }

        // Examine desired overview level and retrieve the corresponding dataset
        // if it exists.
        std::unique_ptr<GDALDataset> oDstDSOverview;
        if (psOptions->nOvLevel >= 0)
        {
            oDstDSOverview.reset(GDALCreateOverviewDataset(
                GDALDataset::FromHandle(hSrcDS), psOptions->nOvLevel,
                /* bThisLevelOnly = */ true));
            if (oDstDSOverview)
                hSrcDS = oDstDSOverview.get();
        }

        /* --------------------------------------------------------------------
         */
        /*      Check if the source dataset shares some files with the dest
         * one.*/
        /* --------------------------------------------------------------------
         */
        if (!oSetExistingDestFiles.empty())
        {
            // We need to reopen in a temporary dataset for the particular
            // case of overwritten a .tif.ovr file from a .tif
            // If we probe the file list of the .tif, it will then open the
            // .tif.ovr !
            auto poSrcDS = GDALDataset::FromHandle(hSrcDS);
            const char *const apszAllowedDrivers[] = {
                poSrcDS->GetDriver() ? poSrcDS->GetDriver()->GetDescription()
                                     : nullptr,
                nullptr};
            auto poSrcDSTmp = std::unique_ptr<GDALDataset>(GDALDataset::Open(
                poSrcDS->GetDescription(), GDAL_OF_RASTER, apszAllowedDrivers));
            if (poSrcDSTmp)
            {
                for (const char *pszFilenameInList :
                     CPLStringList(poSrcDSTmp->GetFileList()))
                {
                    std::string osFilename =
                        CPLString(pszFilenameInList).replaceAll('\\', '/');
                    if (oSetExistingDestFiles.find(osFilename) !=
                        oSetExistingDestFiles.end())
                    {
                        oSetExistingDestFilesFoundInSource.insert(
                            std::move(osFilename));
                    }
                }
            }
        }

        if (eDT == GDT_Unknown)
            eDT = GDALGetRasterDataType(GDALGetRasterBand(hSrcDS, 1));

        /* --------------------------------------------------------------------
         */
        /*      If we are processing the first file, and it has a raster */
        /*      attribute table, then we will copy it to the destination file.
         */
        /* --------------------------------------------------------------------
         */
        if (iSrc == 0)
        {
            hRAT = GDALGetDefaultRAT(GDALGetRasterBand(hSrcDS, 1));
            if (hRAT != nullptr)
            {
                if (psOptions->eResampleAlg != GRA_NearestNeighbour &&
                    psOptions->eResampleAlg != GRA_Mode &&
                    GDALRATGetTableType(hRAT) == GRTT_THEMATIC)
                {
                    if (!psOptions->bQuiet)
                    {
                        CPLError(CE_Warning, CPLE_AppDefined,
                                 "Warning: Input file %s has a thematic RAT, "
                                 "which will likely lead "
                                 "to bad results when using a resampling "
                                 "method other than nearest neighbour "
                                 "or mode so we are discarding it.\n",
                                 GDALGetDescription(hSrcDS));
                    }
                    hRAT = nullptr;
                }
                else
                {
                    if (!psOptions->bQuiet)
                        printf("Copying raster attribute table from %s to new "
                               "file.\n",
                               GDALGetDescription(hSrcDS));
                }
            }
        }

        /* --------------------------------------------------------------------
         */
        /*      If we are processing the first file, and it has a color */
        /*      table, then we will copy it to the destination file. */
        /* --------------------------------------------------------------------
         */
        if (iSrc == 0)
        {
            auto hCT = GDALGetRasterColorTable(GDALGetRasterBand(hSrcDS, 1));
            if (hCT != nullptr)
            {
                poCT.reset(
                    GDALColorTable::FromHandle(GDALCloneColorTable(hCT)));
                if (!psOptions->bQuiet)
                    printf("Copying color table from %s to new file.\n",
                           GDALGetDescription(hSrcDS));
            }

            if (psOptions->anDstBands.empty())
            {
                nDstBandCount = GDALGetRasterCount(hSrcDS);
                for (int iBand = 0; iBand < nDstBandCount; iBand++)
                {
                    if (psOptions->anDstBands.empty())
                    {
                        GDALColorInterp eInterp =
                            GDALGetRasterColorInterpretation(
                                GDALGetRasterBand(hSrcDS, iBand + 1));
                        apeColorInterpretations.push_back(eInterp);
                    }
                }

                // Do we want to generate an alpha band in the output file?
                if (psOptions->bEnableSrcAlpha)
                    nDstBandCount--;

                if (psOptions->bEnableDstAlpha)
                    nDstBandCount++;
            }
            else
            {
                for (int nSrcBand : psOptions->anSrcBands)
                {
                    auto hBand = GDALGetRasterBand(hSrcDS, nSrcBand);
                    GDALColorInterp eInterp =
                        hBand ? GDALGetRasterColorInterpretation(hBand)
                              : GCI_Undefined;
                    apeColorInterpretations.push_back(eInterp);
                }
                nDstBandCount = static_cast<int>(psOptions->anDstBands.size());
                if (psOptions->bEnableDstAlpha)
                {
                    nDstBandCount++;
                    apeColorInterpretations.push_back(GCI_AlphaBand);
                }
                else if (GDALGetRasterCount(hSrcDS) &&
                         GDALGetRasterColorInterpretation(GDALGetRasterBand(
                             hSrcDS, GDALGetRasterCount(hSrcDS))) ==
                             GCI_AlphaBand &&
                         !psOptions->bDisableSrcAlpha)
                {
                    nDstBandCount++;
                    apeColorInterpretations.push_back(GCI_AlphaBand);
                }
            }
        }

        /* --------------------------------------------------------------------
         */
        /*      If we are processing the first file, get the source srs from */
        /*      dataset, if not set already. */
        /* --------------------------------------------------------------------
         */
        const auto osThisSourceSRS = GetSrcDSProjection(hSrcDS, papszTO);
        if (iSrc == 0 && osThisTargetSRS.empty())
        {
            if (!osThisSourceSRS.empty())
            {
                osThisTargetSRS = osThisSourceSRS;
                aoTOList.SetNameValue("DST_SRS", osThisSourceSRS);
            }
        }

        /* --------------------------------------------------------------------
         */
        /*      Create a transformation object from the source to */
        /*      destination coordinate system. */
        /* --------------------------------------------------------------------
         */
        GDALTransformerArgUniquePtr hTransformArg;
        if (hUniqueTransformArg)
            hTransformArg = std::move(hUniqueTransformArg);
        else
        {
            hTransformArg.reset(GDALCreateGenImgProjTransformer2(
                hSrcDS, nullptr, aoTOList.List()));
            if (hTransformArg == nullptr)
            {
                return nullptr;
            }
        }

        GDALTransformerInfo *psInfo =
            static_cast<GDALTransformerInfo *>(hTransformArg.get());

        /* --------------------------------------------------------------------
         */
        /*      Get approximate output resolution */
        /* --------------------------------------------------------------------
         */

        if (bKnownTargetExtentButNotResolution)
        {
            // Sample points along a grid in target CRS
            constexpr int nPointsX = 10;
            constexpr int nPointsY = 10;
            constexpr int nPoints = 3 * nPointsX * nPointsY;
            std::vector<double> padfX;
            std::vector<double> padfY;
            std::vector<double> padfZ(nPoints);
            std::vector<int> pabSuccess(nPoints);
            const double dfEps =
                std::min(psOptions->dfMaxX - psOptions->dfMinX,
                         std::abs(psOptions->dfMaxY - psOptions->dfMinY)) /
                1000;
            for (int iY = 0; iY < nPointsY; iY++)
            {
                for (int iX = 0; iX < nPointsX; iX++)
                {
                    const double dfX =
                        psOptions->dfMinX +
                        static_cast<double>(iX) *
                            (psOptions->dfMaxX - psOptions->dfMinX) /
                            (nPointsX - 1);
                    const double dfY =
                        psOptions->dfMinY +
                        static_cast<double>(iY) *
                            (psOptions->dfMaxY - psOptions->dfMinY) /
                            (nPointsY - 1);

                    // Reproject each destination sample point and its
                    // neighbours at (x+1,y) and (x,y+1), so as to get the local
                    // scale.
                    padfX.push_back(dfX);
                    padfY.push_back(dfY);

                    padfX.push_back((iX == nPointsX - 1) ? dfX - dfEps
                                                         : dfX + dfEps);
                    padfY.push_back(dfY);

                    padfX.push_back(dfX);
                    padfY.push_back((iY == nPointsY - 1) ? dfY - dfEps
                                                         : dfY + dfEps);
                }
            }

            bool transformedToSrcCRS{false};

            GDALGenImgProjTransformInfo *psTransformInfo{
                static_cast<GDALGenImgProjTransformInfo *>(
                    hTransformArg.get())};

            // If a transformer is available, use an extent that covers the
            // target extent instead of the real source image extent, but also
            // check for target extent compatibility with source CRS extent
            if (psTransformInfo && psTransformInfo->pReprojectArg &&
                psTransformInfo->sSrcParams.pTransformer == nullptr)
            {
                const GDALReprojectionTransformInfo *psRTI =
                    static_cast<const GDALReprojectionTransformInfo *>(
                        psTransformInfo->pReprojectArg);
                if (psRTI && psRTI->poReverseTransform)
                {

                    // Compute new geotransform from transformed target extent
                    double adfGeoTransform[6];
                    if (GDALGetGeoTransform(hSrcDS, adfGeoTransform) ==
                            CE_None &&
                        adfGeoTransform[2] == 0 && adfGeoTransform[4] == 0)
                    {

                        // Transform target extent to source CRS
                        double dfMinX = psOptions->dfMinX;
                        double dfMinY = psOptions->dfMinY;

                        // Need this to check if the target extent is compatible with the source extent
                        double dfMaxX = psOptions->dfMaxX;
                        double dfMaxY = psOptions->dfMaxY;

                        // Clone of psRTI->poReverseTransform with CHECK_WITH_INVERT_PROJ set to TRUE
                        // to detect out of source CRS bounds destination extent and fall back to original
                        // algorithm if needed
                        CPLConfigOptionSetter oSetter("CHECK_WITH_INVERT_PROJ",
                                                      "TRUE", false);
                        OGRCoordinateTransformationOptions options;
                        auto poReverseTransform =
                            std::unique_ptr<OGRCoordinateTransformation>(
                                OGRCreateCoordinateTransformation(
                                    psRTI->poReverseTransform->GetSourceCS(),
                                    psRTI->poReverseTransform->GetTargetCS(),
                                    options));

                        if (poReverseTransform)
                        {

                            poReverseTransform->Transform(
                                1, &dfMinX, &dfMinY, nullptr, &pabSuccess[0]);

                            if (pabSuccess[0])
                            {
                                adfGeoTransform[0] = dfMinX;
                                adfGeoTransform[3] = dfMinY;

                                poReverseTransform->Transform(1, &dfMaxX,
                                                              &dfMaxY, nullptr,
                                                              &pabSuccess[0]);

                                if (pabSuccess[0])
                                {

                                    // Reproject to source image CRS
                                    psRTI->poReverseTransform->Transform(
                                        nPoints, &padfX[0], &padfY[0],
                                        &padfZ[0], &pabSuccess[0]);

                                    // Transform back to source image coordinate space using geotransform
                                    for (size_t i = 0; i < padfX.size(); i++)
                                    {
                                        padfX[i] =
                                            (padfX[i] - adfGeoTransform[0]) /
                                            adfGeoTransform[1];
                                        padfY[i] = std::abs(
                                            (padfY[i] - adfGeoTransform[3]) /
                                            adfGeoTransform[5]);
                                    }

                                    transformedToSrcCRS = true;
                                }
                            }
                        }
                    }
                }
            }

            if (!transformedToSrcCRS)
            {
                // Transform to source image coordinate space
                psInfo->pfnTransform(hTransformArg.get(), TRUE, nPoints,
                                     &padfX[0], &padfY[0], &padfZ[0],
                                     &pabSuccess[0]);
            }

            // Compute the resolution at sampling points
            std::vector<std::pair<double, double>> aoResPairs;

            const auto Distance = [](double x, double y)
            { return sqrt(x * x + y * y); };

            const int nSrcXSize = GDALGetRasterXSize(hSrcDS);
            const int nSrcYSize = GDALGetRasterYSize(hSrcDS);

            for (int i = 0; i < nPoints; i += 3)
            {
                if (pabSuccess[i] && pabSuccess[i + 1] && pabSuccess[i + 2] &&
                    padfX[i] >= 0 && padfY[i] >= 0 &&
                    (transformedToSrcCRS ||
                     (padfX[i] <= nSrcXSize && padfY[i] <= nSrcYSize)))
                {
                    const double dfRes1 =
                        std::abs(dfEps) / Distance(padfX[i + 1] - padfX[i],
                                                   padfY[i + 1] - padfY[i]);
                    const double dfRes2 =
                        std::abs(dfEps) / Distance(padfX[i + 2] - padfX[i],
                                                   padfY[i + 2] - padfY[i]);
                    if (std::isfinite(dfRes1) && std::isfinite(dfRes2))
                    {
                        aoResPairs.push_back(
                            std::pair<double, double>(dfRes1, dfRes2));
                    }
                }
            }

            // Find the minimum resolution that is at least 10 times greater
            // than the median, to remove outliers.
            // Start first by doing that on dfRes1, then dfRes2 and then their
            // average.
            std::sort(aoResPairs.begin(), aoResPairs.end(),
                      [](const std::pair<double, double> &oPair1,
                         const std::pair<double, double> &oPair2)
                      { return oPair1.first < oPair2.first; });

            if (!aoResPairs.empty())
            {
                std::vector<std::pair<double, double>> aoResPairsNew;
                const double dfMedian1 =
                    aoResPairs[aoResPairs.size() / 2].first;
                for (const auto &oPair : aoResPairs)
                {
                    if (oPair.first > dfMedian1 / 10)
                    {
                        aoResPairsNew.push_back(oPair);
                    }
                }

                aoResPairs = std::move(aoResPairsNew);
                std::sort(aoResPairs.begin(), aoResPairs.end(),
                          [](const std::pair<double, double> &oPair1,
                             const std::pair<double, double> &oPair2)
                          { return oPair1.second < oPair2.second; });
                if (!aoResPairs.empty())
                {
                    std::vector<double> adfRes;
                    const double dfMedian2 =
                        aoResPairs[aoResPairs.size() / 2].second;
                    for (const auto &oPair : aoResPairs)
                    {
                        if (oPair.second > dfMedian2 / 10)
                        {
                            adfRes.push_back((oPair.first + oPair.second) / 2);
                        }
                    }

                    std::sort(adfRes.begin(), adfRes.end());
                    if (!adfRes.empty())
                    {
                        const double dfMedian = adfRes[adfRes.size() / 2];
                        for (const double dfRes : adfRes)
                        {
                            if (dfRes > dfMedian / 10)
                            {
                                dfResFromSourceAndTargetExtent = std::min(
                                    dfResFromSourceAndTargetExtent, dfRes);
                                break;
                            }
                        }
                    }
                }
            }
        }

        /* --------------------------------------------------------------------
         */
        /*      Get approximate output definition. */
        /* --------------------------------------------------------------------
         */
        double adfThisGeoTransform[6];
        double adfExtent[4];
        if (bNeedsSuggestedWarpOutput)
        {
            int nThisPixels, nThisLines;

            // For sum, round-up dimension, to be sure that the output extent
            // includes all source pixels, to have the sum preserving property.
            int nOptions = (psOptions->eResampleAlg == GRA_Sum)
                               ? GDAL_SWO_ROUND_UP_SIZE
                               : 0;
            if (psOptions->bSquarePixels)
            {
                nOptions |= GDAL_SWO_FORCE_SQUARE_PIXEL;
            }

            if (GDALSuggestedWarpOutput2(
                    hSrcDS, psInfo->pfnTransform, hTransformArg.get(),
                    adfThisGeoTransform, &nThisPixels, &nThisLines, adfExtent,
                    nOptions) != CE_None)
            {
                return nullptr;
            }

            if (CPLGetConfigOption("CHECK_WITH_INVERT_PROJ", nullptr) ==
                nullptr)
            {
                double MinX = adfExtent[0];
                double MaxX = adfExtent[2];
                double MaxY = adfExtent[3];
                double MinY = adfExtent[1];
                int bSuccess = TRUE;

                // +/-180 deg in longitude do not roundtrip sometimes
                if (MinX == -180)
                    MinX += 1e-6;
                if (MaxX == 180)
                    MaxX -= 1e-6;

                // +/-90 deg in latitude do not roundtrip sometimes
                if (MinY == -90)
                    MinY += 1e-6;
                if (MaxY == 90)
                    MaxY -= 1e-6;

                /* Check that the edges of the target image are in the validity
                 * area */
                /* of the target projection */
                const int N_STEPS = 20;
                for (int i = 0; i <= N_STEPS && bSuccess; i++)
                {
                    for (int j = 0; j <= N_STEPS && bSuccess; j++)
                    {
                        const double dfRatioI = i * 1.0 / N_STEPS;
                        const double dfRatioJ = j * 1.0 / N_STEPS;
                        const double expected_x =
                            (1 - dfRatioI) * MinX + dfRatioI * MaxX;
                        const double expected_y =
                            (1 - dfRatioJ) * MinY + dfRatioJ * MaxY;
                        double x = expected_x;
                        double y = expected_y;
                        double z = 0;
                        /* Target SRS coordinates to source image pixel
                         * coordinates */
                        if (!psInfo->pfnTransform(hTransformArg.get(), TRUE, 1,
                                                  &x, &y, &z, &bSuccess) ||
                            !bSuccess)
                            bSuccess = FALSE;
                        /* Source image pixel coordinates to target SRS
                         * coordinates */
                        if (!psInfo->pfnTransform(hTransformArg.get(), FALSE, 1,
                                                  &x, &y, &z, &bSuccess) ||
                            !bSuccess)
                            bSuccess = FALSE;
                        if (fabs(x - expected_x) >
                                (MaxX - MinX) / nThisPixels ||
                            fabs(y - expected_y) > (MaxY - MinY) / nThisLines)
                            bSuccess = FALSE;
                    }
                }

                /* If not, retry with CHECK_WITH_INVERT_PROJ=TRUE that forces
                 * ogrct.cpp */
                /* to check the consistency of each requested projection result
                 * with the */
                /* invert projection */
                if (!bSuccess)
                {
                    CPLSetThreadLocalConfigOption("CHECK_WITH_INVERT_PROJ",
                                                  "TRUE");
                    CPLDebug("WARP", "Recompute out extent with "
                                     "CHECK_WITH_INVERT_PROJ=TRUE");

                    const CPLErr eErr = GDALSuggestedWarpOutput2(
                        hSrcDS, psInfo->pfnTransform, hTransformArg.get(),
                        adfThisGeoTransform, &nThisPixels, &nThisLines,
                        adfExtent, 0);
                    CPLSetThreadLocalConfigOption("CHECK_WITH_INVERT_PROJ",
                                                  nullptr);
                    if (eErr != CE_None)
                    {
                        return nullptr;
                    }
                }
            }
        }

        // If no reprojection or geometry change is involved, and that the
        // source image is north-up, preserve source resolution instead of
        // forcing square pixels.
        const char *pszMethod = FetchSrcMethod(papszTO);
        double adfThisGeoTransformTmp[6];
        if (!psOptions->bSquarePixels && bNeedsSuggestedWarpOutput &&
            psOptions->dfXRes == 0 && psOptions->dfYRes == 0 &&
            psOptions->nForcePixels == 0 && psOptions->nForceLines == 0 &&
            (pszMethod == nullptr || EQUAL(pszMethod, "GEOTRANSFORM")) &&
            CSLFetchNameValue(papszTO, "COORDINATE_OPERATION") == nullptr &&
            CSLFetchNameValue(papszTO, "SRC_METHOD") == nullptr &&
            CSLFetchNameValue(papszTO, "DST_METHOD") == nullptr &&
            GDALGetGeoTransform(hSrcDS, adfThisGeoTransformTmp) == CE_None &&
            adfThisGeoTransformTmp[2] == 0 && adfThisGeoTransformTmp[4] == 0 &&
            adfThisGeoTransformTmp[5] < 0 &&
            GDALGetMetadata(hSrcDS, "GEOLOC_ARRAY") == nullptr &&
            GDALGetMetadata(hSrcDS, "RPC") == nullptr)
        {
            bool bIsSameHorizontal = osThisSourceSRS == osThisTargetSRS;
            if (!bIsSameHorizontal)
            {
                OGRSpatialReference oSrcSRS;
                OGRSpatialReference oDstSRS;
                CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
                // DemoteTo2D requires PROJ >= 6.3
                if (oSrcSRS.SetFromUserInput(osThisSourceSRS.c_str()) ==
                        OGRERR_NONE &&
                    oDstSRS.SetFromUserInput(osThisTargetSRS.c_str()) ==
                        OGRERR_NONE &&
                    (oSrcSRS.GetAxesCount() == 3 ||
                     oDstSRS.GetAxesCount() == 3) &&
                    oSrcSRS.DemoteTo2D(nullptr) == OGRERR_NONE &&
                    oDstSRS.DemoteTo2D(nullptr) == OGRERR_NONE)
                {
                    bIsSameHorizontal = oSrcSRS.IsSame(&oDstSRS);
                }
            }
            if (bIsSameHorizontal)
            {
                memcpy(adfThisGeoTransform, adfThisGeoTransformTmp,
                       6 * sizeof(double));
                adfExtent[0] = adfThisGeoTransform[0];
                adfExtent[1] =
                    adfThisGeoTransform[3] +
                    GDALGetRasterYSize(hSrcDS) * adfThisGeoTransform[5];
                adfExtent[2] =
                    adfThisGeoTransform[0] +
                    GDALGetRasterXSize(hSrcDS) * adfThisGeoTransform[1];
                adfExtent[3] = adfThisGeoTransform[3];
                dfResFromSourceAndTargetExtent =
                    std::numeric_limits<double>::infinity();
            }
        }

        if (bNeedsSuggestedWarpOutput)
        {
            /* --------------------------------------------------------------------
             */
            /*      Expand the working bounds to include this region, ensure the
             */
            /*      working resolution is no more than this resolution. */
            /* --------------------------------------------------------------------
             */
            if (dfWrkMaxX == 0.0 && dfWrkMinX == 0.0)
            {
                dfWrkMinX = adfExtent[0];
                dfWrkMaxX = adfExtent[2];
                dfWrkMaxY = adfExtent[3];
                dfWrkMinY = adfExtent[1];
                dfWrkResX = adfThisGeoTransform[1];
                dfWrkResY = std::abs(adfThisGeoTransform[5]);
            }
            else
            {
                dfWrkMinX = std::min(dfWrkMinX, adfExtent[0]);
                dfWrkMaxX = std::max(dfWrkMaxX, adfExtent[2]);
                dfWrkMaxY = std::max(dfWrkMaxY, adfExtent[3]);
                dfWrkMinY = std::min(dfWrkMinY, adfExtent[1]);
                dfWrkResX = std::min(dfWrkResX, adfThisGeoTransform[1]);
                dfWrkResY =
                    std::min(dfWrkResY, std::abs(adfThisGeoTransform[5]));
            }
        }

        if (nSrcCount == 1)
        {
            hUniqueTransformArg = std::move(hTransformArg);
        }
    }

    // If the source file(s) and the dest one share some files in common,
    // only remove the files that are *not* in common
    if (!oSetExistingDestFilesFoundInSource.empty())
    {
        for (const std::string &osFilename : oSetExistingDestFiles)
        {
            if (oSetExistingDestFilesFoundInSource.find(osFilename) ==
                oSetExistingDestFilesFoundInSource.end())
            {
                VSIUnlink(osFilename.c_str());
            }
        }
    }

    if (std::isfinite(dfResFromSourceAndTargetExtent))
    {
        dfWrkResX = dfResFromSourceAndTargetExtent;
        dfWrkResY = dfResFromSourceAndTargetExtent;
    }

    /* -------------------------------------------------------------------- */
    /*      Did we have any usable sources?                                 */
    /* -------------------------------------------------------------------- */
    if (nDstBandCount == 0)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "No usable source images.");
        return nullptr;
    }

    /* -------------------------------------------------------------------- */
    /*      Turn the suggested region into a geotransform and suggested     */
    /*      number of pixels and lines.                                     */
    /* -------------------------------------------------------------------- */
    double adfDstGeoTransform[6] = {0, 0, 0, 0, 0, 0};
    int nPixels = 0;
    int nLines = 0;

    const auto ComputePixelsFromResAndExtent = [psOptions]()
    {
        return std::max(1.0,
                        std::round((psOptions->dfMaxX - psOptions->dfMinX) /
                                   psOptions->dfXRes));
    };

    const auto ComputeLinesFromResAndExtent = [psOptions]()
    {
        return std::max(
            1.0, std::round(std::fabs(psOptions->dfMaxY - psOptions->dfMinY) /
                            psOptions->dfYRes));
    };

    if (bNeedsSuggestedWarpOutput)
    {
        adfDstGeoTransform[0] = dfWrkMinX;
        adfDstGeoTransform[1] = dfWrkResX;
        adfDstGeoTransform[2] = 0.0;
        adfDstGeoTransform[3] = dfWrkMaxY;
        adfDstGeoTransform[4] = 0.0;
        adfDstGeoTransform[5] = -1 * dfWrkResY;

        const double dfPixels = (dfWrkMaxX - dfWrkMinX) / dfWrkResX;
        const double dfLines = (dfWrkMaxY - dfWrkMinY) / dfWrkResY;
        // guaranteed by GDALSuggestedWarpOutput2() behavior
        CPLAssert(std::round(dfPixels) <= INT_MAX);
        CPLAssert(std::round(dfLines) <= INT_MAX);
        nPixels =
            static_cast<int>(std::min<double>(std::round(dfPixels), INT_MAX));
        nLines =
            static_cast<int>(std::min<double>(std::round(dfLines), INT_MAX));
    }

    /* -------------------------------------------------------------------- */
    /*      Did the user override some parameters?                          */
    /* -------------------------------------------------------------------- */
    if (UseTEAndTSAndTRConsistently(psOptions))
    {
        adfDstGeoTransform[0] = psOptions->dfMinX;
        adfDstGeoTransform[3] = psOptions->dfMaxY;
        adfDstGeoTransform[1] = psOptions->dfXRes;
        adfDstGeoTransform[5] = -psOptions->dfYRes;

        nPixels = psOptions->nForcePixels;
        nLines = psOptions->nForceLines;
    }
    else if (psOptions->dfXRes != 0.0 && psOptions->dfYRes != 0.0)
    {
        bool bDetectBlankBorders = false;

        if (psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
            psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0)
        {
            bDetectBlankBorders = bNeedsSuggestedWarpOutput;

            psOptions->dfMinX = adfDstGeoTransform[0];
            psOptions->dfMaxX =
                adfDstGeoTransform[0] + adfDstGeoTransform[1] * nPixels;
            psOptions->dfMaxY = adfDstGeoTransform[3];
            psOptions->dfMinY =
                adfDstGeoTransform[3] + adfDstGeoTransform[5] * nLines;
        }

        if (psOptions->bTargetAlignedPixels ||
            (psOptions->bCropToCutline &&
             psOptions->aosWarpOptions.FetchBool("CUTLINE_ALL_TOUCHED", false)))
        {
            if ((psOptions->bTargetAlignedPixels &&
                 bNeedsSuggestedWarpOutput) ||
                (psOptions->bCropToCutline &&
                 psOptions->aosWarpOptions.FetchBool("CUTLINE_ALL_TOUCHED",
                                                     false)))
            {
                bDetectBlankBorders = true;
            }
            constexpr double EPS = 1e-8;
            psOptions->dfMinX =
                floor(psOptions->dfMinX / psOptions->dfXRes + EPS) *
                psOptions->dfXRes;
            psOptions->dfMaxX =
                ceil(psOptions->dfMaxX / psOptions->dfXRes - EPS) *
                psOptions->dfXRes;
            psOptions->dfMinY =
                floor(psOptions->dfMinY / psOptions->dfYRes + EPS) *
                psOptions->dfYRes;
            psOptions->dfMaxY =
                ceil(psOptions->dfMaxY / psOptions->dfYRes - EPS) *
                psOptions->dfYRes;
        }

        const auto UpdateGeoTransformandAndPixelLines = [&]()
        {
            const double dfPixels = ComputePixelsFromResAndExtent();
            const double dfLines = ComputeLinesFromResAndExtent();
            if (dfPixels > INT_MAX || dfLines > INT_MAX)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Too large output raster size: %f x %f", dfPixels,
                         dfLines);
                return false;
            }

            nPixels = static_cast<int>(dfPixels);
            nLines = static_cast<int>(dfLines);
            adfDstGeoTransform[0] = psOptions->dfMinX;
            adfDstGeoTransform[3] = psOptions->dfMaxY;
            adfDstGeoTransform[1] = psOptions->dfXRes;
            adfDstGeoTransform[5] = (psOptions->dfMaxY > psOptions->dfMinY)
                                        ? -psOptions->dfYRes
                                        : psOptions->dfYRes;
            return true;
        };

        if (bDetectBlankBorders && nSrcCount == 1 && hUniqueTransformArg &&
            // to avoid too large memory allocations
            std::max(nPixels, nLines) < 100 * 1000 * 1000)
        {
            // Try to detect if the edge of the raster would be blank
            // Cf https://github.com/OSGeo/gdal/issues/7905
            while (nPixels > 1 || nLines > 1)
            {
                if (!UpdateGeoTransformandAndPixelLines())
                    return nullptr;

                GDALSetGenImgProjTransformerDstGeoTransform(
                    hUniqueTransformArg.get(), adfDstGeoTransform);

                std::vector<double> adfX(std::max(nPixels, nLines));
                std::vector<double> adfY(adfX.size());
                std::vector<double> adfZ(adfX.size());
                std::vector<int> abSuccess(adfX.size());

                const auto DetectBlankBorder =
                    [&](int nValues,
                        std::function<bool(double, double)> funcIsOK)
                {
                    if (nValues > 3)
                    {
                        // First try with just a subsample of 3 points
                        double adf3X[3] = {adfX[0], adfX[nValues / 2],
                                           adfX[nValues - 1]};
                        double adf3Y[3] = {adfY[0], adfY[nValues / 2],
                                           adfY[nValues - 1]};
                        double adf3Z[3] = {0};
                        if (GDALGenImgProjTransform(
                                hUniqueTransformArg.get(), TRUE, 3, &adf3X[0],
                                &adf3Y[0], &adf3Z[0], &abSuccess[0]))
                        {
                            for (int i = 0; i < 3; ++i)
                            {
                                if (abSuccess[i] &&
                                    funcIsOK(adf3X[i], adf3Y[i]))
                                {
                                    return false;
                                }
                            }
                        }
                    }

                    // Do on full border to confirm
                    if (GDALGenImgProjTransform(hUniqueTransformArg.get(), TRUE,
                                                nValues, &adfX[0], &adfY[0],
                                                &adfZ[0], &abSuccess[0]))
                    {
                        for (int i = 0; i < nValues; ++i)
                        {
                            if (abSuccess[i] && funcIsOK(adfX[i], adfY[i]))
                            {
                                return false;
                            }
                        }
                    }

                    return true;
                };

                for (int i = 0; i < nPixels; ++i)
                {
                    adfX[i] = i + 0.5;
                    adfY[i] = 0.5;
                    adfZ[i] = 0;
                }
                const bool bTopBlankLine = DetectBlankBorder(
                    nPixels, [](double, double y) { return y >= 0; });

                for (int i = 0; i < nPixels; ++i)
                {
                    adfX[i] = i + 0.5;
                    adfY[i] = nLines - 0.5;
                    adfZ[i] = 0;
                }
                const int nSrcLines = GDALGetRasterYSize(pahSrcDS[0]);
                const bool bBottomBlankLine =
                    DetectBlankBorder(nPixels, [nSrcLines](double, double y)
                                      { return y <= nSrcLines; });

                for (int i = 0; i < nLines; ++i)
                {
                    adfX[i] = 0.5;
                    adfY[i] = i + 0.5;
                    adfZ[i] = 0;
                }
                const bool bLeftBlankCol = DetectBlankBorder(
                    nLines, [](double x, double) { return x >= 0; });

                for (int i = 0; i < nLines; ++i)
                {
                    adfX[i] = nPixels - 0.5;
                    adfY[i] = i + 0.5;
                    adfZ[i] = 0;
                }
                const int nSrcCols = GDALGetRasterXSize(pahSrcDS[0]);
                const bool bRightBlankCol =
                    DetectBlankBorder(nLines, [nSrcCols](double x, double)
                                      { return x <= nSrcCols; });

                if (!bTopBlankLine && !bBottomBlankLine && !bLeftBlankCol &&
                    !bRightBlankCol)
                    break;

                if (bTopBlankLine)
                {
                    if (psOptions->dfMaxY - psOptions->dfMinY <=
                        2 * psOptions->dfYRes)
                        break;
                    psOptions->dfMaxY -= psOptions->dfYRes;
                }
                if (bBottomBlankLine)
                {
                    if (psOptions->dfMaxY - psOptions->dfMinY <=
                        2 * psOptions->dfYRes)
                        break;
                    psOptions->dfMinY += psOptions->dfYRes;
                }
                if (bLeftBlankCol)
                {
                    if (psOptions->dfMaxX - psOptions->dfMinX <=
                        2 * psOptions->dfXRes)
                        break;
                    psOptions->dfMinX += psOptions->dfXRes;
                }
                if (bRightBlankCol)
                {
                    if (psOptions->dfMaxX - psOptions->dfMinX <=
                        2 * psOptions->dfXRes)
                        break;
                    psOptions->dfMaxX -= psOptions->dfXRes;
                }
            }
        }

        if (!UpdateGeoTransformandAndPixelLines())
            return nullptr;
    }

    else if (psOptions->nForcePixels != 0 && psOptions->nForceLines != 0)
    {
        if (psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
            psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0)
        {
            psOptions->dfMinX = dfWrkMinX;
            psOptions->dfMaxX = dfWrkMaxX;
            psOptions->dfMaxY = dfWrkMaxY;
            psOptions->dfMinY = dfWrkMinY;
        }

        psOptions->dfXRes =
            (psOptions->dfMaxX - psOptions->dfMinX) / psOptions->nForcePixels;
        psOptions->dfYRes =
            (psOptions->dfMaxY - psOptions->dfMinY) / psOptions->nForceLines;

        adfDstGeoTransform[0] = psOptions->dfMinX;
        adfDstGeoTransform[3] = psOptions->dfMaxY;
        adfDstGeoTransform[1] = psOptions->dfXRes;
        adfDstGeoTransform[5] = -psOptions->dfYRes;

        nPixels = psOptions->nForcePixels;
        nLines = psOptions->nForceLines;
    }

    else if (psOptions->nForcePixels != 0)
    {
        if (psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
            psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0)
        {
            psOptions->dfMinX = dfWrkMinX;
            psOptions->dfMaxX = dfWrkMaxX;
            psOptions->dfMaxY = dfWrkMaxY;
            psOptions->dfMinY = dfWrkMinY;
        }

        psOptions->dfXRes =
            (psOptions->dfMaxX - psOptions->dfMinX) / psOptions->nForcePixels;
        psOptions->dfYRes = psOptions->dfXRes;

        adfDstGeoTransform[0] = psOptions->dfMinX;
        adfDstGeoTransform[3] = psOptions->dfMaxY;
        adfDstGeoTransform[1] = psOptions->dfXRes;
        adfDstGeoTransform[5] = (psOptions->dfMaxY > psOptions->dfMinY)
                                    ? -psOptions->dfYRes
                                    : psOptions->dfYRes;

        nPixels = psOptions->nForcePixels;
        const double dfLines = ComputeLinesFromResAndExtent();
        if (dfLines > INT_MAX)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Too large output raster size: %d x %f", nPixels, dfLines);
            return nullptr;
        }
        nLines = static_cast<int>(dfLines);
    }

    else if (psOptions->nForceLines != 0)
    {
        if (psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
            psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0)
        {
            psOptions->dfMinX = dfWrkMinX;
            psOptions->dfMaxX = dfWrkMaxX;
            psOptions->dfMaxY = dfWrkMaxY;
            psOptions->dfMinY = dfWrkMinY;
        }

        psOptions->dfYRes =
            (psOptions->dfMaxY - psOptions->dfMinY) / psOptions->nForceLines;
        psOptions->dfXRes = std::fabs(psOptions->dfYRes);

        adfDstGeoTransform[0] = psOptions->dfMinX;
        adfDstGeoTransform[3] = psOptions->dfMaxY;
        adfDstGeoTransform[1] = psOptions->dfXRes;
        adfDstGeoTransform[5] = -psOptions->dfYRes;

        const double dfPixels = ComputePixelsFromResAndExtent();
        nLines = psOptions->nForceLines;
        if (dfPixels > INT_MAX)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Too large output raster size: %f x %d", dfPixels, nLines);
            return nullptr;
        }
        nPixels = static_cast<int>(dfPixels);
    }

    else if (psOptions->dfMinX != 0.0 || psOptions->dfMinY != 0.0 ||
             psOptions->dfMaxX != 0.0 || psOptions->dfMaxY != 0.0)
    {
        psOptions->dfXRes = adfDstGeoTransform[1];
        psOptions->dfYRes = fabs(adfDstGeoTransform[5]);

        const double dfPixels = ComputePixelsFromResAndExtent();
        const double dfLines = ComputeLinesFromResAndExtent();
        if (dfPixels > INT_MAX || dfLines > INT_MAX)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Too large output raster size: %f x %f", dfPixels,
                     dfLines);
            return nullptr;
        }

        nPixels = static_cast<int>(dfPixels);
        nLines = static_cast<int>(dfLines);

        psOptions->dfXRes = (psOptions->dfMaxX - psOptions->dfMinX) / nPixels;
        psOptions->dfYRes = (psOptions->dfMaxY - psOptions->dfMinY) / nLines;

        adfDstGeoTransform[0] = psOptions->dfMinX;
        adfDstGeoTransform[3] = psOptions->dfMaxY;
        adfDstGeoTransform[1] = psOptions->dfXRes;
        adfDstGeoTransform[5] = -psOptions->dfYRes;
    }

    if (EQUAL(pszFormat, "GTiff"))
    {

        /* --------------------------------------------------------------------
         */
        /*      Automatically set PHOTOMETRIC=RGB for GTiff when appropriate */
        /* --------------------------------------------------------------------
         */
        if (apeColorInterpretations.size() >= 3 &&
            apeColorInterpretations[0] == GCI_RedBand &&
            apeColorInterpretations[1] == GCI_GreenBand &&
            apeColorInterpretations[2] == GCI_BlueBand &&
            aosCreateOptions.FetchNameValue("PHOTOMETRIC") == nullptr)
        {
            aosCreateOptions.SetNameValue("PHOTOMETRIC", "RGB");

            // Preserve potential ALPHA=PREMULTIPLIED from source alpha band
            if (aosCreateOptions.FetchNameValue("ALPHA") == nullptr &&
                apeColorInterpretations.size() == 4 &&
                apeColorInterpretations[3] == GCI_AlphaBand &&
                GDALGetRasterCount(pahSrcDS[0]) == 4)
            {
                const char *pszAlpha =
                    GDALGetMetadataItem(GDALGetRasterBand(pahSrcDS[0], 4),
                                        "ALPHA", "IMAGE_STRUCTURE");
                if (pszAlpha)
                {
                    aosCreateOptions.SetNameValue("ALPHA", pszAlpha);
                }
            }
        }

        /* The GTiff driver now supports writing band color interpretation */
        /* in the TIFF_GDAL_METADATA tag */
        bSetColorInterpretation = true;
    }

    /* -------------------------------------------------------------------- */
    /*      Create the output file.                                         */
    /* -------------------------------------------------------------------- */
    if (!psOptions->bQuiet)
        printf("Creating output file that is %dP x %dL.\n", nPixels, nLines);

    hDstDS = GDALCreate(hDriver, pszFilename, nPixels, nLines, nDstBandCount,
                        eDT, aosCreateOptions.List());

    if (hDstDS == nullptr)
    {
        return nullptr;
    }

    if (psOptions->bDeleteOutputFileOnceCreated)
    {
        CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
        GDALDeleteDataset(hDriver, pszFilename);
    }

    /* -------------------------------------------------------------------- */
    /*      Write out the projection definition.                            */
    /* -------------------------------------------------------------------- */
    const char *pszDstMethod = CSLFetchNameValue(papszTO, "DST_METHOD");
    if (pszDstMethod == nullptr || !EQUAL(pszDstMethod, "NO_GEOTRANSFORM"))
    {
        OGRSpatialReference oTargetSRS;
        oTargetSRS.SetFromUserInput(osThisTargetSRS);
        oTargetSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);

        if (oTargetSRS.IsDynamic())
        {
            double dfCoordEpoch = CPLAtof(CSLFetchNameValueDef(
                papszTO, "DST_COORDINATE_EPOCH",
                CSLFetchNameValueDef(papszTO, "COORDINATE_EPOCH", "0")));
            if (dfCoordEpoch == 0)
            {
                const OGRSpatialReferenceH hSrcSRS =
                    GDALGetSpatialRef(pahSrcDS[0]);
                const char *pszMethod = FetchSrcMethod(papszTO);
                if (hSrcSRS &&
                    (pszMethod == nullptr || EQUAL(pszMethod, "GEOTRANSFORM")))
                {
                    dfCoordEpoch = OSRGetCoordinateEpoch(hSrcSRS);
                }
            }
            if (dfCoordEpoch > 0)
                oTargetSRS.SetCoordinateEpoch(dfCoordEpoch);
        }

        if (GDALSetSpatialRef(hDstDS, OGRSpatialReference::ToHandle(
                                          &oTargetSRS)) == CE_Failure ||
            GDALSetGeoTransform(hDstDS, adfDstGeoTransform) == CE_Failure)
        {
            GDALClose(hDstDS);
            return nullptr;
        }
    }
    else
    {
        adfDstGeoTransform[3] += adfDstGeoTransform[5] * nLines;
        adfDstGeoTransform[5] = fabs(adfDstGeoTransform[5]);
    }

    if (hUniqueTransformArg && bUpdateTransformerWithDestGT)
    {
        GDALSetGenImgProjTransformerDstGeoTransform(hUniqueTransformArg.get(),
                                                    adfDstGeoTransform);

        void *pTransformerArg = hUniqueTransformArg.get();
        if (GDALIsTransformer(pTransformerArg,
                              GDAL_GEN_IMG_TRANSFORMER_CLASS_NAME))
        {
            // Detect if there is a change of coordinate operation in the area of
            // interest. The underlying proj_trans_get_last_used_operation() is
            // quite costly due to using proj_clone() internally, so only do that
            // on a restricted set of points.
            GDALGenImgProjTransformInfo *psTransformInfo{
                static_cast<GDALGenImgProjTransformInfo *>(pTransformerArg)};
            GDALTransformerInfo *psInfo = &psTransformInfo->sTI;

            void *pReprojectArg = psTransformInfo->pReprojectArg;
            if (GDALIsTransformer(pReprojectArg,
                                  GDAL_APPROX_TRANSFORMER_CLASS_NAME))
            {
                const auto *pApproxInfo =
                    static_cast<const GDALApproxTransformInfo *>(pReprojectArg);
                pReprojectArg = pApproxInfo->pBaseCBData;
            }

            if (GDALIsTransformer(pReprojectArg,
                                  GDAL_REPROJECTION_TRANSFORMER_CLASS_NAME))
            {
                const GDALReprojectionTransformInfo *psRTI =
                    static_cast<const GDALReprojectionTransformInfo *>(
                        pReprojectArg);
                if (psRTI->poReverseTransform)
                {
                    std::vector<double> adfX, adfY, adfZ;
                    std::vector<int> abSuccess;

                    GDALDatasetH hSrcDS = pahSrcDS[0];

                    // Sample points on a N x N grid in the source raster
                    constexpr int N = 10;
                    const int nSrcXSize = GDALGetRasterXSize(hSrcDS);
                    const int nSrcYSize = GDALGetRasterYSize(hSrcDS);
                    for (int j = 0; j <= N; ++j)
                    {
                        for (int i = 0; i <= N; ++i)
                        {
                            adfX.push_back(static_cast<double>(i) / N *
                                           nSrcXSize);
                            adfY.push_back(static_cast<double>(j) / N *
                                           nSrcYSize);
                            adfZ.push_back(0);
                            abSuccess.push_back(0);
                        }
                    }

                    {
                        CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);

                        // Transform from source raster coordinates to target raster
                        // coordinates
                        psInfo->pfnTransform(hUniqueTransformArg.get(), FALSE,
                                             static_cast<int>(adfX.size()),
                                             &adfX[0], &adfY[0], &adfZ[0],
                                             &abSuccess[0]);

                        const int nDstXSize = nPixels;
                        const int nDstYSize = nLines;

                        // Clamp target raster coordinates
                        for (size_t i = 0; i < adfX.size(); ++i)
                        {
                            if (adfX[i] < 0)
                                adfX[i] = 0;
                            if (adfX[i] > nDstXSize)
                                adfX[i] = nDstXSize;
                            if (adfY[i] < 0)
                                adfY[i] = 0;
                            if (adfY[i] > nDstYSize)
                                adfY[i] = nDstYSize;
                        }

                        // Start recording if different coordinate operations are
                        // going to be used
                        OGRProjCTDifferentOperationsStart(
                            psRTI->poReverseTransform);

                        // Transform back to source raster coordinates.
                        psInfo->pfnTransform(hUniqueTransformArg.get(), TRUE,
                                             static_cast<int>(adfX.size()),
                                             &adfX[0], &adfY[0], &adfZ[0],
                                             &abSuccess[0]);
                    }

                    if (OGRProjCTDifferentOperationsUsed(
                            psRTI->poReverseTransform))
                    {
                        CPLError(
                            CE_Warning, CPLE_AppDefined,
                            "Several coordinate operations are going to be "
                            "used. Artifacts may appear. You may consider "
                            "using the -to ALLOW_BALLPARK=NO and/or "
                            "-to ONLY_BEST=YES transform options, or specify "
                            "a particular coordinate operation with -ct");
                    }

                    // Stop recording
                    OGRProjCTDifferentOperationsStop(psRTI->poReverseTransform);
                }
            }
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Try to set color interpretation of source bands to target       */
    /*      dataset.                                                        */
    /*      FIXME? We should likely do that for other drivers than VRT &    */
    /*      GTiff  but it might create spurious .aux.xml files (at least    */
    /*      with HFA, and netCDF)                                           */
    /* -------------------------------------------------------------------- */
    if (bVRT || bSetColorInterpretation)
    {
        int nBandsToCopy = static_cast<int>(apeColorInterpretations.size());
        if (psOptions->bEnableSrcAlpha)
            nBandsToCopy--;
        for (int iBand = 0; iBand < nBandsToCopy; iBand++)
        {
            GDALSetRasterColorInterpretation(
                GDALGetRasterBand(hDstDS, iBand + 1),
                apeColorInterpretations[iBand]);
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Try to set color interpretation of output file alpha band.      */
    /* -------------------------------------------------------------------- */
    if (psOptions->bEnableDstAlpha)
    {
        GDALSetRasterColorInterpretation(
            GDALGetRasterBand(hDstDS, nDstBandCount), GCI_AlphaBand);
    }

    /* -------------------------------------------------------------------- */
    /*      Copy the raster attribute table, if required.                   */
    /* -------------------------------------------------------------------- */
    if (hRAT != nullptr)
    {
        GDALSetDefaultRAT(GDALGetRasterBand(hDstDS, 1), hRAT);
    }

    /* -------------------------------------------------------------------- */
    /*      Copy the color table, if required.                              */
    /* -------------------------------------------------------------------- */
    if (poCT)
    {
        GDALSetRasterColorTable(GDALGetRasterBand(hDstDS, 1),
                                GDALColorTable::ToHandle(poCT.get()));
    }

    /* -------------------------------------------------------------------- */
    /*      Copy scale/offset if found on source                            */
    /* -------------------------------------------------------------------- */
    if (nSrcCount == 1)
    {
        GDALDataset *poSrcDS = GDALDataset::FromHandle(pahSrcDS[0]);
        GDALDataset *poDstDS = GDALDataset::FromHandle(hDstDS);

        int nBandsToCopy = nDstBandCount;
        if (psOptions->bEnableDstAlpha)
            nBandsToCopy--;
        nBandsToCopy = std::min(nBandsToCopy, poSrcDS->GetRasterCount());

        for (int i = 0; i < nBandsToCopy; i++)
        {
            auto poSrcBand = poSrcDS->GetRasterBand(
                psOptions->anSrcBands.empty() ? i + 1
                                              : psOptions->anSrcBands[i]);
            auto poDstBand = poDstDS->GetRasterBand(
                psOptions->anDstBands.empty() ? i + 1
                                              : psOptions->anDstBands[i]);
            if (poSrcBand && poDstBand)
            {
                int bHasScale = FALSE;
                const double dfScale = poSrcBand->GetScale(&bHasScale);
                if (bHasScale)
                    poDstBand->SetScale(dfScale);

                int bHasOffset = FALSE;
                const double dfOffset = poSrcBand->GetOffset(&bHasOffset);
                if (bHasOffset)
                    poDstBand->SetOffset(dfOffset);
            }
        }
    }

    return hDstDS;
}

/************************************************************************/
/*                      GeoTransform_Transformer()                      */
/*                                                                      */
/*      Convert points from georef coordinates to pixel/line based      */
/*      on a geotransform.                                              */
/************************************************************************/

class CutlineTransformer : public OGRCoordinateTransformation
{
    CPL_DISALLOW_COPY_ASSIGN(CutlineTransformer)

  public:
    void *hSrcImageTransformer = nullptr;

    explicit CutlineTransformer(void *hTransformArg)
        : hSrcImageTransformer(hTransformArg)
    {
    }

    const OGRSpatialReference *GetSourceCS() const override
    {
        return nullptr;
    }

    const OGRSpatialReference *GetTargetCS() const override
    {
        return nullptr;
    }

    ~CutlineTransformer() override;

    virtual int Transform(size_t nCount, double *x, double *y, double *z,
                          double * /* t */, int *pabSuccess) override
    {
        CPLAssert(nCount <=
                  static_cast<size_t>(std::numeric_limits<int>::max()));
        return GDALGenImgProjTransform(hSrcImageTransformer, TRUE,
                                       static_cast<int>(nCount), x, y, z,
                                       pabSuccess);
    }

    OGRCoordinateTransformation *Clone() const override
    {
        return new CutlineTransformer(
            GDALCloneTransformer(hSrcImageTransformer));
    }

    OGRCoordinateTransformation *GetInverse() const override
    {
        return nullptr;
    }
};

CutlineTransformer::~CutlineTransformer()
{
    GDALDestroyTransformer(hSrcImageTransformer);
}

static double GetMaximumSegmentLength(OGRGeometry *poGeom)
{
    switch (wkbFlatten(poGeom->getGeometryType()))
    {
        case wkbLineString:
        {
            OGRLineString *poLS = static_cast<OGRLineString *>(poGeom);
            double dfMaxSquaredLength = 0.0;
            for (int i = 0; i < poLS->getNumPoints() - 1; i++)
            {
                double dfDeltaX = poLS->getX(i + 1) - poLS->getX(i);
                double dfDeltaY = poLS->getY(i + 1) - poLS->getY(i);
                double dfSquaredLength =
                    dfDeltaX * dfDeltaX + dfDeltaY * dfDeltaY;
                dfMaxSquaredLength =
                    std::max(dfMaxSquaredLength, dfSquaredLength);
            }
            return sqrt(dfMaxSquaredLength);
        }

        case wkbPolygon:
        {
            OGRPolygon *poPoly = static_cast<OGRPolygon *>(poGeom);
            double dfMaxLength =
                GetMaximumSegmentLength(poPoly->getExteriorRing());
            for (int i = 0; i < poPoly->getNumInteriorRings(); i++)
            {
                dfMaxLength = std::max(
                    dfMaxLength,
                    GetMaximumSegmentLength(poPoly->getInteriorRing(i)));
            }
            return dfMaxLength;
        }

        case wkbMultiPolygon:
        {
            OGRMultiPolygon *poMP = static_cast<OGRMultiPolygon *>(poGeom);
            double dfMaxLength = 0.0;
            for (int i = 0; i < poMP->getNumGeometries(); i++)
            {
                dfMaxLength =
                    std::max(dfMaxLength,
                             GetMaximumSegmentLength(poMP->getGeometryRef(i)));
            }
            return dfMaxLength;
        }

        default:
            CPLAssert(false);
            return 0.0;
    }
}

/************************************************************************/
/*                      RemoveZeroWidthSlivers()                        */
/*                                                                      */
/* Such slivers can cause issues after reprojection.                    */
/************************************************************************/

static void RemoveZeroWidthSlivers(OGRGeometry *poGeom)
{
    const OGRwkbGeometryType eType = wkbFlatten(poGeom->getGeometryType());
    if (eType == wkbMultiPolygon)
    {
        auto poMP = poGeom->toMultiPolygon();
        int nNumGeometries = poMP->getNumGeometries();
        for (int i = 0; i < nNumGeometries; /* incremented in loop */)
        {
            auto poPoly = poMP->getGeometryRef(i);
            RemoveZeroWidthSlivers(poPoly);
            if (poPoly->IsEmpty())
            {
                CPLDebug("WARP",
                         "RemoveZeroWidthSlivers: removing empty polygon");
                poMP->removeGeometry(i, /* bDelete = */ true);
                --nNumGeometries;
            }
            else
            {
                ++i;
            }
        }
    }
    else if (eType == wkbPolygon)
    {
        auto poPoly = poGeom->toPolygon();
        if (auto poExteriorRing = poPoly->getExteriorRing())
        {
            RemoveZeroWidthSlivers(poExteriorRing);
            if (poExteriorRing->getNumPoints() < 4)
            {
                poPoly->empty();
                return;
            }
        }
        int nNumInteriorRings = poPoly->getNumInteriorRings();
        for (int i = 0; i < nNumInteriorRings; /* incremented in loop */)
        {
            auto poRing = poPoly->getInteriorRing(i);
            RemoveZeroWidthSlivers(poRing);
            if (poRing->getNumPoints() < 4)
            {
                CPLDebug(
                    "WARP",
                    "RemoveZeroWidthSlivers: removing empty interior ring");
                constexpr int OFFSET_EXTERIOR_RING = 1;
                poPoly->removeRing(i + OFFSET_EXTERIOR_RING,
                                   /* bDelete = */ true);
                --nNumInteriorRings;
            }
            else
            {
                ++i;
            }
        }
    }
    else if (eType == wkbLineString)
    {
        OGRLineString *poLS = poGeom->toLineString();
        int numPoints = poLS->getNumPoints();
        for (int i = 1; i < numPoints - 1;)
        {
            const double x1 = poLS->getX(i - 1);
            const double y1 = poLS->getY(i - 1);
            const double x2 = poLS->getX(i);
            const double y2 = poLS->getY(i);
            const double x3 = poLS->getX(i + 1);
            const double y3 = poLS->getY(i + 1);
            const double dx1 = x2 - x1;
            const double dy1 = y2 - y1;
            const double dx2 = x3 - x2;
            const double dy2 = y3 - y2;
            const double scalar_product = dx1 * dx2 + dy1 * dy2;
            const double square_scalar_product =
                scalar_product * scalar_product;
            const double square_norm1 = dx1 * dx1 + dy1 * dy1;
            const double square_norm2 = dx2 * dx2 + dy2 * dy2;
            const double square_norm1_mult_norm2 = square_norm1 * square_norm2;
            if (scalar_product < 0 &&
                fabs(square_scalar_product - square_norm1_mult_norm2) <=
                    1e-15 * square_norm1_mult_norm2)
            {
                CPLDebug("WARP",
                         "RemoveZeroWidthSlivers: removing point %.10g %.10g",
                         x2, y2);
                poLS->removePoint(i);
                numPoints--;
            }
            else
            {
                ++i;
            }
        }
    }
}

/************************************************************************/
/*                      TransformCutlineToSource()                      */
/*                                                                      */
/*      Transform cutline from its SRS to source pixel/line coordinates.*/
/************************************************************************/
static CPLErr TransformCutlineToSource(GDALDataset *poSrcDS,
                                       OGRGeometry *poCutline,
                                       char ***ppapszWarpOptions,
                                       CSLConstList papszTO_In)

{
    RemoveZeroWidthSlivers(poCutline);

    auto poMultiPolygon = std::unique_ptr<OGRGeometry>(poCutline->clone());

    /* -------------------------------------------------------------------- */
    /*      Checkout that if there's a cutline SRS, there's also a raster   */
    /*      one.                                                            */
    /* -------------------------------------------------------------------- */
    std::unique_ptr<OGRSpatialReference> poRasterSRS;
    const CPLString osProjection =
        GetSrcDSProjection(GDALDataset::ToHandle(poSrcDS), papszTO_In);
    if (!osProjection.empty())
    {
        poRasterSRS = std::make_unique<OGRSpatialReference>();
        poRasterSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
        if (poRasterSRS->SetFromUserInput(osProjection) != OGRERR_NONE)
        {
            poRasterSRS.reset();
        }
    }

    std::unique_ptr<OGRSpatialReference> poDstSRS;
    const char *pszThisTargetSRS = CSLFetchNameValue(papszTO_In, "DST_SRS");
    if (pszThisTargetSRS)
    {
        poDstSRS = std::make_unique<OGRSpatialReference>();
        poDstSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
        if (poDstSRS->SetFromUserInput(pszThisTargetSRS) != OGRERR_NONE)
        {
            return CE_Failure;
        }
    }
    else if (poRasterSRS)
    {
        poDstSRS.reset(poRasterSRS->Clone());
    }

    /* -------------------------------------------------------------------- */
    /*      Extract the cutline SRS.                                        */
    /* -------------------------------------------------------------------- */
    const OGRSpatialReference *poCutlineSRS =
        poMultiPolygon->getSpatialReference();

    /* -------------------------------------------------------------------- */
    /*      Detect if there's no transform at all involved, in which case   */
    /*      we can avoid densification.                                     */
    /* -------------------------------------------------------------------- */
    bool bMayNeedDensify = true;
    if (poRasterSRS && poCutlineSRS && poRasterSRS->IsSame(poCutlineSRS) &&
        poSrcDS->GetGCPCount() == 0 && !poSrcDS->GetMetadata("RPC") &&
        !poSrcDS->GetMetadata("GEOLOCATION") &&
        !CSLFetchNameValue(papszTO_In, "GEOLOC_ARRAY") &&
        !CSLFetchNameValue(papszTO_In, "SRC_GEOLOC_ARRAY"))
    {
        CPLStringList aosTOTmp(papszTO_In);
        aosTOTmp.SetNameValue("SRC_SRS", nullptr);
        aosTOTmp.SetNameValue("DST_SRS", nullptr);
        if (aosTOTmp.size() == 0)
        {
            bMayNeedDensify = false;
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Compare source raster SRS and cutline SRS                       */
    /* -------------------------------------------------------------------- */
    if (poRasterSRS && poCutlineSRS)
    {
        /* OK, we will reproject */
    }
    else if (poRasterSRS && !poCutlineSRS)
    {
        CPLError(
            CE_Warning, CPLE_AppDefined,
            "the source raster dataset has a SRS, but the cutline features\n"
            "not.  We assume that the cutline coordinates are expressed in the "
            "destination SRS.\n"
            "If not, cutline results may be incorrect.");
    }
    else if (!poRasterSRS && poCutlineSRS)
    {
        CPLError(CE_Warning, CPLE_AppDefined,
                 "the input vector layer has a SRS, but the source raster "
                 "dataset does not.\n"
                 "Cutline results may be incorrect.");
    }

    auto poCTCutlineToSrc = CreateCTCutlineToSrc(
        poRasterSRS.get(), poDstSRS.get(), poCutlineSRS, papszTO_In);

    CPLStringList aosTO(papszTO_In);

    if (pszThisTargetSRS && !osProjection.empty())
    {
        // Avoid any reprojection when using the GenImgProjTransformer
        aosTO.SetNameValue("DST_SRS", osProjection.c_str());
    }
    aosTO.SetNameValue("SRC_COORDINATE_EPOCH", nullptr);
    aosTO.SetNameValue("DST_COORDINATE_EPOCH", nullptr);
    aosTO.SetNameValue("COORDINATE_OPERATION", nullptr);

    /* -------------------------------------------------------------------- */
    /*      It may be unwise to let the mask geometry be re-wrapped by      */
    /*      the CENTER_LONG machinery as this can easily screw up world     */
    /*      spanning masks and invert the mask topology.                    */
    /* -------------------------------------------------------------------- */
    aosTO.SetNameValue("INSERT_CENTER_LONG", "FALSE");

    /* -------------------------------------------------------------------- */
    /*      Transform the geometry to pixel/line coordinates.               */
    /* -------------------------------------------------------------------- */
    /* The cutline transformer will *invert* the hSrcImageTransformer */
    /* so it will convert from the source SRS to the source pixel/line */
    /* coordinates */
    CutlineTransformer oTransformer(GDALCreateGenImgProjTransformer2(
        GDALDataset::ToHandle(poSrcDS), nullptr, aosTO.List()));

    if (oTransformer.hSrcImageTransformer == nullptr)
    {
        return CE_Failure;
    }

    // Some transforms like RPC can transform a valid geometry into an invalid
    // one if the node density of the input geometry isn't sufficient before
    // reprojection. So after an initial reprojection, we check that the
    // maximum length of a segment is no longer than 1 pixel, and if not,
    // we densify the input geometry before doing a new reprojection
    const double dfMaxLengthInSpatUnits =
        GetMaximumSegmentLength(poMultiPolygon.get());
    OGRErr eErr = OGRERR_NONE;
    if (poCTCutlineToSrc)
    {
        poMultiPolygon.reset(OGRGeometryFactory::transformWithOptions(
            poMultiPolygon.get(), poCTCutlineToSrc.get(), nullptr));
        if (!poMultiPolygon)
        {
            eErr = OGRERR_FAILURE;
            poMultiPolygon.reset(poCutline->clone());
            poMultiPolygon->transform(poCTCutlineToSrc.get());
        }
    }
    if (poMultiPolygon->transform(&oTransformer) != OGRERR_NONE)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "poMultiPolygon->transform(&oTransformer) failed at line %d",
                 __LINE__);
        eErr = OGRERR_FAILURE;
    }
    const double dfInitialMaxLengthInPixels =
        GetMaximumSegmentLength(poMultiPolygon.get());

    CPLPushErrorHandler(CPLQuietErrorHandler);
    const bool bWasValidInitially =
        ValidateCutline(poMultiPolygon.get(), false);
    CPLPopErrorHandler();
    if (!bWasValidInitially)
    {
        CPLDebug("WARP", "Cutline is not valid after initial reprojection");
        char *pszWKT = nullptr;
        poMultiPolygon->exportToWkt(&pszWKT);
        CPLDebug("GDALWARP", "WKT = \"%s\"", pszWKT ? pszWKT : "(null)");
        CPLFree(pszWKT);
    }

    bool bDensify = false;
    if (bMayNeedDensify && eErr == OGRERR_NONE &&
        dfInitialMaxLengthInPixels > 1.0)
    {
        const char *pszDensifyCutline =
            CPLGetConfigOption("GDALWARP_DENSIFY_CUTLINE", "YES");
        if (EQUAL(pszDensifyCutline, "ONLY_IF_INVALID"))
        {
            bDensify = (OGRGeometryFactory::haveGEOS() && !bWasValidInitially);
        }
        else if (CSLFetchNameValue(*ppapszWarpOptions, "CUTLINE_BLEND_DIST") !=
                     nullptr &&
                 CPLGetConfigOption("GDALWARP_DENSIFY_CUTLINE", nullptr) ==
                     nullptr)
        {
            // TODO: we should only emit this message if a
            // transform/reprojection will be actually done
            CPLDebug("WARP",
                     "Densification of cutline could perhaps be useful but as "
                     "CUTLINE_BLEND_DIST is used, this could be very slow. So "
                     "disabled "
                     "unless GDALWARP_DENSIFY_CUTLINE=YES is explicitly "
                     "specified as configuration option");
        }
        else
        {
            bDensify = CPLTestBool(pszDensifyCutline);
        }
    }
    if (bDensify)
    {
        CPLDebug("WARP",
                 "Cutline maximum segment size was %.0f pixel after "
                 "reprojection to source coordinates.",
                 dfInitialMaxLengthInPixels);

        // Densify and reproject with the aim of having a 1 pixel density
        double dfSegmentSize =
            dfMaxLengthInSpatUnits / dfInitialMaxLengthInPixels;
        const int MAX_ITERATIONS = 10;
        for (int i = 0; i < MAX_ITERATIONS; i++)
        {
            poMultiPolygon.reset(poCutline->clone());
            poMultiPolygon->segmentize(dfSegmentSize);
            if (i == MAX_ITERATIONS - 1)
            {
                char *pszWKT = nullptr;
                poMultiPolygon->exportToWkt(&pszWKT);
                CPLDebug("WARP",
                         "WKT of polygon after densification with segment size "
                         "= %f: %s",
                         dfSegmentSize, pszWKT);
                CPLFree(pszWKT);
            }
            eErr = OGRERR_NONE;
            if (poCTCutlineToSrc)
            {
                poMultiPolygon.reset(OGRGeometryFactory::transformWithOptions(
                    poMultiPolygon.get(), poCTCutlineToSrc.get(), nullptr));
                if (!poMultiPolygon)
                {
                    eErr = OGRERR_FAILURE;
                    break;
                }
            }
            if (poMultiPolygon->transform(&oTransformer) != OGRERR_NONE)
                eErr = OGRERR_FAILURE;
            if (eErr == OGRERR_NONE)
            {
                const double dfMaxLengthInPixels =
                    GetMaximumSegmentLength(poMultiPolygon.get());
                if (bWasValidInitially)
                {
                    // In some cases, the densification itself results in a
                    // reprojected invalid polygon due to the non-linearity of
                    // RPC DEM transformation, so in those cases, try a less
                    // dense cutline
                    CPLPushErrorHandler(CPLQuietErrorHandler);
                    const bool bIsValid =
                        ValidateCutline(poMultiPolygon.get(), false);
                    CPLPopErrorHandler();
                    if (!bIsValid)
                    {
                        if (i == MAX_ITERATIONS - 1)
                        {
                            char *pszWKT = nullptr;
                            poMultiPolygon->exportToWkt(&pszWKT);
                            CPLDebug("WARP",
                                     "After densification, cutline maximum "
                                     "segment size is now %.0f pixel, "
                                     "but cutline is invalid. %s",
                                     dfMaxLengthInPixels, pszWKT);
                            CPLFree(pszWKT);
                            break;
                        }
                        CPLDebug("WARP",
                                 "After densification, cutline maximum segment "
                                 "size is now %.0f pixel, "
                                 "but cutline is invalid. So trying a less "
                                 "dense cutline.",
                                 dfMaxLengthInPixels);
                        dfSegmentSize *= 2;
                        continue;
                    }
                }
                CPLDebug("WARP",
                         "After densification, cutline maximum segment size is "
                         "now %.0f pixel.",
                         dfMaxLengthInPixels);
            }
            break;
        }
    }

    if (eErr == OGRERR_FAILURE)
    {
        if (CPLTestBool(
                CPLGetConfigOption("GDALWARP_IGNORE_BAD_CUTLINE", "NO")))
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Cutline transformation failed");
        else
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Cutline transformation failed");
            return CE_Failure;
        }
    }
    else if (!ValidateCutline(poMultiPolygon.get(), true))
    {
        return CE_Failure;
    }

    // Optimization: if the cutline contains the footprint of the source
    // dataset, no need to use the cutline.
    if (OGRGeometryFactory::haveGEOS()
#ifdef DEBUG
        // Env var just for debugging purposes
        && !CPLTestBool(CPLGetConfigOption(
               "GDALWARP_SKIP_CUTLINE_CONTAINMENT_TEST", "NO"))
#endif
    )
    {
        const double dfCutlineBlendDist = CPLAtof(CSLFetchNameValueDef(
            *ppapszWarpOptions, "CUTLINE_BLEND_DIST", "0"));
        auto poRing = std::make_unique<OGRLinearRing>();
        poRing->addPoint(-dfCutlineBlendDist, -dfCutlineBlendDist);
        poRing->addPoint(-dfCutlineBlendDist,
                         dfCutlineBlendDist + poSrcDS->GetRasterYSize());
        poRing->addPoint(dfCutlineBlendDist + poSrcDS->GetRasterXSize(),
                         dfCutlineBlendDist + poSrcDS->GetRasterYSize());
        poRing->addPoint(dfCutlineBlendDist + poSrcDS->GetRasterXSize(),
                         -dfCutlineBlendDist);
        poRing->addPoint(-dfCutlineBlendDist, -dfCutlineBlendDist);
        OGRPolygon oSrcDSFootprint;
        oSrcDSFootprint.addRing(std::move(poRing));
        OGREnvelope sSrcDSEnvelope;
        oSrcDSFootprint.getEnvelope(&sSrcDSEnvelope);
        OGREnvelope sCutlineEnvelope;
        poMultiPolygon->getEnvelope(&sCutlineEnvelope);
        if (sCutlineEnvelope.Contains(sSrcDSEnvelope) &&
            poMultiPolygon->Contains(&oSrcDSFootprint))
        {
            CPLDebug("WARP", "Source dataset fully contained within cutline.");
            return CE_None;
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Convert aggregate geometry into WKT.                            */
    /* -------------------------------------------------------------------- */
    char *pszWKT = nullptr;
    poMultiPolygon->exportToWkt(&pszWKT);
    // fprintf(stderr, "WKT = \"%s\"\n", pszWKT ? pszWKT : "(null)");

    *ppapszWarpOptions = CSLSetNameValue(*ppapszWarpOptions, "CUTLINE", pszWKT);
    CPLFree(pszWKT);
    return CE_None;
}

static void RemoveConflictingMetadata(GDALMajorObjectH hObj,
                                      CSLConstList papszSrcMetadata,
                                      const char *pszValueConflict)
{
    if (hObj == nullptr)
        return;

    for (const auto &[pszKey, pszValue] :
         cpl::IterateNameValue(papszSrcMetadata))
    {
        const char *pszValueComp = GDALGetMetadataItem(hObj, pszKey, nullptr);
        if (pszValueComp == nullptr || (!EQUAL(pszValue, pszValueComp) &&
                                        !EQUAL(pszValueComp, pszValueConflict)))
        {
            if (STARTS_WITH(pszKey, "STATISTICS_"))
                GDALSetMetadataItem(hObj, pszKey, nullptr, nullptr);
            else
                GDALSetMetadataItem(hObj, pszKey, pszValueConflict, nullptr);
        }
    }
}

/************************************************************************/
/*                             IsValidSRS                               */
/************************************************************************/

static bool IsValidSRS(const char *pszUserInput)

{
    OGRSpatialReferenceH hSRS;
    bool bRes = true;

    hSRS = OSRNewSpatialReference(nullptr);
    if (OSRSetFromUserInput(hSRS, pszUserInput) != OGRERR_NONE)
    {
        bRes = false;
    }

    OSRDestroySpatialReference(hSRS);

    return bRes;
}

/************************************************************************/
/*                     GDALWarpAppOptionsGetParser()                    */
/************************************************************************/

static std::unique_ptr<GDALArgumentParser>
GDALWarpAppOptionsGetParser(GDALWarpAppOptions *psOptions,
                            GDALWarpAppOptionsForBinary *psOptionsForBinary)
{
    auto argParser = std::make_unique<GDALArgumentParser>(
        "gdalwarp", /* bForBinary=*/psOptionsForBinary != nullptr);

    argParser->add_description(_("Image reprojection and warping utility."));

    argParser->add_epilog(
        _("For more details, consult https://gdal.org/programs/gdalwarp.html"));

    argParser->add_quiet_argument(
        psOptionsForBinary ? &psOptionsForBinary->bQuiet : nullptr);

    argParser->add_argument("-overwrite")
        .flag()
        .action(
            [psOptionsForBinary](const std::string &)
            {
                if (psOptionsForBinary)
                    psOptionsForBinary->bOverwrite = true;
            })
        .help(_("Overwrite the target dataset if it already exists."));

    argParser->add_output_format_argument(psOptions->osFormat);

    argParser->add_argument("-co")
        .metavar("<NAME>=<VALUE>")
        .append()
        .action(
            [psOptions, psOptionsForBinary](const std::string &s)
            {
                psOptions->aosCreateOptions.AddString(s.c_str());
                psOptions->bCreateOutput = true;

                if (psOptionsForBinary)
                    psOptionsForBinary->aosCreateOptions.AddString(s.c_str());
            })
        .help(_("Creation option(s)."));

    argParser->add_argument("-s_srs")
        .metavar("<srs_def>")
        .action(
            [psOptions](const std::string &s)
            {
                if (!IsValidSRS(s.c_str()))
                {
                    throw std::invalid_argument("Invalid SRS for -s_srs");
                }
                psOptions->aosTransformerOptions.SetNameValue("SRC_SRS",
                                                              s.c_str());
            })
        .help(_("Set source spatial reference."));

    argParser->add_argument("-t_srs")
        .metavar("<srs_def>")
        .action(
            [psOptions](const std::string &s)
            {
                if (!IsValidSRS(s.c_str()))
                {
                    throw std::invalid_argument("Invalid SRS for -t_srs");
                }
                psOptions->aosTransformerOptions.SetNameValue("DST_SRS",
                                                              s.c_str());
            })
        .help(_("Set target spatial reference."));

    {
        auto &group = argParser->add_mutually_exclusive_group();
        group.add_argument("-srcalpha")
            .flag()
            .store_into(psOptions->bEnableSrcAlpha)
            .help(_("Force the last band of a source image to be considered as "
                    "a source alpha band."));
        group.add_argument("-nosrcalpha")
            .flag()
            .store_into(psOptions->bDisableSrcAlpha)
            .help(_("Prevent the alpha band of a source image to be considered "
                    "as such."));
    }

    argParser->add_argument("-dstalpha")
        .flag()
        .store_into(psOptions->bEnableDstAlpha)
        .help(_("Create an output alpha band to identify nodata "
                "(unset/transparent) pixels."));

    // Parsing of that option is done in a preprocessing stage
    argParser->add_argument("-tr")
        .metavar("<xres> <yres>|square")
        .help(_("Target resolution."));

    argParser->add_argument("-ts")
        .metavar("<width> <height>")
        .nargs(2)
        .scan<'i', int>()
        .help(_("Set output file size in pixels and lines."));

    argParser->add_argument("-te")
        .metavar("<xmin> <ymin> <xmax> <ymax>")
        .nargs(4)
        .scan<'g', double>()
        .help(_("Set georeferenced extents of output file to be created."));

    argParser->add_argument("-te_srs")
        .metavar("<srs_def>")
        .action(
            [psOptions](const std::string &s)
            {
                if (!IsValidSRS(s.c_str()))
                {
                    throw std::invalid_argument("Invalid SRS for -te_srs");
                }
                psOptions->osTE_SRS = s;
                psOptions->bCreateOutput = true;
            })
        .help(_("Set source spatial reference."));

    argParser->add_argument("-r")
        .metavar("near|bilinear|cubic|cubicspline|lanczos|average|rms|mode|min|"
                 "max|med|q1|q3|sum")
        .action(
            [psOptions](const std::string &s)
            {
                GDALGetWarpResampleAlg(s.c_str(), psOptions->eResampleAlg,
                                       /*bThrow=*/true);
                psOptions->bResampleAlgSpecifiedByUser = true;
            })
        .help(_("Resampling method to use."));

    argParser->add_output_type_argument(psOptions->eOutputType);

    ///////////////////////////////////////////////////////////////////////
    argParser->add_group("Advanced options");

    const auto CheckSingleMethod = [psOptions]()
    {
        const char *pszMethod =
            FetchSrcMethod(psOptions->aosTransformerOptions);
        if (pszMethod)
            CPLError(CE_Warning, CPLE_IllegalArg,
                     "Warning: only one METHOD can be used. Method %s is "
                     "already defined.",
                     pszMethod);
        const char *pszMAX_GCP_ORDER =
            psOptions->aosTransformerOptions.FetchNameValue("MAX_GCP_ORDER");
        if (pszMAX_GCP_ORDER)
            CPLError(CE_Warning, CPLE_IllegalArg,
                     "Warning: only one METHOD can be used. -order %s "
                     "option was specified, so it is likely that "
                     "GCP_POLYNOMIAL was implied.",
                     pszMAX_GCP_ORDER);
    };

    argParser->add_argument("-wo")
        .metavar("<NAME>=<VALUE>")
        .append()
        .action([psOptions](const std::string &s)
                { psOptions->aosWarpOptions.AddString(s.c_str()); })
        .help(_("Warping option(s)."));

    argParser->add_argument("-multi")
        .flag()
        .store_into(psOptions->bMulti)
        .help(_("Multithreaded input/output."));

    argParser->add_argument("-s_coord_epoch")
        .metavar("<epoch>")
        .action(
            [psOptions](const std::string &s)
            {
                psOptions->aosTransformerOptions.SetNameValue(
                    "SRC_COORDINATE_EPOCH", s.c_str());
            })
        .help(_("Assign a coordinate epoch, linked with the source SRS when "
                "-s_srs is used."));

    argParser->add_argument("-t_coord_epoch")
        .metavar("<epoch>")
        .action(
            [psOptions](const std::string &s)
            {
                psOptions->aosTransformerOptions.SetNameValue(
                    "DST_COORDINATE_EPOCH", s.c_str());
            })
        .help(_("Assign a coordinate epoch, linked with the output SRS when "
                "-t_srs is used."));

    argParser->add_argument("-ct")
        .metavar("<string>")
        .action(
            [psOptions](const std::string &s)
            {
                psOptions->aosTransformerOptions.SetNameValue(
                    "COORDINATE_OPERATION", s.c_str());
            })
        .help(_("Set a coordinate transformation."));

    {
        auto &group = argParser->add_mutually_exclusive_group();
        group.add_argument("-tps")
            .flag()
            .action(
                [psOptions, CheckSingleMethod](const std::string &)
                {
                    CheckSingleMethod();
                    psOptions->aosTransformerOptions.SetNameValue("SRC_METHOD",
                                                                  "GCP_TPS");
                })
            .help(_("Force use of thin plate spline transformer based on "
                    "available GCPs."));

        group.add_argument("-rpc")
            .flag()
            .action(
                [psOptions, CheckSingleMethod](const std::string &)
                {
                    CheckSingleMethod();
                    psOptions->aosTransformerOptions.SetNameValue("SRC_METHOD",
                                                                  "RPC");
                })
            .help(_("Force use of RPCs."));

        group.add_argument("-geoloc")
            .flag()
            .action(
                [psOptions, CheckSingleMethod](const std::string &)
                {
                    CheckSingleMethod();
                    psOptions->aosTransformerOptions.SetNameValue(
                        "SRC_METHOD", "GEOLOC_ARRAY");
                })
            .help(_("Force use of Geolocation Arrays."));
    }

    argParser->add_argument("-order")
        .metavar("<1|2|3>")
        .choices("1", "2", "3")
        .action(
            [psOptions](const std::string &s)
            {
                const char *pszMethod =
                    FetchSrcMethod(psOptions->aosTransformerOptions);
                if (pszMethod)
                    CPLError(
                        CE_Warning, CPLE_IllegalArg,
                        "Warning: only one METHOD can be used. Method %s is "
                        "already defined",
                        pszMethod);
                psOptions->aosTransformerOptions.SetNameValue("MAX_GCP_ORDER",
                                                              s.c_str());
            })
        .help(_("Order of polynomial used for GCP warping."));

    // Parsing of that option is done in a preprocessing stage
    argParser->add_argument("-refine_gcps")
        .metavar("<tolerance> [<minimum_gcps>]")
        .help(_("Refines the GCPs by automatically eliminating outliers."));

    argParser->add_argument("-to")
        .metavar("<NAME>=<VALUE>")
        .append()
        .action([psOptions](const std::string &s)
                { psOptions->aosTransformerOptions.AddString(s.c_str()); })
        .help(_("Transform option(s)."));

    argParser->add_argument("-et")
        .metavar("<err_threshold>")
        .store_into(psOptions->dfErrorThreshold)
        .action(
            [psOptions](const std::string &)
            {
                if (psOptions->dfErrorThreshold < 0)
                {
                    throw std::invalid_argument(
                        "Invalid value for error threshold");
                }
                psOptions->aosWarpOptions.AddString(CPLSPrintf(
                    "ERROR_THRESHOLD=%.16g", psOptions->dfErrorThreshold));
            })
        .help(_("Error threshold."));

    argParser->add_argument("-wm")
        .metavar("<memory_in_mb>")
        .action(
            [psOptions](const std::string &s)
            {
                bool bUnitSpecified = false;
                GIntBig nBytes;
                if (CPLParseMemorySize(s.c_str(), &nBytes, &bUnitSpecified) ==
                    CE_None)
                {
                    if (!bUnitSpecified && nBytes < 10000)
                    {
                        nBytes *= (1024 * 1024);
                    }
                    psOptions->dfWarpMemoryLimit = static_cast<double>(nBytes);
                }
                else
                {
                    throw std::invalid_argument("Failed to parse value of -wm");
                }
            })
        .help(_("Set max warp memory."));

    argParser->add_argument("-srcnodata")
        .metavar("\"<value>[ <value>]...\"")
        .store_into(psOptions->osSrcNodata)
        .help(_("Nodata masking values for input bands."));

    argParser->add_argument("-dstnodata")
        .metavar("\"<value>[ <value>]...\"")
        .store_into(psOptions->osDstNodata)
        .help(_("Nodata masking values for output bands."));

    argParser->add_argument("-tap")
        .flag()
        .store_into(psOptions->bTargetAlignedPixels)
        .help(_("Force target aligned pixels."));

    argParser->add_argument("-wt")
        .metavar("Byte|Int8|[U]Int{16|32|64}|CInt{16|32}|[C]Float{32|64}")
        .action(
            [psOptions](const std::string &s)
            {
                psOptions->eWorkingType = GDALGetDataTypeByName(s.c_str());
                if (psOptions->eWorkingType == GDT_Unknown)
                {
                    throw std::invalid_argument(
                        std::string("Unknown output pixel type: ").append(s));
                }
            })
        .help(_("Working data type."));

    // Non-documented alias of -r nearest
    argParser->add_argument("-rn")
        .flag()
        .hidden()
        .action([psOptions](const std::string &)
                { psOptions->eResampleAlg = GRA_NearestNeighbour; })
        .help(_("Nearest neighbour resampling."));

    // Non-documented alias of -r bilinear
    argParser->add_argument("-rb")
        .flag()
        .hidden()
        .action([psOptions](const std::string &)
                { psOptions->eResampleAlg = GRA_Bilinear; })
        .help(_("Bilinear resampling."));

    // Non-documented alias of -r cubic
    argParser->add_argument("-rc")
        .flag()
        .hidden()
        .action([psOptions](const std::string &)
                { psOptions->eResampleAlg = GRA_Cubic; })
        .help(_("Cubic resampling."));

    // Non-documented alias of -r cubicspline
    argParser->add_argument("-rcs")
        .flag()
        .hidden()
        .action([psOptions](const std::string &)
                { psOptions->eResampleAlg = GRA_CubicSpline; })
        .help(_("Cubic spline resampling."));

    // Non-documented alias of -r lanczos
    argParser->add_argument("-rl")
        .flag()
        .hidden()
        .action([psOptions](const std::string &)
                { psOptions->eResampleAlg = GRA_Lanczos; })
        .help(_("Lanczos resampling."));

    // Non-documented alias of -r average
    argParser->add_argument("-ra")
        .flag()
        .hidden()
        .action([psOptions](const std::string &)
                { psOptions->eResampleAlg = GRA_Average; })
        .help(_("Average resampling."));

    // Non-documented alias of -r rms
    argParser->add_argument("-rrms")
        .flag()
        .hidden()
        .action([psOptions](const std::string &)
                { psOptions->eResampleAlg = GRA_RMS; })
        .help(_("RMS resampling."));

    // Non-documented alias of -r mode
    argParser->add_argument("-rm")
        .flag()
        .hidden()
        .action([psOptions](const std::string &)
                { psOptions->eResampleAlg = GRA_Mode; })
        .help(_("Mode resampling."));

    argParser->add_argument("-cutline")
        .metavar("<datasource>|<WKT>")
        .store_into(psOptions->osCutlineDSNameOrWKT)
        .help(_("Enable use of a blend cutline from the name of a vector "
                "dataset or a WKT geometry."));

    argParser->add_argument("-cutline_srs")
        .metavar("<srs_def>")
        .action(
            [psOptions](const std::string &s)
            {
                if (!IsValidSRS(s.c_str()))
                {
                    throw std::invalid_argument("Invalid SRS for -cutline_srs");
                }
                psOptions->osCutlineSRS = s;
            })
        .help(_("Sets/overrides cutline SRS."));

    argParser->add_argument("-cwhere")
        .metavar("<expression>")
        .store_into(psOptions->osCWHERE)
        .help(_("Restrict desired cutline features based on attribute query."));

    {
        auto &group = argParser->add_mutually_exclusive_group();
        group.add_argument("-cl")
            .metavar("<layername>")
            .store_into(psOptions->osCLayer)
            .help(_("Select the named layer from the cutline datasource."));

        group.add_argument("-csql")
            .metavar("<query>")
            .store_into(psOptions->osCSQL)
            .help(_("Select cutline features using an SQL query."));
    }

    argParser->add_argument("-cblend")
        .metavar("<distance>")
        .action(
            [psOptions](const std::string &s) {
                psOptions->aosWarpOptions.SetNameValue("CUTLINE_BLEND_DIST",
                                                       s.c_str());
            })
        .help(_(
            "Set a blend distance to use to blend over cutlines (in pixels)."));

    argParser->add_argument("-crop_to_cutline")
        .flag()
        .action(
            [psOptions](const std::string &)
            {
                psOptions->bCropToCutline = true;
                psOptions->bCreateOutput = true;
            })
        .help(_("Crop the extent of the target dataset to the extent of the "
                "cutline."));

    argParser->add_argument("-nomd")
        .flag()
        .action(
            [psOptions](const std::string &)
            {
                psOptions->bCopyMetadata = false;
                psOptions->bCopyBandInfo = false;
            })
        .help(_("Do not copy metadata."));

    argParser->add_argument("-cvmd")
        .metavar("<meta_conflict_value>")
        .store_into(psOptions->osMDConflictValue)
        .help(_("Value to set metadata items that conflict between source "
                "datasets."));

    argParser->add_argument("-setci")
        .flag()
        .store_into(psOptions->bSetColorInterpretation)
        .help(_("Set the color interpretation of the bands of the target "
                "dataset from the source dataset."));

    argParser->add_open_options_argument(
        psOptionsForBinary ? &(psOptionsForBinary->aosOpenOptions) : nullptr);

    argParser->add_argument("-doo")
        .metavar("<NAME>=<VALUE>")
        .append()
        .action(
            [psOptionsForBinary](const std::string &s)
            {
                if (psOptionsForBinary)
                    psOptionsForBinary->aosDestOpenOptions.AddString(s.c_str());
            })
        .help(_("Open option(s) for output dataset."));

    argParser->add_argument("-ovr")
        .metavar("<level>|AUTO|AUTO-<n>|NONE")
        .action(
            [psOptions](const std::string &s)
            {
                const char *pszOvLevel = s.c_str();
                if (EQUAL(pszOvLevel, "AUTO"))
                    psOptions->nOvLevel = OVR_LEVEL_AUTO;
                else if (STARTS_WITH_CI(pszOvLevel, "AUTO-"))
                    psOptions->nOvLevel =
                        OVR_LEVEL_AUTO - atoi(pszOvLevel + strlen("AUTO-"));
                else if (EQUAL(pszOvLevel, "NONE"))
                    psOptions->nOvLevel = OVR_LEVEL_NONE;
                else if (CPLGetValueType(pszOvLevel) == CPL_VALUE_INTEGER)
                    psOptions->nOvLevel = atoi(pszOvLevel);
                else
                {
                    throw std::invalid_argument(CPLSPrintf(
                        "Invalid value '%s' for -ov option", pszOvLevel));
                }
            })
        .help(_("Specify which overview level of source files must be used."));

    {
        auto &group = argParser->add_mutually_exclusive_group();
        group.add_argument("-vshift")
            .flag()
            .store_into(psOptions->bVShift)
            .help(_("Force the use of vertical shift."));
        group.add_argument("-novshift", "-novshiftgrid")
            .flag()
            .store_into(psOptions->bNoVShift)
            .help(_("Disable the use of vertical shift."));
    }

    argParser->add_input_format_argument(
        psOptionsForBinary ? &psOptionsForBinary->aosAllowedInputDrivers
                           : nullptr);

    argParser->add_argument("-b", "-srcband")
        .metavar("<band>")
        .append()
        .store_into(psOptions->anSrcBands)
        .help(_("Specify input band(s) number to warp."));

    argParser->add_argument("-dstband")
        .metavar("<band>")
        .append()
        .store_into(psOptions->anDstBands)
        .help(_("Specify the output band number in which to warp."));

    if (psOptionsForBinary)
    {
        argParser->add_argument("src_dataset_name")
            .metavar("<src_dataset_name>")
            .nargs(argparse::nargs_pattern::at_least_one)
            .action([psOptionsForBinary](const std::string &s)
                    { psOptionsForBinary->aosSrcFiles.AddString(s.c_str()); })
            .help(_("Input dataset(s)."));

        argParser->add_argument("dst_dataset_name")
            .metavar("<dst_dataset_name>")
            .store_into(psOptionsForBinary->osDstFilename)
            .help(_("Output dataset."));
    }

    return argParser;
}

/************************************************************************/
/*                       GDALWarpAppGetParserUsage()                    */
/************************************************************************/

std::string GDALWarpAppGetParserUsage()
{
    try
    {
        GDALWarpAppOptions sOptions;
        GDALWarpAppOptionsForBinary sOptionsForBinary;
        auto argParser =
            GDALWarpAppOptionsGetParser(&sOptions, &sOptionsForBinary);
        return argParser->usage();
    }
    catch (const std::exception &err)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Unexpected exception: %s",
                 err.what());
        return std::string();
    }
}

/************************************************************************/
/*                             GDALWarpAppOptionsNew()                  */
/************************************************************************/

#ifndef CheckHasEnoughAdditionalArgs_defined
#define CheckHasEnoughAdditionalArgs_defined

static bool CheckHasEnoughAdditionalArgs(CSLConstList papszArgv, int i,
                                         int nExtraArg, int nArgc)
{
    if (i + nExtraArg >= nArgc)
    {
        CPLError(CE_Failure, CPLE_IllegalArg,
                 "%s option requires %d argument%s", papszArgv[i], nExtraArg,
                 nExtraArg == 1 ? "" : "s");
        return false;
    }
    return true;
}
#endif

#define CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(nExtraArg)                            \
    if (!CheckHasEnoughAdditionalArgs(papszArgv, i, nExtraArg, nArgc))         \
    {                                                                          \
        return nullptr;                                                        \
    }

/**
 * Allocates a GDALWarpAppOptions struct.
 *
 * @param papszArgv NULL terminated list of options (potentially including
 * filename and open options too), or NULL. The accepted options are the ones of
 * the <a href="/programs/gdalwarp.html">gdalwarp</a> utility.
 * @param psOptionsForBinary (output) may be NULL (and should generally be
 * NULL), otherwise (gdal_translate_bin.cpp use case) must be allocated with
 *                           GDALWarpAppOptionsForBinaryNew() prior to this
 * function. Will be filled with potentially present filename, open options,...
 * @return pointer to the allocated GDALWarpAppOptions struct. Must be freed
 * with GDALWarpAppOptionsFree().
 *
 * @since GDAL 2.1
 */

GDALWarpAppOptions *
GDALWarpAppOptionsNew(char **papszArgv,
                      GDALWarpAppOptionsForBinary *psOptionsForBinary)
{
    auto psOptions = std::make_unique<GDALWarpAppOptions>();

    psOptions->aosArgs.Assign(CSLDuplicate(papszArgv), true);

    /* -------------------------------------------------------------------- */
    /*      Pre-processing for custom syntax that ArgumentParser does not   */
    /*      support.                                                        */
    /* -------------------------------------------------------------------- */

    CPLStringList aosArgv;
    const int nArgc = CSLCount(papszArgv);
    for (int i = 0;
         i < nArgc && papszArgv != nullptr && papszArgv[i] != nullptr; i++)
    {
        if (EQUAL(papszArgv[i], "-refine_gcps"))
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            psOptions->aosTransformerOptions.SetNameValue("REFINE_TOLERANCE",
                                                          papszArgv[++i]);
            if (CPLAtof(papszArgv[i]) < 0)
            {
                CPLError(CE_Failure, CPLE_IllegalArg,
                         "The tolerance for -refine_gcps may not be negative.");
                return nullptr;
            }
            if (i < nArgc - 1 && atoi(papszArgv[i + 1]) >= 0 &&
                isdigit(static_cast<unsigned char>(papszArgv[i + 1][0])))
            {
                psOptions->aosTransformerOptions.SetNameValue(
                    "REFINE_MINIMUM_GCPS", papszArgv[++i]);
            }
            else
            {
                psOptions->aosTransformerOptions.SetNameValue(
                    "REFINE_MINIMUM_GCPS", "-1");
            }
        }
        else if (EQUAL(papszArgv[i], "-tr") && i + 1 < nArgc &&
                 EQUAL(papszArgv[i + 1], "square"))
        {
            ++i;
            psOptions->bSquarePixels = true;
            psOptions->bCreateOutput = true;
        }
        else if (EQUAL(papszArgv[i], "-tr"))
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2);
            psOptions->dfXRes = CPLAtofM(papszArgv[++i]);
            psOptions->dfYRes = fabs(CPLAtofM(papszArgv[++i]));
            if (psOptions->dfXRes == 0 || psOptions->dfYRes == 0)
            {
                CPLError(CE_Failure, CPLE_IllegalArg,
                         "Wrong value for -tr parameters.");
                return nullptr;
            }
            psOptions->bCreateOutput = true;
        }
        // argparser will be confused if the value of a string argument
        // starts with a negative sign.
        else if (EQUAL(papszArgv[i], "-srcnodata") && i + 1 < nArgc)
        {
            ++i;
            psOptions->osSrcNodata = papszArgv[i];
        }
        // argparser will be confused if the value of a string argument
        // starts with a negative sign.
        else if (EQUAL(papszArgv[i], "-dstnodata") && i + 1 < nArgc)
        {
            ++i;
            psOptions->osDstNodata = papszArgv[i];
        }
        else
        {
            aosArgv.AddString(papszArgv[i]);
        }
    }

    try
    {
        auto argParser =
            GDALWarpAppOptionsGetParser(psOptions.get(), psOptionsForBinary);

        argParser->parse_args_without_binary_name(aosArgv.List());

        if (auto oTS = argParser->present<std::vector<int>>("-ts"))
        {
            psOptions->nForcePixels = (*oTS)[0];
            psOptions->nForceLines = (*oTS)[1];
            psOptions->bCreateOutput = true;
        }

        if (auto oTE = argParser->present<std::vector<double>>("-te"))
        {
            psOptions->dfMinX = (*oTE)[0];
            psOptions->dfMinY = (*oTE)[1];
            psOptions->dfMaxX = (*oTE)[2];
            psOptions->dfMaxY = (*oTE)[3];
            psOptions->aosTransformerOptions.SetNameValue(
                "TARGET_EXTENT",
                CPLSPrintf("%.17g,%.17g,%.17g,%.17g", psOptions->dfMinX,
                           psOptions->dfMinY, psOptions->dfMaxX,
                           psOptions->dfMaxY));
            psOptions->bCreateOutput = true;
        }

        if (!psOptions->anDstBands.empty() &&
            psOptions->anSrcBands.size() != psOptions->anDstBands.size())
        {
            CPLError(
                CE_Failure, CPLE_IllegalArg,
                "-srcband should be specified as many times as -dstband is");
            return nullptr;
        }
        else if (!psOptions->anSrcBands.empty() &&
                 psOptions->anDstBands.empty())
        {
            for (int i = 0; i < static_cast<int>(psOptions->anSrcBands.size());
                 ++i)
            {
                psOptions->anDstBands.push_back(i + 1);
            }
        }

        if (!psOptions->osFormat.empty() ||
            psOptions->eOutputType != GDT_Unknown)
        {
            psOptions->bCreateOutput = true;
        }

        if (psOptionsForBinary)
            psOptionsForBinary->bCreateOutput = psOptions->bCreateOutput;

        return psOptions.release();
    }
    catch (const std::exception &err)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "%s", err.what());
        return nullptr;
    }
}

/************************************************************************/
/*                        GDALWarpAppOptionsFree()                    */
/************************************************************************/

/**
 * Frees the GDALWarpAppOptions struct.
 *
 * @param psOptions the options struct for GDALWarp().
 *
 * @since GDAL 2.1
 */

void GDALWarpAppOptionsFree(GDALWarpAppOptions *psOptions)
{
    delete psOptions;
}

/************************************************************************/
/*                 GDALWarpAppOptionsSetProgress()                    */
/************************************************************************/

/**
 * Set a progress function.
 *
 * @param psOptions the options struct for GDALWarp().
 * @param pfnProgress the progress callback.
 * @param pProgressData the user data for the progress callback.
 *
 * @since GDAL 2.1
 */

void GDALWarpAppOptionsSetProgress(GDALWarpAppOptions *psOptions,
                                   GDALProgressFunc pfnProgress,
                                   void *pProgressData)
{
    psOptions->pfnProgress = pfnProgress ? pfnProgress : GDALDummyProgress;
    psOptions->pProgressData = pProgressData;
    if (pfnProgress == GDALTermProgress)
        psOptions->bQuiet = false;
}

/************************************************************************/
/*                    GDALWarpAppOptionsSetQuiet()                      */
/************************************************************************/

/**
 * Set a progress function.
 *
 * @param psOptions the options struct for GDALWarp().
 * @param bQuiet whether GDALWarp() should emit messages on stdout.
 *
 * @since GDAL 2.3
 */

void GDALWarpAppOptionsSetQuiet(GDALWarpAppOptions *psOptions, int bQuiet)
{
    psOptions->bQuiet = CPL_TO_BOOL(bQuiet);
}

/************************************************************************/
/*                 GDALWarpAppOptionsSetWarpOption()                    */
/************************************************************************/

/**
 * Set a warp option
 *
 * @param psOptions the options struct for GDALWarp().
 * @param pszKey key.
 * @param pszValue value.
 *
 * @since GDAL 2.1
 */

void GDALWarpAppOptionsSetWarpOption(GDALWarpAppOptions *psOptions,
                                     const char *pszKey, const char *pszValue)
{
    psOptions->aosWarpOptions.SetNameValue(pszKey, pszValue);
}

#undef CHECK_HAS_ENOUGH_ADDITIONAL_ARGS