c2pa 0.91.7

Rust SDK for C2PA (Coalition for Content Provenance and Authenticity) implementors
Documentation
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
// Copyright 2023 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

// The TiffCloner::clone_tiff path is no longer used in favor of append only changes to the TIFF file.  It is kept for reference and possible future use.
#![allow(dead_code, unused_variables)]

use std::{
    collections::{BTreeMap, HashMap, HashSet},
    fs::OpenOptions,
    io::{Cursor, Read, Seek, SeekFrom, Write},
    vec,
};

use atree::{Arena, Token};
use byteorder::{BigEndian, NativeEndian, ReadBytesExt, WriteBytesExt};
use byteordered::{with_order, ByteOrdered, Endianness};

use crate::{
    asset_io::{
        AssetIO, AssetPatch, C2paReader, C2paWriter, ComposedManifestRef, ObjectLocations,
        ObjectType, ReadSeek, ReadWriteSeek, RemoteManifestUrl, WriteXmp,
    },
    error::{Error, Result},
    utils::io_utils::{safe_vec, stream_len, ReaderUtils},
};

const II: [u8; 2] = *b"II";
const MM: [u8; 2] = *b"MM";

const C2PA_TAG: u16 = 0xcd41;
const XMP_TAG: u16 = 0x02bc;
const SUBFILE_TAG: u16 = 0x014a;
const EXIFIFD_TAG: u16 = 0x8769;
const GPSIFD_TAG: u16 = 0x8825;
const INTEROPERABILITY_TAG: u16 = 40965;
const C2PA_FIELD_TYPE: u16 = 7;

const STRIPBYTECOUNTS: u16 = 279;
const STRIPOFFSETS: u16 = 273;
const TILEBYTECOUNTS: u16 = 325;
const TILEOFFSETS: u16 = 324;

const BIGTABLEDIGESTS: u16 = 52540;
const BIGTABLEOFFSETS: u16 = 52541;
const BIGTABLEBYTECOUNTS: u16 = 52542;

/* support when we find a use case
const FREEOFFSETS: u16 = 288;
const FREEBYTECOUNTS: u16 = 289;
*/

const MAX_PAGES: usize = 2000; // avoid arbitrary large allocations and possible DoS attacks.  This is a reasonable limit for TIFF files.
const MAX_SUBFILES: usize = 1000; // avoid arbitrary large allocations and possible DoS attacks.  This is a reasonable limit for TIFF files.

const SUBFILES: [u16; 4] = [SUBFILE_TAG, EXIFIFD_TAG, GPSIFD_TAG, INTEROPERABILITY_TAG];

static SUPPORTED_TYPES: [&str; 10] = [
    "tif",
    "tiff",
    "image/tiff",
    "dng",
    "image/dng",
    "image/x-adobe-dng",
    "arw",
    "image/x-sony-arw",
    "nef",
    "image/x-nikon-nef",
];

// Writing native formats is beyond the scope of the SDK.
static SUPPORTED_WRITER_TYPES: [&str; 6] = [
    "tif",
    "tiff",
    "image/tiff",
    "dng",
    "image/dng",
    "image/x-adobe-dng",
];

// The type of an IFD entry
#[derive(Debug, PartialEq)]
enum IFDEntryType {
    Byte = 1,       // 8-bit unsigned integer
    Ascii = 2,      // 8-bit byte that contains a 7-bit ASCII code; the last byte must be zero
    Short = 3,      // 16-bit unsigned integer
    Long = 4,       // 32-bit unsigned integer
    Rational = 5,   // Fraction stored as two 32-bit unsigned integers
    Sbyte = 6,      // 8-bit signed integer
    Undefined = 7,  // 8-bit byte that may contain anything, depending on the field
    Sshort = 8,     // 16-bit signed integer
    Slong = 9,      // 32-bit signed integer
    Srational = 10, // Fraction stored as two 32-bit signed integers
    Float = 11,     // 32-bit IEEE floating point
    Double = 12,    // 64-bit IEEE floating point
    Ifd = 13,       // 32-bit unsigned integer (offset)
    Long8 = 16,     // BigTIFF 64-bit unsigned integer
    Slong8 = 17,    // BigTIFF 64-bit unsigned integer (offset)
    Ifd8 = 18,      // 64-bit unsigned integer (offset)
}

impl IFDEntryType {
    pub fn from_u16(val: u16) -> Option<IFDEntryType> {
        match val {
            1 => Some(IFDEntryType::Byte),
            2 => Some(IFDEntryType::Ascii),
            3 => Some(IFDEntryType::Short),
            4 => Some(IFDEntryType::Long),
            5 => Some(IFDEntryType::Rational),
            6 => Some(IFDEntryType::Sbyte),
            7 => Some(IFDEntryType::Undefined),
            8 => Some(IFDEntryType::Sshort),
            9 => Some(IFDEntryType::Slong),
            10 => Some(IFDEntryType::Srational),
            11 => Some(IFDEntryType::Float),
            12 => Some(IFDEntryType::Double),
            13 => Some(IFDEntryType::Ifd),
            16 => Some(IFDEntryType::Long8),
            17 => Some(IFDEntryType::Slong8),
            18 => Some(IFDEntryType::Ifd8),
            _ => None,
        }
    }
}

// TIFF IFD Entry (value_offset is in target endian)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IfdEntry {
    entry_tag: u16,
    entry_type: u16,
    value_count: u64,
    value_offset: u64,
}

// helper enum to know if the IFD requires special handling
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IfdType {
    Page,
    Subfile,
    Exif,
    Gps,
}

// TIFF IFD
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImageFileDirectory {
    offset: u64,
    entry_cnt: u64,
    ifd_type: IfdType,
    entries: BTreeMap<u16, IfdEntry>,
    next_ifd_offset: Option<u64>,
    next_idf_offset_location: u64,
}

impl ImageFileDirectory {
    pub fn get_tag(&self, tag_id: u16) -> Option<&IfdEntry> {
        self.entries.get(&tag_id)
    }

    #[allow(dead_code)]
    pub fn get_tag_mut(&mut self, tag_id: u16) -> Option<&mut IfdEntry> {
        self.entries.get_mut(&tag_id)
    }
}

// Struct to map the contents of a TIFF file
pub(crate) struct TiffStructure {
    byte_order: Endianness,
    big_tiff: bool,
    #[allow(dead_code)]
    first_ifd_offset: u64,
    first_ifd: Option<ImageFileDirectory>,
}

impl TiffStructure {
    pub fn load<R>(reader: &mut R) -> Result<Self>
    where
        R: Read + Seek + ?Sized,
    {
        let mut endianness = [0u8, 2];
        reader.read_exact(&mut endianness)?;

        let byte_order = match endianness {
            II => Endianness::Little,
            MM => Endianness::Big,
            endianness => {
                return Err(Error::InvalidAsset(format!(
                    "invalid header signature: expected endianness \"II\" or \"MM\", found \"{}\"",
                    String::from_utf8_lossy(&endianness)
                )))
            }
        };

        let mut byte_reader = ByteOrdered::runtime(reader, byte_order);

        let big_tiff = match byte_reader.read_u16()? {
            42 => false,
            43 => {
                // read Big TIFF structs
                // Read byte size of offsets, must be 8
                let first_ifd_offset = byte_reader.read_u16()?;
                if first_ifd_offset != 8 {
                    return Err(Error::InvalidAsset(
                        format!(
                            "invalid header signature: expected first IFD offset for BigTiff to be \"8\", found \"{first_ifd_offset}\""
                        ),
                    ));
                }
                // must currently be 0
                let reserved = byte_reader.read_u16()?;
                if reserved != 0 {
                    return Err(Error::InvalidAsset(
                        format!(
                            "invalid header signature: expected bytes after first IFD offset for BigTiff to be \"0\", found \"{reserved}\""),
                    ));
                }
                true
            }
            magic => {
                return Err(Error::InvalidAsset(
                    format!(
                        "invalid header signature: expected magic \"2A\" (TIFF) \"2B\" (BigTIFF), found \"{magic:02X}\""),
                ));
            }
        };

        let first_ifd_offset = if big_tiff {
            byte_reader.read_u64()?
        } else {
            byte_reader.read_u32()?.into()
        };

        // move read pointer to IFD
        byte_reader.seek(SeekFrom::Start(first_ifd_offset))?;
        let first_ifd = TiffStructure::read_ifd(
            byte_reader.into_inner(),
            byte_order,
            big_tiff,
            IfdType::Page,
        )?;

        let ts = TiffStructure {
            byte_order,
            big_tiff,
            first_ifd_offset,
            first_ifd: Some(first_ifd),
        };

        Ok(ts)
    }

    // read IFD entries, all value_offset are in source endianness
    pub fn read_ifd_entries<R>(
        byte_reader: &mut ByteOrdered<&mut R, Endianness>,
        big_tiff: bool,
        entry_cnt: u64,
        entries: &mut BTreeMap<u16, IfdEntry>,
    ) -> Result<()>
    where
        R: Read + Seek + ?Sized,
    {
        for _ in 0..entry_cnt {
            let tag = byte_reader.read_u16()?;
            let tag_type = byte_reader.read_u16()?;

            let (count, data_offset) = if big_tiff {
                let count = byte_reader.read_u64()?;
                let mut buf = [0; 8];
                byte_reader.read_exact(&mut buf)?;

                let data_offset = buf
                    .as_slice()
                    .read_u64::<NativeEndian>()
                    .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;
                (count, data_offset)
            } else {
                let count = byte_reader.read_u32()?;
                let mut buf = [0; 4];
                byte_reader.read_exact(&mut buf)?;

                let data_offset = buf
                    .as_slice()
                    .read_u32::<NativeEndian>()
                    .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;
                (count.into(), data_offset.into())
            };

            let ifd_entry = IfdEntry {
                entry_tag: tag,
                entry_type: tag_type,
                value_count: count,
                value_offset: data_offset,
            };

            /*
            println!(
                "{}, {}, {}. {:?}",
                ifd_entry.entry_tag,
                ifd_entry.entry_type,
                ifd_entry.value_count,
                ifd_entry.value_offset.to_ne_bytes()
            );
            */

            entries.insert(tag, ifd_entry);
        }

        Ok(())
    }

    // read IFD from reader
    pub fn read_ifd<R>(
        reader: &mut R,
        byte_order: Endianness,
        big_tiff: bool,
        ifd_type: IfdType,
    ) -> Result<ImageFileDirectory>
    where
        R: Read + Seek + ReadBytesExt + ?Sized,
    {
        let mut byte_reader = ByteOrdered::runtime(reader, byte_order);

        let ifd_offset = byte_reader.stream_position()?;
        //println!("IFD Offset: {:#x}", ifd_offset);

        let entry_cnt = if big_tiff {
            byte_reader.read_u64()?
        } else {
            byte_reader.read_u16()?.into()
        };

        let mut ifd = ImageFileDirectory {
            offset: ifd_offset,
            entry_cnt,
            ifd_type,
            entries: BTreeMap::new(),
            next_ifd_offset: None,
            next_idf_offset_location: 0,
        };

        TiffStructure::read_ifd_entries(&mut byte_reader, big_tiff, entry_cnt, &mut ifd.entries)?;

        // save for easy patching
        ifd.next_idf_offset_location = byte_reader.stream_position()?;

        let next_ifd = if big_tiff {
            byte_reader.read_u64()?
        } else {
            byte_reader.read_u32()?.into()
        };

        match next_ifd {
            0 => (),
            _ => ifd.next_ifd_offset = Some(next_ifd),
        };

        Ok(ifd)
    }
}

// offset are stored in source endianness so to use offset value in Seek calls we must convert to native endianness
fn decode_offset(offset_file_native: u64, endianness: Endianness, big_tiff: bool) -> Result<u64> {
    let offset: u64;
    let offset_bytes = offset_file_native.to_ne_bytes();
    let offset_reader = Cursor::new(offset_bytes);

    with_order!(offset_reader, endianness, |src| {
        if big_tiff {
            let o = src.read_u64()?;
            offset = o;
        } else {
            let o = src.read_u32()?;
            offset = o.into();
        }
    });

    Ok(offset)
}

/// Reject forged IFD `value_count` fields whose claimed byte size exceeds the
/// actual file size. Used before every `safe_vec`/`read_to_vec` allocation
/// driven by attacker-controlled count fields, so a 52-byte BigTIFF can't
/// trigger a multi-GB allocation.
fn check_ifd_data_size(claimed_size: u64, file_size: u64) -> Result<()> {
    if claimed_size > file_size {
        return Err(Error::InvalidAsset(
            "IFD entry data size exceeds file size".to_string(),
        ));
    }
    Ok(())
}

/// The authoritative length of the C2PA manifest store: the JUMBF superbox
/// LBox/XLBox at `offset` (big-endian, per ISO BMFF, independent of TIFF byte
/// order). Returns `None` when the data isn't a parseable JUMBF box header
/// (e.g. the zero placeholder written during signing before the real manifest).
fn c2pa_manifest_jumbf_len<R: Read + Seek + ?Sized>(stream: &mut R, offset: u64) -> Option<u64> {
    stream.seek(SeekFrom::Start(offset)).ok()?;
    let lbox = u64::from(stream.read_u32::<BigEndian>().ok()?);
    let len = if lbox == 1 {
        stream.read_u64::<BigEndian>().ok()?
    } else {
        lbox
    };
    // A valid JUMBF box is at least LBox(4) + TBox(4) bytes.
    (len >= 8).then_some(len)
}

#[derive(Debug)]
struct MappedTiff {
    tiff_tree: Arena<ImageFileDirectory>,
    page_tokens: Vec<Token>,
    sub_files_map: HashMap<Token, Vec<ImageFileDirectory>>,
    endianness: Endianness,
    big_tiff: bool,
}

// create tree of TIFF structure IFDs and IFD entries.
fn map_tiff<R>(mut input: &mut R) -> Result<MappedTiff>
where
    R: Read + Seek + ?Sized,
{
    let file_size = stream_len(input)?;
    input.rewind()?;

    let mut tokens = Vec::new();
    let mut sub_files_map: HashMap<Token, Vec<ImageFileDirectory>> = HashMap::new();

    let ts = TiffStructure::load(input)?;

    let tiff_tree: Arena<ImageFileDirectory> =
        if let Some(ifd) = ts.first_ifd.clone() {
            let first_offset = ifd.offset;
            let (mut tiff_tree, page_0) = Arena::with_data(ifd);
            let mut current_token = page_0;
            let mut visited_offsets: HashSet<u64> = HashSet::new();
            visited_offsets.insert(first_offset);

            // get the pages
            loop {
                tokens.push(current_token);
                if tokens.len() > MAX_PAGES {
                    return Err(Error::InvalidAsset(
                        "TIFF file has too many pages".to_string(),
                    ));
                }

                // look for known special IFDs
                let page_subifd = tiff_tree[current_token].data.get_tag(SUBFILE_TAG).copied();

                // grab SubIFDs for page (DNG)
                if let Some(subifd) = page_subifd {
                    let decoded_offset =
                        decode_offset(subifd.value_offset, ts.byte_order, ts.big_tiff)?;
                    input.seek(SeekFrom::Start(decoded_offset))?;

                    let num_longs_x4 =
                        usize::try_from(subifd.value_count.checked_mul(4).ok_or_else(|| {
                            Error::InvalidAsset("value out of range".to_string())
                        })?)
                        .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

                    check_ifd_data_size(num_longs_x4 as u64, file_size)?;

                    let mut subfile_offsets = safe_vec(subifd.value_count, Some(0u32))?; // will contain offsets in native endianness

                    if num_longs_x4 <= 4 || ts.big_tiff && num_longs_x4 <= 8 {
                        let offset_bytes = subifd.value_offset.to_ne_bytes();
                        let offset_reader = Cursor::new(offset_bytes);

                        with_order!(offset_reader, ts.byte_order, |src| {
                            for item in subfile_offsets.iter_mut().take(num_longs_x4 / 4) {
                                let s = src.read_u32()?; // read a long from offset
                                *item = s; // write a long in output endian
                            }
                        });
                    } else {
                        let buf = input.read_to_vec(num_longs_x4 as u64)?;
                        let offsets_buf = Cursor::new(buf);

                        with_order!(offsets_buf, ts.byte_order, |src| {
                            for item in subfile_offsets.iter_mut().take(num_longs_x4 / 4) {
                                let s = src.read_u32()?; // read a long from offset
                                *item = s; // write a long in output endian
                            }
                        });
                    }

                    // make sure this is resonable number of subfiles, avoid arbitrary large allocations and possible DoS attacks
                    if subfile_offsets.len() > MAX_SUBFILES {
                        return Err(Error::InvalidAsset(
                            "TIFF file has too many subfiles".to_string(),
                        ));
                    }

                    // get all subfiles
                    for subfile_offset in subfile_offsets {
                        let u64_offset = subfile_offset as u64;
                        input.seek(SeekFrom::Start(u64_offset))?;

                        //println!("Reading SubIFD: {}", u64_offset);

                        let subfile_ifd = TiffStructure::read_ifd(
                            input,
                            ts.byte_order,
                            ts.big_tiff,
                            IfdType::Subfile,
                        )?;

                        sub_files_map
                            .entry(current_token)
                            .and_modify(|v| v.push(subfile_ifd.clone()))
                            .or_insert(vec![subfile_ifd]);
                    }
                }

                // grab EXIF IFD for page (DNG)
                if let Some(exififd) = tiff_tree[current_token].data.get_tag(EXIFIFD_TAG) {
                    let decoded_offset =
                        decode_offset(exififd.value_offset, ts.byte_order, ts.big_tiff)?;
                    input.seek(SeekFrom::Start(decoded_offset))?;

                    //println!("EXIF Reading SubIFD: {}", decoded_offset);

                    let exif_ifd =
                        TiffStructure::read_ifd(input, ts.byte_order, ts.big_tiff, IfdType::Exif)?;

                    sub_files_map
                        .entry(current_token)
                        .and_modify(|v| v.push(exif_ifd.clone()))
                        .or_insert(vec![exif_ifd]);
                }

                // grab GPS IFD for page (DNG)
                if let Some(gpsifd) = tiff_tree[current_token].data.get_tag(GPSIFD_TAG) {
                    let decoded_offset =
                        decode_offset(gpsifd.value_offset, ts.byte_order, ts.big_tiff)?;
                    input.seek(SeekFrom::Start(decoded_offset))?;

                    //println!("GPS Reading SubIFD: {}", decoded_offset);

                    let gps_ifd =
                        TiffStructure::read_ifd(input, ts.byte_order, ts.big_tiff, IfdType::Gps)?;

                    sub_files_map
                        .entry(current_token)
                        .and_modify(|v| v.push(gps_ifd.clone()))
                        .or_insert(vec![gps_ifd]);
                }

                // move to next page
                if let Some(next_ifd_offset) = tiff_tree[current_token].data.next_ifd_offset {
                    if !visited_offsets.insert(next_ifd_offset) {
                        return Err(Error::InvalidAsset("Cyclic IFD chain detected".to_string()));
                    }
                    input.seek(SeekFrom::Start(next_ifd_offset))?;
                    let next_ifd =
                        TiffStructure::read_ifd(input, ts.byte_order, ts.big_tiff, IfdType::Page)?;
                    current_token = current_token.insert_after(&mut tiff_tree, next_ifd);
                } else {
                    break;
                }
            }

            tiff_tree
        } else {
            return Err(Error::InvalidAsset("TIFF structure invalid".to_string()));
        };

    Ok(MappedTiff {
        tiff_tree,
        page_tokens: tokens,
        sub_files_map,
        endianness: ts.byte_order,
        big_tiff: ts.big_tiff,
    })
}

// struct used to clone source IFD entries. value_bytes are in target endianness
#[derive(Eq, PartialEq, Clone)]
pub(crate) struct IfdClonedEntry {
    pub entry_tag: u16,
    pub entry_type: u16,
    pub value_count: u64,
    pub value_bytes: Vec<u8>,
}

// struct to clone a TIFF/DNG and new tags if desired
pub(crate) struct TiffCloner<T>
where
    T: Read + Write + Seek,
{
    endianness: Endianness,
    big_tiff: bool,
    first_idf_offset: u64,
    writer: ByteOrdered<T, Endianness>,
    additional_ifds: BTreeMap<u16, IfdClonedEntry>,
    c2pa_mode: bool,
}

/// Accumulates one strip/tile/BigTable byte count into `copied` and rejects the
/// tag once the running total exceeds the source stream length.
///
/// TIFF strip/tile/BigTable data lives inside the source file, so a legitimate
/// `sum(byte_counts)` is at most the file size. A crafted file can instead list
/// many entries whose offsets all point at the same bytes and whose counts sum
/// to far more than the file, making the clone re-copy the input over and over
/// and grow the in-memory output to gigabytes (memory amplification → OOM
/// abort; ~4.9 GB from a 293 KB input in the reported PoC). Capping the
/// cumulative copy length at the source length stops that while leaving
/// well-formed files untouched.
///
/// `kind` labels the error ("strip", "tile", "BigTable"). The error is returned
/// via `Result` so the caller propagates it with `?`. Note that `with_order!`
/// inlines its body into a `match` arm — it is not a real closure — so that `?`
/// (like a bare `return`) exits `clone_image_data` directly, not just a closure.
fn accumulate_copy_len(copied: &mut u64, cnt: u64, source_len: u64, kind: &str) -> Result<()> {
    *copied = copied
        .checked_add(cnt)
        .ok_or_else(|| Error::InvalidAsset(format!("TIFF {kind} byte counts overflow")))?;
    if *copied > source_len {
        return Err(Error::InvalidAsset(format!(
            "TIFF {kind} byte counts exceed source length"
        )));
    }
    Ok(())
}

impl<T: Read + Write + Seek> TiffCloner<T> {
    pub fn new(endianness: Endianness, big_tiff: bool, writer: T) -> Result<TiffCloner<T>> {
        let bo = ByteOrdered::runtime(writer, endianness);

        let mut tc = TiffCloner {
            endianness,
            big_tiff,
            first_idf_offset: 0,
            writer: bo,
            additional_ifds: BTreeMap::new(),
            c2pa_mode: false,
        };

        tc.write_header()?;

        Ok(tc)
    }

    // Start with a copy of the source file to writer, then we will adjust the IFDs and add new tags as needed.
    // Use this constructor if you are cloning with C2PA mode
    pub fn new_from_source<R: Read + Seek + ?Sized>(
        endianness: Endianness,
        big_tiff: bool,
        writer: T,
        source: &mut R,
    ) -> Result<TiffCloner<T>> {
        let bo = ByteOrdered::runtime(writer, endianness);

        let mut tc = TiffCloner {
            endianness,
            big_tiff,
            first_idf_offset: 0,
            writer: bo,
            additional_ifds: BTreeMap::new(),
            c2pa_mode: true,
        };

        // start with copy of source file to writer, then we will adjust the IFDs and add new tags as needed
        source.rewind()?;
        std::io::copy(source, tc.writer.inner_mut())?;
        source.rewind()?;

        Ok(tc)
    }

    fn offset(&mut self) -> Result<u64> {
        Ok(self.writer.stream_position()?)
    }

    fn pad_word_boundary(&mut self) -> Result<()> {
        let curr_offset = self.offset()?;
        if curr_offset % 4 != 0 {
            let padding = [0, 0, 0];
            let pad_len = 4 - (curr_offset % 4);
            self.writer.write_all(&padding[..pad_len as usize])?;
        }

        Ok(())
    }

    fn write_header(&mut self) -> Result<u64> {
        let boi = match self.endianness {
            Endianness::Big => 0x4d,
            Endianness::Little => 0x49,
        };
        let offset;

        if self.big_tiff {
            self.writer.write_all(&[boi, boi])?;
            self.writer.write_u16(43u16)?;
            self.writer.write_u16(8u16)?;
            self.writer.write_u16(0u16)?;
            offset = self.writer.stream_position()?; // first ifd offset

            self.writer.write_u64(0)?;
        } else {
            self.writer.write_all(&[boi, boi])?;
            self.writer.write_u16(42u16)?;
            offset = self.writer.stream_position()?; // first ifd offset

            self.writer.write_u32(0)?;
        }

        self.first_idf_offset = offset;
        Ok(offset)
    }

    fn adjust_header_ifd_offset(&mut self, offset: u64) -> Result<()> {
        if self.big_tiff {
            self.writer.seek(SeekFrom::Start(8))?;
            self.writer.write_u64(offset)?;
        } else {
            self.writer.seek(SeekFrom::Start(4))?;
            let offset_u32 = u32::try_from(offset)
                .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

            self.writer.write_u32(offset_u32)?;
        }

        Ok(())
    }

    fn write_entry_count(&mut self, count: usize) -> Result<()> {
        if self.big_tiff {
            let cnt = u64::try_from(count)
                .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?; // get beginning of chunk which starts 4 bytes before label

            self.writer.write_u64(cnt)?;
        } else {
            let cnt = u16::try_from(count)
                .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?; // get beginning of chunk which starts 4 bytes before label

            self.writer.write_u16(cnt)?;
        }

        Ok(())
    }

    fn write_ifd(&mut self, target_ifd: &mut BTreeMap<u16, IfdClonedEntry>) -> Result<u64> {
        let is_c2pa_idf = target_ifd.len() == 1 && target_ifd.contains_key(&C2PA_TAG);

        // Write out the data and IFD at end of file
        self.writer.seek(SeekFrom::End(0))?;

        if !is_c2pa_idf {
            // write out all data and save the offsets, skipping subfiles since the data is already written
            for &mut IfdClonedEntry {
                value_bytes: ref mut value_bytes_ref,
                ..
            } in target_ifd.values_mut()
            {
                let data_bytes = if self.big_tiff { 8 } else { 4 };

                if value_bytes_ref.len() > data_bytes {
                    // get location of entry data start
                    let offset = self.writer.stream_position()?;

                    // write out the data bytes
                    self.writer.write_all(value_bytes_ref)?;

                    // set offset pointer in file source endian
                    let mut offset_vec = vec![0; data_bytes];

                    with_order!(offset_vec.as_mut_slice(), self.endianness, |ew| {
                        if self.big_tiff {
                            ew.write_u64(offset)?;
                        } else {
                            let offset_u32 = u32::try_from(offset).map_err(|_err| {
                                Error::InvalidAsset("value out of range".to_string())
                            })?; // get beginning of chunk which starts 4 bytes before label

                            ew.write_u32(offset_u32)?;
                        }
                    });

                    // set to new data offset position
                    *value_bytes_ref = offset_vec;
                } else {
                    while value_bytes_ref.len() < data_bytes {
                        value_bytes_ref.push(0);
                    }
                }
            }
        }

        // start on a WORD boundary
        self.pad_word_boundary()?;

        // save location of start of IFD
        let ifd_offset = self.writer.stream_position()?;

        // write out the entry count
        self.write_entry_count(target_ifd.len())?;

        // save the bytes
        let mut c2pa_bytes = None;
        // write out the directory entries
        for (tag, entry) in target_ifd.iter() {
            self.writer.write_u16(*tag)?;
            self.writer.write_u16(entry.entry_type)?;

            if self.big_tiff {
                self.writer.write_u64(entry.value_count)?;
            } else {
                let cnt = u32::try_from(entry.value_count)
                    .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

                self.writer.write_u32(cnt)?;
            }

            if *tag == C2PA_TAG && is_c2pa_idf {
                let data_bytes = if self.big_tiff { 8u64 } else { 4u64 };

                // does the data fit within size of value_bytes
                if entry.value_bytes.len() > data_bytes as usize {
                    c2pa_bytes = Some(entry.value_bytes.to_owned());
                    let c2pa_bytes_pos = self.writer.stream_position()?
                        + data_bytes // size of pointer
                        + data_bytes; // size of IFD terminator

                    if self.big_tiff {
                        self.writer.write_u64(c2pa_bytes_pos)?;
                    } else {
                        let offset32 = u32::try_from(c2pa_bytes_pos)?;
                        self.writer.write_u32(offset32)?;
                    }
                } else {
                    self.writer.write_all(&entry.value_bytes)?;
                }
            } else {
                self.writer.write_all(&entry.value_bytes)?;
            }
        }

        // terminate IFD
        if self.big_tiff {
            self.writer.write_u64(0)?;
        } else {
            self.writer.write_u32(0)?;
        }

        // write manifest after IFD if needed
        if let Some(c2pa_bytes) = c2pa_bytes {
            self.writer.write_all(&c2pa_bytes)?;
        }

        Ok(ifd_offset)
    }

    // add new TAG by supplying the IDF entry
    pub fn add_target_tag(&mut self, entry: IfdClonedEntry) {
        self.additional_ifds.insert(entry.entry_tag, entry);
    }

    // Writes a clone of the incoming IFD, only writing new data if it has changed to the end of the file, otherwise the
    // entries point to existing data.  If the entry contains C2PA data, it is written at the end of the file.
    // Returns location of start of IFD.
    fn write_adjusted_ifd(
        &mut self,
        target_ifd: &mut BTreeMap<u16, IfdClonedEntry>,
        adjust_tags: &[u16],
        next_ifd: u64,
        c2pa_buf: Option<Vec<u8>>,
    ) -> Result<u64> {
        let data_bytes = if self.big_tiff { 8 } else { 4 };

        // write new IFD data at the end
        self.writer.seek(SeekFrom::End(0))?;

        // Write out the IFD

        // start on a WORD boundary
        self.pad_word_boundary()?;

        // save location of start of IFD
        let ifd_offset = self.writer.stream_position()?;

        // write out the entry count
        self.write_entry_count(target_ifd.len())?;

        // write out the placeholder entries, all value_bytes are data_bytes in size
        let entry_array_offset = self.writer.stream_position()?;
        for (tag, entry) in target_ifd.iter() {
            self.writer.write_u16(*tag)?;
            self.writer.write_u16(entry.entry_type)?;

            if self.big_tiff {
                self.writer.write_u64(entry.value_count)?;
            } else {
                let cnt = u32::try_from(entry.value_count)
                    .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

                self.writer.write_u32(cnt)?;
            }
            // just write out 0s for this placeholder pass
            let buf = vec![0u8; data_bytes];
            self.writer.write_all(&buf)?;
        }

        // terminate IFD
        if self.big_tiff {
            self.writer.write_u64(next_ifd)?;
        } else {
            let next_ifd32 = u32::try_from(next_ifd)?;
            self.writer.write_u32(next_ifd32)?;
        }

        // Update all changed data and save the offsets, existing tag pointers will be used for unchanged data.
        // C2PA data is written last per the spec.
        let mut adjust_c2pa_data = false;
        for &mut IfdClonedEntry {
            entry_tag,
            value_bytes: ref mut value_bytes_ref,
            ..
        } in target_ifd.values_mut()
        {
            if value_bytes_ref.len() > data_bytes {
                if entry_tag == C2PA_TAG {
                    // C2PA data must be written after all other data and is done after IFD write
                    continue;
                }

                // if this value should be adjusted write out the data bytes
                if adjust_tags.contains(&entry_tag) {
                    adjust_c2pa_data = true;

                    // get location of entry data start
                    let offset = self.writer.stream_position()?;

                    self.writer.write_all(value_bytes_ref)?;

                    // set offset pointer in file source endian
                    let mut offset_vec = vec![0; data_bytes];

                    with_order!(offset_vec.as_mut_slice(), self.endianness, |ew| {
                        if self.big_tiff {
                            ew.write_u64(offset)?;
                        } else {
                            let offset_u32 = u32::try_from(offset).map_err(|_err| {
                                Error::InvalidAsset("value out of range".to_string())
                            })?; // get beginning of chunk which starts 4 bytes before label

                            ew.write_u32(offset_u32)?;
                        }
                    });

                    // set value_buf new data offset position pointer
                    *value_bytes_ref = offset_vec;
                }
            }
        }

        // Write out the C2PA data if it is in the entry list, we will rewrite the C2PA manifest to
        // make sure it is last. If we have adjusted tags we need to move the C2PA manifest to the end
        let c2pa_data_changed = adjust_tags.contains(&C2PA_TAG);
        if adjust_c2pa_data || c2pa_data_changed {
            if let Some(c2pa_entry) = target_ifd.get_mut(&C2PA_TAG) {
                if c2pa_entry.value_bytes.len() > data_bytes {
                    // write data to output and make value_bytes its pointer
                    // get location of entry data start
                    let offset = self.writer.stream_position()?;
                    if c2pa_data_changed {
                        self.writer.write_all(&c2pa_entry.value_bytes)?;
                    } else {
                        // migrate existing manifest
                        if let Some(data) = c2pa_buf {
                            self.writer.write_all(&data)?;
                        } else {
                            return Err(Error::InternalError(
                                "could not relocate manifest".to_string(),
                            ));
                        }
                    }

                    // update the entry value_bytes to point to the new offset
                    let mut offset_vec = vec![0; data_bytes];
                    with_order!(offset_vec.as_mut_slice(), self.endianness, |ew| {
                        if self.big_tiff {
                            ew.write_u64(offset)?;
                        } else {
                            let offset_u32 = u32::try_from(offset).map_err(|_err| {
                                Error::InvalidAsset("value out of range".to_string())
                            })?;
                            ew.write_u32(offset_u32)?;
                        }
                    });
                    c2pa_entry.value_bytes = offset_vec;
                } else {
                    // since it fits set value_buf as the actual data
                    while c2pa_entry.value_bytes.len() < data_bytes {
                        c2pa_entry.value_bytes.push(0);
                    }
                }
            }
        }

        // seek to the start of the entries and write out again with the true offsets
        self.writer.seek(SeekFrom::Start(entry_array_offset))?;
        for (tag, entry) in target_ifd.iter() {
            self.writer.write_u16(*tag)?;
            self.writer.write_u16(entry.entry_type)?;

            if self.big_tiff {
                self.writer.write_u64(entry.value_count)?;
            } else {
                let cnt = u32::try_from(entry.value_count)
                    .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

                self.writer.write_u32(cnt)?;
            }

            self.writer.write_all(&entry.value_bytes[0..data_bytes])?;
        }

        Ok(ifd_offset)
    }

    // Leave original content intact and replace first IDF with a new cloned IFD appended to the asset.
    // Any tag changes in the new IFD will be written to new data locations.  Existing data is preserved.
    // Since 2.4 now allows the C2PA tag to be in the first IFD for single page TIFF, and in its own last IFD for
    // the case of multi-page TIFF.
    pub fn clone_c2pa_mode<R: Read + Seek + ?Sized>(
        &mut self,
        mut asset_reader: &mut R,
        tiff_tree: &mut Arena<ImageFileDirectory>,
        page_tokens: &[Token],
        new_tiff_tags: Vec<IfdClonedEntry>,
        remove_tiff_tags: &[u16],
    ) -> Result<()> {
        if !self.c2pa_mode {
            return Err(Error::InternalError(
                "clone_c2pa_mode called without using new_from_source constructor".to_string(),
            ));
        }

        let first_page = page_tokens
            .first()
            .ok_or(Error::InvalidAsset("no IFD found".to_string()))?;

        let mut last_page = page_tokens
            .last()
            .ok_or(Error::InvalidAsset("no IFD found".to_string()))?;

        let mut last_page_ifd = tiff_tree
            .get(*last_page)
            .ok_or_else(|| Error::InvalidAsset("TIFF does not have IFD".to_string()))?;

        let first_page_ifd = tiff_tree
            .get(*first_page)
            .ok_or_else(|| Error::InvalidAsset("TIFF does not have IFD".to_string()))?;

        // separate out the C2PA entry since it may go into its own IFD
        let c2pa_entry = new_tiff_tags
            .iter()
            .find(|t| t.entry_tag == C2PA_TAG)
            .cloned();

        // if this is a single page TIFF then we can insert the C2PA tag into the first IFD, otherwise it must be in its own IFD
        let insert_to_first_page = *first_page == *last_page;

        // can we patch the existing C2PA tag in place
        // this case is required since we don't want to add a new IFD entry if we are replacing a placeholder C2PA manifest
        let try_patch = new_tiff_tags.len() == 1
            && c2pa_entry.is_some()
            && remove_tiff_tags.is_empty()
            && last_page_ifd.data.entries.contains_key(&C2PA_TAG);

        if try_patch {
            let cai_ifd_entry = last_page_ifd
                .data
                .entries
                .get(&C2PA_TAG)
                .ok_or(Error::JumbfNotFound)?;

            // make sure data type is for unstructured data
            if cai_ifd_entry.entry_type != C2PA_FIELD_TYPE {
                return Err(Error::InvalidAsset(
                    "Ifd entry for C2PA must be type UNKNOWN(7)".to_string(),
                ));
            }

            let manifest_len: usize = usize::try_from(cai_ifd_entry.value_count)
                .map_err(|_err| Error::InvalidAsset("TIFF/DNG out of range".to_string()))?;

            let store_bytes = c2pa_entry
                .as_ref()
                .ok_or(Error::JumbfNotFound)?
                .value_bytes
                .as_slice();

            // only patch if they are the same size
            if store_bytes.len() == manifest_len {
                // move read point to start of entry
                let decoded_offset =
                    decode_offset(cai_ifd_entry.value_offset, self.endianness, self.big_tiff)?;
                self.writer.seek(SeekFrom::Start(decoded_offset))?;

                self.writer.write_all(store_bytes)?;
                return Ok(());
            }
        }

        // find out if we need to replace first IFD if the first IFD contains the C2PA tag or if we have to add new tag or remove a tag that is in the first IFD.
        let needs_new_first_page_ifd = first_page_ifd.data.entries.contains_key(&C2PA_TAG)
            && !insert_to_first_page
            || (new_tiff_tags
                .iter()
                .find(|t| t.entry_tag == C2PA_TAG)
                .is_some()
                && insert_to_first_page)
            || new_tiff_tags.iter().any(|t| t.entry_tag != C2PA_TAG)
            || remove_tiff_tags
                .iter()
                .any(|t| first_page_ifd.data.entries.contains_key(t));

        let mut first_ifd_updated = false;
        if needs_new_first_page_ifd {
            let mut new_first_ifd_entries: BTreeMap<u16, IfdClonedEntry> = BTreeMap::new();

            // duplicate the first IFD entries but skip any tags in the remove list and add any new tags
            for (tag, entry) in &first_page_ifd.data.entries {
                if !remove_tiff_tags.contains(tag) {
                    new_first_ifd_entries.insert(
                        *tag,
                        IfdClonedEntry {
                            entry_tag: *tag,
                            entry_type: entry.entry_type,
                            value_count: entry.value_count,
                            value_bytes: entry.value_offset.to_ne_bytes().to_vec(), // note: this is in source byte order
                        },
                    );
                }
            }
            let had_removals = first_page_ifd.data.entries.len() > new_first_ifd_entries.len();

            // add in the new tags to the new first IFD
            let mut changed_ifd_tags: Vec<u16> = Vec::new();
            for new_tag in &new_tiff_tags {
                // C2PA will be added to its own tag for multi-page TIFF
                if new_tag.entry_tag == C2PA_TAG && !insert_to_first_page {
                    new_first_ifd_entries.remove(&C2PA_TAG);
                    continue;
                }
                changed_ifd_tags.push(new_tag.entry_tag);
                new_first_ifd_entries.insert(new_tag.entry_tag, new_tag.clone());
            }

            if !changed_ifd_tags.is_empty() || had_removals {
                // pass in existing manifest in case this is a manifest move only case
                // (i.e. no new manifest data but we need to move the manifest to the end of the file)
                let existing_c2pa_data = match last_page_ifd.data.get_tag(C2PA_TAG) {
                    Some(e) => {
                        // make sure data type is for unstructured data
                        if e.entry_type != C2PA_FIELD_TYPE {
                            return Err(Error::InvalidAsset(
                                "Ifd entry for C2PA must be type UNDEFINED(7)".to_string(),
                            ));
                        }

                        // move read point to start of entry
                        let decoded_offset =
                            decode_offset(e.value_offset, self.endianness, self.big_tiff)?;
                        asset_reader.seek(SeekFrom::Start(decoded_offset))?;

                        let data = asset_reader.read_to_vec(e.value_count).map_err(|_err| {
                            Error::InvalidAsset("TIFF/DNG out of range".to_string())
                        })?;
                        Some(data)
                    }
                    None => None,
                };

                // write out the new first IDF needed
                let second_ifd_offset = first_page_ifd.data.next_ifd_offset.unwrap_or(0);

                let new_ifd_offset = self.write_adjusted_ifd(
                    &mut new_first_ifd_entries,
                    &changed_ifd_tags,
                    second_ifd_offset,
                    existing_c2pa_data,
                )?;

                // patch the header first IFD pointer to point to second IFD if present
                self.adjust_header_ifd_offset(new_ifd_offset)?;

                first_ifd_updated = true;
            }
        }

        // if we updated the first IFD then we need to reread the current state so that
        // IFDs are accurate
        self.writer.rewind()?;
        let mapped = map_tiff(self.writer.inner_mut())?;
        let page_tokens = &mapped.page_tokens;
        if first_ifd_updated {
            last_page = page_tokens
                .last()
                .ok_or(Error::InvalidAsset("no IFD found".to_string()))?;

            last_page_ifd = mapped
                .tiff_tree
                .get(*last_page)
                .ok_or_else(|| Error::InvalidAsset("TIFF does not have IFD".to_string()))?;
        }

        // write out the new C2PA IFD if we have one and it was not added to the first IFD
        if let Some(c2pa_entry) = c2pa_entry {
            // C2PA manifest is in its own IFD
            if last_page_ifd.data.entries.contains_key(&C2PA_TAG) && !insert_to_first_page {
                let last_ifd_offset = last_page_ifd.data.offset;

                // we can just update the existing last page C2PA entry
                let existing_c2pa_entry = last_page_ifd
                    .data
                    .entries
                    .get(&C2PA_TAG)
                    .ok_or(Error::NotFound)?;
                let len_size = if self.big_tiff { 8 } else { 4 };

                let c2pa_offset = decode_offset(
                    existing_c2pa_entry.value_offset,
                    self.endianness,
                    self.big_tiff,
                )?;

                // if c2pa_offset is the last content in the file we can just overwrite the new C2PA data there
                let asset_len = stream_len(&mut self.writer)?;

                // if the manifest is at the end of the file and the new manifest is larger than the existing manifest
                // we can overwrite it and update the offset in the IFD entry
                if c2pa_offset + existing_c2pa_entry.value_count == asset_len
                    && c2pa_entry.value_count >= existing_c2pa_entry.value_count
                {
                    self.writer.seek(SeekFrom::Start(c2pa_offset))?;

                    // write the new C2PA data bytes in place
                    self.writer.write_all(&c2pa_entry.value_bytes)?;

                    // jump to location to write the updated offset
                    let entry_offset = last_ifd_offset
                        + if self.big_tiff { 8u64 } else { 2u64 } // entry count
                        + (if self.big_tiff { 16u64 } else { 12u64 } * last_page_ifd.data.entries.keys().position(|t| t == &C2PA_TAG).ok_or(Error::NotFound)? as u64); // offset of C2PA entry

                    // adjust the c2pa IFD entry count to the size of the new C2PA data
                    let new_c2pa_count = c2pa_entry.value_count;
                    self.writer.seek(SeekFrom::Start(entry_offset + 4))?;

                    if self.big_tiff {
                        self.writer.write_u64(new_c2pa_count)?;
                    } else {
                        let cnt = u32::try_from(new_c2pa_count).map_err(|_err| {
                            Error::InvalidAsset("value out of range".to_string())
                        })?;

                        self.writer.write_u32(cnt)?;
                    }
                } else {
                    // we have to write the new C2PA data at the end of the file and update the offset in the IFD entry
                    self.writer.seek(SeekFrom::End(0))?;
                    let new_c2pa_offset = self.offset()?;

                    // write the new C2PA data bytes at the end of the file
                    self.writer.write_all(&c2pa_entry.value_bytes)?;

                    // patch the IFD entry to point to the new C2PA data location
                    let mut new_offset_buf = vec![0; len_size];

                    with_order!(new_offset_buf.as_mut_slice(), self.endianness, |ew| {
                        if self.big_tiff {
                            ew.write_u64(new_c2pa_offset)?;
                        } else {
                            let offset_u32 = u32::try_from(new_c2pa_offset)?;
                            ew.write_u32(offset_u32)?;
                        }
                    });

                    // jump to location to write the updated offset
                    let entry_offset = last_ifd_offset
                        + if self.big_tiff { 8u64 } else { 2u64 } // entry count
                        + (if self.big_tiff { 16u64 } else { 12u64 } * last_page_ifd.data.entries.keys().position(|t| t == &C2PA_TAG).ok_or(Error::NotFound)? as u64); // offset of C2PA entry

                    self.writer.seek(SeekFrom::Start(
                        entry_offset + if self.big_tiff { 12u64 } else { 8u64 },
                    ))?;

                    // write the updated offset
                    self.writer.write_all(&new_offset_buf)?;

                    // adjust the c2pa IFD entry count to the size of the new C2PA data
                    let new_c2pa_count = c2pa_entry.value_count;
                    self.writer.seek(SeekFrom::Start(entry_offset + 4))?;

                    if self.big_tiff {
                        self.writer.write_u64(new_c2pa_count)?;
                    } else {
                        let cnt = u32::try_from(new_c2pa_count).map_err(|_err| {
                            Error::InvalidAsset("value out of range".to_string())
                        })?;

                        self.writer.write_u32(cnt)?;
                    }
                }
            } else {
                // write out the new C2PA IFD
                if !insert_to_first_page {
                    let last_ifd_offset = last_page_ifd.data.offset;

                    let mut c2pa_ifd_entries: BTreeMap<u16, IfdClonedEntry> = BTreeMap::new();
                    c2pa_ifd_entries.insert(c2pa_entry.entry_tag, c2pa_entry);

                    let new_c2pa_ifd_offset = self.write_ifd(&mut c2pa_ifd_entries)?;

                    // point last page IFD to the new C2PA IFD
                    self.writer.seek(SeekFrom::Start(last_ifd_offset))?;
                    let prior_ifd = TiffStructure::read_ifd(
                        &mut self.writer.inner_mut(),
                        self.endianness,
                        self.big_tiff,
                        IfdType::Page,
                    )?;

                    self.set_next_ifd_offset(&prior_ifd, new_c2pa_ifd_offset)?;
                }
            }
        } else {
            // is this a manifest removal?
            // remove the last IDF just by set a new last IFD if there is a C2PA tag in the remove list and we are not inserting to the first page
            if remove_tiff_tags.contains(&C2PA_TAG) && !insert_to_first_page {
                let second_to_last = &page_tokens[page_tokens.len() - 2];

                let second_to_last_ifd = tiff_tree
                    .get(*second_to_last)
                    .ok_or_else(|| Error::InvalidAsset("TIFF does not have IFD".to_string()))?;

                // make last page IFD to the prior IFD
                self.set_next_ifd_offset(&second_to_last_ifd.data, 0)?;

                return Ok(());
            }

            // wrote a new first IFD so we need to move C2PA data to end if there is a C2PA entry
            if first_ifd_updated && !insert_to_first_page {
                let last_ifd_offset = last_page_ifd.data.offset;

                // we can just update the existing last page C2PA entry
                if let Some(existing_c2pa_entry) = last_page_ifd.data.entries.get(&C2PA_TAG) {
                    let len_size = if self.big_tiff { 8 } else { 4 };

                    let c2pa_offset = decode_offset(
                        existing_c2pa_entry.value_offset,
                        self.endianness,
                        self.big_tiff,
                    )?;

                    // read old data
                    let mut c2pa_buf: Vec<u8> = safe_vec(existing_c2pa_entry.value_count, None)?;
                    self.writer.seek(SeekFrom::Start(c2pa_offset))?;
                    std::io::copy(&mut self.writer, &mut c2pa_buf)?;

                    // write manifest at the end of asset
                    let new_c2pa_offset = self.writer.seek(SeekFrom::End(0))?;
                    self.writer.write_all(&c2pa_buf)?;

                    let mut new_offset_buf = vec![0; len_size];
                    with_order!(new_offset_buf.as_mut_slice(), self.endianness, |ew| {
                        if self.big_tiff {
                            ew.write_u64(new_c2pa_offset)?;
                        } else {
                            let offset_u32 = u32::try_from(new_c2pa_offset)?;
                            ew.write_u32(offset_u32)?;
                        }
                    });

                    // fix up the location
                    // jump to location to write the updated offset
                    let entry_offset = last_ifd_offset
                        + if self.big_tiff { 8u64 } else { 2u64 } // entry count
                        + (if self.big_tiff { 16u64 } else { 12u64 } * last_page_ifd.data.entries.keys().position(|t| t == &C2PA_TAG).ok_or(Error::NotFound)? as u64); // offset of C2PA entry

                    self.writer.seek(SeekFrom::Start(
                        entry_offset + if self.big_tiff { 12u64 } else { 8u64 },
                    ))?;

                    // write the updated offset
                    self.writer.write_all(&new_offset_buf)?;
                }
            }
        }

        Ok(())
    }

    pub fn set_next_ifd_offset(&mut self, entry: &ImageFileDirectory, offset: u64) -> Result<()> {
        self.writer
            .seek(SeekFrom::Start(entry.next_idf_offset_location))?;

        // write 0s for next offset
        if self.big_tiff {
            self.writer.write_u64(offset)?;
        } else {
            let offset32 = u32::try_from(offset)?;
            self.writer.write_u32(offset32)?;
        }
        Ok(())
    }

    fn clone_image_data<R: Read + Seek + ?Sized>(
        &mut self,
        target_ifd: &mut BTreeMap<u16, IfdClonedEntry>,
        asset_reader: &mut R,
    ) -> Result<()> {
        match (
            target_ifd.contains_key(&STRIPBYTECOUNTS),
            target_ifd.contains_key(&STRIPOFFSETS),
            target_ifd.contains_key(&TILEBYTECOUNTS),
            target_ifd.contains_key(&TILEOFFSETS),
        ) {
            (true, true, false, false) => {
                // stripped image data
                let sbc_entry = target_ifd[&STRIPBYTECOUNTS].clone();
                let so_entry = target_ifd.get_mut(&STRIPOFFSETS).ok_or(Error::NotFound)?;

                // check for well formed TIFF
                if so_entry.value_count != sbc_entry.value_count {
                    return Err(Error::InvalidAsset(
                        "TIFF strip count does not match strip offset count".to_string(),
                    ));
                }

                let mut sbcs: Vec<u64> = safe_vec(sbc_entry.value_count, Some(0))?;
                let mut dest_offsets: Vec<u64> = Vec::new();

                // get the byte counts
                with_order!(sbc_entry.value_bytes.as_slice(), self.endianness, |src| {
                    for c in &mut sbcs {
                        match sbc_entry.entry_type {
                            4u16 => {
                                let s = src.read_u32()?;
                                *c = s.into();
                            }
                            3u16 => {
                                let s = src.read_u16()?;
                                *c = s.into();
                            }
                            16u16 => {
                                let s = src.read_u64()?;
                                *c = s;
                            }
                            _ => return Err(Error::InvalidAsset("invalid TIFF strip".to_string())),
                        }
                    }
                });

                // Seek to our tracked write position (not End(0) which could be wrong if stream has leftover data)
                let current_offset = self.offset()?;
                self.writer.seek(SeekFrom::Start(current_offset))?;

                // Cap cumulative copy bytes at the source stream length. Legit
                // TIFF strip data lives inside the file, so sum(byte_counts)
                // is at most the file size. A crafted file where 50 000 strip
                // offsets all point to byte 0 could otherwise cause each strip
                // to re-copy the whole file (~5 GiB output from a 293 KiB
                // input, OOM abort).
                let source_len = stream_len(asset_reader)?;
                let mut copied: u64 = 0;

                // copy the strips
                with_order!(so_entry.value_bytes.as_slice(), self.endianness, |src| {
                    for cnt in sbcs.iter() {
                        // Reject byte counts that would push the cumulative copy
                        // past the source length before doing any per-strip work.
                        accumulate_copy_len(&mut copied, *cnt, source_len, "strip")?;

                        // get the offset
                        let so: u64 = match so_entry.entry_type {
                            4u16 => {
                                let s = src.read_u32()?;
                                s.into()
                            }
                            3u16 => {
                                let s = src.read_u16()?;
                                s.into()
                            }
                            16u16 => src.read_u64()?,
                            _ => return Err(Error::InvalidAsset("invalid TIFF strip".to_string())),
                        };

                        let dest_offset = self.writer.stream_position()?;
                        dest_offsets.push(dest_offset);

                        // copy the strip to new file
                        asset_reader.seek(SeekFrom::Start(so))?;
                        let mut data_reader = asset_reader.take(*cnt);
                        std::io::copy(&mut data_reader, &mut self.writer)?; // copy the BigTable block to new file
                    }
                });

                // patch the offsets
                with_order!(
                    so_entry.value_bytes.as_mut_slice(),
                    self.endianness,
                    |dest| {
                        for o in dest_offsets.iter() {
                            // get the offset
                            match so_entry.entry_type {
                                4u16 => {
                                    let offset = u32::try_from(*o).map_err(|_err| {
                                        Error::InvalidAsset("value out of range".to_string())
                                    })?;
                                    dest.write_u32(offset)?;
                                }
                                3u16 => {
                                    let offset = u16::try_from(*o).map_err(|_err| {
                                        Error::InvalidAsset("value out of range".to_string())
                                    })?;
                                    dest.write_u16(offset)?;
                                }
                                16u16 => {
                                    let offset = *o;
                                    dest.write_u64(offset)?;
                                }
                                _ => {
                                    return Err(Error::InvalidAsset(
                                        "invalid TIFF strip".to_string(),
                                    ))
                                }
                            }
                        }
                    }
                );
            }
            (false, false, true, true) => {
                // tiled image data
                let tbc_entry = target_ifd[&TILEBYTECOUNTS].clone();
                let to_entry = target_ifd.get_mut(&TILEOFFSETS).ok_or(Error::NotFound)?;

                // check for well formed TIFF
                if to_entry.value_count != tbc_entry.value_count {
                    return Err(Error::InvalidAsset(
                        "TIFF tile count does not match tile offset count".to_string(),
                    ));
                }

                let mut tbcs: Vec<u64> = safe_vec(tbc_entry.value_count, Some(0u64))?;
                let mut dest_offsets: Vec<u64> = Vec::new();

                // get the byte counts
                with_order!(tbc_entry.value_bytes.as_slice(), self.endianness, |src| {
                    for val in &mut tbcs {
                        match tbc_entry.entry_type {
                            4u16 => {
                                let s = src.read_u32()?;
                                *val = s.into();
                            }
                            3u16 => {
                                let s = src.read_u16()?;
                                *val = s.into();
                            }
                            16u16 => {
                                let s = src.read_u64()?;
                                *val = s;
                            }
                            _ => return Err(Error::InvalidAsset("invalid TIFF tile".to_string())),
                        }
                    }
                });

                // Seek to our tracked write position (not End(0) which could be wrong if stream has leftover data)
                let current_offset = self.offset()?;
                self.writer.seek(SeekFrom::Start(current_offset))?;

                // Cap cumulative copy bytes at the source stream length (see
                // the strip path above for rationale).
                let source_len = stream_len(asset_reader)?;
                let mut copied: u64 = 0;

                // copy the tiles
                with_order!(to_entry.value_bytes.as_slice(), self.endianness, |src| {
                    for cnt in tbcs.iter() {
                        // Reject byte counts that would push the cumulative copy
                        // past the source length before doing any per-tile work.
                        accumulate_copy_len(&mut copied, *cnt, source_len, "tile")?;

                        // get the offset
                        let to: u64 = match to_entry.entry_type {
                            4u16 => {
                                let s = src.read_u32()?;
                                s.into()
                            }
                            16u16 => src.read_u64()?,
                            _ => return Err(Error::InvalidAsset("invalid TIFF tile".to_string())),
                        };

                        let dest_offset = self.writer.stream_position()?;
                        dest_offsets.push(dest_offset);

                        // copy the tile to new file
                        asset_reader.seek(SeekFrom::Start(to))?;
                        let mut data_reader = asset_reader.take(*cnt);
                        std::io::copy(&mut data_reader, &mut self.writer)?; // copy the BigTable block to new file
                    }
                });

                // patch the offsets
                with_order!(
                    to_entry.value_bytes.as_mut_slice(),
                    self.endianness,
                    |dest| {
                        for v in dest_offsets.iter() {
                            // get the offset
                            match to_entry.entry_type {
                                4u16 => {
                                    let offset = u32::try_from(*v).map_err(|_err| {
                                        Error::InvalidAsset("value out of range".to_string())
                                    })?;
                                    dest.write_u32(offset)?;
                                }
                                3u16 => {
                                    let offset = u16::try_from(*v).map_err(|_err| {
                                        Error::InvalidAsset("value out of range".to_string())
                                    })?;
                                    dest.write_u16(offset)?;
                                }
                                16u16 => {
                                    let offset = *v;
                                    dest.write_u64(offset)?;
                                }
                                _ => {
                                    return Err(Error::InvalidAsset(
                                        "invalid TIFF tile".to_string(),
                                    ))
                                }
                            }
                        }
                    }
                );
            }
            (_, _, _, _) => (),
        };

        Ok(())
    }

    // Special DNG case - clone BigTable data if present. BigTable data is stored similarly
    // to strip/tile data but with three separate tags for offsets, byte counts, and digests.
    // We need to clone the data and patch the offsets to preserve the integrity of the DNG.
    // Note: this is not a general DNG feature. Converts the target_ifd to the final
    // IFD with the copied data and actual offsets.
    fn clone_dng_bigtable_data<R: Read + Seek + ?Sized>(
        &mut self,
        target_ifd: &mut BTreeMap<u16, IfdClonedEntry>,
        asset_reader: &mut R,
    ) -> Result<()> {
        // BigTable image data — only when all three BigTable tags are present.
        if target_ifd.contains_key(&BIGTABLEOFFSETS)
            && target_ifd.contains_key(&BIGTABLEDIGESTS)
            && target_ifd.contains_key(&BIGTABLEBYTECOUNTS)
        {
            let bbc_entry = target_ifd[&BIGTABLEBYTECOUNTS].clone();
            let bo_entry = target_ifd
                .get_mut(&BIGTABLEOFFSETS)
                .ok_or(Error::NotFound)?;

            if bo_entry.value_count != bbc_entry.value_count {
                return Err(Error::InvalidAsset(
                    "TIFF BigTable count does not match BigTable offset count".to_string(),
                ));
            }

            let mut bbcs: Vec<u64> = safe_vec(bbc_entry.value_count, Some(0u64))?;
            let mut dest_offsets: Vec<u64> = Vec::new();

            // get the byte counts
            with_order!(bbc_entry.value_bytes.as_slice(), self.endianness, |src| {
                for val in &mut bbcs {
                    match bbc_entry.entry_type {
                        4u16 => {
                            let s = src.read_u32()?;
                            *val = s.into();
                        }
                        3u16 => {
                            let s = src.read_u16()?;
                            *val = s.into();
                        }
                        16u16 => {
                            let s = src.read_u64()?;
                            *val = s;
                        }
                        _ => return Err(Error::InvalidAsset("invalid TIFF BigTable".to_string())),
                    }
                }
            });

            // Seek to our tracked write position (not End(0) which could be wrong if stream has leftover data)
            let current_offset = self.offset()?;
            self.writer.seek(SeekFrom::Start(current_offset))?;

            // Cap cumulative copy bytes at the source stream length (see
            // clone_image_data strip path for rationale).
            let source_len = stream_len(asset_reader)?;
            let mut copied: u64 = 0;

            // copy the BigTable blocks
            with_order!(bo_entry.value_bytes.as_slice(), self.endianness, |src| {
                for cnt in bbcs.iter() {
                    // Reject byte counts that would push the cumulative copy past
                    // the source length before doing any per-block work.
                    accumulate_copy_len(&mut copied, *cnt, source_len, "BigTable")?;

                    let bo: u64 = match bo_entry.entry_type {
                        4u16 => {
                            let s = src.read_u32()?;
                            s.into()
                        }
                        3u16 => {
                            let s = src.read_u16()?;
                            s.into()
                        }
                        16u16 => src.read_u64()?,
                        _ => return Err(Error::InvalidAsset("invalid TIFF BigTable".to_string())),
                    };

                    let dest_offset = self.writer.stream_position()?;
                    dest_offsets.push(dest_offset); // save offset where the new BigTable block is written for patching later

                    asset_reader.seek(SeekFrom::Start(bo))?;
                    let mut data_reader = asset_reader.take(*cnt);
                    std::io::copy(&mut data_reader, &mut self.writer)?; // copy the BigTable block to new file
                }
            });

            // patch with final offsets where the BigTable blocks were written in the new file
            with_order!(
                bo_entry.value_bytes.as_mut_slice(),
                self.endianness,
                |dest| {
                    for o in dest_offsets.iter() {
                        match bo_entry.entry_type {
                            4u16 => {
                                let offset = u32::try_from(*o).map_err(|_err| {
                                    Error::InvalidAsset("value out of range".to_string())
                                })?;
                                dest.write_u32(offset)?;
                            }
                            3u16 => {
                                let offset = u16::try_from(*o).map_err(|_err| {
                                    Error::InvalidAsset("value out of range".to_string())
                                })?;
                                dest.write_u16(offset)?;
                            }
                            16u16 => {
                                dest.write_u64(*o)?;
                            }
                            _ => {
                                return Err(Error::InvalidAsset(
                                    "invalid TIFF BigTable".to_string(),
                                ))
                            }
                        }
                    }
                }
            );
        }
        Ok(())
    }

    fn clone_sub_files<R: Read + Seek + ?Sized>(
        &mut self,
        tiff_tree: &Arena<ImageFileDirectory>,
        page_sub_files: &Vec<ImageFileDirectory>,
        asset_reader: &mut R,
    ) -> Result<BTreeMap<u16, Vec<u64>>> {
        // offset map
        let mut offset_map: BTreeMap<u16, Vec<u64>> = BTreeMap::new();

        let mut offsets_ifd: Vec<u64> = Vec::new();
        let mut offsets_exif: Vec<u64> = Vec::new();
        let mut offsets_gps: Vec<u64> = Vec::new();

        // clone the EXIF entry and DNG entries
        for ifd in page_sub_files {
            // clone IFD entries
            let mut cloned_ifd = self.clone_ifd_entries(&ifd.entries, asset_reader)?;

            // clone the image data
            self.clone_image_data(&mut cloned_ifd, asset_reader)?;

            // clone bigtable data if DNG
            self.clone_dng_bigtable_data(&mut cloned_ifd, asset_reader)?;

            // write directory
            let sub_ifd_offset = self.write_ifd(&mut cloned_ifd)?;

            // fix up offset in main page known IFDs
            match ifd.ifd_type {
                IfdType::Page => (),
                IfdType::Subfile => offsets_ifd.push(sub_ifd_offset),
                IfdType::Exif => offsets_exif.push(sub_ifd_offset),
                IfdType::Gps => offsets_gps.push(sub_ifd_offset),
            };
        }

        offset_map.insert(SUBFILE_TAG, offsets_ifd);
        offset_map.insert(EXIFIFD_TAG, offsets_exif);
        offset_map.insert(GPSIFD_TAG, offsets_gps);

        Ok(offset_map)
    }

    pub fn clone_tiff<R: Read + Seek + ?Sized>(
        &mut self,
        tiff_tree: &mut Arena<ImageFileDirectory>,
        tokens: &[Token],
        page_sub_files_map: &HashMap<Token, Vec<ImageFileDirectory>>,
        asset_reader: &mut R,
    ) -> Result<()> {
        let mut page_ifd_offsets = Vec::new();

        let first_page = tokens
            .first()
            .ok_or(Error::InvalidAsset("no IFD found".to_string()))?;

        let last_page = tokens
            .last()
            .ok_or(Error::InvalidAsset("no IFD found".to_string()))?;

        let last_page_ifd = tiff_tree
            .get(*last_page)
            .ok_or_else(|| Error::InvalidAsset("TIFF does not have IFD".to_string()))?;

        // separate out the C2PA entry since it goes in its own IFD
        let new_c2pa_entry = self.additional_ifds.remove(&C2PA_TAG);

        // is this an old manifest so we need to add a manifest or a
        // multipage tiff without a manifest
        let needs_end_ifd = last_page == first_page
            || !last_page_ifd.data.entries.contains_key(&C2PA_TAG) && new_c2pa_entry.is_some();

        // if multipage, make sure last page containing C2PA contains a single entry
        if last_page != first_page
            && last_page_ifd.data.entries.contains_key(&C2PA_TAG)
            && last_page_ifd.data.entries.len() > 1
        {
            return Err(Error::ValidationRule(
                "Last IDF with C2PA manifest contained additional tags, expected 1 tag".to_string(),
            ));
        }

        // is there and existing valid new end C2PA IFD
        let has_c2pa_ifd =
            last_page != first_page || last_page_ifd.data.entries.contains_key(&C2PA_TAG);

        for page_token in tokens {
            // clone the subfile entries (DNG)
            let page_subfiles = page_sub_files_map
                .get(page_token)
                .cloned()
                .unwrap_or_else(Vec::new);
            let subfile_offsets = self.clone_sub_files(tiff_tree, &page_subfiles, asset_reader)?;

            let page_ifd = tiff_tree
                .get(*page_token)
                .ok_or_else(|| Error::InvalidAsset("TIFF does not have IFD".to_string()))?;

            // clone IFD entries
            let mut cloned_ifd = self.clone_ifd_entries(&page_ifd.data.entries, asset_reader)?;

            // clone the image data
            self.clone_image_data(&mut cloned_ifd, asset_reader)?;

            // clone bigtable data if DNG
            self.clone_dng_bigtable_data(&mut cloned_ifd, asset_reader)?;

            // add in new Tags to first IFD (XMP for example)
            if page_token == first_page {
                for (tag, new_entry) in &self.additional_ifds {
                    cloned_ifd.insert(*tag, new_entry.clone());
                }
            }

            // replace C2PA content
            if page_token == last_page && has_c2pa_ifd {
                if let Some(new_entry) = &new_c2pa_entry {
                    cloned_ifd.insert(C2PA_TAG, new_entry.clone());
                }
            }

            // fix up subfile offsets
            for t in SUBFILES {
                if let Some(offsets) = subfile_offsets.get(&t) {
                    if offsets.is_empty() {
                        continue;
                    }

                    let e = cloned_ifd
                        .get_mut(&t)
                        .ok_or_else(|| Error::InvalidAsset("TIFF does not have IFD".to_string()))?;
                    let mut adjust_offsets: Vec<u8> = if self.big_tiff {
                        safe_vec(offsets.len() as u64 * 8, Some(0))?
                    } else {
                        safe_vec(offsets.len() as u64 * 4, Some(0))?
                    };

                    with_order!(adjust_offsets.as_mut_slice(), self.endianness, |dest| {
                        for o in offsets {
                            if self.big_tiff {
                                dest.write_u64(*o)?;
                            } else {
                                let offset_u32 = u32::try_from(*o).map_err(|_err| {
                                    Error::InvalidAsset("value out of range".to_string())
                                })?;

                                dest.write_u32(offset_u32)?;
                            }
                        }
                    });

                    e.value_bytes = adjust_offsets;
                }
            }

            // write directory
            let ifd_offset = self.write_ifd(&mut cloned_ifd)?;

            page_ifd_offsets.push((ifd_offset, self.offset()?));
        }

        // add new C2PA IFD if needed
        if needs_end_ifd {
            if let Some(new_entry) = &new_c2pa_entry {
                let mut cloned_entry = BTreeMap::new();
                cloned_entry.insert(C2PA_TAG, new_entry.clone());

                // write directory
                let ifd_offset = self.write_ifd(&mut cloned_entry)?;

                page_ifd_offsets.push((ifd_offset, self.offset()?));
            }
        }

        // link all IFDs
        let mut prior_ifd_start = 0u64;
        for (index, (offset, _write_point)) in page_ifd_offsets.iter().enumerate() {
            // if this is the first IFD we need to patch the TIFF header
            if index == 0 {
                self.writer.seek(SeekFrom::Start(4))?; // header first IDF offset location

                if self.big_tiff {
                    self.writer.write_u64(*offset)?;
                } else {
                    let offset_u32 = u32::try_from(*offset)
                        .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;
                    self.writer.write_u32(offset_u32)?;
                }
                prior_ifd_start = *offset;
            } else {
                // seek and patch the prior IFD next offset field
                self.writer.seek(SeekFrom::Start(prior_ifd_start))?;
                let prior_ifd = TiffStructure::read_ifd(
                    &mut self.writer.inner_mut(),
                    self.endianness,
                    self.big_tiff,
                    IfdType::Page,
                )?;

                self.set_next_ifd_offset(&prior_ifd, *offset)?;

                prior_ifd_start = *offset;
            }
        }

        self.writer.flush()?;

        Ok(())
    }

    fn clone_ifd_entries<R: Read + Seek + ?Sized>(
        &mut self,
        entries: &BTreeMap<u16, IfdEntry>,
        mut asset_reader: &mut R,
    ) -> Result<BTreeMap<u16, IfdClonedEntry>> {
        let file_size = stream_len(asset_reader)?;
        let mut target_ifd: BTreeMap<u16, IfdClonedEntry> = BTreeMap::new();

        // Bound bytes cloned across all entries in this IFD, not just each one alone.
        let mut cumulative_ifd_bytes: u64 = 0;

        for (tag, entry) in entries {
            let target_endianness = self.writer.endianness();

            // get bytes for tag
            let cnt = entry.value_count;
            let et = entry.entry_type;

            let entry_type = IFDEntryType::from_u16(et).ok_or(Error::UnsupportedType)?;

            // read IFD raw data in file native endian format
            let data = match entry_type {
                IFDEntryType::Byte
                | IFDEntryType::Sbyte
                | IFDEntryType::Undefined
                | IFDEntryType::Ascii => {
                    let num_bytes = usize::try_from(cnt)
                        .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

                    check_ifd_data_size(cnt, file_size)?;
                    accumulate_copy_len(&mut cumulative_ifd_bytes, cnt, file_size, "IFD entry")?;

                    let mut data = safe_vec(cnt, Some(0u8))?;

                    if num_bytes <= 4 || self.big_tiff && num_bytes <= 8 {
                        let offset_bytes = entry.value_offset.to_ne_bytes();
                        for (i, item) in offset_bytes.iter().take(num_bytes).enumerate() {
                            data[i] = *item;
                        }
                    } else {
                        // move to start of data
                        asset_reader.seek(SeekFrom::Start(decode_offset(
                            entry.value_offset,
                            target_endianness,
                            self.big_tiff,
                        )?))?;
                        asset_reader.read_exact(data.as_mut_slice())?;
                    }

                    data
                }
                IFDEntryType::Short => {
                    let num_shorts_x2 =
                        usize::try_from(cnt.checked_mul(2).ok_or_else(|| {
                            Error::InvalidAsset("value out of range".to_string())
                        })?)
                        .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

                    check_ifd_data_size(num_shorts_x2 as u64, file_size)?;
                    accumulate_copy_len(
                        &mut cumulative_ifd_bytes,
                        num_shorts_x2 as u64,
                        file_size,
                        "IFD entry",
                    )?;

                    let mut data = safe_vec(num_shorts_x2 as u64, Some(0u8))?;

                    if num_shorts_x2 <= 4 || self.big_tiff && num_shorts_x2 <= 8 {
                        let offset_bytes = entry.value_offset.to_ne_bytes();
                        let mut offset_reader = Cursor::new(offset_bytes);

                        let mut w = Cursor::new(data.as_mut_slice());
                        for _i in 0..num_shorts_x2 / 2 {
                            let s = offset_reader.read_u16::<NativeEndian>()?; // read a short from offset
                            w.write_u16::<NativeEndian>(s)?; // write a short in output endian
                        }
                    } else {
                        // move to start of data
                        asset_reader.seek(SeekFrom::Start(decode_offset(
                            entry.value_offset,
                            target_endianness,
                            self.big_tiff,
                        )?))?;
                        asset_reader.read_exact(data.as_mut_slice())?;
                    }

                    data
                }
                IFDEntryType::Long | IFDEntryType::Ifd => {
                    let num_longs_x4 =
                        usize::try_from(cnt.checked_mul(4).ok_or_else(|| {
                            Error::InvalidAsset("value out of range".to_string())
                        })?)
                        .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

                    check_ifd_data_size(num_longs_x4 as u64, file_size)?;
                    accumulate_copy_len(
                        &mut cumulative_ifd_bytes,
                        num_longs_x4 as u64,
                        file_size,
                        "IFD entry",
                    )?;

                    let mut data = safe_vec(num_longs_x4 as u64, Some(0u8))?;

                    if num_longs_x4 <= 4 || self.big_tiff && num_longs_x4 <= 8 {
                        let offset_bytes = entry.value_offset.to_ne_bytes();
                        let mut offset_reader = Cursor::new(offset_bytes);

                        let mut w = Cursor::new(data.as_mut_slice());
                        for _i in 0..num_longs_x4 / 4 {
                            let s = offset_reader.read_u32::<NativeEndian>()?; // read a long from offset
                            w.write_u32::<NativeEndian>(s)?; // write a long in output endian
                        }
                    } else {
                        // move to start of data
                        asset_reader.seek(SeekFrom::Start(decode_offset(
                            entry.value_offset,
                            target_endianness,
                            self.big_tiff,
                        )?))?;
                        asset_reader.read_exact(data.as_mut_slice())?;
                    }

                    data
                }
                IFDEntryType::Sshort => {
                    let num_sshorts_x2 =
                        usize::try_from(cnt.checked_mul(2).ok_or_else(|| {
                            Error::InvalidAsset("value out of range".to_string())
                        })?)
                        .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

                    check_ifd_data_size(num_sshorts_x2 as u64, file_size)?;
                    accumulate_copy_len(
                        &mut cumulative_ifd_bytes,
                        num_sshorts_x2 as u64,
                        file_size,
                        "IFD entry",
                    )?;

                    let mut data = safe_vec(num_sshorts_x2 as u64, Some(0u8))?;

                    if num_sshorts_x2 <= 4 || self.big_tiff && num_sshorts_x2 <= 8 {
                        let offset_bytes = entry.value_offset.to_ne_bytes();
                        let mut offset_reader = Cursor::new(offset_bytes);

                        let mut w = Cursor::new(data.as_mut_slice());
                        for _i in 0..num_sshorts_x2 / 2 {
                            let s = offset_reader.read_i16::<NativeEndian>()?; // read a short from offset
                            w.write_i16::<NativeEndian>(s)?; // write a short in output endian
                        }
                    } else {
                        // move to start of data
                        asset_reader.seek(SeekFrom::Start(decode_offset(
                            entry.value_offset,
                            target_endianness,
                            self.big_tiff,
                        )?))?;
                        asset_reader.read_exact(data.as_mut_slice())?;
                    }

                    data
                }
                IFDEntryType::Slong => {
                    let num_slongs_x4 =
                        usize::try_from(cnt.checked_mul(4).ok_or_else(|| {
                            Error::InvalidAsset("value out of range".to_string())
                        })?)
                        .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

                    check_ifd_data_size(num_slongs_x4 as u64, file_size)?;
                    accumulate_copy_len(
                        &mut cumulative_ifd_bytes,
                        num_slongs_x4 as u64,
                        file_size,
                        "IFD entry",
                    )?;

                    let mut data = safe_vec(num_slongs_x4 as u64, Some(0u8))?;

                    if num_slongs_x4 <= 4 || self.big_tiff && num_slongs_x4 <= 8 {
                        let offset_bytes = entry.value_offset.to_ne_bytes();
                        let mut offset_reader = Cursor::new(offset_bytes);

                        let mut w = Cursor::new(data.as_mut_slice());
                        for _i in 0..num_slongs_x4 / 4 {
                            let s = offset_reader.read_i32::<NativeEndian>()?; // read a slong from offset
                            w.write_i32::<NativeEndian>(s)?; // write a slong in output endian
                        }
                    } else {
                        // move to start of data
                        asset_reader.seek(SeekFrom::Start(decode_offset(
                            entry.value_offset,
                            target_endianness,
                            self.big_tiff,
                        )?))?;
                        asset_reader.read_exact(data.as_mut_slice())?;
                    }

                    data
                }
                IFDEntryType::Float => {
                    let num_floats_x4 =
                        usize::try_from(cnt.checked_mul(4).ok_or_else(|| {
                            Error::InvalidAsset("value out of range".to_string())
                        })?)
                        .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

                    check_ifd_data_size(num_floats_x4 as u64, file_size)?;
                    accumulate_copy_len(
                        &mut cumulative_ifd_bytes,
                        num_floats_x4 as u64,
                        file_size,
                        "IFD entry",
                    )?;

                    let mut data = safe_vec(num_floats_x4 as u64, Some(0u8))?;

                    if num_floats_x4 <= 4 || self.big_tiff && num_floats_x4 <= 8 {
                        let offset_bytes = entry.value_offset.to_ne_bytes();
                        let mut offset_reader = Cursor::new(offset_bytes);

                        let mut w = Cursor::new(data.as_mut_slice());
                        for _i in 0..num_floats_x4 / 4 {
                            let s = offset_reader.read_f32::<NativeEndian>()?; // read a float from offset
                            w.write_f32::<NativeEndian>(s)?; // write a float in output endian
                        }
                    } else {
                        // move to start of data
                        asset_reader.seek(SeekFrom::Start(decode_offset(
                            entry.value_offset,
                            target_endianness,
                            self.big_tiff,
                        )?))?;
                        asset_reader.read_exact(data.as_mut_slice())?;
                    }

                    data
                }
                IFDEntryType::Rational
                | IFDEntryType::Srational
                | IFDEntryType::Slong8
                | IFDEntryType::Double
                | IFDEntryType::Long8
                | IFDEntryType::Ifd8 => {
                    // Each element is 8 bytes wide. Use checked_mul to prevent u64 overflow
                    // when a crafted BigTIFF supplies a malicious value_count (e.g.
                    // 0x2000000000000001 * 8 wraps past u64::MAX in release builds and
                    // panics in debug builds).
                    let num_bytes_8 = cnt
                        .checked_mul(8)
                        .ok_or_else(|| Error::InvalidAsset("value out of range".to_string()))?;

                    check_ifd_data_size(num_bytes_8, file_size)?;
                    accumulate_copy_len(
                        &mut cumulative_ifd_bytes,
                        num_bytes_8,
                        file_size,
                        "IFD entry",
                    )?;

                    // move to start of data
                    asset_reader.seek(SeekFrom::Start(decode_offset(
                        entry.value_offset,
                        target_endianness,
                        self.big_tiff,
                    )?))?;

                    asset_reader.read_to_vec(num_bytes_8)?
                }
            };

            target_ifd.insert(
                *tag,
                IfdClonedEntry {
                    entry_tag: *tag,
                    entry_type: entry_type as u16,
                    value_count: cnt,
                    value_bytes: data,
                },
            );
        }

        Ok(target_ifd)
    }
}

fn tiff_clone_with_tags<R: Read + Seek + ?Sized, W: Read + Write + Seek + ?Sized>(
    asset_writer: &mut W,
    asset_reader: &mut R,
    tiff_tags: Vec<IfdClonedEntry>,
) -> Result<()> {
    let MappedTiff {
        mut tiff_tree,
        page_tokens,
        sub_files_map: _sub_files_map,
        endianness,
        big_tiff,
    } = map_tiff(asset_reader)?;

    let mut bo = ByteOrdered::new(asset_writer, endianness);
    let mut tc = TiffCloner::new_from_source(endianness, big_tiff, &mut bo, asset_reader)?;

    tc.clone_c2pa_mode(
        asset_reader,
        &mut tiff_tree,
        &page_tokens,
        tiff_tags.clone(),
        &[],
    )?;

    Ok(())
}
fn add_required_tags_to_stream(
    input_stream: &mut dyn ReadSeek,
    output_stream: &mut dyn ReadWriteSeek,
) -> Result<()> {
    let tiff_io = TiffIO {};

    match tiff_io.read_c2pa(input_stream) {
        Ok(_) => {
            // just clone
            input_stream.rewind()?;
            output_stream.rewind()?;
            std::io::copy(input_stream, output_stream)?;
            Ok(())
        }
        Err(Error::JumbfNotFound) => {
            // allocate enough bytes so that value is not stored in offset field
            let some_bytes = vec![0u8; 10];
            let tio = TiffIO {};
            tio.write_c2pa(input_stream, output_stream, &some_bytes)
        }
        Err(e) => Err(e),
    }
}

fn get_cai_data<R>(mut asset_reader: &mut R) -> Result<Vec<u8>>
where
    R: Read + Seek + ?Sized,
{
    let mapped = map_tiff(asset_reader)?;
    let tiff_tree = mapped.tiff_tree;
    let page_tokens = mapped.page_tokens;
    let e = mapped.endianness;
    let big_tiff = mapped.big_tiff;

    let first_page = page_tokens
        .first()
        .ok_or(Error::InvalidAsset("no IFD".to_string()))?;
    let last_page = page_tokens
        .last()
        .ok_or(Error::InvalidAsset("no IFD".to_string()))?;
    let last_ifd = &tiff_tree[*last_page].data;

    let cai_ifd_entry = match last_ifd.get_tag(C2PA_TAG) {
        Some(entry) => entry,
        None => {
            // if the last page doesn't have the C2PA tag, check the first page for backwards compatibility with older TIFFs
            let first_ifd = &tiff_tree[*first_page].data;
            first_ifd.get_tag(C2PA_TAG).ok_or(Error::JumbfNotFound)?
        }
    };

    // make sure data type is for unstructured data
    if cai_ifd_entry.entry_type != C2PA_FIELD_TYPE {
        return Err(Error::InvalidAsset(
            "Ifd entry for C2PA must be type UNDEFINED(7)".to_string(),
        ));
    }

    // move read point to start of entry
    let decoded_offset = decode_offset(cai_ifd_entry.value_offset, e, big_tiff)?;
    asset_reader.seek(SeekFrom::Start(decoded_offset))?;

    let data = asset_reader
        .read_to_vec(cai_ifd_entry.value_count)
        .map_err(|_err| Error::InvalidAsset("TIFF/DNG out of range".to_string()))?;

    Ok(data)
}

fn get_xmp_data<R>(mut asset_reader: &mut R) -> Option<Vec<u8>>
where
    R: Read + Seek + ?Sized,
{
    let mapped = map_tiff(asset_reader).ok()?;
    let tiff_tree = mapped.tiff_tree;
    let page_tokens = mapped.page_tokens;
    let e = mapped.endianness;
    let big_tiff = mapped.big_tiff;

    let first_page = page_tokens.first()?;
    let first_ifd = &tiff_tree[*first_page].data;

    let xmp_ifd_entry = first_ifd.get_tag(XMP_TAG)?;
    // make sure the tag type is correct
    if IFDEntryType::from_u16(xmp_ifd_entry.entry_type)? != IFDEntryType::Byte {
        return None;
    }

    // move read point to start of entry
    let decoded_offset = decode_offset(xmp_ifd_entry.value_offset, e, big_tiff).ok()?;
    asset_reader.seek(SeekFrom::Start(decoded_offset)).ok()?;

    asset_reader.read_to_vec(xmp_ifd_entry.value_count).ok()
}

pub struct TiffIO {}

impl C2paReader for TiffIO {
    fn read_c2pa(&self, input_stream: &mut dyn ReadSeek) -> Result<Vec<u8>> {
        let cai_data = get_cai_data(input_stream)?;
        Ok(cai_data)
    }

    fn read_xmp(&self, input_stream: &mut dyn ReadSeek) -> Option<String> {
        let xmp_data = get_xmp_data(input_stream)?;
        String::from_utf8(xmp_data).ok()
    }
}

impl AssetIO for TiffIO {
    fn asset_patch_ref(&self) -> Option<&dyn AssetPatch> {
        Some(self)
    }

    fn new(_asset_type: &str) -> Self
    where
        Self: Sized,
    {
        TiffIO {}
    }

    fn get_handler(&self, asset_type: &str) -> Box<dyn AssetIO> {
        Box::new(TiffIO::new(asset_type))
    }

    fn get_reader(&self) -> &dyn C2paReader {
        self
    }

    fn get_writer(&self, asset_type: &str) -> Option<Box<dyn C2paWriter>> {
        if SUPPORTED_WRITER_TYPES.contains(&asset_type) {
            Some(Box::new(TiffIO::new(asset_type)))
        } else {
            None
        }
    }

    fn remote_manifest_url_ref(&self) -> Option<&dyn RemoteManifestUrl> {
        Some(self)
    }

    fn write_xmp_ref(&self) -> Option<&dyn WriteXmp> {
        Some(self)
    }

    fn composed_data_ref(&self) -> Option<&dyn ComposedManifestRef> {
        Some(self)
    }

    fn supported_types(&self) -> &[&str] {
        &SUPPORTED_TYPES
    }

    // TIFF, DNG, ARW, and NEF share the same magic bytes and handler, but each needs its
    // own MIME type, so the default single-MIME derivation from `supported_types()`
    // doesn't apply here.
    fn mime_type_map(&self) -> Vec<(String, String)> {
        [
            ("tif", "image/tiff"),
            ("tiff", "image/tiff"),
            ("dng", "image/x-adobe-dng"),
            ("arw", "image/x-sony-arw"),
            ("nef", "image/x-nikon-nef"),
        ]
        .into_iter()
        .map(|(ext, mime)| (ext.to_string(), mime.to_string()))
        .collect()
    }
}

impl C2paWriter for TiffIO {
    fn write_c2pa(
        &self,
        input_stream: &mut dyn ReadSeek,
        output_stream: &mut dyn ReadWriteSeek,
        store_bytes: &[u8],
    ) -> Result<()> {
        let l = u64::try_from(store_bytes.len())
            .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

        let entry = IfdClonedEntry {
            entry_tag: C2PA_TAG,
            entry_type: C2PA_FIELD_TYPE,
            value_count: l,
            value_bytes: store_bytes.to_vec(),
        };

        tiff_clone_with_tags(output_stream, input_stream, vec![entry])
    }

    fn get_object_locations(
        &self,
        input_stream: &mut dyn ReadSeek,
    ) -> Result<Vec<ObjectLocations>> {
        let len = stream_len(input_stream)?;
        let vec_cap = usize::try_from(len)
            .map_err(|_err| Error::InvalidAsset("value out of range".to_owned()))?;
        let output_buf: Vec<u8> = Vec::with_capacity(vec_cap + 100);

        let mut output_stream = Cursor::new(output_buf);

        add_required_tags_to_stream(input_stream, &mut output_stream)?;
        output_stream.rewind()?;

        let mapped = map_tiff(&mut output_stream)?;
        let tiff_tree = mapped.tiff_tree;
        let page_tokens = mapped.page_tokens;
        let e = mapped.endianness;
        let big_tiff = mapped.big_tiff;

        let first_page = page_tokens
            .first()
            .ok_or(Error::InvalidAsset("no IFD".to_string()))?;
        let last_page = page_tokens
            .last()
            .ok_or(Error::InvalidAsset("no IFD".to_string()))?;
        let last_page_ifd = &tiff_tree[*last_page].data;

        let cai_ifd_entry = match last_page_ifd.get_tag(C2PA_TAG) {
            Some(entry) => entry,
            None => {
                // if the last page doesn't have the C2PA tag, check the first page for backwards compatibility with older TIFFs
                let first_ifd = &tiff_tree[*first_page].data;
                first_ifd.get_tag(C2PA_TAG).ok_or(Error::JumbfNotFound)?
            }
        };

        // make sure data type is for unstructured data
        if cai_ifd_entry.entry_type != C2PA_FIELD_TYPE {
            return Err(Error::InvalidAsset(
                "Ifd entry for C2PA must be type UNDEFINED(7)".to_string(),
            ));
        }

        let manifest_offset = decode_offset(cai_ifd_entry.value_offset, e, big_tiff)?;
        let manifest_len = cai_ifd_entry.value_count;

        // The IFD value_count is attacker-controlled; bound the manifest exclusion
        // to the actual JUMBF superbox length so a forged, over-long count can't
        // exclude non-manifest bytes (C2PA 15.12.1). Skipped for the signing-time
        // placeholder, which is not yet a JUMBF box.
        if let Some(jumbf_len) = c2pa_manifest_jumbf_len(&mut output_stream, manifest_offset) {
            if manifest_len != jumbf_len {
                return Err(Error::InvalidAsset(
                    "C2PA IFD value_count does not match manifest store length".to_string(),
                ));
            }
        }

        // figure out count to exclude
        let c2p_entry_pos = last_page_ifd
            .entries
            .keys()
            .position(|t| t == &C2PA_TAG)
            .ok_or(Error::NotFound)?;
        let count_offset = last_page_ifd.offset
                        + if big_tiff { 8u64 } else { 2u64 } // entry count
                        + (if big_tiff { 16u64 } else { 12u64 } * c2p_entry_pos as u64) // offset of C2PA entry
                        + 4; // tag(2) + type(2)

        // size of the count field
        let count_size: u64 = if big_tiff { 8 } else { 4 };

        Ok(vec![
            ObjectLocations {
                offset: manifest_offset,
                length: manifest_len,
                htype: ObjectType::C2pa,
            },
            ObjectLocations {
                offset: count_offset,
                length: count_size,
                htype: ObjectType::OtherExclusion,
            },
        ])
    }

    fn remove_c2pa(
        &self,
        input_stream: &mut dyn ReadSeek,
        output_stream: &mut dyn ReadWriteSeek,
    ) -> Result<()> {
        let mapped = map_tiff(input_stream)?;
        let mut tiff_tree = mapped.tiff_tree;
        let page_tokens = mapped.page_tokens;
        let e = mapped.endianness;
        let big_tiff = mapped.big_tiff;

        let last_page = page_tokens
            .last()
            .ok_or(Error::InvalidAsset("no IFD found".to_string()))?;

        // we remove tag if found and rewrite the file
        if tiff_tree[*last_page].data.entries.contains_key(&C2PA_TAG) {
            let mut bo = ByteOrdered::new(output_stream, e);
            let mut tc = TiffCloner::new_from_source(e, big_tiff, &mut bo, input_stream)?;

            tc.clone_c2pa_mode(
                input_stream,
                &mut tiff_tree,
                &page_tokens,
                Vec::new(),
                &[C2PA_TAG],
            )?;
        } else {
            // just copy if no changes made
            input_stream.rewind()?;
            std::io::copy(input_stream, output_stream)?;
        }

        Ok(())
    }
}

impl AssetPatch for TiffIO {
    fn patch_c2pa_file(&self, asset_path: &std::path::Path, store_bytes: &[u8]) -> Result<()> {
        let mut asset_io = OpenOptions::new()
            .write(true)
            .read(true)
            .create(false)
            .open(asset_path)?;

        let mapped = map_tiff(&mut asset_io)?;
        let tiff_tree = mapped.tiff_tree;
        let page_tokens = mapped.page_tokens;
        let e = mapped.endianness;
        let big_tiff = mapped.big_tiff;

        let last_page = page_tokens
            .last()
            .ok_or(Error::InvalidAsset("no IFD".to_string()))?;
        let last_ifd = &tiff_tree[*last_page].data;

        let cai_ifd_entry = last_ifd.get_tag(C2PA_TAG).ok_or(Error::JumbfNotFound)?;

        // make sure data type is for unstructured data
        if cai_ifd_entry.entry_type != C2PA_FIELD_TYPE {
            return Err(Error::InvalidAsset(
                "Ifd entry for C2PA must be type UNKNOWN(7)".to_string(),
            ));
        }

        let manifest_len: usize = usize::try_from(cai_ifd_entry.value_count)
            .map_err(|_err| Error::InvalidAsset("TIFF/DNG out of range".to_string()))?;

        if store_bytes.len() == manifest_len {
            // move read point to start of entry
            let decoded_offset = decode_offset(cai_ifd_entry.value_offset, e, big_tiff)?;
            asset_io.seek(SeekFrom::Start(decoded_offset))?;

            asset_io.write_all(store_bytes)?;
            Ok(())
        } else {
            Err(Error::InvalidAsset(
                "patch_cai_store store size mismatch.".to_string(),
            ))
        }
    }
}

impl WriteXmp for TiffIO {
    fn write_xmp(
        &self,
        input_stream: &mut dyn ReadSeek,
        output_stream: &mut dyn ReadWriteSeek,
        xmp: &str,
    ) -> Result<()> {
        let l = u64::try_from(xmp.len())
            .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))?;

        let entry = IfdClonedEntry {
            entry_tag: XMP_TAG,
            entry_type: IFDEntryType::Byte as u16,
            value_count: l,
            value_bytes: xmp.as_bytes().to_vec(),
        };
        tiff_clone_with_tags(output_stream, input_stream, vec![entry])
    }
}

impl ComposedManifestRef for TiffIO {
    // Return entire CAI block as Vec<u8>
    fn compose_manifest(&self, manifest_data: &[u8], _format: &str) -> Result<Vec<u8>> {
        Ok(manifest_data.to_vec())
    }
}

#[cfg(test)]
pub mod tests {
    #![allow(clippy::expect_used)]
    #![allow(clippy::panic)]
    #![allow(clippy::unwrap_used)]

    use core::panic;

    use super::*;
    use crate::utils::{io_utils::tempdirectory, test::temp_dir_path};

    #[test]
    fn test_multipage_read_write_manifest() {
        let data = "some data";
        let data2 = "some different data";

        let source = crate::utils::test::fixture_path("MultiPage.tif");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.tif");

        std::fs::copy(source, &output).unwrap();

        let tiff_io = TiffIO {};

        // save data to tiff
        tiff_io.save_c2pa_store(&output, data.as_bytes()).unwrap();

        // read data back
        let loaded = tiff_io.read_cai_store(&output).unwrap();

        assert_eq!(&loaded, data.as_bytes());

        // test adding over existing
        tiff_io.save_c2pa_store(&output, data2.as_bytes()).unwrap();

        // read data back
        let loaded = tiff_io.read_cai_store(&output).unwrap();

        assert_eq!(&loaded, data2.as_bytes());

        // let's remove the manifest
        tiff_io.remove_c2pa_store(&output).unwrap();

        // should not contain a manifest
        let result = tiff_io.read_cai_store(&output);
        assert!(result.is_err());
    }

    #[test]
    fn test_multipage_read_write_manifest_xmp() {
        let data = "some data";
        let data2 = "some xmp data";

        let source = crate::utils::test::fixture_path("MultiPage.tif");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.tif");

        std::fs::copy(source, &output).unwrap();

        let tiff_io = TiffIO {};

        // save data to tiff
        tiff_io.save_c2pa_store(&output, data.as_bytes()).unwrap();

        // read data back
        let loaded = tiff_io.read_cai_store(&output).unwrap();

        assert_eq!(&loaded, data.as_bytes());

        // test adding over existing
        let eh = tiff_io.remote_manifest_url_ref().unwrap();
        let mut input_stream = std::fs::File::open(&output).unwrap();
        let mut embed_stream = Cursor::new(Vec::new());
        eh.write_remote_manifest_url(&mut input_stream, &mut embed_stream, data2)
            .unwrap();
        std::fs::write(&output, embed_stream.into_inner()).unwrap();

        // read xmp data back
        let mut output_file = std::fs::File::open(&output).unwrap();
        let loaded = tiff_io.read_xmp(&mut output_file).unwrap();

        assert!(loaded.contains(data2));

        // make sure manifest was relocated correctly
        let loaded = tiff_io.read_cai_store(&output).unwrap();
        assert_eq!(&loaded, data.as_bytes());

        // now test shrinking the manifest at the end of the file
        let data3 = "short";
        tiff_io.save_c2pa_store(&output, data3.as_bytes()).unwrap();

        // read data back
        let loaded = tiff_io.read_cai_store(&output).unwrap();
        assert_eq!(&loaded, data3.as_bytes());
    }

    #[test]
    fn cyclic_ifd_self_loop_returns_error() {
        // 14-byte little-endian TIFF: IFD at offset 8 has next-offset = 8.
        // Chain: A → A
        #[rustfmt::skip]
        let crafted_tiff: &[u8] = &[
            0x49, 0x49, // byte order: little-endian
            0x2A, 0x00, // magic: 42
            0x08, 0x00, 0x00, 0x00, // first IFD at offset 8
            0x00, 0x00, // IFD entry count: 0
            0x08, 0x00, 0x00, 0x00, // next IFD offset: 8 (self-loop)
        ];
        let mut cursor = Cursor::new(crafted_tiff);
        let result = map_tiff(&mut cursor);
        assert!(result.is_err(), "self-loop IFD must return an error");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Cyclic IFD chain"),
            "unexpected error message: {err_msg}"
        );
    }

    #[test]
    fn cyclic_ifd_two_node_cycle_returns_error() {
        // 20-byte little-endian TIFF with two IFDs forming a cycle.
        // Chain: A (offset 8) → B (offset 14) → A (offset 8)
        #[rustfmt::skip]
        let crafted_tiff: &[u8] = &[
            0x49, 0x49, // byte order: little-endian
            0x2A, 0x00, // magic: 42
            0x08, 0x00, 0x00, 0x00, // first IFD at offset 8
            // IFD A at offset 8
            0x00, 0x00, // entry count: 0
            0x0E, 0x00, 0x00, 0x00, // next IFD offset: 14 (IFD B)
            // IFD B at offset 14
            0x00, 0x00, // entry count: 0
            0x08, 0x00, 0x00, 0x00, // next IFD offset: 8 (back to IFD A)
        ];
        let mut cursor = Cursor::new(crafted_tiff);
        let result = map_tiff(&mut cursor);
        assert!(result.is_err(), "A→B→A IFD cycle must return an error");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Cyclic IFD chain"),
            "unexpected error message: {err_msg}"
        );
    }

    #[test]
    fn test_read_write_manifest() {
        let data = "some data";
        let data2 = "some different data";

        let source = crate::utils::test::fixture_path("TUSCANY.TIF");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.tif");

        std::fs::copy(source, &output).unwrap();

        let tiff_io = TiffIO {};

        // save data to tiff
        tiff_io.save_c2pa_store(&output, data.as_bytes()).unwrap();
        tiff_io.save_c2pa_store(&output, data2.as_bytes()).unwrap();

        // read data back
        let loaded = tiff_io.read_cai_store(&output).unwrap();

        assert_eq!(&loaded, data2.as_bytes());
    }

    #[test]
    fn test_read_write_manifest_dng() {
        let data = "some data";

        let source = crate::utils::test::fixture_path("subfiles.dng");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.dng");

        std::fs::copy(source, &output).unwrap();

        let tiff_io = TiffIO {};

        // save data to tiff
        tiff_io.save_c2pa_store(&output, data.as_bytes()).unwrap();

        // read data back
        let loaded = tiff_io.read_cai_store(&output).unwrap();

        assert_eq!(&loaded, data.as_bytes());
    }

    #[test]
    fn test_read_write_manifest_dng_bigdata() {
        let data = "some data";

        let source = crate::utils::test::fixture_path("Foo.dng");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.dng");

        std::fs::copy(source, &output).unwrap();

        let tiff_io = TiffIO {};

        // save data to tiff
        tiff_io.save_c2pa_store(&output, data.as_bytes()).unwrap();

        // read data back
        let loaded = tiff_io.read_cai_store(&output).unwrap();

        assert_eq!(&loaded, data.as_bytes());
    }

    #[test]
    fn test_legacy_cloner_tiff_bomb() {
        let data = "some data";

        let source = crate::utils::test::fixture_path("tiff_poc.tiff");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.tiff");

        std::fs::copy(&source, &output).unwrap();
        let asset_writer = std::fs::OpenOptions::new()
            .write(true)
            .read(true)
            .create(false)
            .open(&output)
            .unwrap();

        let mut asset_reader = std::fs::OpenOptions::new()
            .write(false)
            .read(true)
            .create(false)
            .open(&source)
            .unwrap();

        let l = u64::try_from(data.len())
            .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))
            .unwrap();

        let entry = IfdClonedEntry {
            entry_tag: C2PA_TAG,
            entry_type: C2PA_FIELD_TYPE,
            value_count: l,
            value_bytes: data.as_bytes().to_vec(),
        };

        let result = map_tiff(&mut asset_reader);
        assert!(result.is_err(), "should not be able to map tiff bomb");
    }

    #[test]
    fn test_cloner_tiff_bomb() {
        let data = "some data";

        let source = crate::utils::test::fixture_path("tiff_poc.tiff");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.tif");

        std::fs::copy(source, &output).unwrap();
        let mut asset_writer = std::fs::OpenOptions::new()
            .write(true)
            .read(true)
            .create(false)
            .open(&output)
            .unwrap();

        let mut asset_reader = std::fs::OpenOptions::new()
            .write(false)
            .read(true)
            .create(false)
            .open(&output)
            .unwrap();

        let l = u64::try_from(data.len())
            .map_err(|_err| Error::InvalidAsset("value out of range".to_string()))
            .unwrap();

        let entry = IfdClonedEntry {
            entry_tag: C2PA_TAG,
            entry_type: C2PA_FIELD_TYPE,
            value_count: l,
            value_bytes: data.as_bytes().to_vec(),
        };

        let result = tiff_clone_with_tags(&mut asset_writer, &mut asset_reader, vec![entry]);
        assert!(result.is_err(), "should not be able to clone tiff bomb");
    }

    #[test]
    fn test_write_xmp() {
        let data = "some data";

        let source = crate::utils::test::fixture_path("TUSCANY.TIF");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.tif");

        std::fs::copy(source, &output).unwrap();

        let tiff_io = TiffIO {};

        // add a manifest first to stress this case
        // save data to tiff
        tiff_io.save_c2pa_store(&output, data.as_bytes()).unwrap();

        // save data to tiff
        let eh = tiff_io.remote_manifest_url_ref().unwrap();
        let mut input_stream = std::fs::File::open(&output).unwrap();
        let mut embed_stream = Cursor::new(Vec::new());
        eh.write_remote_manifest_url(&mut input_stream, &mut embed_stream, data)
            .unwrap();
        std::fs::write(&output, embed_stream.into_inner()).unwrap();

        // read data back
        let mut output_stream = std::fs::File::open(&output).unwrap();
        let xmp = tiff_io.read_xmp(&mut output_stream).unwrap();
        let loaded = crate::utils::xmp_inmemory_utils::extract_provenance(&xmp).unwrap();

        assert_eq!(&loaded, data);
    }

    #[test]
    fn test_remove_remote_manifest_url() {
        let url = "https://example.com/manifest.c2pa";

        let source = crate::utils::test::fixture_path("TUSCANY.TIF");
        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.tif");
        std::fs::copy(source, &output).unwrap();

        let tiff_io = TiffIO {};

        // write_xmp_ref must be wired up for this handler.
        assert!(tiff_io.write_xmp_ref().is_some());

        // embed a remote manifest URL reference.
        let eh = tiff_io.remote_manifest_url_ref().unwrap();
        let mut input_stream = std::fs::File::open(&output).unwrap();
        let mut embed_stream = Cursor::new(Vec::new());
        eh.write_remote_manifest_url(&mut input_stream, &mut embed_stream, url)
            .unwrap();
        std::fs::write(&output, embed_stream.into_inner()).unwrap();

        let mut with_url_stream = std::fs::File::open(&output).unwrap();
        let xmp = tiff_io.read_xmp(&mut with_url_stream).unwrap();
        assert_eq!(
            crate::utils::xmp_inmemory_utils::extract_provenance(&xmp).as_deref(),
            Some(url)
        );

        // remove_remote_manifest_url strips just the reference, in one pass.
        let mut input_stream = std::fs::File::open(&output).unwrap();
        let mut stripped_stream = Cursor::new(Vec::new());
        eh.remove_remote_manifest_url(&mut input_stream, &mut stripped_stream)
            .unwrap();
        stripped_stream.rewind().unwrap();
        let xmp = tiff_io.read_xmp(&mut stripped_stream).unwrap();
        assert_eq!(
            crate::utils::xmp_inmemory_utils::extract_provenance(&xmp),
            None
        );
    }

    #[test]
    fn test_remove_manifest() {
        let data = "some data";

        let source = crate::utils::test::fixture_path("TUSCANY.TIF");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.tif");

        std::fs::copy(source, &output).unwrap();

        let tiff_io = TiffIO {};

        // first make sure that calling this without a manifest does not error
        tiff_io.remove_c2pa_store(&output).unwrap();

        // save data to tiff
        tiff_io.save_c2pa_store(&output, data.as_bytes()).unwrap();

        // read data back
        let loaded = tiff_io.read_cai_store(&output).unwrap();

        assert_eq!(&loaded, data.as_bytes());

        tiff_io.remove_c2pa_store(&output).unwrap();

        match tiff_io.read_cai_store(&output) {
            Err(Error::JumbfNotFound) => (),
            _ => panic!("should be no C2PA store"),
        }
    }

    #[test]
    fn test_get_object_location() {
        // The C2PA manifest store is always a JUMBF box; get_object_locations
        // bounds the IFD value_count to that box's length, so use a minimal
        // valid JUMBF superbox (LBox = 8, TBox = "jumb") as the stored data.
        let data: [u8; 8] = [0x00, 0x00, 0x00, 0x08, 0x6a, 0x75, 0x6d, 0x62];

        let source = crate::utils::test::fixture_path("TUSCANY.TIF");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.tif");

        std::fs::copy(source, &output).unwrap();

        let tiff_io = TiffIO {};

        // save data to tiff
        tiff_io.save_c2pa_store(&output, &data).unwrap();

        // read data back
        let loaded = tiff_io.read_cai_store(&output).unwrap();

        assert_eq!(loaded.as_slice(), data.as_slice());

        let mut success = false;
        let mut output_reader = std::fs::File::open(&output).unwrap();
        if let Ok(locations) = tiff_io.get_object_locations(&mut output_reader) {
            for op in locations {
                if op.htype == ObjectType::C2pa {
                    let mut of = std::fs::File::open(&output).unwrap();

                    let mut manifests_buf: Vec<u8> = vec![0u8; usize::try_from(op.length).unwrap()];
                    of.seek(SeekFrom::Start(op.offset)).unwrap();
                    of.read_exact(manifests_buf.as_mut_slice()).unwrap();
                    if crate::hash_utils::vec_compare(&manifests_buf, &data) {
                        success = true;
                    }
                }
            }
        }
        assert!(success);
    }

    #[test]
    #[ignore = "This code is no longer accessed.  We do not clone ifd entries."]
    fn test_overflow_clone_ifd_entries() {
        let data = [
            0x49, 0x49, 0x2b, 0x00, 0x08, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49,
            0x49, 0x2a, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xf9, 0x00,
            0x00, 0x00, 0x00, 0x05, 0x00, 0x07, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
            // entry
            //
            0x00, 0x00, // entry_tag
            0x04, 0x00, // entry_type
            0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, // value_count (cnt)
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value_offset
            //
            // entry
            //
            0x00, 0x00, // entry_tag
            0x04, 0x00, // entry_type
            0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, // value_count (cnt)
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value_offset
            //
            // ...
            //
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00,
        ];

        let mut stream = Cursor::new(&data);

        let tiff_io = TiffIO {};

        let locations = tiff_io.get_object_locations(&mut stream);
        assert!(matches!(locations, Err(Error::InvalidAsset(_))));
    }

    /// Regression test for integer overflow in `clone_ifd_entries` for 8-byte element types.
    ///
    /// IFD entry types Rational, SRational, Double, Long8, SLong8, and Ifd8 are all 8 bytes
    /// wide per element. Before the fix, the byte count was computed as `cnt * 8` with no
    /// overflow guard. A crafted BigTIFF carrying `value_count = 0x2000000000000001` causes
    /// `0x2000000000000001 * 8 = 0x10000000000000008`, which wraps past u64::MAX:
    ///   - debug builds: immediate panic (exit code 101)
    ///   - release builds: silent truncation to 0x8, producing wrong results
    ///
    /// The fix adds `checked_mul(8)` — matching the pattern already used for every other
    /// multi-byte type — and returns `Error::InvalidAsset` instead of overflowing.
    ///
    /// The binary blob below is the same crafted BigTIFF as in `test_overflow_clone_ifd_entries`
    /// but with entry_type changed from 0x04 (Long, ×4) to 0x05 (Rational, ×8) and
    /// value_count set to 0x2000000000000001 (overflows ×8).
    #[test]
    #[ignore = "This code is no longer accessed.  We do not clone ifd entries."]
    fn test_overflow_clone_ifd_entries_rational_type() {
        let data = [
            0x49, 0x49, 0x2b, 0x00, 0x08, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49,
            0x49, 0x2a, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xf9, 0x00,
            0x00, 0x00, 0x00, 0x05, 0x00, 0x07, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
            // entry — type 0x05 (Rational, 8 bytes/element), count overflows × 8
            //
            0x00, 0x00, // entry_tag
            0x05, 0x00, // entry_type: Rational (was 0x04 Long)
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x20, // value_count = 0x2000000000000001
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value_offset
            //
            // entry
            //
            0x00, 0x00, // entry_tag
            0x05, 0x00, // entry_type: Rational (was 0x04 Long)
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x20, // value_count = 0x2000000000000001
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value_offset
            //
            // ...
            //
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00,
        ];

        let mut stream = Cursor::new(&data);
        let tiff_io = TiffIO {};

        // Before the fix: this would panic (exit 101) in debug or silently overflow in release.
        // After the fix: must return Err(Error::InvalidAsset) without any panic.
        let locations = tiff_io.get_object_locations(&mut stream);
        assert!(matches!(locations, Err(Error::InvalidAsset(_))));
    }

    /// Regression test for OOM in `clone_ifd_entries` for Byte/1-byte element types.
    ///
    /// On Linux containers with memory overcommit (the default), `safe_vec` uses
    /// `try_reserve_exact` which succeeds for a 10 GB allocation because the OS commits
    /// virtual address space lazily. The subsequent `resize` then touches all 10 GB of
    /// pages, triggering the OOM killer (exit 137) in any 8 GB container.
    ///
    /// The fix validates `cnt <= file_size` before calling `safe_vec`, returning
    /// `Err(InvalidAsset)` for any count that exceeds the file's actual byte count.
    ///
    /// The binary blob is the same crafted BigTIFF as `test_overflow_clone_ifd_entries`
    /// but with entry_type changed from 0x04 (Long, ×4) to 0x01 (Byte, ×1) and
    /// value_count set to 10_000_000_000 (0x00000002540BE400 little-endian).
    #[test]
    #[ignore = "This code is no longer accessed.  We do not clone ifd entries."]
    fn test_oom_clone_ifd_entries_byte_type() {
        // Same BigTIFF blob as test_overflow_clone_ifd_entries, with entry_type changed from
        // 0x04 (Long, ×4) to 0x01 (Byte, ×1) and value_count changed from the overflow-inducing
        // 0x8000000000000003 to 10_000_000_000 (0x00000002540BE400 LE). The IFD offset (0x31 = 49)
        // and entry count (3) at that offset must stay identical to the original blob.
        let data = [
            0x49, 0x49, 0x2b, 0x00, 0x08, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49,
            0x49, 0x2a, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xf9, 0x00,
            0x00, 0x00, 0x00, 0x05, 0x00, 0x07, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
            // entry — type 0x01 (Byte, 1 byte/element), value_count = 10_000_000_000
            //
            0x00, 0x00, // entry_tag
            0x01, 0x00, // entry_type: Byte (was 0x04 Long)
            0x00, 0xe4, 0x0b, 0x54, 0x02, 0x00, 0x00, 0x00, // value_count = 10_000_000_000 LE
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value_offset
            //
            // entry
            //
            0x00, 0x00, // entry_tag
            0x01, 0x00, // entry_type: Byte (was 0x04 Long)
            0x00, 0xe4, 0x0b, 0x54, 0x02, 0x00, 0x00, 0x00, // value_count = 10_000_000_000 LE
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value_offset
            //
            // ...
            //
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00,
        ];

        let mut stream = Cursor::new(&data);
        let tiff_io = TiffIO {};

        // Before the fix: this would OOM-kill an 8 GB Linux container.
        // After the fix: must return Err(Error::InvalidAsset) without any allocation.
        let locations = tiff_io.get_object_locations(&mut stream);
        assert!(matches!(locations, Err(Error::InvalidAsset(_))));
    }

    // Helper: build an IfdClonedEntry of LONG (u32) values in little-endian.
    fn u32_strip_entry(tag: u16, values: &[u32]) -> IfdClonedEntry {
        let mut value_bytes = Vec::with_capacity(values.len() * 4);
        for v in values {
            value_bytes.extend_from_slice(&v.to_le_bytes());
        }
        IfdClonedEntry {
            entry_tag: tag,
            entry_type: 4, // LONG
            value_count: values.len() as u64,
            value_bytes,
        }
    }

    // Regression: a TIFF whose strip byte counts sum to more than the actual
    // source stream length must be rejected. Pre-fix, `clone_image_data`
    // would honor an attacker-chosen sum (50 000 strips × source_len) and
    // grow the in-memory output to gigabytes, aborting with OOM (~4.9 GB
    // from a 293 KB input in the reported PoC).
    #[test]
    fn clone_image_data_rejects_strip_byte_count_amplification() {
        // 100-byte source; 10 strips claiming 200 bytes each → sum 2000 > 100.
        let mut asset_reader = Cursor::new(vec![0u8; 100]);

        let n = 10;
        let byte_counts: Vec<u32> = vec![200u32; n];
        let offsets: Vec<u32> = vec![0u32; n];

        let mut ifd: BTreeMap<u16, IfdClonedEntry> = BTreeMap::new();
        ifd.insert(
            STRIPBYTECOUNTS,
            u32_strip_entry(STRIPBYTECOUNTS, &byte_counts),
        );
        ifd.insert(STRIPOFFSETS, u32_strip_entry(STRIPOFFSETS, &offsets));

        let writer = Cursor::new(Vec::<u8>::new());
        let mut cloner = TiffCloner::new(Endianness::Little, false, writer).unwrap();
        let result = cloner.clone_image_data(&mut ifd, &mut asset_reader);

        assert!(
            matches!(&result, Err(Error::InvalidAsset(msg)) if msg.contains("exceed source length")),
            "expected InvalidAsset for over-cap strip byte counts, got {result:?}",
        );
    }

    // Regression: same amplification pattern in the tile branch of
    // `clone_image_data`. `sum(tile_byte_counts) > source_len` must be
    // rejected before any copy is performed.
    #[test]
    fn clone_image_data_rejects_tile_byte_count_amplification() {
        let mut asset_reader = Cursor::new(vec![0u8; 100]);

        let n = 8;
        let byte_counts: Vec<u32> = vec![u32::MAX / n as u32; n]; // huge sum
        let offsets: Vec<u32> = vec![0u32; n];

        let mut ifd: BTreeMap<u16, IfdClonedEntry> = BTreeMap::new();
        ifd.insert(
            TILEBYTECOUNTS,
            u32_strip_entry(TILEBYTECOUNTS, &byte_counts),
        );
        ifd.insert(TILEOFFSETS, u32_strip_entry(TILEOFFSETS, &offsets));

        let writer = Cursor::new(Vec::<u8>::new());
        let mut cloner = TiffCloner::new(Endianness::Little, false, writer).unwrap();
        let result = cloner.clone_image_data(&mut ifd, &mut asset_reader);

        assert!(
            matches!(&result, Err(Error::InvalidAsset(msg)) if msg.contains("exceed source length")),
            "expected InvalidAsset for over-cap tile byte counts, got {result:?}",
        );
    }

    // Happy path: strip byte counts that legitimately sum to <= source_len
    // must still copy successfully. Guards against a future refactor that
    // makes the cap too strict.
    #[test]
    fn clone_image_data_accepts_valid_strip_byte_counts() {
        let mut asset_reader = Cursor::new(vec![0xaau8; 100]);

        // 5 strips × 10 bytes = 50 bytes, well within 100.
        let byte_counts: Vec<u32> = vec![10u32; 5];
        let offsets: Vec<u32> = vec![0u32; 5];

        let mut ifd: BTreeMap<u16, IfdClonedEntry> = BTreeMap::new();
        ifd.insert(
            STRIPBYTECOUNTS,
            u32_strip_entry(STRIPBYTECOUNTS, &byte_counts),
        );
        ifd.insert(STRIPOFFSETS, u32_strip_entry(STRIPOFFSETS, &offsets));

        let writer = Cursor::new(Vec::<u8>::new());
        let mut cloner = TiffCloner::new(Endianness::Little, false, writer).unwrap();
        cloner
            .clone_image_data(&mut ifd, &mut asset_reader)
            .expect("valid strip byte counts should copy successfully");
    }

    // Regression: entries individually within file size but summing over it must be rejected.
    #[test]
    fn clone_ifd_entries_rejects_cumulative_amplification() {
        let file_size = 1000u64;
        let mut asset_reader = Cursor::new(vec![0xaau8; file_size as usize]);

        let mut entries: BTreeMap<u16, IfdEntry> = BTreeMap::new();
        for tag in 0..2u16 {
            entries.insert(
                tag,
                IfdEntry {
                    entry_tag: tag,
                    entry_type: IFDEntryType::Byte as u16,
                    value_count: 600, // fits alone (600 <= 1000) but 2x600 > 1000
                    value_offset: 0,
                },
            );
        }

        let writer = Cursor::new(Vec::<u8>::new());
        let mut cloner = TiffCloner::new(Endianness::Little, false, writer).unwrap();
        let result = cloner.clone_ifd_entries(&entries, &mut asset_reader);

        match result {
            Err(Error::InvalidAsset(msg)) => {
                assert!(
                    msg.contains("IFD entry") && msg.contains("exceed"),
                    "unexpected error message: {msg}",
                );
            }
            Err(other) => panic!("expected InvalidAsset, got other error: {other}"),
            Ok(_) => panic!("expected InvalidAsset for cumulative IFD entry amplification"),
        }
    }

    // Happy path: entries summing to <= file size must still clone successfully.
    #[test]
    fn clone_ifd_entries_accepts_valid_cumulative_size() {
        let file_size = 1000u64;
        let mut asset_reader = Cursor::new(vec![0xaau8; file_size as usize]);

        let mut entries: BTreeMap<u16, IfdEntry> = BTreeMap::new();
        for tag in 0..2u16 {
            entries.insert(
                tag,
                IfdEntry {
                    entry_tag: tag,
                    entry_type: IFDEntryType::Byte as u16,
                    value_count: 400, // 2x400 = 800 <= 1000
                    value_offset: 0,
                },
            );
        }

        let writer = Cursor::new(Vec::<u8>::new());
        let mut cloner = TiffCloner::new(Endianness::Little, false, writer).unwrap();
        cloner
            .clone_ifd_entries(&entries, &mut asset_reader)
            .expect("valid cumulative IFD entry sizes should clone successfully");
    }

    // The cumulative bound must hold for every element-type branch, not just Byte.
    // For each type, two entries that each fit the file but together exceed it must
    // be rejected -- exercising accumulate_copy_len (and, for 8-byte types, the
    // added per-entry check) in the Short/Long/Sshort/Slong/Float/8-byte branches.
    #[test]
    fn clone_ifd_entries_cumulative_bound_covers_all_types() {
        let file_size = 40u64;
        // (entry_type discriminant, per-entry value_count, label): each entry's byte
        // size is 24 (<= 40, fits alone), two entries sum to 48 (> 40, rejected).
        let cases: [(u16, u64, &str); 6] = [
            (IFDEntryType::Short as u16, 12, "Short"),
            (IFDEntryType::Long as u16, 6, "Long"),
            (IFDEntryType::Sshort as u16, 12, "Sshort"),
            (IFDEntryType::Slong as u16, 6, "Slong"),
            (IFDEntryType::Float as u16, 6, "Float"),
            (IFDEntryType::Double as u16, 3, "Double"),
        ];

        for (entry_type, value_count, label) in cases {
            let mut asset_reader = Cursor::new(vec![0xaau8; file_size as usize]);
            let mut entries: BTreeMap<u16, IfdEntry> = BTreeMap::new();
            for tag in 0..2u16 {
                entries.insert(
                    tag,
                    IfdEntry {
                        entry_tag: tag,
                        entry_type,
                        value_count,
                        value_offset: 0,
                    },
                );
            }

            let writer = Cursor::new(Vec::<u8>::new());
            let mut cloner = TiffCloner::new(Endianness::Little, false, writer).unwrap();

            // Map to a message so the assert doesn't require Debug on the Ok map:
            // Ok -> empty (fails), a different error -> its text (fails), the
            // expected InvalidAsset -> its message (passes the contains check).
            let msg = match cloner.clone_ifd_entries(&entries, &mut asset_reader) {
                Err(Error::InvalidAsset(msg)) => msg,
                Err(other) => other.to_string(),
                Ok(_) => String::new(),
            };
            assert!(
                msg.contains("IFD entry") && msg.contains("exceed"),
                "type {label}: expected cumulative rejection, got message {msg:?}",
            );
        }
    }

    // Unit test for the shared cap helper used by the strip, tile, and BigTable
    // copy loops. Covers the running-total accounting, the exceed-source-length
    // rejection (with the per-kind label), and the checked_add overflow guard.
    #[test]
    fn accumulate_copy_len_caps_and_labels() {
        // Accumulates within the cap.
        let mut copied = 0u64;
        accumulate_copy_len(&mut copied, 40, 100, "strip").expect("within cap");
        accumulate_copy_len(&mut copied, 60, 100, "strip").expect("exactly at cap");
        assert_eq!(copied, 100);

        // One more byte exceeds the source length and is rejected with the label.
        let err = accumulate_copy_len(&mut copied, 1, 100, "tile").unwrap_err();
        assert!(
            matches!(&err, Error::InvalidAsset(msg)
                if msg.contains("tile") && msg.contains("exceed source length")),
            "got {err:?}",
        );

        // A count that overflows the u64 running total is rejected too.
        let mut copied = u64::MAX;
        let err = accumulate_copy_len(&mut copied, 1, u64::MAX, "BigTable").unwrap_err();
        assert!(
            matches!(&err, Error::InvalidAsset(msg)
                if msg.contains("BigTable") && msg.contains("overflow")),
            "got {err:?}",
        );
    }

    /*  disable until I find smaller DNG
    #[test]
    fn test_read_write_dng_manifest() {
        let data = "some data";

        let source = crate::utils::test::fixture_path("test.DNG");
        //let source = crate::utils::test::fixture_path("sample1.dng");

        let temp_dir = tempdirectory().unwrap();
        let output = temp_dir_path(&temp_dir, "test.DNG");

        std::fs::copy(&source, &output).unwrap();

        let tiff_io = TiffIO {};

        // save data to tiff
        tiff_io.save_cai_store(&output, data.as_bytes()).unwrap();

        // read data back
        println!("Reading TIFF");
        let loaded = tiff_io.read_cai_store(&output).unwrap();

        assert_eq!(&loaded, data.as_bytes());
    }
    #[test]
    fn test_read_write_dng_parse() {
        //let data = "some data";

        let source = crate::utils::test::fixture_path("test.DNG");
        let mut f = std::fs::File::open(&source).unwrap();

        let (idfs, token, _endianness, _big_tiff) = map_tiff(&mut f).unwrap();

        println!("IFD {}", idfs[token].data.entry_cnt);
    }
    */
}