aboutsummaryrefslogtreecommitdiffstats
path: root/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
blob: 480344191177681808000ad7c496efa2dfcef2b5 (plain)
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
/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
==================================================================== */

package org.apache.poi.poifs.filesystem;

import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.NoSuchElementException;

import org.apache.poi.POIDataSamples;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.common.POIFSConstants;
import org.apache.poi.poifs.property.DirectoryProperty;
import org.apache.poi.poifs.property.Property;
import org.apache.poi.poifs.property.PropertyTable;
import org.apache.poi.poifs.property.RootProperty;
import org.apache.poi.poifs.storage.BATBlock;
import org.apache.poi.poifs.storage.HeaderBlock;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

/**
 * Tests {@link POIFSStream}
 */
public final class TestPOIFSStream {
    private static final POIDataSamples _inst = POIDataSamples.getPOIFSInstance();

    /**
     * Read a single block stream
     */
    @Test
    public void testReadTinyStream() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));

        // 98 is actually the last block in a two block stream...
        POIFSStream stream = new POIFSStream(fs, 98);
        Iterator<ByteBuffer> i = stream.getBlockIterator();
        assertTrue(i.hasNext());
        ByteBuffer b = i.next();
        assertFalse(i.hasNext());

        // Check the contents
        assertEquals((byte) 0x81, b.get());
        assertEquals((byte) 0x00, b.get());
        assertEquals((byte) 0x00, b.get());
        assertEquals((byte) 0x00, b.get());
        assertEquals((byte) 0x82, b.get());
        assertEquals((byte) 0x00, b.get());
        assertEquals((byte) 0x00, b.get());
        assertEquals((byte) 0x00, b.get());

        fs.close();
    }

    /**
     * Read a stream with only two blocks in it
     */
    @Test
    public void testReadShortStream() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));

        // 97 -> 98 -> end
        POIFSStream stream = new POIFSStream(fs, 97);
        Iterator<ByteBuffer> i = stream.getBlockIterator();
        assertTrue(i.hasNext());
        ByteBuffer b97 = i.next();
        assertTrue(i.hasNext());
        ByteBuffer b98 = i.next();
        assertFalse(i.hasNext());

        // Check the contents of the 1st block
        assertEquals((byte) 0x01, b97.get());
        assertEquals((byte) 0x00, b97.get());
        assertEquals((byte) 0x00, b97.get());
        assertEquals((byte) 0x00, b97.get());
        assertEquals((byte) 0x02, b97.get());
        assertEquals((byte) 0x00, b97.get());
        assertEquals((byte) 0x00, b97.get());
        assertEquals((byte) 0x00, b97.get());

        // Check the contents of the 2nd block
        assertEquals((byte) 0x81, b98.get());
        assertEquals((byte) 0x00, b98.get());
        assertEquals((byte) 0x00, b98.get());
        assertEquals((byte) 0x00, b98.get());
        assertEquals((byte) 0x82, b98.get());
        assertEquals((byte) 0x00, b98.get());
        assertEquals((byte) 0x00, b98.get());
        assertEquals((byte) 0x00, b98.get());

        fs.close();
    }

    /**
     * Read a stream with many blocks
     */
    @Test
    public void testReadLongerStream() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));

        ByteBuffer b0 = null;
        ByteBuffer b1 = null;
        ByteBuffer b22 = null;

        // The stream at 0 has 23 blocks in it
        POIFSStream stream = new POIFSStream(fs, 0);
        Iterator<ByteBuffer> i = stream.getBlockIterator();
        int count = 0;
        while (i.hasNext()) {
            ByteBuffer b = i.next();
            if (count == 0) {
                b0 = b;
            }
            if (count == 1) {
                b1 = b;
            }
            if (count == 22) {
                b22 = b;
            }

            count++;
        }
        assertEquals(23, count);

        // Check the contents
        //  1st block is at 0
        assertNotNull(b0);
        assertEquals((byte) 0x9e, b0.get());
        assertEquals((byte) 0x75, b0.get());
        assertEquals((byte) 0x97, b0.get());
        assertEquals((byte) 0xf6, b0.get());

        //  2nd block is at 1
        assertNotNull(b1);
        assertEquals((byte) 0x86, b1.get());
        assertEquals((byte) 0x09, b1.get());
        assertEquals((byte) 0x22, b1.get());
        assertEquals((byte) 0xfb, b1.get());

        //  last block is at 89
        assertNotNull(b22);
        assertEquals((byte) 0xfe, b22.get());
        assertEquals((byte) 0xff, b22.get());
        assertEquals((byte) 0x00, b22.get());
        assertEquals((byte) 0x00, b22.get());
        assertEquals((byte) 0x05, b22.get());
        assertEquals((byte) 0x01, b22.get());
        assertEquals((byte) 0x02, b22.get());
        assertEquals((byte) 0x00, b22.get());

        fs.close();
    }

    /**
     * Read a stream with several blocks in a 4096 byte block file
     */
    @Test
    public void testReadStream4096() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));

        // 0 -> 1 -> 2 -> end
        POIFSStream stream = new POIFSStream(fs, 0);
        Iterator<ByteBuffer> i = stream.getBlockIterator();
        assertTrue(i.hasNext());
        ByteBuffer b0 = i.next();
        assertTrue(i.hasNext());
        ByteBuffer b1 = i.next();
        assertTrue(i.hasNext());
        ByteBuffer b2 = i.next();
        assertFalse(i.hasNext());

        // Check the contents of the 1st block
        assertEquals((byte) 0x9E, b0.get());
        assertEquals((byte) 0x75, b0.get());
        assertEquals((byte) 0x97, b0.get());
        assertEquals((byte) 0xF6, b0.get());
        assertEquals((byte) 0xFF, b0.get());
        assertEquals((byte) 0x21, b0.get());
        assertEquals((byte) 0xD2, b0.get());
        assertEquals((byte) 0x11, b0.get());

        // Check the contents of the 2nd block
        assertEquals((byte) 0x00, b1.get());
        assertEquals((byte) 0x00, b1.get());
        assertEquals((byte) 0x03, b1.get());
        assertEquals((byte) 0x00, b1.get());
        assertEquals((byte) 0x00, b1.get());
        assertEquals((byte) 0x00, b1.get());
        assertEquals((byte) 0x00, b1.get());
        assertEquals((byte) 0x00, b1.get());

        // Check the contents of the 3rd block
        assertEquals((byte) 0x6D, b2.get());
        assertEquals((byte) 0x00, b2.get());
        assertEquals((byte) 0x00, b2.get());
        assertEquals((byte) 0x00, b2.get());
        assertEquals((byte) 0x03, b2.get());
        assertEquals((byte) 0x00, b2.get());
        assertEquals((byte) 0x46, b2.get());
        assertEquals((byte) 0x00, b2.get());

        fs.close();
    }

    /**
     * Craft a nasty file with a loop, and ensure we don't get stuck
     */
    @Test
    public void testReadFailsOnLoop() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));

        // Hack the FAT so that it goes 0->1->2->0
        fs.setNextBlock(0, 1);
        fs.setNextBlock(1, 2);
        fs.setNextBlock(2, 0);

        // Now try to read
        POIFSStream stream = new POIFSStream(fs, 0);
        Iterator<ByteBuffer> i = stream.getBlockIterator();
        assertTrue(i.hasNext());

        // 1st read works
        i.next();
        assertTrue(i.hasNext());

        // 2nd read works
        i.next();
        assertTrue(i.hasNext());

        // 3rd read works
        i.next();
        assertTrue(i.hasNext());

        // 4th read blows up as it loops back to 0
        assertThrows(RuntimeException.class, i::next, "Loop should have been detected but wasn't!");
        assertTrue(i.hasNext());

        fs.close();
    }

    /**
     * Tests that we can load some streams that are
     * stored in the mini stream.
     */
    @Test
    public void testReadMiniStreams() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
        POIFSMiniStore ministore = fs.getMiniStore();

        // 178 -> 179 -> 180 -> end
        POIFSStream stream = new POIFSStream(ministore, 178);
        Iterator<ByteBuffer> i = stream.getBlockIterator();
        assertTrue(i.hasNext());
        ByteBuffer b178 = i.next();
        assertTrue(i.hasNext());
        ByteBuffer b179 = i.next();
        assertTrue(i.hasNext());
        ByteBuffer b180 = i.next();
        assertFalse(i.hasNext());

        // Check the contents of the 1st block
        assertEquals((byte) 0xfe, b178.get());
        assertEquals((byte) 0xff, b178.get());
        assertEquals((byte) 0x00, b178.get());
        assertEquals((byte) 0x00, b178.get());
        assertEquals((byte) 0x05, b178.get());
        assertEquals((byte) 0x01, b178.get());
        assertEquals((byte) 0x02, b178.get());
        assertEquals((byte) 0x00, b178.get());

        // And the 2nd
        assertEquals((byte) 0x6c, b179.get());
        assertEquals((byte) 0x00, b179.get());
        assertEquals((byte) 0x00, b179.get());
        assertEquals((byte) 0x00, b179.get());
        assertEquals((byte) 0x28, b179.get());
        assertEquals((byte) 0x00, b179.get());
        assertEquals((byte) 0x00, b179.get());
        assertEquals((byte) 0x00, b179.get());

        // And the 3rd
        assertEquals((byte) 0x30, b180.get());
        assertEquals((byte) 0x00, b180.get());
        assertEquals((byte) 0x00, b180.get());
        assertEquals((byte) 0x00, b180.get());
        assertEquals((byte) 0x00, b180.get());
        assertEquals((byte) 0x00, b180.get());
        assertEquals((byte) 0x00, b180.get());
        assertEquals((byte) 0x80, b180.get());

        fs.close();
    }

    /**
     * Writing the same amount of data as before
     */
    @Test
    public void testReplaceStream() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));

        byte[] data = new byte[512];
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) (i % 256);
        }

        // 98 is actually the last block in a two block stream...
        POIFSStream stream = new POIFSStream(fs, 98);
        stream.updateContents(data);

        // Check the reading of blocks
        Iterator<ByteBuffer> it = stream.getBlockIterator();
        assertTrue(it.hasNext());
        ByteBuffer b = it.next();
        assertFalse(it.hasNext());

        // Now check the contents
        data = new byte[512];
        b.get(data);
        for (int i = 0; i < data.length; i++) {
            byte exp = (byte) (i % 256);
            assertEquals(exp, data[i]);
        }

        fs.close();
    }

    /**
     * Writes less data than before, some blocks will need
     * to be freed
     */
    @Test
    public void testReplaceStreamWithLess() throws Exception {
        try (InputStream is = _inst.openResourceAsStream("BlockSize512.zvi");
             POIFSFileSystem fs = new POIFSFileSystem(is)) {

            byte[] data = new byte[512];
            for (int i = 0; i < data.length; i++) {
                data[i] = (byte) (i % 256);
            }

            // 97 -> 98 -> end
            assertEquals(98, fs.getNextBlock(97));
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98));

            // Create a 2 block stream, will become a 1 block one
            POIFSStream stream = new POIFSStream(fs, 97);
            stream.updateContents(data);

            // 97 should now be the end, and 98 free
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(97));
            assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(98));

            // Check the reading of blocks
            Iterator<ByteBuffer> it = stream.getBlockIterator();
            assertTrue(it.hasNext());
            ByteBuffer b = it.next();
            assertFalse(it.hasNext());

            // Now check the contents
            data = new byte[512];
            b.get(data);
            for (int i = 0; i < data.length; i++) {
                byte exp = (byte) (i % 256);
                assertEquals(exp, data[i]);
            }
        }
    }

    /**
     * Writes more data than before, new blocks will be needed
     */
    @Test
    public void testReplaceStreamWithMore() throws Exception {
        try (InputStream is = _inst.openResourceAsStream("BlockSize512.zvi");
             POIFSFileSystem fs = new POIFSFileSystem(is)) {

            byte[] data = new byte[512 * 3];
            for (int i = 0; i < data.length; i++) {
                data[i] = (byte) (i % 256);
            }

            // 97 -> 98 -> end
            assertEquals(98, fs.getNextBlock(97));
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98));

            // 100 is our first free one
            assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
            assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));

            // Create a 2 block stream, will become a 3 block one
            POIFSStream stream = new POIFSStream(fs, 97);
            stream.updateContents(data);

            // 97 -> 98 -> 100 -> end
            assertEquals(98, fs.getNextBlock(97));
            assertEquals(100, fs.getNextBlock(98));
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));

            // Check the reading of blocks
            Iterator<ByteBuffer> it = stream.getBlockIterator();
            int count = 0;
            while (it.hasNext()) {
                ByteBuffer b = it.next();
                data = new byte[512];
                b.get(data);
                for (int i = 0; i < data.length; i++) {
                    byte exp = (byte) (i % 256);
                    assertEquals(exp, data[i]);
                }
                count++;
            }
            assertEquals(3, count);
        }
    }

    /**
     * Writes to a new stream in the file
     */
    @Test
    public void testWriteNewStream() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));

        // 100 is our first free one
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));


        // Add a single block one
        byte[] data = new byte[512];
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) (i % 256);
        }

        POIFSStream stream = new POIFSStream(fs);
        stream.updateContents(data);

        // Check it was allocated properly
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));

        // And check the contents
        Iterator<ByteBuffer> it = stream.getBlockIterator();
        int count = 0;
        while (it.hasNext()) {
            ByteBuffer b = it.next();
            data = new byte[512];
            b.get(data);
            for (int i = 0; i < data.length; i++) {
                byte exp = (byte) (i % 256);
                assertEquals(exp, data[i]);
            }
            count++;
        }
        assertEquals(1, count);


        // And a multi block one
        data = new byte[512 * 3];
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) (i % 256);
        }

        stream = new POIFSStream(fs);
        stream.updateContents(data);

        // Check it was allocated properly
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
        assertEquals(102, fs.getNextBlock(101));
        assertEquals(103, fs.getNextBlock(102));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(103));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));

        // And check the contents
        it = stream.getBlockIterator();
        count = 0;
        while (it.hasNext()) {
            ByteBuffer b = it.next();
            data = new byte[512];
            b.get(data);
            for (int i = 0; i < data.length; i++) {
                byte exp = (byte) (i % 256);
                assertEquals(exp, data[i]);
            }
            count++;
        }
        assertEquals(3, count);

        // Free it
        stream.free();
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));

        fs.close();
    }

    /**
     * Writes to a new stream in the file, where we've not enough
     * free blocks so new FAT segments will need to be allocated
     * to support this
     */
    @Test
    public void testWriteNewStreamExtraFATs() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));

        // Allocate almost all the blocks
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127));
        for (int i = 100; i < 127; i++) {
            fs.setNextBlock(i, POIFSConstants.END_OF_CHAIN);
        }
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127));
        assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());


        // Write a 3 block stream
        byte[] data = new byte[512 * 3];
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) (i % 256);
        }
        POIFSStream stream = new POIFSStream(fs);
        stream.updateContents(data);

        // Check we got another BAT
        assertFalse(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
        assertTrue(fs.getBATBlockAndIndex(128).getBlock().hasFreeSectors());

        // the BAT will be in the first spot of the new block
        assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(126));
        assertEquals(129, fs.getNextBlock(127));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(128));
        assertEquals(130, fs.getNextBlock(129));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(130));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(131));

        fs.close();
    }

    /**
     * Replaces data in an existing stream, with a bit
     * more data than before, in a 4096 byte block file
     */
    @Test
    public void testWriteStream4096() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));

        // 0 -> 1 -> 2 -> end
        assertEquals(1, fs.getNextBlock(0));
        assertEquals(2, fs.getNextBlock(1));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2));
        assertEquals(4, fs.getNextBlock(3));

        // First free one is at 15
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(15));


        // Write a 5 block file
        byte[] data = new byte[4096 * 5];
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) (i % 256);
        }
        POIFSStream stream = new POIFSStream(fs, 0);
        stream.updateContents(data);


        // Check it
        assertEquals(1, fs.getNextBlock(0));
        assertEquals(2, fs.getNextBlock(1));
        assertEquals(15, fs.getNextBlock(2)); // Jumps
        assertEquals(4, fs.getNextBlock(3));  // Next stream
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14));
        assertEquals(16, fs.getNextBlock(15)); // Continues
        assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(16)); // Ends
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(17)); // Free

        // Check the contents too
        Iterator<ByteBuffer> it = stream.getBlockIterator();
        int count = 0;
        while (it.hasNext()) {
            ByteBuffer b = it.next();
            data = new byte[512];
            b.get(data);
            for (int i = 0; i < data.length; i++) {
                byte exp = (byte) (i % 256);
                assertEquals(exp, data[i]);
            }
            count++;
        }
        assertEquals(5, count);

        fs.close();
    }

    /**
     * Tests that we can write into the mini stream
     */
    @Test
    public void testWriteMiniStreams() throws Exception {
        try (InputStream is = _inst.openResourceAsStream("BlockSize512.zvi");
             POIFSFileSystem fs = new POIFSFileSystem(is)) {

            POIFSMiniStore ministore = fs.getMiniStore();

            // 178 -> 179 -> 180 -> end
            assertEquals(179, ministore.getNextBlock(178));
            assertEquals(180, ministore.getNextBlock(179));
            assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180));


            // Try writing 3 full blocks worth
            byte[] data = new byte[64 * 3];
            for (int i = 0; i < data.length; i++) {
                data[i] = (byte) i;
            }
            POIFSStream stream = new POIFSStream(ministore, 178);
            stream.updateContents(data);

            // Check
            assertEquals(179, ministore.getNextBlock(178));
            assertEquals(180, ministore.getNextBlock(179));
            assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180));

            stream = new POIFSStream(ministore, 178);
            Iterator<ByteBuffer> it = stream.getBlockIterator();
            ByteBuffer b178 = it.next();
            ByteBuffer b179 = it.next();
            ByteBuffer b180 = it.next();
            assertFalse(it.hasNext());

            assertEquals((byte) 0x00, b178.get());
            assertEquals((byte) 0x01, b178.get());
            assertEquals((byte) 0x40, b179.get());
            assertEquals((byte) 0x41, b179.get());
            assertEquals((byte) 0x80, b180.get());
            assertEquals((byte) 0x81, b180.get());


            // Try writing just into 3 blocks worth
            data = new byte[64 * 2 + 12];
            for (int i = 0; i < data.length; i++) {
                data[i] = (byte) (i + 4);
            }
            stream = new POIFSStream(ministore, 178);
            stream.updateContents(data);

            // Check
            assertEquals(179, ministore.getNextBlock(178));
            assertEquals(180, ministore.getNextBlock(179));
            assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180));

            stream = new POIFSStream(ministore, 178);
            it = stream.getBlockIterator();
            b178 = it.next();
            b179 = it.next();
            b180 = it.next();
            assertFalse(it.hasNext());

            assertEquals((byte) 0x04, b178.get(0));
            assertEquals((byte) 0x05, b178.get(1));
            assertEquals((byte) 0x44, b179.get(0));
            assertEquals((byte) 0x45, b179.get(1));
            assertEquals((byte) 0x84, b180.get(0));
            assertEquals((byte) 0x85, b180.get(1));


            // Try writing 1, should truncate
            data = new byte[12];
            for (int i = 0; i < data.length; i++) {
                data[i] = (byte) (i + 9);
            }
            stream = new POIFSStream(ministore, 178);
            stream.updateContents(data);

            assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(178));
            assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(179));
            assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(180));

            stream = new POIFSStream(ministore, 178);
            it = stream.getBlockIterator();
            b178 = it.next();
            assertFalse(it.hasNext());

            assertEquals((byte) 0x09, b178.get(0));
            assertEquals((byte) 0x0a, b178.get(1));


            // Try writing 5, should extend
            assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(178));
            assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(179));
            assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(180));
            assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(181));
            assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(182));
            assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(183));

            data = new byte[64 * 4 + 12];
            for (int i = 0; i < data.length; i++) {
                data[i] = (byte) (i + 3);
            }
            stream = new POIFSStream(ministore, 178);
            stream.updateContents(data);

            assertEquals(179, ministore.getNextBlock(178));
            assertEquals(180, ministore.getNextBlock(179));
            assertEquals(181, ministore.getNextBlock(180));
            assertEquals(182, ministore.getNextBlock(181));
            assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(182));

            stream = new POIFSStream(ministore, 178);
            it = stream.getBlockIterator();
            b178 = it.next();
            b179 = it.next();
            b180 = it.next();
            ByteBuffer b181 = it.next();
            ByteBuffer b182 = it.next();
            assertFalse(it.hasNext());

            assertEquals((byte) 0x03, b178.get(0));
            assertEquals((byte) 0x04, b178.get(1));
            assertEquals((byte) 0x43, b179.get(0));
            assertEquals((byte) 0x44, b179.get(1));
            assertEquals((byte) 0x83, b180.get(0));
            assertEquals((byte) 0x84, b180.get(1));
            assertEquals((byte) 0xc3, b181.get(0));
            assertEquals((byte) 0xc4, b181.get(1));
            assertEquals((byte) 0x03, b182.get(0));
            assertEquals((byte) 0x04, b182.get(1));


            // Write lots, so it needs another big block
            ministore.getBlockAt(183);
            assertThrows(NoSuchElementException.class, () -> ministore.getBlockAt(184), "Block 184 should be off the end of the list");

            data = new byte[64 * 6 + 12];
            for (int i = 0; i < data.length; i++) {
                data[i] = (byte) (i + 1);
            }
            stream = new POIFSStream(ministore, 178);
            stream.updateContents(data);

            // Should have added 2 more blocks to the chain
            assertEquals(179, ministore.getNextBlock(178));
            assertEquals(180, ministore.getNextBlock(179));
            assertEquals(181, ministore.getNextBlock(180));
            assertEquals(182, ministore.getNextBlock(181));
            assertEquals(183, ministore.getNextBlock(182));
            assertEquals(184, ministore.getNextBlock(183));
            assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(184));
            assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(185));

            // Block 184 should exist
            ministore.getBlockAt(183);
            ministore.getBlockAt(184);
            ministore.getBlockAt(185);

            // Check contents
            stream = new POIFSStream(ministore, 178);
            it = stream.getBlockIterator();
            b178 = it.next();
            b179 = it.next();
            b180 = it.next();
            b181 = it.next();
            b182 = it.next();
            ByteBuffer b183 = it.next();
            ByteBuffer b184 = it.next();
            assertFalse(it.hasNext());

            assertEquals((byte) 0x01, b178.get(0));
            assertEquals((byte) 0x02, b178.get(1));
            assertEquals((byte) 0x41, b179.get(0));
            assertEquals((byte) 0x42, b179.get(1));
            assertEquals((byte) 0x81, b180.get(0));
            assertEquals((byte) 0x82, b180.get(1));
            assertEquals((byte) 0xc1, b181.get(0));
            assertEquals((byte) 0xc2, b181.get(1));
            assertEquals((byte) 0x01, b182.get(0));
            assertEquals((byte) 0x02, b182.get(1));
            assertEquals((byte) 0x41, b183.get(0));
            assertEquals((byte) 0x42, b183.get(1));
            assertEquals((byte) 0x81, b184.get(0));
            assertEquals((byte) 0x82, b184.get(1));

        }
    }

    /**
     * Craft a nasty file with a loop, and ensure we don't get stuck
     */
    @Test
    public void testWriteFailsOnLoop() throws Exception {
        try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) {

            // Hack the FAT so that it goes 0->1->2->0
            fs.setNextBlock(0, 1);
            fs.setNextBlock(1, 2);
            fs.setNextBlock(2, 0);

            // Try to write a large amount, should fail on the write
            POIFSStream stream1 = new POIFSStream(fs, 0);
            assertThrows(IllegalStateException.class,
                () -> stream1.updateContents(new byte[512 * 4]), "Loop should have been detected but wasn't!");

            // Now reset, and try on a small bit
            // Should fail during the freeing set
            fs.setNextBlock(0, 1);
            fs.setNextBlock(1, 2);
            fs.setNextBlock(2, 0);

            POIFSStream stream2 = new POIFSStream(fs, 0);
            assertThrows(IllegalStateException.class,
                () -> stream2.updateContents(new byte[512]), "Loop should have been detected but wasn't!");
        }
    }

    /**
     * Tests adding a new stream, writing and reading it.
     */
    @Test
    public void testReadWriteNewStream() throws Exception {
        try (POIFSFileSystem fs = new POIFSFileSystem()) {
            POIFSStream stream = new POIFSStream(fs);

            // Check our filesystem has Properties then BAT
            assertEquals(2, fs.getFreeBlock());
            BATBlock bat = fs.getBATBlockAndIndex(0).getBlock();
            assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
            assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
            assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2));

            // Check the stream as-is
            assertEquals(POIFSConstants.END_OF_CHAIN, stream.getStartBlock());
            assertThrows(IllegalStateException.class, stream::getBlockIterator,
                "Shouldn't be able to get an iterator before writing");

            // Write in two blocks
            byte[] data = new byte[512 + 20];
            for (int i = 0; i < 512; i++) {
                data[i] = (byte) (i % 256);
            }
            for (int i = 512; i < data.length; i++) {
                data[i] = (byte) (i % 256 + 100);
            }
            stream.updateContents(data);

            // Check now
            assertEquals(4, fs.getFreeBlock());
            bat = fs.getBATBlockAndIndex(0).getBlock();
            assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
            assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
            assertEquals(3, bat.getValueAt(2));
            assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3));
            assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(4));


            Iterator<ByteBuffer> it = stream.getBlockIterator();
            assertTrue(it.hasNext());
            ByteBuffer b = it.next();

            byte[] read = new byte[512];
            b.get(read);
            for (int i = 0; i < read.length; i++) {
                assertEquals(data[i], read[i], "Wrong value at " + i);
            }

            assertTrue(it.hasNext());
            b = it.next();

            read = new byte[512];
            b.get(read);
            for (int i = 0; i < 20; i++) {
                assertEquals(data[i + 512], read[i]);
            }
            for (int i = 20; i < read.length; i++) {
                assertEquals(0, read[i]);
            }

            assertFalse(it.hasNext());
        }
    }

    /**
     * Writes a stream, then replaces it
     */
    @Test
    public void testWriteThenReplace() throws Exception {
        POIFSFileSystem fs = new POIFSFileSystem();

        // Starts empty, other that Properties and BAT
        BATBlock bat = fs.getBATBlockAndIndex(0).getBlock();
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2));

        // Write something that uses a main stream
        byte[] main4106 = new byte[4106];
        main4106[0] = -10;
        main4106[4105] = -11;
        fs.getRoot().createDocument("Normal", new ByteArrayInputStream(main4106));

        // Should have used 9 blocks
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
        assertEquals(3, bat.getValueAt(2));
        assertEquals(4, bat.getValueAt(3));
        assertEquals(5, bat.getValueAt(4));
        assertEquals(6, bat.getValueAt(5));
        assertEquals(7, bat.getValueAt(6));
        assertEquals(8, bat.getValueAt(7));
        assertEquals(9, bat.getValueAt(8));
        assertEquals(10, bat.getValueAt(9));
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));

        DocumentEntry normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
        assertEquals(4106, normal.getSize());
        assertEquals(4106, ((DocumentNode) normal).getProperty().getSize());


        // Replace with one still big enough for a main stream, but one block smaller
        byte[] main4096 = new byte[4096];
        main4096[0] = -10;
        main4096[4095] = -11;

        DocumentOutputStream nout = new DocumentOutputStream(normal);
        nout.write(main4096);
        nout.close();

        // Will have dropped to 8
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
        assertEquals(3, bat.getValueAt(2));
        assertEquals(4, bat.getValueAt(3));
        assertEquals(5, bat.getValueAt(4));
        assertEquals(6, bat.getValueAt(5));
        assertEquals(7, bat.getValueAt(6));
        assertEquals(8, bat.getValueAt(7));
        assertEquals(9, bat.getValueAt(8));
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));

        normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
        assertEquals(4096, normal.getSize());
        assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());


        // Write and check
        fs = writeOutAndReadBack(fs);
        bat = fs.getBATBlockAndIndex(0).getBlock();

        // No change after write
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); // Properties
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
        assertEquals(3, bat.getValueAt(2));
        assertEquals(4, bat.getValueAt(3));
        assertEquals(5, bat.getValueAt(4));
        assertEquals(6, bat.getValueAt(5));
        assertEquals(7, bat.getValueAt(6));
        assertEquals(8, bat.getValueAt(7));
        assertEquals(9, bat.getValueAt(8));
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9)); // End of Normal
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));

        normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
        assertEquals(4096, normal.getSize());
        assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());


        // Make longer, take 1 block at the end
        normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
        nout = new DocumentOutputStream(normal);
        nout.write(main4106);
        nout.close();

        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
        assertEquals(3, bat.getValueAt(2));
        assertEquals(4, bat.getValueAt(3));
        assertEquals(5, bat.getValueAt(4));
        assertEquals(6, bat.getValueAt(5));
        assertEquals(7, bat.getValueAt(6));
        assertEquals(8, bat.getValueAt(7));
        assertEquals(9, bat.getValueAt(8));
        assertEquals(10, bat.getValueAt(9));
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10)); // Normal
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));

        normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
        assertEquals(4106, normal.getSize());
        assertEquals(4106, ((DocumentNode) normal).getProperty().getSize());


        // Make it small, will trigger the SBAT stream and free lots up
        byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42};
        normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
        nout = new DocumentOutputStream(normal);
        nout.write(mini);
        nout.close();

        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(4));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(5));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(6));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(7));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(8));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(9));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));

        normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
        assertEquals(7, normal.getSize());
        assertEquals(7, ((DocumentNode) normal).getProperty().getSize());


        // Finally back to big again
        nout = new DocumentOutputStream(normal);
        nout.write(main4096);
        nout.close();

        // Will keep the mini stream, now empty
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
        assertEquals(5, bat.getValueAt(4));
        assertEquals(6, bat.getValueAt(5));
        assertEquals(7, bat.getValueAt(6));
        assertEquals(8, bat.getValueAt(7));
        assertEquals(9, bat.getValueAt(8));
        assertEquals(10, bat.getValueAt(9));
        assertEquals(11, bat.getValueAt(10));
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13));

        normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
        assertEquals(4096, normal.getSize());
        assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());


        // Save, re-load, re-check
        fs = writeOutAndReadBack(fs);
        bat = fs.getBATBlockAndIndex(0).getBlock();

        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
        assertEquals(5, bat.getValueAt(4));
        assertEquals(6, bat.getValueAt(5));
        assertEquals(7, bat.getValueAt(6));
        assertEquals(8, bat.getValueAt(7));
        assertEquals(9, bat.getValueAt(8));
        assertEquals(10, bat.getValueAt(9));
        assertEquals(11, bat.getValueAt(10));
        assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
        assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13));

        normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
        assertEquals(4096, normal.getSize());
        assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());

        fs.close();
    }


    /**
     * Returns test files with 512 byte and 4k block sizes, loaded
     * both from InputStreams and Files
     */
    private POIFSFileSystem[] get512and4kFileAndInput() throws IOException {
        POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
        POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
        POIFSFileSystem fsC = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
        POIFSFileSystem fsD = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
        return new POIFSFileSystem[]{fsA, fsB, fsC, fsD};
    }

    private static void assertBATCount(POIFSFileSystem fs, int expectedBAT, int expectedXBAT) throws IOException {
        int foundBAT = 0;
        int foundXBAT = 0;
        int sz = (int) (fs.size() / fs.getBigBlockSize());
        for (int i = 0; i < sz; i++) {
            if (fs.getNextBlock(i) == POIFSConstants.FAT_SECTOR_BLOCK) {
                foundBAT++;
            }
            if (fs.getNextBlock(i) == POIFSConstants.DIFAT_SECTOR_BLOCK) {
                foundXBAT++;
            }
        }
        assertEquals(expectedBAT, foundBAT, "Wrong number of BATs");
        assertEquals(expectedXBAT, foundXBAT, "Wrong number of XBATs with " + expectedBAT + " BATs");
    }

    private void assertContentsMatches(byte[] expected, DocumentEntry doc) throws IOException {
        DocumentInputStream inp = new DocumentInputStream(doc);
        byte[] contents = new byte[doc.getSize()];
        assertEquals(doc.getSize(), inp.read(contents));
        inp.close();

        if (expected != null) {
            assertThat(expected, equalTo(contents));
        }
    }

    private static HeaderBlock writeOutAndReadHeader(POIFSFileSystem fs) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        fs.writeFilesystem(baos);

        return new HeaderBlock(new ByteArrayInputStream(baos.toByteArray()));
    }

    private static POIFSFileSystem writeOutAndReadBack(POIFSFileSystem original) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        original.writeFilesystem(baos);
        return new POIFSFileSystem(new ByteArrayInputStream(baos.toByteArray()));
    }

    private static POIFSFileSystem writeOutFileAndReadBack(POIFSFileSystem original) throws IOException {
        final File file = TempFile.createTempFile("TestPOIFS", ".ole2");
        try (OutputStream fout = new FileOutputStream(file)) {
            original.writeFilesystem(fout);
        }
        return new POIFSFileSystem(file, false);
    }

    @Test
    public void basicOpen() throws IOException {
        POIFSFileSystem fsA, fsB;

        // With a simple 512 block file
        fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
        fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
        for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
            assertEquals(512, fs.getBigBlockSize());
        }
        fsA.close();
        fsB.close();

        // Now with a simple 4096 block file
        fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
        fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
        for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
            assertEquals(4096, fs.getBigBlockSize());
        }
        fsA.close();
        fsB.close();
    }

    @Test
    public void propertiesAndFatOnRead() throws IOException {
        POIFSFileSystem fsA, fsB;

        // With a simple 512 block file
        fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
        fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
        for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
            // Check the FAT was properly processed:
            // Verify we only got one block
            fs.getBATBlockAndIndex(0);
            fs.getBATBlockAndIndex(1);
            assertThrows(IndexOutOfBoundsException.class, () -> fs.getBATBlockAndIndex(140),
                "Should only be one BAT, but a 2nd was found");

            // Verify a few next offsets
            // 97 -> 98 -> END
            assertEquals(98, fs.getNextBlock(97));
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98));


            // Check the properties
            PropertyTable props = fs._get_property_table();
            assertEquals(90, props.getStartBlock());
            assertEquals(7, props.countBlocks());

            // Root property tells us about the Mini Stream
            RootProperty root = props.getRoot();
            assertEquals("Root Entry", root.getName());
            assertEquals(11564, root.getSize());
            assertEquals(0, root.getStartBlock());

            // Check its children too
            Property prop;
            Iterator<Property> pi = root.getChildren();
            prop = pi.next();
            assertEquals("Thumbnail", prop.getName());
            prop = pi.next();
            assertEquals("\u0005DocumentSummaryInformation", prop.getName());
            prop = pi.next();
            assertEquals("\u0005SummaryInformation", prop.getName());
            prop = pi.next();
            assertEquals("Image", prop.getName());
            prop = pi.next();
            assertEquals("Tags", prop.getName());
            assertFalse(pi.hasNext());


            // Check the SBAT (Small Blocks FAT) was properly processed
            POIFSMiniStore ministore = fs.getMiniStore();

            // Verify we only got two SBAT blocks
            ministore.getBATBlockAndIndex(0);
            ministore.getBATBlockAndIndex(128);
            assertThrows(IndexOutOfBoundsException.class, () -> ministore.getBATBlockAndIndex(256),
                "Should only be two SBATs, but a 3rd was found");

            // Verify a few offsets: 0->50 is a stream
            for (int i = 0; i < 50; i++) {
                assertEquals(i + 1, ministore.getNextBlock(i));
            }
            assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50));

            fs.close();
        }

        // Now with a simple 4096 block file
        fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
        fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
        for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
            // Check the FAT was properly processed
            // Verify we only got one block
            fs.getBATBlockAndIndex(0);
            fs.getBATBlockAndIndex(1);
            assertThrows(IndexOutOfBoundsException.class, () -> fs.getBATBlockAndIndex(1040),
                "Should only be one BAT, but a 2nd was found");

            // Verify a few next offsets
            // 0 -> 1 -> 2 -> END
            assertEquals(1, fs.getNextBlock(0));
            assertEquals(2, fs.getNextBlock(1));
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2));


            // Check the properties
            PropertyTable props = fs._get_property_table();
            assertEquals(12, props.getStartBlock());
            assertEquals(1, props.countBlocks());

            // Root property tells us about the Mini Stream
            RootProperty root = props.getRoot();
            assertEquals("Root Entry", root.getName());
            assertEquals(11564, root.getSize());
            assertEquals(0, root.getStartBlock());

            // Check its children too
            Property prop;
            Iterator<Property> pi = root.getChildren();
            prop = pi.next();
            assertEquals("Thumbnail", prop.getName());
            prop = pi.next();
            assertEquals("\u0005DocumentSummaryInformation", prop.getName());
            prop = pi.next();
            assertEquals("\u0005SummaryInformation", prop.getName());
            prop = pi.next();
            assertEquals("Image", prop.getName());
            prop = pi.next();
            assertEquals("Tags", prop.getName());
            assertFalse(pi.hasNext());


            // Check the SBAT (Small Blocks FAT) was properly processed
            POIFSMiniStore ministore = fs.getMiniStore();

            // Verify we only got one SBAT block
            ministore.getBATBlockAndIndex(0);
            ministore.getBATBlockAndIndex(128);
            ministore.getBATBlockAndIndex(1023);
            assertThrows(IndexOutOfBoundsException.class, () -> ministore.getBATBlockAndIndex(1024),
                "Should only be one SBAT, but a 2nd was found");

            // Verify a few offsets: 0->50 is a stream
            for (int i = 0; i < 50; i++) {
                assertEquals(i + 1, ministore.getNextBlock(i));
            }
            assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50));

            fs.close();
        }
    }

    /**
     * Check that for a given block, we can correctly figure
     * out what the next one is
     */
    @Test
    public void nextBlock() throws IOException {
        POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
        POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
        for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
            // 0 -> 21 are simple
            for (int i = 0; i < 21; i++) {
                assertEquals(i + 1, fs.getNextBlock(i));
            }
            // 21 jumps to 89, then ends
            assertEquals(89, fs.getNextBlock(21));
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(89));

            // 22 -> 88 simple sequential stream
            for (int i = 22; i < 88; i++) {
                assertEquals(i + 1, fs.getNextBlock(i));
            }
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(88));

            // 90 -> 96 is another stream
            for (int i = 90; i < 96; i++) {
                assertEquals(i + 1, fs.getNextBlock(i));
            }
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(96));

            // 97+98 is another
            assertEquals(98, fs.getNextBlock(97));
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98));

            // 99 is our FAT block
            assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));

            // 100 onwards is free
            for (int i = 100; i < fs.getBigBlockSizeDetails().getBATEntriesPerBlock(); i++) {
                assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(i));
            }

            fs.close();
        }

        // Quick check on 4096 byte blocks too
        fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
        fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
        for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
            // 0 -> 1 -> 2 -> end
            assertEquals(1, fs.getNextBlock(0));
            assertEquals(2, fs.getNextBlock(1));
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2));

            // 4 -> 11 then end
            for (int i = 4; i < 11; i++) {
                assertEquals(i + 1, fs.getNextBlock(i));
            }
            assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(11));

            fs.close();
        }
    }

    /**
     * Check we get the right data back for each block
     */
    @Test
    public void getBlock() throws IOException {
        POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
        POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
        for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
            ByteBuffer b;

            // The 0th block is the first data block
            b = fs.getBlockAt(0);
            assertEquals((byte) 0x9e, b.get());
            assertEquals((byte) 0x75, b.get());
            assertEquals((byte) 0x97, b.get());
            assertEquals((byte) 0xf6, b.get());

            // And the next block
            b = fs.getBlockAt(1);
            assertEquals((byte) 0x86, b.get());
            assertEquals((byte) 0x09, b.get());
            assertEquals((byte) 0x22, b.get());
            assertEquals((byte) 0xfb, b.get());

            // Check the final block too
            b = fs.getBlockAt(99);
            assertEquals((byte) 0x01, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x02, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x00, b.get());

            fs.close();
        }

        // Quick check on 4096 byte blocks too
        fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
        fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
        for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
            ByteBuffer b;

            // The 0th block is the first data block
            b = fs.getBlockAt(0);
            assertEquals((byte) 0x9e, b.get());
            assertEquals((byte) 0x75, b.get());
            assertEquals((byte) 0x97, b.get());
            assertEquals((byte) 0xf6, b.get());

            // And the next block
            b = fs.getBlockAt(1);
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x03, b.get());
            assertEquals((byte) 0x00, b.get());

            // The 14th block is the FAT
            b = fs.getBlockAt(14);
            assertEquals((byte) 0x01, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x02, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x00, b.get());
            assertEquals((byte) 0x00, b.get());

            fs.close();
        }
    }

    /**
     * Ask for free blocks where there are some already
     * to be had from the FAT
     */
    @Test
    public void getFreeBlockWithSpare() throws IOException {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));

        // Our first BAT block has spares
        assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());

        // First free one is 100
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));

        // Ask, will get 100
        assertEquals(100, fs.getFreeBlock());

        // Ask again, will still get 100 as not written to
        assertEquals(100, fs.getFreeBlock());

        // Allocate it, then ask again
        fs.setNextBlock(100, POIFSConstants.END_OF_CHAIN);
        assertEquals(101, fs.getFreeBlock());

        // All done
        fs.close();
    }

    /**
     * Ask for free blocks where no free ones exist, and so the
     * file needs to be extended and another BAT/XBAT added
     */
    @Test
    public void getFreeBlockWithNoneSpare() throws IOException {
        POIFSFileSystem fs1 = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
        int free;

        // We have one BAT at block 99
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(99));
        assertBATCount(fs1, 1, 0);

        // We've spare ones from 100 to 128
        for (int i = 100; i < 128; i++) {
            assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(i));
        }

        // Check our BAT knows it's free
        assertTrue(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());

        // Allocate all the spare ones
        for (int i = 100; i < 128; i++) {
            fs1.setNextBlock(i, POIFSConstants.END_OF_CHAIN);
        }

        // BAT is now full, but there's only the one
        assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
        assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(128), "Should only be one BAT");
        assertBATCount(fs1, 1, 0);


        // Now ask for a free one, will need to extend the file
        assertEquals(129, fs1.getFreeBlock());

        assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
        assertTrue(fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(128));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(129));

        // We now have 2 BATs, but no XBATs
        assertBATCount(fs1, 2, 0);


        // Fill up to hold 109 BAT blocks
        for (int i = 0; i < 109; i++) {
            fs1.getFreeBlock();
            int startOffset = i * 128;
            while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) {
                free = fs1.getFreeBlock();
                fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN);
            }
        }

        assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors());
        assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(109 * 128), "Should only be 109 BATs");

        // We now have 109 BATs, but no XBATs
        assertBATCount(fs1, 109, 0);


        // Ask for it to be written out, and check the header
        HeaderBlock header = writeOutAndReadHeader(fs1);
        assertEquals(109, header.getBATCount());
        assertEquals(0, header.getXBATCount());


        // Ask for another, will get our first XBAT
        free = fs1.getFreeBlock();
        assertTrue(free > 0, "Had: " + free);

        assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors());
        assertTrue(fs1.getBATBlockAndIndex(110 * 128 - 1).getBlock().hasFreeSectors());
        assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(110 * 128), "Should only be 110 BATs");
        assertBATCount(fs1, 110, 1);

        header = writeOutAndReadHeader(fs1);
        assertEquals(110, header.getBATCount());
        assertEquals(1, header.getXBATCount());


        // Fill the XBAT, which means filling 127 BATs
        for (int i = 109; i < 109 + 127; i++) {
            fs1.getFreeBlock();
            int startOffset = i * 128;
            while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) {
                free = fs1.getFreeBlock();
                fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN);
            }
            assertBATCount(fs1, i + 1, 1);
        }

        // Should now have 109+127 = 236 BATs
        assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
        assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(236 * 128), "Should only be 236 BATs");
        assertBATCount(fs1, 236, 1);


        // Ask for another, will get our 2nd XBAT
        free = fs1.getFreeBlock();
        assertTrue(free > 0, "Had: " + free);

        assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
        assertTrue(fs1.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors());
        assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs");


        // Check the counts now
        assertBATCount(fs1, 237, 2);

        // Check the header
        header = writeOutAndReadHeader(fs1);
        assertNotNull(header);

        // Now, write it out, and read it back in again fully
        POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
        fs1.close();

        // Check that it is seen correctly
        assertBATCount(fs2, 237, 2);

        assertFalse(fs2.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
        assertTrue(fs2.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors());
        assertThrows(IndexOutOfBoundsException.class, () -> fs2.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs");

        // All done
        fs2.close();
    }

    /**
     * Test that we can correctly get the list of directory
     * entries, and the details on the files in them
     */
    @Test
    public void listEntries() throws IOException {
        for (POIFSFileSystem fs : get512and4kFileAndInput()) {
            DirectoryEntry root = fs.getRoot();
            assertEquals(5, root.getEntryCount());

            // Check by the names
            Entry thumbnail = root.getEntry("Thumbnail");
            Entry dsi = root.getEntry("\u0005DocumentSummaryInformation");
            Entry si = root.getEntry("\u0005SummaryInformation");
            Entry image = root.getEntry("Image");
            Entry tags = root.getEntry("Tags");

            assertFalse(thumbnail.isDirectoryEntry());
            assertFalse(dsi.isDirectoryEntry());
            assertFalse(si.isDirectoryEntry());
            assertTrue(image.isDirectoryEntry());
            assertFalse(tags.isDirectoryEntry());

            // Check via the iterator
            Iterator<Entry> it = root.getEntries();
            assertEquals(thumbnail.getName(), it.next().getName());
            assertEquals(dsi.getName(), it.next().getName());
            assertEquals(si.getName(), it.next().getName());
            assertEquals(image.getName(), it.next().getName());
            assertEquals(tags.getName(), it.next().getName());

            // Look inside another
            DirectoryEntry imageD = (DirectoryEntry) image;
            assertEquals(7, imageD.getEntryCount());

            fs.close();
        }
    }

    /**
     * Tests that we can get the correct contents for
     * a document in the filesystem
     */
    @Test
    public void getDocumentEntry() throws Exception {
        for (POIFSFileSystem fs : get512and4kFileAndInput()) {
            DirectoryEntry root = fs.getRoot();
            Entry si = root.getEntry("\u0005SummaryInformation");

            assertTrue(si.isDocumentEntry());
            DocumentNode doc = (DocumentNode) si;

            // Check we can read it
            assertContentsMatches(null, doc);

            // Now try to build the property set
            DocumentInputStream inp = new DocumentInputStream(doc);
            PropertySet ps = PropertySetFactory.create(inp);
            SummaryInformation inf = (SummaryInformation) ps;

            // Check some bits in it
            assertNull(inf.getApplicationName());
            assertNull(inf.getAuthor());
            assertNull(inf.getSubject());
            assertEquals(131333, inf.getOSVersion());

            // Finish with this one
            inp.close();


            // Try the other summary information
            si = root.getEntry("\u0005DocumentSummaryInformation");
            assertTrue(si.isDocumentEntry());
            doc = (DocumentNode) si;
            assertContentsMatches(null, doc);

            inp = new DocumentInputStream(doc);
            ps = PropertySetFactory.create(inp);
            DocumentSummaryInformation dinf = (DocumentSummaryInformation) ps;
            assertEquals(131333, dinf.getOSVersion());

            fs.close();
        }
    }

    /**
     * Read a file, write it and read it again.
     * Then, alter+add some streams, write and read
     */
    @Test
    public void readWriteRead() throws Exception {
        SummaryInformation sinf;
        DocumentSummaryInformation dinf;
        DirectoryEntry root, testDir;

        for (POIFSFileSystem fs1 : get512and4kFileAndInput()) {
            // Check we can find the entries we expect
            root = fs1.getRoot();
            assertEquals(5, root.getEntryCount());
            assertThat(root.getEntryNames(), hasItem("Thumbnail"));
            assertThat(root.getEntryNames(), hasItem("Image"));
            assertThat(root.getEntryNames(), hasItem("Tags"));
            assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
            assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));


            // Write out, re-load
            POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
            fs1.close();

            // Check they're still there
            root = fs2.getRoot();
            assertEquals(5, root.getEntryCount());
            assertThat(root.getEntryNames(), hasItem("Thumbnail"));
            assertThat(root.getEntryNames(), hasItem("Image"));
            assertThat(root.getEntryNames(), hasItem("Tags"));
            assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
            assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));


            // Check the contents of them - parse the summary block and check
            sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream(
                (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME)));
            assertEquals(131333, sinf.getOSVersion());

            dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream(
                (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)));
            assertEquals(131333, dinf.getOSVersion());


            // Add a test mini stream
            testDir = root.createDirectory("Testing 123");
            testDir.createDirectory("Testing 456");
            testDir.createDirectory("Testing 789");
            byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42};
            testDir.createDocument("Mini", new ByteArrayInputStream(mini));


            // Write out, re-load
            POIFSFileSystem fs3 = writeOutAndReadBack(fs2);
            fs2.close();

            root = fs3.getRoot();
            testDir = (DirectoryEntry) root.getEntry("Testing 123");
            assertEquals(6, root.getEntryCount());
            assertThat(root.getEntryNames(), hasItem("Thumbnail"));
            assertThat(root.getEntryNames(), hasItem("Image"));
            assertThat(root.getEntryNames(), hasItem("Tags"));
            assertThat(root.getEntryNames(), hasItem("Testing 123"));
            assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
            assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));


            // Check old and new are there
            sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream(
                (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME)));
            assertEquals(131333, sinf.getOSVersion());

            dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream(
                (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)));
            assertEquals(131333, dinf.getOSVersion());

            assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini"));


            // Write out and read once more, just to be sure
            POIFSFileSystem fs4 = writeOutAndReadBack(fs3);
            fs3.close();

            root = fs4.getRoot();
            testDir = (DirectoryEntry) root.getEntry("Testing 123");
            assertEquals(6, root.getEntryCount());
            assertThat(root.getEntryNames(), hasItem("Thumbnail"));
            assertThat(root.getEntryNames(), hasItem("Image"));
            assertThat(root.getEntryNames(), hasItem("Tags"));
            assertThat(root.getEntryNames(), hasItem("Testing 123"));
            assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
            assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));

            sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream(
                (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME)));
            assertEquals(131333, sinf.getOSVersion());

            dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream(
                (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)));
            assertEquals(131333, dinf.getOSVersion());

            assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini"));


            // Add a full stream, delete a full stream
            byte[] main4096 = new byte[4096];
            main4096[0] = -10;
            main4096[4095] = -11;
            testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096));

            root.getEntry("Tags").delete();


            // Write out, re-load
            POIFSFileSystem fs5 = writeOutAndReadBack(fs4);
            fs4.close();

            // Check it's all there
            root = fs5.getRoot();
            testDir = (DirectoryEntry) root.getEntry("Testing 123");
            assertEquals(5, root.getEntryCount());
            assertThat(root.getEntryNames(), hasItem("Thumbnail"));
            assertThat(root.getEntryNames(), hasItem("Image"));
            assertThat(root.getEntryNames(), hasItem("Testing 123"));
            assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
            assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));


            // Check old and new are there
            sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream(
                (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME)));
            assertEquals(131333, sinf.getOSVersion());

            dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream(
                (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)));
            assertEquals(131333, dinf.getOSVersion());

            assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini"));
            assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096"));


            // Delete a directory, and add one more
            testDir.getEntry("Testing 456").delete();
            testDir.createDirectory("Testing ABC");


            // Save
            POIFSFileSystem fs6 = writeOutAndReadBack(fs5);
            fs5.close();

            // Check
            root = fs6.getRoot();
            testDir = (DirectoryEntry) root.getEntry("Testing 123");

            assertEquals(5, root.getEntryCount());
            assertThat(root.getEntryNames(), hasItem("Thumbnail"));
            assertThat(root.getEntryNames(), hasItem("Image"));
            assertThat(root.getEntryNames(), hasItem("Testing 123"));
            assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
            assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));

            assertEquals(4, testDir.getEntryCount());
            assertThat(testDir.getEntryNames(), hasItem("Mini"));
            assertThat(testDir.getEntryNames(), hasItem("Normal4096"));
            assertThat(testDir.getEntryNames(), hasItem("Testing 789"));
            assertThat(testDir.getEntryNames(), hasItem("Testing ABC"));


            // Add another mini stream
            byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42};
            testDir.createDocument("Mini2", new ByteArrayInputStream(mini2));

            // Save, load, check
            POIFSFileSystem fs7 = writeOutAndReadBack(fs6);
            fs6.close();

            root = fs7.getRoot();
            testDir = (DirectoryEntry) root.getEntry("Testing 123");

            assertEquals(5, root.getEntryCount());
            assertThat(root.getEntryNames(), hasItem("Thumbnail"));
            assertThat(root.getEntryNames(), hasItem("Image"));
            assertThat(root.getEntryNames(), hasItem("Testing 123"));
            assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
            assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));

            assertEquals(5, testDir.getEntryCount());
            assertThat(testDir.getEntryNames(), hasItem("Mini"));
            assertThat(testDir.getEntryNames(), hasItem("Mini2"));
            assertThat(testDir.getEntryNames(), hasItem("Normal4096"));
            assertThat(testDir.getEntryNames(), hasItem("Testing 789"));
            assertThat(testDir.getEntryNames(), hasItem("Testing ABC"));

            assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini"));
            assertContentsMatches(mini2, (DocumentEntry) testDir.getEntry("Mini2"));
            assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096"));


            // Delete a mini stream, add one more
            testDir.getEntry("Mini").delete();

            byte[] mini3 = new byte[]{42, 0, 42, 0, 42, 0, 42};
            testDir.createDocument("Mini3", new ByteArrayInputStream(mini3));


            // Save, load, check
            POIFSFileSystem fs8 = writeOutAndReadBack(fs7);
            fs7.close();

            root = fs8.getRoot();
            testDir = (DirectoryEntry) root.getEntry("Testing 123");

            assertEquals(5, root.getEntryCount());
            assertThat(root.getEntryNames(), hasItem("Thumbnail"));
            assertThat(root.getEntryNames(), hasItem("Image"));
            assertThat(root.getEntryNames(), hasItem("Testing 123"));
            assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
            assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));

            assertEquals(5, testDir.getEntryCount());
            assertThat(testDir.getEntryNames(), hasItem("Mini2"));
            assertThat(testDir.getEntryNames(), hasItem("Mini3"));
            assertThat(testDir.getEntryNames(), hasItem("Normal4096"));
            assertThat(testDir.getEntryNames(), hasItem("Testing 789"));
            assertThat(testDir.getEntryNames(), hasItem("Testing ABC"));

            assertContentsMatches(mini2, (DocumentEntry) testDir.getEntry("Mini2"));
            assertContentsMatches(mini3, (DocumentEntry) testDir.getEntry("Mini3"));
            assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096"));


            // Change some existing streams
            POIFSDocument mini2Doc = new POIFSDocument((DocumentNode) testDir.getEntry("Mini2"));
            mini2Doc.replaceContents(new ByteArrayInputStream(mini));

            byte[] main4106 = new byte[4106];
            main4106[0] = 41;
            main4106[4105] = 42;
            POIFSDocument mainDoc = new POIFSDocument((DocumentNode) testDir.getEntry("Normal4096"));
            mainDoc.replaceContents(new ByteArrayInputStream(main4106));


            // Re-check
            POIFSFileSystem fs9 = writeOutAndReadBack(fs8);
            fs8.close();

            root = fs9.getRoot();
            testDir = (DirectoryEntry) root.getEntry("Testing 123");

            assertEquals(5, root.getEntryCount());
            assertThat(root.getEntryNames(), hasItem("Thumbnail"));
            assertThat(root.getEntryNames(), hasItem("Image"));
            assertThat(root.getEntryNames(), hasItem("Testing 123"));
            assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
            assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));

            assertEquals(5, testDir.getEntryCount());
            assertThat(testDir.getEntryNames(), hasItem("Mini2"));
            assertThat(testDir.getEntryNames(), hasItem("Mini3"));
            assertThat(testDir.getEntryNames(), hasItem("Normal4096"));
            assertThat(testDir.getEntryNames(), hasItem("Testing 789"));
            assertThat(testDir.getEntryNames(), hasItem("Testing ABC"));

            assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini2"));
            assertContentsMatches(mini3, (DocumentEntry) testDir.getEntry("Mini3"));
            assertContentsMatches(main4106, (DocumentEntry) testDir.getEntry("Normal4096"));


            // All done
            fs9.close();
        }
    }

    /**
     * Create a new file, write it and read it again
     * Then, add some streams, write and read
     */
    @Test
    public void createWriteRead() throws IOException {
        POIFSFileSystem fs1 = new POIFSFileSystem();
        DocumentEntry miniDoc;
        DocumentEntry normDoc;

        // Initially has Properties + BAT but not SBAT
        assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2));

        // Check that the SBAT is empty
        assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getRoot().getProperty().getStartBlock());

        // Check that properties table was given block 0
        assertEquals(0, fs1._get_property_table().getStartBlock());

        // Write and read it
        POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
        fs1.close();

        // No change, SBAT remains empty
        assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(2));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(3));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getRoot().getProperty().getStartBlock());
        assertEquals(0, fs2._get_property_table().getStartBlock());
        fs2.close();

        // Check the same but with saving to a file
        POIFSFileSystem fs3 = new POIFSFileSystem();
        POIFSFileSystem fs4 = writeOutFileAndReadBack(fs3);
        fs3.close();

        // Same, no change, SBAT remains empty
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(2));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(3));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock());
        assertEquals(0, fs4._get_property_table().getStartBlock());


        // Put everything within a new directory
        DirectoryEntry testDir = fs4.createDirectory("Test Directory");

        // Add a new Normal Stream (Normal Streams minimum 4096 bytes)
        byte[] main4096 = new byte[4096];
        main4096[0] = -10;
        main4096[4095] = -11;
        testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096));

        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
        assertEquals(3, fs4.getNextBlock(2));
        assertEquals(4, fs4.getNextBlock(3));
        assertEquals(5, fs4.getNextBlock(4));
        assertEquals(6, fs4.getNextBlock(5));
        assertEquals(7, fs4.getNextBlock(6));
        assertEquals(8, fs4.getNextBlock(7));
        assertEquals(9, fs4.getNextBlock(8));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(10));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(11));
        // SBAT still unused
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock());


        // Add a bigger Normal Stream
        byte[] main5124 = new byte[5124];
        main5124[0] = -22;
        main5124[5123] = -33;
        testDir.createDocument("Normal5124", new ByteArrayInputStream(main5124));

        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
        assertEquals(3, fs4.getNextBlock(2));
        assertEquals(4, fs4.getNextBlock(3));
        assertEquals(5, fs4.getNextBlock(4));
        assertEquals(6, fs4.getNextBlock(5));
        assertEquals(7, fs4.getNextBlock(6));
        assertEquals(8, fs4.getNextBlock(7));
        assertEquals(9, fs4.getNextBlock(8));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9));

        assertEquals(11, fs4.getNextBlock(10));
        assertEquals(12, fs4.getNextBlock(11));
        assertEquals(13, fs4.getNextBlock(12));
        assertEquals(14, fs4.getNextBlock(13));
        assertEquals(15, fs4.getNextBlock(14));
        assertEquals(16, fs4.getNextBlock(15));
        assertEquals(17, fs4.getNextBlock(16));
        assertEquals(18, fs4.getNextBlock(17));
        assertEquals(19, fs4.getNextBlock(18));
        assertEquals(20, fs4.getNextBlock(19));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(21));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(22));

        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock());


        // Now Add a mini stream
        byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42};
        testDir.createDocument("Mini", new ByteArrayInputStream(mini));

        // Mini stream will get one block for fat + one block for data
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
        assertEquals(3, fs4.getNextBlock(2));
        assertEquals(4, fs4.getNextBlock(3));
        assertEquals(5, fs4.getNextBlock(4));
        assertEquals(6, fs4.getNextBlock(5));
        assertEquals(7, fs4.getNextBlock(6));
        assertEquals(8, fs4.getNextBlock(7));
        assertEquals(9, fs4.getNextBlock(8));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9));

        assertEquals(11, fs4.getNextBlock(10));
        assertEquals(12, fs4.getNextBlock(11));
        assertEquals(13, fs4.getNextBlock(12));
        assertEquals(14, fs4.getNextBlock(13));
        assertEquals(15, fs4.getNextBlock(14));
        assertEquals(16, fs4.getNextBlock(15));
        assertEquals(17, fs4.getNextBlock(16));
        assertEquals(18, fs4.getNextBlock(17));
        assertEquals(19, fs4.getNextBlock(18));
        assertEquals(20, fs4.getNextBlock(19));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(21));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(22));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(23));

        // Check the mini stream location was set
        // (21 is mini fat, 22 is first mini stream block)
        assertEquals(22, fs4.getRoot().getProperty().getStartBlock());


        // Write and read back
        POIFSFileSystem fs5 = writeOutAndReadBack(fs4);
        fs4.close();
        HeaderBlock header = writeOutAndReadHeader(fs5);

        // Check the header has the right points in it
        assertEquals(1, header.getBATCount());
        assertEquals(1, header.getBATArray()[0]);
        assertEquals(0, header.getPropertyStart());
        assertEquals(1, header.getSBATCount());
        assertEquals(21, header.getSBATStart());
        assertEquals(22, fs5._get_property_table().getRoot().getStartBlock());

        // Block use should be almost the same, except the properties
        //  stream will have grown out to cover 2 blocks
        // Check the block use is all unchanged
        assertEquals(23, fs5.getNextBlock(0)); // Properties now extends over 2 blocks
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs5.getNextBlock(1));

        assertEquals(3, fs5.getNextBlock(2));
        assertEquals(4, fs5.getNextBlock(3));
        assertEquals(5, fs5.getNextBlock(4));
        assertEquals(6, fs5.getNextBlock(5));
        assertEquals(7, fs5.getNextBlock(6));
        assertEquals(8, fs5.getNextBlock(7));
        assertEquals(9, fs5.getNextBlock(8));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(9)); // End of normal4096

        assertEquals(11, fs5.getNextBlock(10));
        assertEquals(12, fs5.getNextBlock(11));
        assertEquals(13, fs5.getNextBlock(12));
        assertEquals(14, fs5.getNextBlock(13));
        assertEquals(15, fs5.getNextBlock(14));
        assertEquals(16, fs5.getNextBlock(15));
        assertEquals(17, fs5.getNextBlock(16));
        assertEquals(18, fs5.getNextBlock(17));
        assertEquals(19, fs5.getNextBlock(18));
        assertEquals(20, fs5.getNextBlock(19));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(20)); // End of normal5124

        assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(21)); // Mini Stream FAT
        assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(22)); // Mini Stream data
        assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(23)); // Properties #2
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs5.getNextBlock(24));


        // Check some data
        assertEquals(1, fs5.getRoot().getEntryCount());
        testDir = (DirectoryEntry) fs5.getRoot().getEntry("Test Directory");
        assertEquals(3, testDir.getEntryCount());

        miniDoc = (DocumentEntry) testDir.getEntry("Mini");
        assertContentsMatches(mini, miniDoc);

        normDoc = (DocumentEntry) testDir.getEntry("Normal4096");
        assertContentsMatches(main4096, normDoc);

        normDoc = (DocumentEntry) testDir.getEntry("Normal5124");
        assertContentsMatches(main5124, normDoc);


        // Delete a couple of streams
        miniDoc.delete();
        normDoc.delete();


        // Check - will have un-used sectors now
        POIFSFileSystem fs6 = writeOutAndReadBack(fs5);
        fs5.close();

        assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(0)); // Props back in 1 block
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs6.getNextBlock(1));

        assertEquals(3, fs6.getNextBlock(2));
        assertEquals(4, fs6.getNextBlock(3));
        assertEquals(5, fs6.getNextBlock(4));
        assertEquals(6, fs6.getNextBlock(5));
        assertEquals(7, fs6.getNextBlock(6));
        assertEquals(8, fs6.getNextBlock(7));
        assertEquals(9, fs6.getNextBlock(8));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(9)); // End of normal4096

        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(10));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(11));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(12));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(13));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(14));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(15));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(16));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(17));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(18));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(19));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(20));

        assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(21)); // Mini Stream FAT
        assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(22)); // Mini Stream data
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(23)); // Properties gone
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(24));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(25));

        // All done
        fs6.close();
    }

    @Test
    public void addBeforeWrite() throws IOException {
        POIFSFileSystem fs1 = new POIFSFileSystem();
        DocumentEntry miniDoc;
        DocumentEntry normDoc;
        HeaderBlock hdr;

        // Initially has Properties + BAT but nothing else
        assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2));

        hdr = writeOutAndReadHeader(fs1);
        // No mini stream, and no xbats
        // Will have fat then properties stream
        assertEquals(1, hdr.getBATCount());
        assertEquals(1, hdr.getBATArray()[0]);
        assertEquals(0, hdr.getPropertyStart());
        assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getSBATStart());
        assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex());
        assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 3, fs1.size());
        fs1.close();

        // Get a clean filesystem to start with
        fs1 = new POIFSFileSystem();

        // Put our test files in a non-standard place
        DirectoryEntry parentDir = fs1.createDirectory("Parent Directory");
        DirectoryEntry testDir = parentDir.createDirectory("Test Directory");


        // Add to the mini stream
        byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42};
        testDir.createDocument("Mini", new ByteArrayInputStream(mini));

        // Add to the main stream
        byte[] main4096 = new byte[4096];
        main4096[0] = -10;
        main4096[4095] = -11;
        testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096));


        // Check the mini stream was added, then the main stream
        assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0));
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(2)); // Mini Fat
        assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(3)); // Mini Stream
        assertEquals(5, fs1.getNextBlock(4)); // Main Stream
        assertEquals(6, fs1.getNextBlock(5));
        assertEquals(7, fs1.getNextBlock(6));
        assertEquals(8, fs1.getNextBlock(7));
        assertEquals(9, fs1.getNextBlock(8));
        assertEquals(10, fs1.getNextBlock(9));
        assertEquals(11, fs1.getNextBlock(10));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(11));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(12));
        assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 13, fs1.size());


        // Check that we can read the right data pre-write
        miniDoc = (DocumentEntry) testDir.getEntry("Mini");
        assertContentsMatches(mini, miniDoc);

        normDoc = (DocumentEntry) testDir.getEntry("Normal4096");
        assertContentsMatches(main4096, normDoc);


        // Write, read, check
        hdr = writeOutAndReadHeader(fs1);
        POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
        fs1.close();

        // Check the header details - will have the sbat near the start,
        //  then the properties at the end
        assertEquals(1, hdr.getBATCount());
        assertEquals(1, hdr.getBATArray()[0]);
        assertEquals(2, hdr.getSBATStart());
        assertEquals(0, hdr.getPropertyStart());
        assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex());

        // Check the block allocation is unchanged, other than
        //  the properties stream going in at the end
        assertEquals(12, fs2.getNextBlock(0)); // Properties
        assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(2));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(3));
        assertEquals(5, fs2.getNextBlock(4));
        assertEquals(6, fs2.getNextBlock(5));
        assertEquals(7, fs2.getNextBlock(6));
        assertEquals(8, fs2.getNextBlock(7));
        assertEquals(9, fs2.getNextBlock(8));
        assertEquals(10, fs2.getNextBlock(9));
        assertEquals(11, fs2.getNextBlock(10));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(11));
        assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(12));
        assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(13));
        assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 14, fs2.size());


        // Check the data
        DirectoryEntry fsRoot = fs2.getRoot();
        assertEquals(1, fsRoot.getEntryCount());

        parentDir = (DirectoryEntry) fsRoot.getEntry("Parent Directory");
        assertEquals(1, parentDir.getEntryCount());

        testDir = (DirectoryEntry) parentDir.getEntry("Test Directory");
        assertEquals(2, testDir.getEntryCount());

        miniDoc = (DocumentEntry) testDir.getEntry("Mini");
        assertContentsMatches(mini, miniDoc);

        normDoc = (DocumentEntry) testDir.getEntry("Normal4096");
        assertContentsMatches(main4096, normDoc);


        // Add one more stream to each, then save and re-load
        byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42};
        testDir.createDocument("Mini2", new ByteArrayInputStream(mini2));

        // Add to the main stream
        byte[] main4106 = new byte[4106];
        main4106[0] = 41;
        main4106[4105] = 42;
        testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106));


        // Recheck the data in all 4 streams
        POIFSFileSystem fs3 = writeOutAndReadBack(fs2);
        fs2.close();

        fsRoot = fs3.getRoot();
        assertEquals(1, fsRoot.getEntryCount());

        parentDir = (DirectoryEntry) fsRoot.getEntry("Parent Directory");
        assertEquals(1, parentDir.getEntryCount());

        testDir = (DirectoryEntry) parentDir.getEntry("Test Directory");
        assertEquals(4, testDir.getEntryCount());

        miniDoc = (DocumentEntry) testDir.getEntry("Mini");
        assertContentsMatches(mini, miniDoc);

        miniDoc = (DocumentEntry) testDir.getEntry("Mini2");
        assertContentsMatches(mini2, miniDoc);

        normDoc = (DocumentEntry) testDir.getEntry("Normal4106");
        assertContentsMatches(main4106, normDoc);

        // All done
        fs3.close();
    }

    @Test
    public void readZeroLengthEntries() throws IOException {
        POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("only-zero-byte-streams.ole2"));
        DirectoryNode testDir = fs.getRoot();
        assertEquals(3, testDir.getEntryCount());
        DocumentEntry entry;

        entry = (DocumentEntry) testDir.getEntry("test-zero-1");
        assertNotNull(entry);
        assertEquals(0, entry.getSize());

        entry = (DocumentEntry) testDir.getEntry("test-zero-2");
        assertNotNull(entry);
        assertEquals(0, entry.getSize());

        entry = (DocumentEntry) testDir.getEntry("test-zero-3");
        assertNotNull(entry);
        assertEquals(0, entry.getSize());

        // Check properties, all have zero length, no blocks
        PropertyTable props = fs._get_property_table();
        assertEquals(POIFSConstants.END_OF_CHAIN, props.getRoot().getStartBlock());
        for (Property prop : props.getRoot()) {
            assertEquals("test-zero-", prop.getName().substring(0, 10));
            assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock());
        }

        // All done
        fs.close();
    }

    @Test
    public void writeZeroLengthEntries() throws IOException {
        POIFSFileSystem fs1 = new POIFSFileSystem();
        DirectoryNode testDir = fs1.getRoot();
        DocumentEntry miniDoc;
        DocumentEntry normDoc;
        DocumentEntry emptyDoc;

        // Add mini and normal sized entries to start
        byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42};
        testDir.createDocument("Mini2", new ByteArrayInputStream(mini2));

        // Add to the main stream
        byte[] main4106 = new byte[4106];
        main4106[0] = 41;
        main4106[4105] = 42;
        testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106));

        // Now add some empty ones
        byte[] empty = new byte[0];
        testDir.createDocument("empty-1", new ByteArrayInputStream(empty));
        testDir.createDocument("empty-2", new ByteArrayInputStream(empty));
        testDir.createDocument("empty-3", new ByteArrayInputStream(empty));

        // Check
        miniDoc = (DocumentEntry) testDir.getEntry("Mini2");
        assertContentsMatches(mini2, miniDoc);

        normDoc = (DocumentEntry) testDir.getEntry("Normal4106");
        assertContentsMatches(main4106, normDoc);

        emptyDoc = (DocumentEntry) testDir.getEntry("empty-1");
        assertContentsMatches(empty, emptyDoc);

        emptyDoc = (DocumentEntry) testDir.getEntry("empty-2");
        assertContentsMatches(empty, emptyDoc);

        emptyDoc = (DocumentEntry) testDir.getEntry("empty-3");
        assertContentsMatches(empty, emptyDoc);

        // Look at the properties entry, and check the empty ones
        //  have zero size and no start block
        PropertyTable props = fs1._get_property_table();
        Iterator<Property> propsIt = props.getRoot().getChildren();

        Property prop = propsIt.next();
        assertEquals("Mini2", prop.getName());
        assertEquals(0, prop.getStartBlock());
        assertEquals(7, prop.getSize());

        prop = propsIt.next();
        assertEquals("Normal4106", prop.getName());
        assertEquals(4, prop.getStartBlock()); // BAT, Props, SBAT, MIni
        assertEquals(4106, prop.getSize());

        prop = propsIt.next();
        assertEquals("empty-1", prop.getName());
        assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock());
        assertEquals(0, prop.getSize());

        prop = propsIt.next();
        assertEquals("empty-2", prop.getName());
        assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock());
        assertEquals(0, prop.getSize());

        prop = propsIt.next();
        assertEquals("empty-3", prop.getName());
        assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock());
        assertEquals(0, prop.getSize());


        // Save and re-check
        POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
        fs1.close();
        testDir = fs2.getRoot();

        miniDoc = (DocumentEntry) testDir.getEntry("Mini2");
        assertContentsMatches(mini2, miniDoc);

        normDoc = (DocumentEntry) testDir.getEntry("Normal4106");
        assertContentsMatches(main4106, normDoc);

        emptyDoc = (DocumentEntry) testDir.getEntry("empty-1");
        assertContentsMatches(empty, emptyDoc);

        emptyDoc = (DocumentEntry) testDir.getEntry("empty-2");
        assertContentsMatches(empty, emptyDoc);

        emptyDoc = (DocumentEntry) testDir.getEntry("empty-3");
        assertContentsMatches(empty, emptyDoc);

        // Check that a mini-stream was assigned, with one block used
        assertEquals(3, testDir.getProperty().getStartBlock());
        assertEquals(64, testDir.getProperty().getSize());

        // All done
        fs2.close();
    }

    /**
     * Test that we can read a file with POIFS, create a new POIFS instance,
     * write it out, read it with POIFS, and see the original data
     */
    @Test
    public void POIFSReadCopyWritePOIFSRead() throws IOException {
        File testFile = POIDataSamples.getSpreadSheetInstance().getFile("Simple.xls");
        POIFSFileSystem src = new POIFSFileSystem(testFile);
        byte[] wbDataExp = IOUtils.toByteArray(src.createDocumentInputStream("Workbook"));

        POIFSFileSystem nfs = new POIFSFileSystem();
        EntryUtils.copyNodes(src.getRoot(), nfs.getRoot());
        src.close();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        nfs.writeFilesystem(bos);
        nfs.close();

        POIFSFileSystem pfs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
        byte[] wbDataAct = IOUtils.toByteArray(pfs.createDocumentInputStream("Workbook"));

        assertThat(wbDataExp, equalTo(wbDataAct));
        pfs.close();
    }

    /**
     * Ensure that you can recursively delete directories and their
     * contents
     */
    @Test
    public void RecursiveDelete() throws IOException {
        File testFile = POIDataSamples.getSpreadSheetInstance().getFile("SimpleMacro.xls");
        POIFSFileSystem src = new POIFSFileSystem(testFile);

        // Starts out with 5 entries:
        //  _VBA_PROJECT_CUR
        //  SummaryInformation <(0x05)SummaryInformation>
        //  DocumentSummaryInformation <(0x05)DocumentSummaryInformation>
        //  Workbook
        //  CompObj <(0x01)CompObj>
        assertEquals(5, _countChildren(src._get_property_table().getRoot()));
        assertEquals(5, src.getRoot().getEntryCount());

        // Grab the VBA project root
        DirectoryEntry vbaProj = (DirectoryEntry) src.getRoot().getEntry("_VBA_PROJECT_CUR");
        assertEquals(3, vbaProj.getEntryCount());
        // Can't delete yet, has stuff
        assertFalse(vbaProj.delete());
        // Recursively delete
        _recursiveDeletee(vbaProj);

        // Entries gone
        assertEquals(4, _countChildren(src._get_property_table().getRoot()));
        assertEquals(4, src.getRoot().getEntryCount());

        // Done
        src.close();
    }

    private void _recursiveDeletee(Entry entry) throws IOException {
        if (entry.isDocumentEntry()) {
            assertTrue(entry.delete());
            return;
        }

        DirectoryEntry dir = (DirectoryEntry) entry;
        String[] names = dir.getEntryNames().toArray(new String[dir.getEntryCount()]);
        for (String name : names) {
            Entry ce = dir.getEntry(name);
            _recursiveDeletee(ce);
        }
        assertTrue(dir.delete());
    }

    @SuppressWarnings("unused")
    private int _countChildren(DirectoryProperty p) {
        int count = 0;
        for (Property cp : p) {
            count++;
        }
        return count;
    }

    /**
     * To ensure we can create a file >2gb in size, as well as to
     * extend existing files past the 2gb boundary.
     * <p>
     * Note that to run this test, you will require 2.5+gb of free
     * space on your TMP/TEMP partition/disk
     * <p>
     * Note that to run this test, you need to be able to mmap 2.5+gb
     * files, which may need bigger kernel.shmmax and vm.max_map_count
     * settings on Linux.
     * <p>
     * TODO Fix this to work...
     */
    @Test
    @Disabled("Work in progress test for #60670")
    public void creationAndExtensionPast2GB() throws Exception {
        File big = TempFile.createTempFile("poi-test-", ".ole2");
        assumeTrue(big.getFreeSpace() > 2.5 * 1024 * 1024 * 1024,
            "2.5gb of free space is required on your tmp/temp partition/disk to run large file tests");
        System.out.println("Slow, memory heavy test in progress....");

        int s100mb = 100 * 1024 * 1024;
        int s512mb = 512 * 1024 * 1024;
        long s2gb = 2L * 1024 * 1024 * 1024;
        DocumentEntry entry;
        POIFSFileSystem fs;

        // Create a just-sub 2gb file
        fs = POIFSFileSystem.create(big);
        for (int i = 0; i < 19; i++) {
            fs.createDocument(new DummyDataInputStream(s100mb), "Entry" + i);
        }
        fs.writeFilesystem();
        fs.close();

        // Extend it past the 2gb mark
        fs = new POIFSFileSystem(big, false);
        for (int i = 0; i < 19; i++) {
            entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i);
            assertNotNull(entry);
            assertEquals(s100mb, entry.getSize());
        }

        fs.createDocument(new DummyDataInputStream(s512mb), "Bigger");
        fs.writeFilesystem();
        fs.close();

        // Check it still works
        fs = new POIFSFileSystem(big, false);
        for (int i = 0; i < 19; i++) {
            entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i);
            assertNotNull(entry);
            assertEquals(s100mb, entry.getSize());
        }
        entry = (DocumentEntry) fs.getRoot().getEntry("Bigger");
        assertNotNull(entry);
        assertEquals(s512mb, entry.getSize());

        // Tidy
        fs.close();
        assertTrue(big.delete());


        // Create a >2gb file
        fs = POIFSFileSystem.create(big);
        for (int i = 0; i < 4; i++) {
            fs.createDocument(new DummyDataInputStream(s512mb), "Entry" + i);
        }
        fs.writeFilesystem();
        fs.close();

        // Read it
        fs = new POIFSFileSystem(big, false);
        for (int i = 0; i < 4; i++) {
            entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i);
            assertNotNull(entry);
            assertEquals(s512mb, entry.getSize());
        }

        // Extend it
        fs.createDocument(new DummyDataInputStream(s512mb), "Entry4");
        fs.writeFilesystem();
        fs.close();

        // Check it worked
        fs = new POIFSFileSystem(big, false);
        for (int i = 0; i < 5; i++) {
            entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i);
            assertNotNull(entry);
            assertEquals(s512mb, entry.getSize());
        }

        // Tidy
        fs.close();
        assertTrue(big.delete());

        // Create a file with a 2gb entry
        fs = POIFSFileSystem.create(big);
        fs.createDocument(new DummyDataInputStream(s100mb), "Small");
        // TODO Check we get a helpful error about the max size
        fs.createDocument(new DummyDataInputStream(s2gb), "Big");
    }

    private static final class DummyDataInputStream extends InputStream {
        private final long maxSize;
        private long size;

        private DummyDataInputStream(long maxSize) {
            this.maxSize = maxSize;
            this.size = 0;
        }

        public int read() {
            if (size >= maxSize) return -1;
            size++;
            return (int) (size % 128);
        }

        public int read(byte[] b) {
            return read(b, 0, b.length);
        }

        public int read(byte[] b, int offset, int len) {
            if (size >= maxSize) return -1;
            int sz = (int) Math.min(len, maxSize - size);
            for (int i = 0; i < sz; i++) {
                b[i + offset] = (byte) ((size + i) % 128);
            }
            size += sz;
            return sz;
        }
    }

    @Disabled("Takes a long time to run")
    @Test
    public void performance() throws Exception {
        int iterations = 200;//1_000;

        System.out.println("NPOI:");
        long start = System.currentTimeMillis();

        for (int i = 0; i < iterations; i++) {

            try (InputStream inputStream = POIDataSamples.getHSMFInstance().openResourceAsStream("lots-of-recipients.msg");
                 POIFSFileSystem srcFileSystem = new POIFSFileSystem(inputStream);
                 POIFSFileSystem destFileSystem = new POIFSFileSystem()) {

                copyAllEntries(srcFileSystem.getRoot(), destFileSystem.getRoot());

                File file = File.createTempFile("npoi", ".dat");
                try (OutputStream outputStream = new FileOutputStream(file)) {
                    destFileSystem.writeFilesystem(outputStream);
                }

                assertTrue(file.delete());
                if (i % 10 == 0) System.out.print(".");
            }
        }

        System.out.println();
        System.out.println("NPOI took: " + (System.currentTimeMillis() - start));

        System.out.println();
        System.out.println();
    }

    private static void copyAllEntries(DirectoryEntry srcDirectory, DirectoryEntry destDirectory) throws IOException {
        Iterator<Entry> iterator = srcDirectory.getEntries();

        while (iterator.hasNext()) {
            Entry entry = iterator.next();

            if (entry.isDirectoryEntry()) {
                DirectoryEntry childDest = destDirectory.createDirectory(entry.getName());
                copyAllEntries((DirectoryEntry) entry, childDest);

            } else {
                DocumentEntry srcEntry = (DocumentEntry) entry;

                try (InputStream inputStream = new DocumentInputStream(srcEntry)) {
                    destDirectory.createDocument(entry.getName(), inputStream);
                }
            }
        }
    }

}