summaryrefslogtreecommitdiff
path: root/sw/source/filter/ww8/ww8par.cxx
blob: 3b9c9c54231c2ad6ebbc1519df35f6bd05affdde (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
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include <config_features.h>

#include <sal/config.h>

#include <com/sun/star/embed/ElementModes.hpp>

#include <i18nlangtag/languagetag.hxx>

#include <unotools/configmgr.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <rtl/random.h>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>

#include <sfx2/docinf.hxx>
#include <sfx2/request.hxx>
#include <sfx2/frame.hxx>
#include <tools/urlobj.hxx>
#include <unotools/tempfile.hxx>

#include <comphelper/docpasswordrequest.hxx>
#include <comphelper/string.hxx>

#include <editeng/brushitem.hxx>
#include <editeng/tstpitem.hxx>
#include <editeng/ulspitem.hxx>
#include <editeng/langitem.hxx>
#include <editeng/opaqitem.hxx>
#include <editeng/charhiddenitem.hxx>
#include <editeng/fontitem.hxx>
#include <svx/unoapi.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdoashp.hxx>
#include <svx/svxerr.hxx>
#include <filter/msfilter/mscodec.hxx>
#include <svx/svdmodel.hxx>
#include <svx/xflclit.hxx>

#include <unotools/fltrcfg.hxx>
#include <fmtfld.hxx>
#include <fmturl.hxx>
#include <fmtinfmt.hxx>
#include <reffld.hxx>
#include <fmthdft.hxx>
#include <fmtcntnt.hxx>
#include <fmtcnct.hxx>
#include <fmtanchr.hxx>
#include <fmtpdsc.hxx>
#include <ftninfo.hxx>
#include <fmtftn.hxx>
#include <txtftn.hxx>
#include <ndtxt.hxx>
#include <pagedesc.hxx>
#include <paratr.hxx>
#include <fmtclbl.hxx>
#include <section.hxx>
#include <docsh.hxx>
#include <IDocumentFieldsAccess.hxx>
#include <IDocumentLayoutAccess.hxx>
#include <IDocumentStylePoolAccess.hxx>
#include <IDocumentExternalData.hxx>
#include <docufld.hxx>
#include <swfltopt.hxx>
#include <viewsh.hxx>
#include <viewopt.hxx>
#include <shellres.hxx>
#include <mdiexp.hxx>
#include <statstr.hrc>
#include <swerror.h>
#include <swtable.hxx>
#include <fchrfmt.hxx>
#include <charfmt.hxx>
#include <unocrsr.hxx>
#include <IDocumentSettingAccess.hxx>

#include <fltini.hxx>

#include "writerwordglue.hxx"

#include "ndgrf.hxx"
#include <editeng/editids.hrc>
#include <txtflcnt.hxx>
#include <fmtflcnt.hxx>
#include <txatbase.hxx>

#include "ww8par2.hxx"

#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
#include <com/sun/star/document/XViewDataSupplier.hpp>
#include <com/sun/star/document/IndexedPropertyValues.hpp>
#include <svl/itemiter.hxx>

#include <comphelper/processfactory.hxx>
#include <basic/basmgr.hxx>

#include "ww8toolbar.hxx"
#include <osl/file.hxx>

#include <breakit.hxx>

#if OSL_DEBUG_LEVEL > 1
#include <iostream>
#include <dbgoutsw.hxx>
#endif

#include <svx/hlnkitem.hxx>
#include "swdll.hxx"
#include "WW8Sttbf.hxx"
#include "WW8FibData.hxx"
#include <unordered_set>
#include <memory>

using namespace ::com::sun::star;
using namespace sw::util;
using namespace sw::types;
using namespace nsHdFtFlags;

#include <com/sun/star/i18n/ScriptType.hpp>
#include <unotools/pathoptions.hxx>
#include <com/sun/star/ucb/SimpleFileAccess.hpp>

#include <com/sun/star/script/vba/XVBACompatibility.hpp>
#include <comphelper/sequenceashashmap.hxx>
#include <oox/ole/vbaproject.hxx>
#include <oox/ole/olestorage.hxx>
#include <comphelper/storagehelper.hxx>
#include <sfx2/DocumentMetadataAccess.hxx>

//#define VT_EMPTY            0
//#define VT_I4               3
//#define VT_LPSTR            30
//#define VT_LPWSTR           31
//#define VT_BLOB             65
//#define VT_TYPEMASK         0xFFF
/** Expands to a pointer after the last element of a STATIC data array (like STL end()). */
//#define STATIC_TABLE_END( array )   ((array)+STATIC_TABLE_SIZE(array))
/** Expands to the size of a STATIC data array. */
//#define STATIC_TABLE_SIZE( array )  (sizeof(array)/sizeof(*(array)))

SwMacroInfo* GetMacroInfo( SdrObject* pObj, bool bCreate )             // static
{
    if ( pObj )
    {
        sal_uInt16 nCount = pObj->GetUserDataCount();
        for( sal_uInt16 i = 0; i < nCount; i++ )
        {
            SdrObjUserData* pData = pObj->GetUserData( i );
            if( pData && pData->GetInventor() == SdrInventor::ScOrSwDraw
                && pData->GetId() == SW_UD_IMAPDATA)
            {
                return dynamic_cast<SwMacroInfo*>(pData);
            }
        }
        if ( bCreate )
        {
            SwMacroInfo* pData = new SwMacroInfo;
            pObj->AppendUserData(pData);
            return pData;
        }
    }

    return nullptr;
};

void lclGetAbsPath(OUString& rPath, sal_uInt16 nLevel, SwDocShell* pDocShell)
{
    OUString aTmpStr;
    while( nLevel )
    {
        aTmpStr += "../";
        --nLevel;
    }
    if (!aTmpStr.isEmpty())
        aTmpStr += rPath;
    else
        aTmpStr = rPath;

    if (!aTmpStr.isEmpty())
    {
        bool bWasAbs = false;
        rPath = pDocShell->GetMedium()->GetURLObject().smartRel2Abs( aTmpStr, bWasAbs ).GetMainURL( INetURLObject::DecodeMechanism::NONE );
        // full path as stored in SvxURLField must be encoded
    }
}

namespace
{
    void lclIgnoreString32(SvStream& rStrm, bool b16Bit)
    {
        sal_uInt32 nChars(0);
        rStrm.ReadUInt32(nChars);
        if (b16Bit)
            nChars *= 2;
        rStrm.SeekRel(nChars);
    }
}

void SwWW8ImplReader::ReadEmbeddedData(SvStream& rStrm, SwDocShell* pDocShell, struct HyperLinksTable& hlStr)
{
    // (0x01B8) HLINK
    // const sal_uInt16 WW8_ID_HLINK               = 0x01B8;
    const sal_uInt32 WW8_HLINK_BODY             = 0x00000001;   /// Contains file link or URL.
    const sal_uInt32 WW8_HLINK_ABS              = 0x00000002;   /// Absolute path.
    const sal_uInt32 WW8_HLINK_DESCR            = 0x00000014;   /// Description.
    const sal_uInt32 WW8_HLINK_MARK             = 0x00000008;   /// Text mark.
    const sal_uInt32 WW8_HLINK_FRAME            = 0x00000080;   /// Target frame.
    const sal_uInt32 WW8_HLINK_UNC              = 0x00000100;   /// UNC path.

    //sal_uInt8 maGuidStdLink[ 16 ] ={
    //    0xD0, 0xC9, 0xEA, 0x79, 0xF9, 0xBA, 0xCE, 0x11, 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9, 0x0B };

    sal_uInt8 aGuidUrlMoniker[ 16 ] = {
        0xE0, 0xC9, 0xEA, 0x79, 0xF9, 0xBA, 0xCE, 0x11, 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9, 0x0B };

    sal_uInt8 aGuidFileMoniker[ 16 ] = {
        0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 };

    sal_uInt8 aGuid[16];
    sal_uInt32 nFlags(0);

    rStrm.ReadBytes(aGuid, 16);
    rStrm.SeekRel( 4 );
    rStrm.ReadUInt32( nFlags );

    sal_uInt16 nLevel = 0;                  // counter for level to climb down in path
    std::unique_ptr< OUString > xLongName;    // link / file name
    std::unique_ptr< OUString > xShortName;   // 8.3-representation of file name
    std::unique_ptr< OUString > xTextMark;    // text mark

    // description (ignore)
    if( ::get_flag( nFlags, WW8_HLINK_DESCR ) )
        lclIgnoreString32( rStrm, true );

    // target frame
    if( ::get_flag( nFlags, WW8_HLINK_FRAME ) )
    {
        hlStr.tarFrame = read_uInt32_lenPrefixed_uInt16s_ToOUString(rStrm);
    }

        // UNC path
    if( ::get_flag( nFlags, WW8_HLINK_UNC ) )
    {
        xLongName.reset(new OUString(read_uInt32_lenPrefixed_uInt16s_ToOUString(rStrm)));
        lclGetAbsPath( *xLongName, 0 , pDocShell);
    }
    // file link or URL
    else if( ::get_flag( nFlags, WW8_HLINK_BODY ) )
    {
        rStrm.ReadBytes(aGuid, 16);

        if( (memcmp(aGuid, aGuidFileMoniker, 16) == 0) )
        {
            rStrm.ReadUInt16( nLevel );
            xShortName.reset(new OUString(read_uInt32_lenPrefixed_uInt8s_ToOUString(rStrm, GetCharSetFromLanguage())));
            rStrm.SeekRel( 24 );

            sal_uInt32 nStrLen(0);
            rStrm.ReadUInt32( nStrLen );
            if( nStrLen )
            {
                nStrLen = 0;
                rStrm.ReadUInt32( nStrLen );
                nStrLen /= 2;
                rStrm.SeekRel( 2 );
                xLongName.reset(new OUString(read_uInt32_lenPrefixed_uInt16s_ToOUString(rStrm)));
                lclGetAbsPath( *xLongName, nLevel, pDocShell);
            }
            else
                lclGetAbsPath( *xShortName, nLevel, pDocShell);
        }
        else if( (memcmp(aGuid, aGuidUrlMoniker, 16) == 0) )
        {
            sal_uInt32 nStrLen(0);
            rStrm.ReadUInt32( nStrLen );
            nStrLen /= 2;
            xLongName.reset(new OUString(read_uInt32_lenPrefixed_uInt16s_ToOUString(rStrm)));
            if( !::get_flag( nFlags, WW8_HLINK_ABS ) )
                lclGetAbsPath( *xLongName, 0 ,pDocShell);
        }
        else
        {
            SAL_INFO("sw.ww8", "WW8Hyperlink::ReadEmbeddedData - unknown content GUID");
        }
    }

    // text mark
    if( ::get_flag( nFlags, WW8_HLINK_MARK ) )
    {
        xTextMark.reset(new OUString(read_uInt32_lenPrefixed_uInt16s_ToOUString(rStrm)));
    }

    if( !xLongName.get() && xShortName.get() )
    {
        xLongName.reset( new OUString );
        *xLongName = xLongName->concat(*xShortName);
    }
    else if( !xLongName.get() && xTextMark.get() )
        xLongName.reset( new OUString );

    if( xLongName.get() )
    {
        if( xTextMark.get() )
        {
            if (xLongName->isEmpty())
                *xTextMark = xTextMark->replace('!', '.');
            *xLongName = xLongName->concat("#");
            *xLongName = xLongName->concat(*xTextMark);
        }
        hlStr.hLinkAddr = *xLongName;
    }
}

class BasicProjImportHelper
{
    SwDocShell& mrDocShell;
    uno::Reference< uno::XComponentContext > mxCtx;
public:
    explicit BasicProjImportHelper( SwDocShell& rShell ) : mrDocShell( rShell )
    {
        mxCtx = comphelper::getProcessComponentContext();
    }
    bool import( const uno::Reference< io::XInputStream >& rxIn );
    OUString getProjectName();
};

bool BasicProjImportHelper::import( const uno::Reference< io::XInputStream >& rxIn )
{
    bool bRet = false;
    try
    {
        oox::ole::OleStorage root( mxCtx, rxIn, false );
        oox::StorageRef vbaStg = root.openSubStorage( "Macros" , false );
        if ( vbaStg.get() )
        {
            oox::ole::VbaProject aVbaPrj( mxCtx, mrDocShell.GetModel(), "Writer" );
            bRet = aVbaPrj.importVbaProject( *vbaStg );
        }
    }
    catch( const uno::Exception& )
    {
        bRet = false;
    }
    return bRet;
}

OUString BasicProjImportHelper::getProjectName()
{
    OUString sProjName( "Standard" );
    uno::Reference< beans::XPropertySet > xProps( mrDocShell.GetModel(), uno::UNO_QUERY );
    if ( xProps.is() )
    {
        try
        {
            uno::Reference< script::vba::XVBACompatibility > xVBA( xProps->getPropertyValue( "BasicLibraries" ), uno::UNO_QUERY_THROW  );
            sProjName = xVBA->getProjectName();

        }
        catch( const uno::Exception& )
        {
        }
    }
    return sProjName;
}

class Sttb : public TBBase
{
struct SBBItem
{
    sal_uInt16 cchData;
    OUString data;
    SBBItem() : cchData(0){}
};
    sal_uInt16 fExtend;
    sal_uInt16 cData;
    sal_uInt16 cbExtra;

    std::vector< SBBItem > dataItems;

    Sttb(Sttb const&) = delete;
    Sttb& operator=(Sttb const&) = delete;

public:
    Sttb();

    bool Read(SvStream &rS) override;
#if OSL_DEBUG_LEVEL > 1
    virtual void Print( FILE* fp ) override;
#endif
    OUString getStringAtIndex( sal_uInt32 );
};

Sttb::Sttb()
    : fExtend(0)
    , cData(0)
    , cbExtra(0)
{
}

bool Sttb::Read( SvStream& rS )
{
    SAL_INFO("sw.ww8", "stream pos " << rS.Tell());
    nOffSet = rS.Tell();
    rS.ReadUInt16( fExtend ).ReadUInt16( cData ).ReadUInt16( cbExtra );
    if ( cData )
    {
        //if they are all going to be empty strings, how many could there be
        const size_t nMaxPossibleRecords = rS.remainingSize() / sizeof(sal_uInt16);
        if (cData > nMaxPossibleRecords)
            return false;
        for ( sal_Int32 index = 0; index < cData; ++index )
        {
            SBBItem aItem;
            rS.ReadUInt16( aItem.cchData );
            aItem.data = read_uInt16s_ToOUString(rS, aItem.cchData);
            dataItems.push_back( aItem );
        }
    }
    return true;
}

#if OSL_DEBUG_LEVEL > 1
void Sttb::Print( FILE* fp )
{
    fprintf( fp, "[ 0x%" SAL_PRIxUINT32 " ] Sttb - dump\n", nOffSet);
    fprintf( fp, " fExtend 0x%x [expected 0xFFFF ]\n", fExtend );
    fprintf( fp, " cData no. or string data items %d (0x%x)\n", cData, cData );

    if ( cData )
    {
        for (sal_uInt16 index = 0; index < cData; ++index)
        {
            if (index >= dataItems.size())
            {
                fprintf(fp, "   Sttb truncated at entry %d(0x%x)\n", static_cast< int >( index ), static_cast< unsigned int >( index ));
                break;
            }
            fprintf(fp,"   string dataItem[ %d(0x%x) ] has name %s\n", static_cast< int >( index ), static_cast< unsigned int >( index ), OUStringToOString( dataItems[ index ].data, RTL_TEXTENCODING_UTF8 ).getStr() );
        }
    }
}
#endif

OUString
Sttb::getStringAtIndex( sal_uInt32 index )
{
    OUString aRet;
    if ( index < dataItems.size() )
        aRet = dataItems[ index ].data;
    return aRet;

}

SwMSDffManager::SwMSDffManager( SwWW8ImplReader& rRdr, bool bSkipImages )
    : SvxMSDffManager(*rRdr.m_pTableStream, rRdr.GetBaseURL(), rRdr.m_pWwFib->m_fcDggInfo,
        rRdr.m_pDataStream, nullptr, 0, COL_WHITE, rRdr.m_pStrm, bSkipImages),
    rReader(rRdr), pFallbackStream(nullptr)
{
    SetSvxMSDffSettings( GetSvxMSDffSettings() );
    nSvxMSDffOLEConvFlags = SwMSDffManager::GetFilterFlags();
}

sal_uInt32 SwMSDffManager::GetFilterFlags()
{
    sal_uInt32 nFlags(0);
    const SvtFilterOptions& rOpt = SvtFilterOptions::Get();
    if (rOpt.IsMathType2Math())
        nFlags |= OLE_MATHTYPE_2_STARMATH;
    if (rOpt.IsExcel2Calc())
        nFlags |= OLE_EXCEL_2_STARCALC;
    if (rOpt.IsPowerPoint2Impress())
        nFlags |= OLE_POWERPOINT_2_STARIMPRESS;
    if (rOpt.IsWinWord2Writer())
        nFlags |= OLE_WINWORD_2_STARWRITER;
    return nFlags;
}

/*
 * I would like to override the default OLE importing to add a test
 * and conversion of OCX controls from their native OLE type into our
 * native nonOLE Form Control Objects.
 */
// #i32596# - consider new parameter <_nCalledByGroup>
SdrObject* SwMSDffManager::ImportOLE( sal_uInt32 nOLEId,
                                      const Graphic& rGrf,
                                      const tools::Rectangle& rBoundRect,
                                      const tools::Rectangle& rVisArea,
                                      const int _nCalledByGroup,
                                      sal_Int64 nAspect ) const
{
    // #i32596# - no import of OLE object, if it's inside a group.
    // NOTE: This can be undone, if grouping of Writer fly frames is possible or
    // if drawing OLE objects are allowed in Writer.
    if ( _nCalledByGroup > 0 )
    {
        return nullptr;
    }

    SdrObject* pRet = nullptr;
    OUString sStorageName;
    tools::SvRef<SotStorage> xSrcStg;
    uno::Reference < embed::XStorage > xDstStg;
    if( GetOLEStorageName( nOLEId, sStorageName, xSrcStg, xDstStg ))
    {
        tools::SvRef<SotStorage> xSrc = xSrcStg->OpenSotStorage( sStorageName );
        OSL_ENSURE(rReader.m_pFormImpl, "No Form Implementation!");
        css::uno::Reference< css::drawing::XShape > xShape;
        if ( (!(rReader.m_bIsHeader || rReader.m_bIsFooter)) &&
            rReader.m_pFormImpl->ReadOCXStream(xSrc,&xShape,true))
        {
            pRet = GetSdrObjectFromXShape(xShape);
        }
        else
        {
            ErrCode nError = ERRCODE_NONE;
            pRet = CreateSdrOLEFromStorage( sStorageName, xSrcStg, xDstStg,
                rGrf, rBoundRect, rVisArea, pStData, nError,
                nSvxMSDffOLEConvFlags, nAspect, rReader.GetBaseURL());
        }
    }
    return pRet;
}

void SwMSDffManager::DisableFallbackStream()
{
    OSL_ENSURE(!pFallbackStream,
        "if you're recursive, you're broken");
    pFallbackStream = pStData2;
    aOldEscherBlipCache = aEscherBlipCache;
    aEscherBlipCache.clear();
    pStData2 = nullptr;
}

void SwMSDffManager::EnableFallbackStream()
{
    pStData2 = pFallbackStream;
    aEscherBlipCache = aOldEscherBlipCache;
    aOldEscherBlipCache.clear();
    pFallbackStream = nullptr;
}

sal_uInt16 SwWW8ImplReader::GetToggleAttrFlags() const
{
    return m_pCtrlStck ? m_pCtrlStck->GetToggleAttrFlags() : 0;
}

sal_uInt16 SwWW8ImplReader::GetToggleBiDiAttrFlags() const
{
    return m_pCtrlStck ? m_pCtrlStck->GetToggleBiDiAttrFlags() : 0;
}

void SwWW8ImplReader::SetToggleAttrFlags(sal_uInt16 nFlags)
{
    if (m_pCtrlStck)
        m_pCtrlStck->SetToggleAttrFlags(nFlags);
}

void SwWW8ImplReader::SetToggleBiDiAttrFlags(sal_uInt16 nFlags)
{
    if (m_pCtrlStck)
        m_pCtrlStck->SetToggleBiDiAttrFlags(nFlags);
}

SdrObject* SwMSDffManager::ProcessObj(SvStream& rSt,
                                       DffObjData& rObjData,
                                       void* pData,
                                       tools::Rectangle& rTextRect,
                                       SdrObject* pObj
                                       )
{
    if( !rTextRect.IsEmpty() )
    {
        SvxMSDffImportData& rImportData = *static_cast<SvxMSDffImportData*>(pData);
        SvxMSDffImportRec* pImpRec = new SvxMSDffImportRec;

        // fill Import Record with data
        pImpRec->nShapeId   = rObjData.nShapeId;
        pImpRec->eShapeType = rObjData.eShapeType;

        rObjData.bClientAnchor = maShapeRecords.SeekToContent( rSt,
                                            DFF_msofbtClientAnchor,
                                            SEEK_FROM_CURRENT_AND_RESTART );
        if( rObjData.bClientAnchor )
            ProcessClientAnchor( rSt,
                    maShapeRecords.Current()->nRecLen,
                    pImpRec->pClientAnchorBuffer, pImpRec->nClientAnchorLen );

        rObjData.bClientData = maShapeRecords.SeekToContent( rSt,
                                            DFF_msofbtClientData,
                                            SEEK_FROM_CURRENT_AND_RESTART );
        if( rObjData.bClientData )
            ProcessClientData( rSt,
                    maShapeRecords.Current()->nRecLen,
                    pImpRec->pClientDataBuffer, pImpRec->nClientDataLen );

        // process user (== Winword) defined parameters in 0xF122 record
        // #i84783# - set special value to determine, if property is provided or not.
        pImpRec->nLayoutInTableCell = 0xFFFFFFFF;

        if(    maShapeRecords.SeekToContent( rSt,
                                             DFF_msofbtUDefProp,
                                             SEEK_FROM_CURRENT_AND_RESTART )
            && maShapeRecords.Current()->nRecLen )
        {
            sal_uInt32 nBytesLeft = maShapeRecords.Current()->nRecLen;
            auto nAvailableBytes = rSt.remainingSize();
            if (nBytesLeft > nAvailableBytes)
            {
                SAL_WARN("sw.ww8", "Document claimed to have shape record of " << nBytesLeft << " bytes, but only " << nAvailableBytes << " available");
                nBytesLeft = nAvailableBytes;
            }
            while( 5 < nBytesLeft )
            {
                sal_uInt16 nPID(0);
                rSt.ReadUInt16(nPID);
                sal_uInt32 nUDData(0);
                rSt.ReadUInt32(nUDData);
                if (!rSt.good())
                    break;
                switch (nPID)
                {
                    case 0x038F: pImpRec->nXAlign = nUDData; break;
                    case 0x0390:
                        delete pImpRec->pXRelTo;
                        pImpRec->pXRelTo = new sal_uInt32;
                        *(pImpRec->pXRelTo) = nUDData;
                        break;
                    case 0x0391: pImpRec->nYAlign = nUDData; break;
                    case 0x0392:
                        delete pImpRec->pYRelTo;
                        pImpRec->pYRelTo = new sal_uInt32;
                        *(pImpRec->pYRelTo) = nUDData;
                        break;
                    case 0x03BF: pImpRec->nLayoutInTableCell = nUDData; break;
                    case 0x0393:
                    // This seems to correspond to o:hrpct from .docx (even including
                    // the difference that it's in 0.1% even though the .docx spec
                    // says it's in 1%).
                        pImpRec->relativeHorizontalWidth = nUDData;
                        break;
                    case 0x0394:
                    // And this is really just a guess, but a mere presence of this
                    // flag makes a horizontal rule be as wide as the page (unless
                    // overridden by something), so it probably matches o:hr from .docx.
                        pImpRec->isHorizontalRule = true;
                        break;
                }
                nBytesLeft  -= 6;
            }
        }

        // Text Frame also Title or Outline
        sal_uInt32 nTextId = GetPropertyValue( DFF_Prop_lTxid, 0 );
        if( nTextId )
        {
            SfxItemSet aSet( pSdrModel->GetItemPool() );

            // Originally anything that as a mso_sptTextBox was created as a
            // textbox, this was changed to be created as a simple
            // rect to keep impress happy. For the rest of us we'd like to turn
            // it back into a textbox again.
            bool bIsSimpleDrawingTextBox = (pImpRec->eShapeType == mso_sptTextBox);
            if (!bIsSimpleDrawingTextBox)
            {
                // Either
                // a) it's a simple text object or
                // b) it's a rectangle with text and square wrapping.
                bIsSimpleDrawingTextBox =
                (
                    (pImpRec->eShapeType == mso_sptTextSimple) ||
                    (
                        (pImpRec->eShapeType == mso_sptRectangle)
                        && ShapeHasText(pImpRec->nShapeId, rObjData.rSpHd.GetRecBegFilePos() )
                    )
                );
            }

            // Distance of Textbox to its surrounding Autoshape
            sal_Int32 nTextLeft = GetPropertyValue( DFF_Prop_dxTextLeft, 91440L);
            sal_Int32 nTextRight = GetPropertyValue( DFF_Prop_dxTextRight, 91440L );
            sal_Int32 nTextTop = GetPropertyValue( DFF_Prop_dyTextTop, 45720L  );
            sal_Int32 nTextBottom = GetPropertyValue( DFF_Prop_dyTextBottom, 45720L );

            ScaleEmu( nTextLeft );
            ScaleEmu( nTextRight );
            ScaleEmu( nTextTop );
            ScaleEmu( nTextBottom );

            sal_Int32 nTextRotationAngle=0;
            bool bVerticalText = false;
            if ( IsProperty( DFF_Prop_txflTextFlow ) )
            {
                MSO_TextFlow eTextFlow = (MSO_TextFlow)(GetPropertyValue(
                    DFF_Prop_txflTextFlow, 0) & 0xFFFF);
                switch( eTextFlow )
                {
                    case mso_txflBtoT:
                        nTextRotationAngle = 9000;
                    break;
                    case mso_txflVertN:
                    case mso_txflTtoBN:
                        nTextRotationAngle = 27000;
                        break;
                    case mso_txflTtoBA:
                        bVerticalText = true;
                    break;
                    case mso_txflHorzA:
                        bVerticalText = true;
                        nTextRotationAngle = 9000;
                    break;
                    case mso_txflHorzN:
                    default :
                        break;
                }
            }

            if (nTextRotationAngle)
            {
                if (nTextRotationAngle == 9000)
                {
                    long nWidth = rTextRect.GetWidth();
                    rTextRect.Right() = rTextRect.Left() + rTextRect.GetHeight();
                    rTextRect.Bottom() = rTextRect.Top() + nWidth;

                    sal_Int32 nOldTextLeft = nTextLeft;
                    sal_Int32 nOldTextRight = nTextRight;
                    sal_Int32 nOldTextTop = nTextTop;
                    sal_Int32 nOldTextBottom = nTextBottom;

                    nTextLeft = nOldTextBottom;
                    nTextRight = nOldTextTop;
                    nTextTop = nOldTextLeft;
                    nTextBottom = nOldTextRight;
                }
                else if (nTextRotationAngle == 27000)
                {
                    long nWidth = rTextRect.GetWidth();
                    rTextRect.Right() = rTextRect.Left() + rTextRect.GetHeight();
                    rTextRect.Bottom() = rTextRect.Top() + nWidth;

                    sal_Int32 nOldTextLeft = nTextLeft;
                    sal_Int32 nOldTextRight = nTextRight;
                    sal_Int32 nOldTextTop = nTextTop;
                    sal_Int32 nOldTextBottom = nTextBottom;

                    nTextLeft = nOldTextTop;
                    nTextRight = nOldTextBottom;
                    nTextTop = nOldTextRight;
                    nTextBottom = nOldTextLeft;
                }
            }

            if (bIsSimpleDrawingTextBox)
            {
                SdrObject::Free( pObj );
                pObj = new SdrRectObj(OBJ_TEXT, rTextRect);
            }

            // The vertical paragraph justification are contained within the
            // BoundRect so calculate it here
            tools::Rectangle aNewRect(rTextRect);
            aNewRect.Bottom() -= nTextTop + nTextBottom;
            aNewRect.Right() -= nTextLeft + nTextRight;

            // Only if it's a simple Textbox, Writer can replace the Object
            // with a Frame, else
            if( bIsSimpleDrawingTextBox )
            {
                std::shared_ptr<SvxMSDffShapeInfo> const xTmpRec(
                        new SvxMSDffShapeInfo(0, pImpRec->nShapeId));

                SvxMSDffShapeInfos_ById::const_iterator const it =
                    GetShapeInfos()->find(xTmpRec);
                if (it != GetShapeInfos()->end())
                {
                    SvxMSDffShapeInfo& rInfo = **it;
                    pImpRec->bReplaceByFly   = rInfo.bReplaceByFly;
                }
            }

            if( bIsSimpleDrawingTextBox )
                ApplyAttributes( rSt, aSet, rObjData );

            if (GetPropertyValue(DFF_Prop_FitTextToShape, 0) & 2)
            {
                aSet.Put( makeSdrTextAutoGrowHeightItem( true ) );
                aSet.Put( makeSdrTextMinFrameHeightItem(
                    aNewRect.Bottom() - aNewRect.Top() ) );
                aSet.Put( makeSdrTextMinFrameWidthItem(
                    aNewRect.Right() - aNewRect.Left() ) );
            }
            else
            {
                aSet.Put( makeSdrTextAutoGrowHeightItem( false ) );
                aSet.Put( makeSdrTextAutoGrowWidthItem( false ) );
            }

            switch ( (MSO_WrapMode)
                GetPropertyValue( DFF_Prop_WrapText, mso_wrapSquare ) )
            {
                case mso_wrapNone :
                    aSet.Put( makeSdrTextAutoGrowWidthItem( true ) );
                    pImpRec->bAutoWidth = true;
                break;
                case mso_wrapByPoints :
                    aSet.Put( makeSdrTextContourFrameItem( true ) );
                break;
                default:
                    ;
            }

            // Set distances on Textbox's margins
            aSet.Put( makeSdrTextLeftDistItem( nTextLeft ) );
            aSet.Put( makeSdrTextRightDistItem( nTextRight ) );
            aSet.Put( makeSdrTextUpperDistItem( nTextTop ) );
            aSet.Put( makeSdrTextLowerDistItem( nTextBottom ) );
            pImpRec->nDxTextLeft    = nTextLeft;
            pImpRec->nDyTextTop     = nTextTop;
            pImpRec->nDxTextRight   = nTextRight;
            pImpRec->nDyTextBottom  = nTextBottom;

            // Taking the correct default (which is mso_anchorTop)
            sal_uInt32 eTextAnchor =
                GetPropertyValue( DFF_Prop_anchorText, mso_anchorTop );

            SdrTextVertAdjust eTVA = bVerticalText
                                     ? SDRTEXTVERTADJUST_BLOCK
                                     : SDRTEXTVERTADJUST_CENTER;
            SdrTextHorzAdjust eTHA = bVerticalText
                                     ? SDRTEXTHORZADJUST_CENTER
                                     : SDRTEXTHORZADJUST_BLOCK;

            switch( eTextAnchor )
            {
                case mso_anchorTop:
                {
                    if ( bVerticalText )
                        eTHA = SDRTEXTHORZADJUST_RIGHT;
                    else
                        eTVA = SDRTEXTVERTADJUST_TOP;
                }
                break;
                case mso_anchorTopCentered:
                {
                    if ( bVerticalText )
                        eTHA = SDRTEXTHORZADJUST_RIGHT;
                    else
                        eTVA = SDRTEXTVERTADJUST_TOP;
                }
                break;
                case mso_anchorMiddle:
                break;
                case mso_anchorMiddleCentered:
                break;
                case mso_anchorBottom:
                {
                    if ( bVerticalText )
                        eTHA = SDRTEXTHORZADJUST_LEFT;
                    else
                        eTVA = SDRTEXTVERTADJUST_BOTTOM;
                }
                break;
                case mso_anchorBottomCentered:
                {
                    if ( bVerticalText )
                        eTHA = SDRTEXTHORZADJUST_LEFT;
                    else
                        eTVA = SDRTEXTVERTADJUST_BOTTOM;
                }
                break;
                default:
                    ;
            }

            aSet.Put( SdrTextVertAdjustItem( eTVA ) );
            aSet.Put( SdrTextHorzAdjustItem( eTHA ) );

            if (pObj != nullptr)
            {
                pObj->SetMergedItemSet(aSet);
                pObj->SetModel(pSdrModel);

                if (bVerticalText)
                {
                    SdrTextObj *pTextObj = dynamic_cast< SdrTextObj* >(pObj);
                    if (pTextObj)
                        pTextObj->SetVerticalWriting(true);
                }

                if ( bIsSimpleDrawingTextBox )
                {
                    if ( nTextRotationAngle )
                    {
                        long nMinWH = rTextRect.GetWidth() < rTextRect.GetHeight() ?
                            rTextRect.GetWidth() : rTextRect.GetHeight();
                        nMinWH /= 2;
                        Point aPivot(rTextRect.TopLeft());
                        aPivot.X() += nMinWH;
                        aPivot.Y() += nMinWH;
                        double a = nTextRotationAngle * nPi180;
                        pObj->NbcRotate(aPivot, nTextRotationAngle, sin(a), cos(a));
                    }
                }

                if ( ( ( rObjData.nSpFlags & SP_FFLIPV ) || mnFix16Angle || nTextRotationAngle ) && dynamic_cast< SdrObjCustomShape* >( pObj ) )
                {
                    SdrObjCustomShape* pCustomShape = dynamic_cast< SdrObjCustomShape* >( pObj );
                    if (pCustomShape)
                    {
                        double fExtraTextRotation = 0.0;
                        if ( mnFix16Angle && !( GetPropertyValue( DFF_Prop_FitTextToShape, 0 ) & 4 ) )
                        {   // text is already rotated, we have to take back the object rotation if DFF_Prop_RotateText is false
                            fExtraTextRotation = -mnFix16Angle;
                        }
                        if ( rObjData.nSpFlags & SP_FFLIPV )    // sj: in ppt the text is flipped, whereas in word the text
                        {                                       // remains unchanged, so we have to take back the flipping here
                            fExtraTextRotation += 18000.0;      // because our core will flip text if the shape is flipped.
                        }
                        fExtraTextRotation += nTextRotationAngle;
                        if ( !::basegfx::fTools::equalZero( fExtraTextRotation ) )
                        {
                            fExtraTextRotation /= 100.0;
                            SdrCustomShapeGeometryItem aGeometryItem( static_cast<const SdrCustomShapeGeometryItem&>(pCustomShape->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY )) );
                            const OUString sTextRotateAngle( "TextRotateAngle" );
                            css::beans::PropertyValue aPropVal;
                            aPropVal.Name = sTextRotateAngle;
                            aPropVal.Value <<= fExtraTextRotation;
                            aGeometryItem.SetPropertyValue( aPropVal );
                            pCustomShape->SetMergedItem( aGeometryItem );
                        }
                    }
                }
                else if ( mnFix16Angle )
                {
                    // rotate text with shape ?
                    double a = mnFix16Angle * nPi180;
                    pObj->NbcRotate( rObjData.aBoundRect.Center(), mnFix16Angle,
                                     sin( a ), cos( a ) );
                }
            }
        }
        else if( !pObj )
        {
            // simple rectangular objects are ignored by ImportObj()  :-(
            // this is OK for Draw but not for Calc and Writer
            // cause here these objects have a default border
            pObj = new SdrRectObj(rTextRect);
            pObj->SetModel( pSdrModel );
            SfxItemSet aSet( pSdrModel->GetItemPool() );
            ApplyAttributes( rSt, aSet, rObjData );

            const SfxPoolItem* pPoolItem=nullptr;
            SfxItemState eState = aSet.GetItemState( XATTR_FILLCOLOR,
                                                     false, &pPoolItem );
            if( SfxItemState::DEFAULT == eState )
                aSet.Put( XFillColorItem( OUString(),
                          Color( mnDefaultColor ) ) );
            pObj->SetMergedItemSet(aSet);
        }

        // Means that fBehindDocument is set
        if (GetPropertyValue(DFF_Prop_fPrint, 0) & 0x20)
            pImpRec->bDrawHell = true;
        else
            pImpRec->bDrawHell = false;
        if (GetPropertyValue(DFF_Prop_fPrint, 0) & 0x02)
            pImpRec->bHidden = true;
        pImpRec->nNextShapeId   = GetPropertyValue( DFF_Prop_hspNext, 0 );

        if ( nTextId )
        {
            pImpRec->aTextId.nTxBxS = (sal_uInt16)( nTextId >> 16 );
            pImpRec->aTextId.nSequence = (sal_uInt16)nTextId;
        }

        pImpRec->nDxWrapDistLeft = GetPropertyValue(
                                    DFF_Prop_dxWrapDistLeft, 114935L ) / 635L;
        pImpRec->nDyWrapDistTop = GetPropertyValue(
                                    DFF_Prop_dyWrapDistTop, 0 ) / 635L;
        pImpRec->nDxWrapDistRight = GetPropertyValue(
                                    DFF_Prop_dxWrapDistRight, 114935L ) / 635L;
        pImpRec->nDyWrapDistBottom = GetPropertyValue(
                                    DFF_Prop_dyWrapDistBottom, 0 ) / 635L;
        // 16.16 fraction times total image width or height, as appropriate.

        if (SeekToContent(DFF_Prop_pWrapPolygonVertices, rSt))
        {
            delete pImpRec->pWrapPolygon;
            pImpRec->pWrapPolygon = nullptr;

            sal_uInt16 nNumElemVert(0), nNumElemMemVert(0), nElemSizeVert(0);
            rSt.ReadUInt16( nNumElemVert ).ReadUInt16( nNumElemMemVert ).ReadUInt16( nElemSizeVert );
            bool bOk = false;
            if (nNumElemVert && ((nElemSizeVert == 8) || (nElemSizeVert == 4)))
            {
                //check if there is enough data in the file to make the
                //record sane
                bOk = rSt.remainingSize() / nElemSizeVert >= nNumElemVert;
            }
            if (bOk)
            {
                pImpRec->pWrapPolygon = new tools::Polygon(nNumElemVert);
                for (sal_uInt16 i = 0; i < nNumElemVert; ++i)
                {
                    sal_Int32 nX(0), nY(0);
                    if (nElemSizeVert == 8)
                        rSt.ReadInt32( nX ).ReadInt32( nY );
                    else
                    {
                        sal_Int16 nSmallX(0), nSmallY(0);
                        rSt.ReadInt16( nSmallX ).ReadInt16( nSmallY );
                        nX = nSmallX;
                        nY = nSmallY;
                    }
                    (*(pImpRec->pWrapPolygon))[i].X() = nX;
                    (*(pImpRec->pWrapPolygon))[i].Y() = nY;
                }
            }
        }

        pImpRec->nCropFromTop = GetPropertyValue(
                                    DFF_Prop_cropFromTop, 0 );
        pImpRec->nCropFromBottom = GetPropertyValue(
                                    DFF_Prop_cropFromBottom, 0 );
        pImpRec->nCropFromLeft = GetPropertyValue(
                                    DFF_Prop_cropFromLeft, 0 );
        pImpRec->nCropFromRight = GetPropertyValue(
                                    DFF_Prop_cropFromRight, 0 );

        sal_uInt32 nLineFlags = GetPropertyValue( DFF_Prop_fNoLineDrawDash, 0 );

        if ( !IsHardAttribute( DFF_Prop_fLine ) &&
             pImpRec->eShapeType == mso_sptPictureFrame )
        {
            nLineFlags &= ~0x08;
        }

        pImpRec->eLineStyle = (nLineFlags & 8)
                              ? (MSO_LineStyle)GetPropertyValue(
                                                    DFF_Prop_lineStyle,
                                                    mso_lineSimple )
                              : (MSO_LineStyle)USHRT_MAX;
        pImpRec->eLineDashing = (MSO_LineDashing)GetPropertyValue(
                                        DFF_Prop_lineDashing, mso_lineSolid );

        pImpRec->nFlags = rObjData.nSpFlags;

        if( pImpRec->nShapeId )
        {
            // Complement Import Record List
            pImpRec->pObj = pObj;
            rImportData.m_Records.insert(std::unique_ptr<SvxMSDffImportRec>(pImpRec));

            // Complement entry in Z Order List with a pointer to this Object
            // Only store objects which are not deep inside the tree
            if( ( rObjData.nCalledByGroup == 0 )
                ||
                ( (rObjData.nSpFlags & SP_FGROUP)
                 && (rObjData.nCalledByGroup < 2) )
              )
                StoreShapeOrder( pImpRec->nShapeId,
                                ( ( (sal_uLong)pImpRec->aTextId.nTxBxS ) << 16 )
                                    + pImpRec->aTextId.nSequence, pObj );
        }
        else
            delete pImpRec;
    }

    sal_uInt32 nBufferSize = GetPropertyValue( DFF_Prop_pihlShape, 0 );
    if( (0 < nBufferSize) && (nBufferSize <= 0xFFFF) && SeekToContent( DFF_Prop_pihlShape, rSt ) )
    {
        SvMemoryStream aMemStream;
        struct HyperLinksTable hlStr;
        sal_uInt16 nRawRecId,nRawRecSize;
        aMemStream.WriteUInt16( 0 ).WriteUInt16( nBufferSize );

        // copy from DFF stream to memory stream
        std::vector< sal_uInt8 > aBuffer( nBufferSize );
        if (rSt.ReadBytes(aBuffer.data(), nBufferSize) == nBufferSize)
        {
            aMemStream.WriteBytes(aBuffer.data(), nBufferSize);
            aMemStream.Seek( STREAM_SEEK_TO_END );
            sal_uInt8 nStreamSize = aMemStream.Tell();
            aMemStream.Seek( STREAM_SEEK_TO_BEGIN );
            bool bRet = 4 <= nStreamSize;
            if( bRet )
                aMemStream.ReadUInt16( nRawRecId ).ReadUInt16( nRawRecSize );
            SwDocShell* pDocShell = rReader.m_pDocShell;
            if (pDocShell)
            {
                rReader.ReadEmbeddedData(aMemStream, pDocShell, hlStr);
            }
        }

        if (pObj && !hlStr.hLinkAddr.isEmpty())
        {
            SwMacroInfo* pInfo = GetMacroInfo( pObj, true );
            if( pInfo )
            {
                pInfo->SetShapeId( rObjData.nShapeId );
                pInfo->SetHlink( hlStr.hLinkAddr );
                if (!hlStr.tarFrame.isEmpty())
                    pInfo->SetTarFrame( hlStr.tarFrame );
                OUString aNameStr = GetPropertyString( DFF_Prop_wzName, rSt );
                if (!aNameStr.isEmpty())
                    pInfo->SetName( aNameStr );
            }
        }
    }

    return pObj;
}

/**
 * Special FastSave - Attributes
 */
void SwWW8ImplReader::Read_StyleCode( sal_uInt16, const sal_uInt8* pData, short nLen )
{
    if (nLen < 0)
    {
        m_bCpxStyle = false;
        return;
    }
    sal_uInt16 nColl = 0;
    if (m_pWwFib->GetFIBVersion() <= ww::eWW2)
        nColl = *pData;
    else
        nColl = SVBT16ToShort(pData);
    if (nColl < m_vColl.size())
    {
        SetTextFormatCollAndListLevel( *m_pPaM, m_vColl[nColl] );
        m_bCpxStyle = true;
    }
}

/**
 * Read_Majority is for Majority (103) and Majority50 (108)
 */
void SwWW8ImplReader::Read_Majority( sal_uInt16, const sal_uInt8* , short )
{
}

/**
 * Stack
 */
void SwWW8FltControlStack::NewAttr(const SwPosition& rPos,
    const SfxPoolItem& rAttr)
{
    OSL_ENSURE(RES_TXTATR_FIELD != rAttr.Which(), "probably don't want to put"
        "fields into the control stack");
    OSL_ENSURE(RES_TXTATR_INPUTFIELD != rAttr.Which(), "probably don't want to put"
        "input fields into the control stack");
    OSL_ENSURE(RES_TXTATR_ANNOTATION != rAttr.Which(), "probably don't want to put"
        "annotations into the control stack");
    OSL_ENSURE(RES_FLTR_REDLINE != rAttr.Which(), "probably don't want to put"
        "redlines into the control stack");
    SwFltControlStack::NewAttr(rPos, rAttr);
}

SwFltStackEntry* SwWW8FltControlStack::SetAttr(const SwPosition& rPos, sal_uInt16 nAttrId,
    bool bTstEnde, long nHand, bool )
{
    SwFltStackEntry *pRet = nullptr;
    // Doing a textbox, and using the control stack only as a temporary
    // collection point for properties which will are not to be set into
    // the real document
    if (rReader.m_pPlcxMan && rReader.m_pPlcxMan->GetDoingDrawTextBox())
    {
        size_t nCnt = size();
        for (size_t i=0; i < nCnt; ++i)
        {
            SwFltStackEntry& rEntry = (*this)[i];
            if (nAttrId == rEntry.pAttr->Which())
            {
                DeleteAndDestroy(i--);
                --nCnt;
            }
        }
    }
    else // Normal case, set the attribute into the document
        pRet = SwFltControlStack::SetAttr(rPos, nAttrId, bTstEnde, nHand);
    return pRet;
}

long GetListFirstLineIndent(const SwNumFormat &rFormat)
{
    OSL_ENSURE( rFormat.GetPositionAndSpaceMode() == SvxNumberFormat::LABEL_WIDTH_AND_POSITION,
            "<GetListFirstLineIndent> - misusage: position-and-space-mode does not equal LABEL_WIDTH_AND_POSITION" );

    SvxAdjust eAdj = rFormat.GetNumAdjust();
    long nReverseListIndented;
    if (eAdj == SvxAdjust::Right)
        nReverseListIndented = -rFormat.GetCharTextDistance();
    else if (eAdj == SvxAdjust::Center)
        nReverseListIndented = rFormat.GetFirstLineOffset()/2;
    else
        nReverseListIndented = rFormat.GetFirstLineOffset();
    return nReverseListIndented;
}

static long lcl_GetTrueMargin(const SvxLRSpaceItem &rLR, const SwNumFormat &rFormat,
    long &rFirstLinePos)
{
    OSL_ENSURE( rFormat.GetPositionAndSpaceMode() == SvxNumberFormat::LABEL_WIDTH_AND_POSITION,
            "<lcl_GetTrueMargin> - misusage: position-and-space-mode does not equal LABEL_WIDTH_AND_POSITION" );

    const long nBodyIndent = rLR.GetTextLeft();
    const long nFirstLineDiff = rLR.GetTextFirstLineOfst();
    rFirstLinePos = nBodyIndent + nFirstLineDiff;

    const long nPseudoListBodyIndent = rFormat.GetAbsLSpace();
    const long nReverseListIndented = GetListFirstLineIndent(rFormat);
    long nExtraListIndent = nPseudoListBodyIndent + nReverseListIndented;

    return nExtraListIndent > 0 ? nExtraListIndent : 0;
}

// #i103711#
// #i105414#
void SyncIndentWithList( SvxLRSpaceItem &rLR,
                         const SwNumFormat &rFormat,
                         const bool bFirstLineOfstSet,
                         const bool bLeftIndentSet )
{
    if ( rFormat.GetPositionAndSpaceMode() == SvxNumberFormat::LABEL_WIDTH_AND_POSITION )
    {
        long nWantedFirstLinePos;
        long nExtraListIndent = lcl_GetTrueMargin(rLR, rFormat, nWantedFirstLinePos);
        rLR.SetTextLeft(nWantedFirstLinePos - nExtraListIndent);
        rLR.SetTextFirstLineOfst(0);
    }
    else if ( rFormat.GetPositionAndSpaceMode() == SvxNumberFormat::LABEL_ALIGNMENT )
    {
        if ( !bFirstLineOfstSet && bLeftIndentSet &&
             rFormat.GetFirstLineIndent() != 0 )
        {
            rLR.SetTextFirstLineOfst( rFormat.GetFirstLineIndent() );
        }
        else if ( bFirstLineOfstSet && !bLeftIndentSet &&
                  rFormat.GetIndentAt() != 0 )
        {
            rLR.SetTextLeft( rFormat.GetIndentAt() );
        }
        else if (!bFirstLineOfstSet && !bLeftIndentSet )
        {
            if ( rFormat.GetFirstLineIndent() != 0 )
            {
                rLR.SetTextFirstLineOfst( rFormat.GetFirstLineIndent() );
            }
            if ( rFormat.GetIndentAt() != 0 )
            {
                rLR.SetTextLeft( rFormat.GetIndentAt() );
            }
        }
    }
}

const SwNumFormat* SwWW8FltControlStack::GetNumFormatFromStack(const SwPosition &rPos,
    const SwTextNode &rTextNode)
{
    const SwNumFormat *pRet = nullptr;
    const SfxPoolItem *pItem = GetStackAttr(rPos, RES_FLTR_NUMRULE);
    if (pItem && rTextNode.GetNumRule())
    {
        if (rTextNode.IsCountedInList())
        {
            OUString sName(static_cast<const SfxStringItem*>(pItem)->GetValue());
            const SwNumRule *pRule = pDoc->FindNumRulePtr(sName);
            if (pRule)
                pRet = GetNumFormatFromSwNumRuleLevel(*pRule, rTextNode.GetActualListLevel());
        }
    }
    return pRet;
}

sal_Int32 SwWW8FltControlStack::GetCurrAttrCP() const
{
    return rReader.GetCurrAttrCP();
}

bool SwWW8FltControlStack::IsParaEndInCPs(sal_Int32 nStart,sal_Int32 nEnd,bool bSdOD) const
{
    return rReader.IsParaEndInCPs(nStart,nEnd,bSdOD);
}

/**
 * Clear the para end position recorded in reader intermittently
 * for the least impact on loading performance.
 */
void SwWW8FltControlStack::ClearParaEndPosition()
{
    if ( !empty() )
        return;

    rReader.ClearParaEndPosition();
}

bool SwWW8FltControlStack::CheckSdOD(sal_Int32 nStart,sal_Int32 nEnd)
{
    return rReader.IsParaEndInCPs(nStart,nEnd);
}

void SwWW8ReferencedFltEndStack::SetAttrInDoc( const SwPosition& rTmpPos,
                                               SwFltStackEntry& rEntry )
{
    switch( rEntry.pAttr->Which() )
    {
    case RES_FLTR_BOOKMARK:
        {
            // suppress insertion of bookmark, which is recognized as an internal bookmark used for table-of-content
            // and which is not referenced.
            bool bInsertBookmarkIntoDoc = true;

            SwFltBookmark* pFltBookmark = dynamic_cast<SwFltBookmark*>(rEntry.pAttr.get());
            if ( pFltBookmark != nullptr && pFltBookmark->IsTOCBookmark() )
            {
                const OUString& rName = pFltBookmark->GetName();
                std::set< OUString, SwWW8::ltstr >::const_iterator aResult = aReferencedTOCBookmarks.find(rName);
                if ( aResult == aReferencedTOCBookmarks.end() )
                {
                    bInsertBookmarkIntoDoc = false;
                }
            }
            if ( bInsertBookmarkIntoDoc )
            {
                SwFltEndStack::SetAttrInDoc( rTmpPos, rEntry );
            }
            break;
        }
    default:
        SwFltEndStack::SetAttrInDoc( rTmpPos, rEntry );
        break;
    }

}

void SwWW8FltControlStack::SetAttrInDoc(const SwPosition& rTmpPos,
    SwFltStackEntry& rEntry)
{
    switch (rEntry.pAttr->Which())
    {
        case RES_LR_SPACE:
            {
                /*
                 Loop over the affected nodes and
                 a) convert the word style absolute indent to indent relative
                    to any numbering indent active on the nodes
                 b) adjust the writer style tabstops relative to the old
                    paragraph indent to be relative to the new paragraph indent
                */
                using namespace sw::util;
                SwPaM aRegion(rTmpPos);
                if (rEntry.MakeRegion(pDoc, aRegion, false))
                {
                    SvxLRSpaceItem aNewLR( *static_cast<SvxLRSpaceItem*>(rEntry.pAttr.get()) );
                    sal_uLong nStart = aRegion.Start()->nNode.GetIndex();
                    sal_uLong nEnd   = aRegion.End()->nNode.GetIndex();
                    for(; nStart <= nEnd; ++nStart)
                    {
                        SwNode* pNode = pDoc->GetNodes()[ nStart ];
                        if (!pNode || !pNode->IsTextNode())
                            continue;

                        SwContentNode* pNd = static_cast<SwContentNode*>(pNode);
                        SvxLRSpaceItem aOldLR = static_cast<const SvxLRSpaceItem&>(pNd->GetAttr(RES_LR_SPACE));

                        SwTextNode *pTextNode = static_cast<SwTextNode*>(pNode);

                        const SwNumFormat *pNum = nullptr;
                        pNum = GetNumFormatFromStack( *aRegion.GetPoint(), *pTextNode );
                        if (!pNum)
                        {
                            pNum = GetNumFormatFromTextNode(*pTextNode);
                        }

                        if ( pNum )
                        {
                            // #i103711#
                            const bool bFirstLineIndentSet =
                                ( rReader.m_aTextNodesHavingFirstLineOfstSet.end() !=
                                    rReader.m_aTextNodesHavingFirstLineOfstSet.find( pNode ) );
                            // #i105414#
                            const bool bLeftIndentSet =
                                (  rReader.m_aTextNodesHavingLeftIndentSet.end() !=
                                    rReader.m_aTextNodesHavingLeftIndentSet.find( pNode ) );
                            SyncIndentWithList( aNewLR, *pNum,
                                                bFirstLineIndentSet,
                                                bLeftIndentSet );
                        }

                        if (aNewLR == aOldLR)
                            continue;

                        pNd->SetAttr(aNewLR);

                    }
                }
            }
            break;

        case RES_TXTATR_FIELD:
            OSL_ENSURE(false, "What is a field doing in the control stack,"
                "probably should have been in the endstack");
            break;

        case RES_TXTATR_ANNOTATION:
            OSL_ENSURE(false, "What is a annotation doing in the control stack,"
                "probably should have been in the endstack");
            break;

        case RES_TXTATR_INPUTFIELD:
            OSL_ENSURE(false, "What is a input field doing in the control stack,"
                "probably should have been in the endstack");
            break;

        case RES_TXTATR_INETFMT:
            {
                SwPaM aRegion(rTmpPos);
                if (rEntry.MakeRegion(pDoc, aRegion, false))
                {
                    SwFrameFormat *pFrame;
                    // If we have just one single inline graphic then
                    // don't insert a field for the single frame, set
                    // the frames hyperlink field attribute directly.
                    if (nullptr != (pFrame = SwWW8ImplReader::ContainsSingleInlineGraphic(aRegion)))
                    {
                        const SwFormatINetFormat *pAttr = static_cast<const SwFormatINetFormat *>(
                            rEntry.pAttr.get());
                        SwFormatURL aURL;
                        aURL.SetURL(pAttr->GetValue(), false);
                        aURL.SetTargetFrameName(pAttr->GetTargetFrame());
                        pFrame->SetFormatAttr(aURL);
                    }
                    else
                    {
                        pDoc->getIDocumentContentOperations().InsertPoolItem(aRegion, *rEntry.pAttr);
                    }
                }
            }
            break;
        default:
            SwFltControlStack::SetAttrInDoc(rTmpPos, rEntry);
            break;
    }
}

const SfxPoolItem* SwWW8FltControlStack::GetFormatAttr(const SwPosition& rPos,
    sal_uInt16 nWhich)
{
    const SfxPoolItem *pItem = GetStackAttr(rPos, nWhich);
    if (!pItem)
    {
        SwContentNode const*const pNd = rPos.nNode.GetNode().GetContentNode();
        if (!pNd)
            pItem = &pDoc->GetAttrPool().GetDefaultItem(nWhich);
        else
        {
            /*
            If we're hunting for the indent on a paragraph and need to use the
            parent style indent, then return the indent in msword format, and
            not writer format, because that's the style that the filter works
            in (naturally)
            */
            if (nWhich == RES_LR_SPACE)
            {
                SfxItemState eState = SfxItemState::DEFAULT;
                if (const SfxItemSet *pSet = pNd->GetpSwAttrSet())
                    eState = pSet->GetItemState(RES_LR_SPACE, false);
                if (eState != SfxItemState::SET && rReader.m_nAktColl < rReader.m_vColl.size())
                    pItem = &(rReader.m_vColl[rReader.m_nAktColl].maWordLR);
            }

            /*
            If we're hunting for a character property, try and exact position
            within the text node for lookup
            */
            if (pNd->IsTextNode())
            {
                const sal_Int32 nPos = rPos.nContent.GetIndex();
                SfxItemSet aSet(pDoc->GetAttrPool(), nWhich, nWhich);
                if (pNd->GetTextNode()->GetAttr(aSet, nPos, nPos))
                    pItem = aSet.GetItem(nWhich);
            }

            if (!pItem)
                pItem = &pNd->GetAttr(nWhich);
        }
    }
    return pItem;
}

const SfxPoolItem* SwWW8FltControlStack::GetStackAttr(const SwPosition& rPos,
    sal_uInt16 nWhich)
{
    SwFltPosition aFltPos(rPos);

    size_t nSize = size();
    while (nSize)
    {
        const SwFltStackEntry& rEntry = (*this)[ --nSize ];
        if (rEntry.pAttr->Which() == nWhich)
        {
            if ( (rEntry.bOpen) ||
                 (
                  (rEntry.m_aMkPos.m_nNode <= aFltPos.m_nNode) &&
                  (rEntry.m_aPtPos.m_nNode >= aFltPos.m_nNode) &&
                  (rEntry.m_aMkPos.m_nContent <= aFltPos.m_nContent) &&
                  (rEntry.m_aPtPos.m_nContent > aFltPos.m_nContent)
                 )
               )
                /*
                 * e.g. half-open range [0-3) so asking for properties at 3
                 * means props that end at 3 are not included
                 */
            {
                return rEntry.pAttr.get();
            }
        }
    }
    return nullptr;
}

bool SwWW8FltRefStack::IsFootnoteEdnBkmField(
    const SwFormatField& rFormatField,
    sal_uInt16& rBkmNo)
{
    const SwField* pField = rFormatField.GetField();
    sal_uInt16 nSubType;
    if(pField && (SwFieldIds::GetRef == pField->Which())
        && ((REF_FOOTNOTE == (nSubType = pField->GetSubType())) || (REF_ENDNOTE  == nSubType))
        && !static_cast<const SwGetRefField*>(pField)->GetSetRefName().isEmpty())
    {
        const IDocumentMarkAccess* const pMarkAccess = pDoc->getIDocumentMarkAccess();
        IDocumentMarkAccess::const_iterator_t ppBkmk =
            pMarkAccess->findMark( static_cast<const SwGetRefField*>(pField)->GetSetRefName() );
        if(ppBkmk != pMarkAccess->getAllMarksEnd())
        {
            // find Sequence No of corresponding Foot-/Endnote
            rBkmNo = ppBkmk - pMarkAccess->getAllMarksBegin();
            return true;
        }
    }
    return false;
}

void SwWW8FltRefStack::SetAttrInDoc(const SwPosition& rTmpPos,
    SwFltStackEntry& rEntry)
{
    switch (rEntry.pAttr->Which())
    {
        /*
        Look up these in our lists of bookmarks that were changed to
        variables, and replace the ref field with a var field, otherwise
        do normal (?) strange stuff
        */
        case RES_TXTATR_FIELD:
        case RES_TXTATR_ANNOTATION:
        case RES_TXTATR_INPUTFIELD:
        {
            SwNodeIndex aIdx(rEntry.m_aMkPos.m_nNode, 1);
            SwPaM aPaM(aIdx, rEntry.m_aMkPos.m_nContent);

            SwFormatField& rFormatField   = *static_cast<SwFormatField*>(rEntry.pAttr.get());
            SwField* pField = rFormatField.GetField();

            if (!RefToVar(pField, rEntry))
            {
                sal_uInt16 nBkmNo;
                if( IsFootnoteEdnBkmField(rFormatField, nBkmNo) )
                {
                    ::sw::mark::IMark const * const pMark = (pDoc->getIDocumentMarkAccess()->getAllMarksBegin() + nBkmNo)->get();

                    const SwPosition& rBkMrkPos = pMark->GetMarkPos();

                    SwTextNode* pText = rBkMrkPos.nNode.GetNode().GetTextNode();
                    if( pText && rBkMrkPos.nContent.GetIndex() )
                    {
                        SwTextAttr* const pFootnote = pText->GetTextAttrForCharAt(
                            rBkMrkPos.nContent.GetIndex()-1, RES_TXTATR_FTN );
                        if( pFootnote )
                        {
                            sal_uInt16 nRefNo = static_cast<SwTextFootnote*>(pFootnote)->GetSeqRefNo();

                            static_cast<SwGetRefField*>(pField)->SetSeqNo( nRefNo );

                            if( pFootnote->GetFootnote().IsEndNote() )
                                static_cast<SwGetRefField*>(pField)->SetSubType(REF_ENDNOTE);
                        }
                    }
                }
            }

            pDoc->getIDocumentContentOperations().InsertPoolItem(aPaM, *rEntry.pAttr);
            MoveAttrs(*aPaM.GetPoint());
        }
        break;
        case RES_FLTR_TOX:
            SwFltEndStack::SetAttrInDoc(rTmpPos, rEntry);
            break;
        default:
        case RES_FLTR_BOOKMARK:
            OSL_ENSURE(false, "EndStck used with non field, not what we want");
            SwFltEndStack::SetAttrInDoc(rTmpPos, rEntry);
            break;
    }
}

/*
 For styles we will do our tabstop arithmetic in word style and adjust them to
 writer style after all the styles have been finished and the dust settles as
 to what affects what.

 For explicit attributes we turn the adjusted writer tabstops back into 0 based
 word indexes and we'll turn them back into writer indexes when setting them
 into the document. If explicit left indent exist which affects them, then this
 is handled when the explicit left indent is set into the document
*/
void SwWW8ImplReader::Read_Tab(sal_uInt16 , const sal_uInt8* pData, short nLen)
{
    if (nLen < 0)
    {
        m_pCtrlStck->SetAttr(*m_pPaM->GetPoint(), RES_PARATR_TABSTOP);
        return;
    }

    sal_uInt8 nDel = (nLen > 0) ? pData[0] : 0;
    const sal_uInt8* pDel = pData + 1;                   // Del - Array

    sal_uInt8 nIns = (nLen > nDel*2+1) ? pData[nDel*2+1] : 0;
    const sal_uInt8* pIns = pData + 2*nDel + 2;          // Ins - Array

    short nRequiredLength = 2 + 2*nDel + 2*nIns + 1*nIns;
    if (nRequiredLength > nLen)
    {
        // would require more data than available to describe!
        // discard invalid record
        nIns = 0;
        nDel = 0;
    }

    WW8_TBD const * pTyp = reinterpret_cast<WW8_TBD const *>(pData + 2*nDel + 2*nIns + 2); // Type Array

    SvxTabStopItem aAttr(0, 0, SvxTabAdjust::Default, RES_PARATR_TABSTOP);

    const SwTextFormatColl* pSty = nullptr;
    sal_uInt16 nTabBase;
    if (m_pAktColl && m_nAktColl < m_vColl.size()) // StyleDef
    {
        nTabBase = m_vColl[m_nAktColl].m_nBase;
        if (nTabBase < m_vColl.size())  // Based On
            pSty = static_cast<const SwTextFormatColl*>(m_vColl[nTabBase].m_pFormat);
    }
    else
    { // Text
        nTabBase = m_nAktColl;
        if (m_nAktColl < m_vColl.size())
            pSty = static_cast<const SwTextFormatColl*>(m_vColl[m_nAktColl].m_pFormat);
        //TODO: figure out else here
    }

    bool bFound = false;
    std::unordered_set<size_t> aLoopWatch;
    while (pSty && !bFound)
    {
        const SfxPoolItem* pTabs;
        bFound = pSty->GetAttrSet().GetItemState(RES_PARATR_TABSTOP, false,
            &pTabs) == SfxItemState::SET;
        if( bFound )
            aAttr = *static_cast<const SvxTabStopItem*>(pTabs);
        else
        {
            sal_uInt16 nOldTabBase = nTabBase;
            // If based on another
            if (nTabBase < m_vColl.size())
                nTabBase = m_vColl[nTabBase].m_nBase;

            if (
                    nTabBase < m_vColl.size() &&
                    nOldTabBase != nTabBase &&
                    nTabBase != ww::stiNil
               )
            {
                // #i61789: Stop searching when next style is the same as the
                // current one (prevent loop)
                aLoopWatch.insert(reinterpret_cast<size_t>(pSty));
                if (nTabBase < m_vColl.size())
                    pSty = static_cast<const SwTextFormatColl*>(m_vColl[nTabBase].m_pFormat);
                //TODO figure out the else branch

                if (aLoopWatch.find(reinterpret_cast<size_t>(pSty)) !=
                    aLoopWatch.end())
                    pSty = nullptr;
            }
            else
                pSty = nullptr; // Give up on the search
        }
    }

    SvxTabStop aTabStop;
    for (short i=0; i < nDel; ++i)
    {
        sal_uInt16 nPos = aAttr.GetPos(SVBT16ToShort(pDel + i*2));
        if( nPos != SVX_TAB_NOTFOUND )
            aAttr.Remove( nPos );
    }

    for (short i=0; i < nIns; ++i)
    {
        short nPos = SVBT16ToShort(pIns + i*2);
        aTabStop.GetTabPos() = nPos;
        switch( pTyp[i].aBits1 & 0x7 ) // pTyp[i].jc
        {
            case 0:
                aTabStop.GetAdjustment() = SvxTabAdjust::Left;
                break;
            case 1:
                aTabStop.GetAdjustment() = SvxTabAdjust::Center;
                break;
            case 2:
                aTabStop.GetAdjustment() = SvxTabAdjust::Right;
                break;
            case 3:
                aTabStop.GetAdjustment() = SvxTabAdjust::Decimal;
                break;
            case 4:
                continue; // Ignore Bar
        }

        switch( pTyp[i].aBits1 >> 3 & 0x7 )
        {
            case 0:
                aTabStop.GetFill() = ' ';
                break;
            case 1:
                aTabStop.GetFill() = '.';
                break;
            case 2:
                aTabStop.GetFill() = '-';
                break;
            case 3:
            case 4:
                aTabStop.GetFill() = '_';
                break;
        }

        sal_uInt16 nPos2 = aAttr.GetPos( nPos );
        if (nPos2 != SVX_TAB_NOTFOUND)
            aAttr.Remove(nPos2); // Or else Insert() refuses
        aAttr.Insert(aTabStop);
    }

    if (nIns || nDel)
        NewAttr(aAttr);
    else
    {
        // Here we have a tab definition which inserts no extra tabs, or deletes
        // no existing tabs. An older version of writer is probably the creater
        // of the document  :-( . So if we are importing a style we can just
        // ignore it. But if we are importing into text we cannot as during
        // text SwWW8ImplReader::Read_Tab is called at the begin and end of
        // the range the attrib affects, and ignoring it would upset the
        // balance
        if (!m_pAktColl) // not importing into a style
        {
            using namespace sw::util;
            SvxTabStopItem aOrig = pSty ?
            ItemGet<SvxTabStopItem>(*pSty, RES_PARATR_TABSTOP) :
            DefaultItemGet<SvxTabStopItem>(m_rDoc, RES_PARATR_TABSTOP);
            NewAttr(aOrig);
        }
    }
}

/**
 * DOP
*/
void SwWW8ImplReader::ImportDop()
{
    // correct the LastPrinted date in DocumentProperties
    uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
        m_pDocShell->GetModel(), uno::UNO_QUERY_THROW);
    uno::Reference<document::XDocumentProperties> xDocuProps(
        xDPS->getDocumentProperties());
    OSL_ENSURE(xDocuProps.is(), "DocumentProperties is null");
    if (xDocuProps.is())
    {
        DateTime aLastPrinted(
            msfilter::util::DTTM2DateTime(m_pWDop->dttmLastPrint));
        ::util::DateTime uDT = aLastPrinted.GetUNODateTime();
        xDocuProps->setPrintDate(uDT);
    }

    // COMPATIBILITY FLAGS START

    // #i78951# - remember the unknown compatibility options
    // so as to export them out
    m_rDoc.getIDocumentSettingAccess().Setn32DummyCompatibilityOptions1( m_pWDop->GetCompatibilityOptions());
    m_rDoc.getIDocumentSettingAccess().Setn32DummyCompatibilityOptions2( m_pWDop->GetCompatibilityOptions2());

    // The distance between two paragraphs is the sum of the bottom distance of
    // the first paragraph and the top distance of the second one
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::PARA_SPACE_MAX, m_pWDop->fDontUseHTMLAutoSpacing);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::PARA_SPACE_MAX_AT_PAGES, true );
    // move tabs on alignment
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::TAB_COMPAT, true);
    // #i24363# tab stops relative to indent
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::TABS_RELATIVE_TO_INDENT, false);

    // Import Default Tabs
    long nDefTabSiz = m_pWDop->dxaTab;
    if( nDefTabSiz < 56 )
        nDefTabSiz = 709;

    // We want exactly one DefaultTab
    SvxTabStopItem aNewTab( 1, sal_uInt16(nDefTabSiz), SvxTabAdjust::Default, RES_PARATR_TABSTOP );
    const_cast<SvxTabStop&>(aNewTab[0]).GetAdjustment() = SvxTabAdjust::Default;

    m_rDoc.GetAttrPool().SetPoolDefaultItem( aNewTab );

    // Import zoom factor
    if (m_pWDop->wScaleSaved)
    {
        uno::Sequence<beans::PropertyValue> aViewProps(3);
        aViewProps[0].Name = "ZoomFactor";
        aViewProps[0].Value <<= sal_Int16(m_pWDop->wScaleSaved);
        aViewProps[1].Name = "VisibleBottom";
        aViewProps[1].Value <<= sal_Int32(0);
        aViewProps[2].Name = "ZoomType";
        //Import zoom type
        switch (m_pWDop->zkSaved) {
            case 1:  aViewProps[2].Value <<= sal_Int16(SvxZoomType::WHOLEPAGE); break;
            case 2:  aViewProps[2].Value <<= sal_Int16(SvxZoomType::PAGEWIDTH); break;
            case 3:  aViewProps[2].Value <<= sal_Int16(SvxZoomType::OPTIMAL);   break;
            default: aViewProps[2].Value <<= sal_Int16(SvxZoomType::PERCENT);   break;
        }

        uno::Reference< uno::XComponentContext > xComponentContext(comphelper::getProcessComponentContext());
        uno::Reference<container::XIndexContainer> xBox = document::IndexedPropertyValues::create(xComponentContext);
        xBox->insertByIndex(sal_Int32(0), uno::makeAny(aViewProps));
        uno::Reference<container::XIndexAccess> xIndexAccess(xBox, uno::UNO_QUERY);
        uno::Reference<document::XViewDataSupplier> xViewDataSupplier(m_pDocShell->GetModel(), uno::UNO_QUERY);
        xViewDataSupplier->setViewData(xIndexAccess);
    }

    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::USE_VIRTUAL_DEVICE, !m_pWDop->fUsePrinterMetrics);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::USE_HIRES_VIRTUAL_DEVICE, true);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::ADD_FLY_OFFSETS, true );
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::ADD_EXT_LEADING, !m_pWDop->fNoLeading);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::OLD_NUMBERING, false);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::IGNORE_FIRST_LINE_INDENT_IN_NUMBERING, false); // #i47448#
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::DO_NOT_JUSTIFY_LINES_WITH_MANUAL_BREAK, !m_pWDop->fExpShRtn); // #i49277#, #i56856#
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::DO_NOT_RESET_PARA_ATTRS_FOR_NUM_FONT, false);  // #i53199#
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::OLD_LINE_SPACING, false);

    // #i25901# - set new compatibility option
    //      'Add paragraph and table spacing at bottom of table cells'
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::ADD_PARA_SPACING_TO_TABLE_CELLS, true);

    // #i11860# - set new compatibility option
    //      'Use former object positioning' to <false>
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::USE_FORMER_OBJECT_POS, false);

    // #i27767# - set new compatibility option
    //      'Consider Wrapping mode when positioning object' to <true>
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::CONSIDER_WRAP_ON_OBJECT_POSITION, true);

    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::USE_FORMER_TEXT_WRAPPING, false); // #i13832#, #i24135#

    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::TABLE_ROW_KEEP, true); //SetTableRowKeep( true );

    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::IGNORE_TABS_AND_BLANKS_FOR_LINE_CALCULATION, true); // #i3952#

    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::INVERT_BORDER_SPACING, true);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::COLLAPSE_EMPTY_CELL_PARA, true);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::TAB_OVERFLOW, true);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::UNBREAKABLE_NUMBERINGS, true);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::CLIPPED_PICTURES, true);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::TAB_OVER_MARGIN, true);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::SURROUND_TEXT_WRAP_SMALL, true);
    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::PROP_LINE_SPACING_SHRINKS_FIRST_LINE, true);

    // COMPATIBILITY FLAGS END

    // Import magic doptypography information, if its there
    if (m_pWwFib->m_nFib > 105)
        ImportDopTypography(m_pWDop->doptypography);

    // disable form design mode to be able to use imported controls directly
    // #i31239# always disable form design mode, not only in protected docs
    {
        using namespace com::sun::star;

        uno::Reference<lang::XComponent> xModelComp(m_pDocShell->GetModel(),
           uno::UNO_QUERY);
        uno::Reference<beans::XPropertySet> xDocProps(xModelComp,
           uno::UNO_QUERY);
        if (xDocProps.is())
        {
            uno::Reference<beans::XPropertySetInfo> xInfo =
                xDocProps->getPropertySetInfo();
            if (xInfo.is())
            {
                if (xInfo->hasPropertyByName("ApplyFormDesignMode"))
                {
                    bool bValue = false;
                    xDocProps->setPropertyValue("ApplyFormDesignMode", css::uno::makeAny(bValue));
                }
            }
        }
    }

    // Still allow editing of form fields.
    if (!m_pWDop->fProtEnabled)
        m_pDocShell->SetModifyPasswordHash(m_pWDop->lKeyProtDoc);

    const SvtFilterOptions& rOpt = SvtFilterOptions::Get();
    if (rOpt.IsUseEnhancedFields())
        m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::PROTECT_FORM, m_pWDop->fProtEnabled );
}

void SwWW8ImplReader::ImportDopTypography(const WW8DopTypography &rTypo)
{
    using namespace com::sun::star;
    switch (rTypo.iLevelOfKinsoku)
    {
        case 2: // custom
            {
                i18n::ForbiddenCharacters aForbidden(rTypo.rgxchFPunct,
                    rTypo.rgxchLPunct);
                m_rDoc.getIDocumentSettingAccess().setForbiddenCharacters(rTypo.GetConvertedLang(),
                        aForbidden);
                // Obviously cannot set the standard level 1 for japanese, so
                // bail out now while we can.
                if (rTypo.GetConvertedLang() == LANGUAGE_JAPANESE)
                    return;
            }
            break;
        default:
            break;
    }

    /*
    This MS hack means that level 2 of japanese is not in operation, so we put
    in what we know are the MS defaults, there is a complementary reverse
    hack in the writer. Its our default as well, but we can set it anyway
    as a flag for later.
    */
    if (!rTypo.reserved2)
    {
        i18n::ForbiddenCharacters aForbidden(WW8DopTypography::GetJapanNotBeginLevel1(),
            WW8DopTypography::GetJapanNotEndLevel1());
        m_rDoc.getIDocumentSettingAccess().setForbiddenCharacters(LANGUAGE_JAPANESE,aForbidden);
    }

    m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::KERN_ASIAN_PUNCTUATION, rTypo.fKerningPunct);
    m_rDoc.getIDocumentSettingAccess().setCharacterCompressionType((CharCompressType)rTypo.iJustification);
}

/**
 * Footnotes and Endnotes
 */
WW8ReaderSave::WW8ReaderSave(SwWW8ImplReader* pRdr ,WW8_CP nStartCp) :
    maTmpPos(*pRdr->m_pPaM->GetPoint()),
    mpOldStck(pRdr->m_pCtrlStck),
    mpOldAnchorStck(pRdr->m_pAnchorStck),
    mpOldRedlines(pRdr->m_pRedlineStack),
    mpOldPlcxMan(pRdr->m_pPlcxMan),
    mpWFlyPara(pRdr->m_xWFlyPara.release()),
    mpSFlyPara(pRdr->m_xSFlyPara.release()),
    mpPreviousNumPaM(pRdr->m_pPreviousNumPaM),
    mpPrevNumRule(pRdr->m_pPrevNumRule),
    mpTableDesc(pRdr->m_pTableDesc),
    mnInTable(pRdr->m_nInTable),
    mnAktColl(pRdr->m_nAktColl),
    mcSymbol(pRdr->m_cSymbol),
    mbIgnoreText(pRdr->m_bIgnoreText),
    mbSymbol(pRdr->m_bSymbol),
    mbHdFtFootnoteEdn(pRdr->m_bHdFtFootnoteEdn),
    mbTxbxFlySection(pRdr->m_bTxbxFlySection),
    mbAnl(pRdr->m_bAnl),
    mbInHyperlink(pRdr->m_bInHyperlink),
    mbPgSecBreak(pRdr->m_bPgSecBreak),
    mbWasParaEnd(pRdr->m_bWasParaEnd),
    mbHasBorder(pRdr->m_bHasBorder),
    mbFirstPara(pRdr->m_bFirstPara)
{
    pRdr->m_bSymbol = false;
    pRdr->m_bHdFtFootnoteEdn = true;
    pRdr->m_bTxbxFlySection = pRdr->m_bAnl = pRdr->m_bPgSecBreak = pRdr->m_bWasParaEnd
        = pRdr->m_bHasBorder = false;
    pRdr->m_bFirstPara = true;
    pRdr->m_nInTable = 0;
    pRdr->m_pPreviousNumPaM = nullptr;
    pRdr->m_pPrevNumRule = nullptr;
    pRdr->m_pTableDesc = nullptr;
    pRdr->m_nAktColl = 0;

    pRdr->m_pCtrlStck = new SwWW8FltControlStack(&pRdr->m_rDoc, pRdr->m_nFieldFlags,
        *pRdr);

    pRdr->m_pRedlineStack = new sw::util::RedlineStack(pRdr->m_rDoc);

    pRdr->m_pAnchorStck = new SwWW8FltAnchorStack(&pRdr->m_rDoc, pRdr->m_nFieldFlags);

    // Save the attribute manager: we need this as the newly created PLCFx Manager
    // access the same FKPs as the old one and their Start-End position changes.
    if (pRdr->m_pPlcxMan)
        pRdr->m_pPlcxMan->SaveAllPLCFx(maPLCFxSave);

    if (nStartCp != -1)
    {
        pRdr->m_pPlcxMan = new WW8PLCFMan(pRdr->m_pSBase,
            mpOldPlcxMan->GetManType(), nStartCp);
    }

    maOldApos.push_back(false);
    maOldApos.swap(pRdr->m_aApos);
    maOldFieldStack.swap(pRdr->m_aFieldStack);
}

void WW8ReaderSave::Restore( SwWW8ImplReader* pRdr )
{
    pRdr->m_xWFlyPara.reset(mpWFlyPara);
    pRdr->m_xSFlyPara.reset(mpSFlyPara);
    pRdr->m_pPreviousNumPaM = mpPreviousNumPaM;
    pRdr->m_pPrevNumRule = mpPrevNumRule;
    pRdr->m_pTableDesc = mpTableDesc;
    pRdr->m_cSymbol = mcSymbol;
    pRdr->m_bSymbol = mbSymbol;
    pRdr->m_bIgnoreText = mbIgnoreText;
    pRdr->m_bHdFtFootnoteEdn = mbHdFtFootnoteEdn;
    pRdr->m_bTxbxFlySection = mbTxbxFlySection;
    pRdr->m_nInTable = mnInTable;
    pRdr->m_bAnl = mbAnl;
    pRdr->m_bInHyperlink = mbInHyperlink;
    pRdr->m_bWasParaEnd = mbWasParaEnd;
    pRdr->m_bPgSecBreak = mbPgSecBreak;
    pRdr->m_nAktColl = mnAktColl;
    pRdr->m_bHasBorder = mbHasBorder;
    pRdr->m_bFirstPara = mbFirstPara;

    // Close all attributes as attributes could be created that extend the Fly
    pRdr->DeleteCtrlStack();
    pRdr->m_pCtrlStck = mpOldStck;

    pRdr->m_pRedlineStack->closeall(*pRdr->m_pPaM->GetPoint());
    delete pRdr->m_pRedlineStack;
    pRdr->m_pRedlineStack = mpOldRedlines;

    pRdr->DeleteAnchorStack();
    pRdr->m_pAnchorStck = mpOldAnchorStck;

    *pRdr->m_pPaM->GetPoint() = maTmpPos;

    if (mpOldPlcxMan != pRdr->m_pPlcxMan)
    {
        delete pRdr->m_pPlcxMan;
        pRdr->m_pPlcxMan = mpOldPlcxMan;
    }
    if (pRdr->m_pPlcxMan)
        pRdr->m_pPlcxMan->RestoreAllPLCFx(maPLCFxSave);
    pRdr->m_aApos.swap(maOldApos);
    pRdr->m_aFieldStack.swap(maOldFieldStack);
}

void SwWW8ImplReader::Read_HdFtFootnoteText( const SwNodeIndex* pSttIdx,
    WW8_CP nStartCp, WW8_CP nLen, ManTypes nType )
{
    // Saves Flags (amongst other things) and resets them
    WW8ReaderSave aSave( this );

    m_pPaM->GetPoint()->nNode = pSttIdx->GetIndex() + 1;
    m_pPaM->GetPoint()->nContent.Assign( m_pPaM->GetContentNode(), 0 );

    // Read Text for Header, Footer or Footnote
    ReadText( nStartCp, nLen, nType ); // Ignore Sepx when doing so
    aSave.Restore( this );
}

/**
 * Use authornames, if not available fall back to initials.
 */
long SwWW8ImplReader::Read_And(WW8PLCFManResult* pRes)
{
    WW8PLCFx_SubDoc* pSD = m_pPlcxMan->GetAtn();
    if( !pSD )
        return 0;

    OUString sAuthor;
    OUString sInitials;
    if( m_bVer67 )
    {
        const WW67_ATRD* pDescri = static_cast<const WW67_ATRD*>(pSD->GetData());
        const OUString* pA = GetAnnotationAuthor(SVBT16ToShort(pDescri->ibst));
        if (pA)
            sAuthor = *pA;
        else
        {
            const sal_uInt8 nLen = std::min<sal_uInt8>(pDescri->xstUsrInitl[0],
                                                       SAL_N_ELEMENTS(pDescri->xstUsrInitl)-1);
            sAuthor = OUString(pDescri->xstUsrInitl + 1, nLen, RTL_TEXTENCODING_MS_1252);
        }
    }
    else
    {
        const WW8_ATRD* pDescri = static_cast<const WW8_ATRD*>(pSD->GetData());
        {
            const sal_uInt16 nLen = std::min<sal_uInt16>(SVBT16ToShort(pDescri->xstUsrInitl[0]),
                                                         SAL_N_ELEMENTS(pDescri->xstUsrInitl)-1);
            OUStringBuffer aBuf;
            aBuf.setLength(nLen);
            for(sal_uInt16 nIdx = 1; nIdx <= nLen; ++nIdx)
                aBuf[nIdx-1] = SVBT16ToShort(pDescri->xstUsrInitl[nIdx]);
            sInitials = aBuf.makeStringAndClear();
        }

        if (const OUString* pA = GetAnnotationAuthor(SVBT16ToShort(pDescri->ibst)))
            sAuthor = *pA;
        else
            sAuthor = sInitials;
    }

    sal_uInt32 nDateTime = 0;

    if (sal_uInt8 * pExtended = m_pPlcxMan->GetExtendedAtrds()) // Word < 2002 has no date data for comments
    {
        sal_uLong nIndex = pSD->GetIdx() & 0xFFFF; // Index is (stupidly) multiplexed for WW8PLCFx_SubDocs
        if (m_pWwFib->m_lcbAtrdExtra/18 > nIndex)
            nDateTime = SVBT32ToUInt32(*reinterpret_cast<SVBT32*>(pExtended+(nIndex*18)));
    }

    DateTime aDate = msfilter::util::DTTM2DateTime(nDateTime);

    OUString sText;
    OutlinerParaObject *pOutliner = ImportAsOutliner( sText, pRes->nCp2OrIdx,
        pRes->nCp2OrIdx + pRes->nMemLen, MAN_AND );

    m_pFormatOfJustInsertedApo = nullptr;
    SwPostItField aPostIt(
        static_cast<SwPostItFieldType*>(m_rDoc.getIDocumentFieldsAccess().GetSysFieldType(SwFieldIds::Postit)), sAuthor,
        sText, sInitials, OUString(), aDate );
    aPostIt.SetTextObject(pOutliner);

    SwPaM aEnd(*m_pPaM->End(), *m_pPaM->End());
    m_pCtrlStck->NewAttr(*aEnd.GetPoint(), SvxCharHiddenItem(false, RES_CHRATR_HIDDEN));
    m_rDoc.getIDocumentContentOperations().InsertPoolItem(aEnd, SwFormatField(aPostIt));
    m_pCtrlStck->SetAttr(*aEnd.GetPoint(), RES_CHRATR_HIDDEN);
    // If this is a range, make sure that it ends after the just inserted character, not before it.
    m_pReffedStck->MoveAttrs(*aEnd.GetPoint());

    return 0;
}

void SwWW8ImplReader::Read_HdFtTextAsHackedFrame(WW8_CP nStart, WW8_CP nLen,
    SwFrameFormat &rHdFtFormat, sal_uInt16 nPageWidth)
{
    const SwNodeIndex* pSttIdx = rHdFtFormat.GetContent().GetContentIdx();
    OSL_ENSURE(pSttIdx, "impossible");
    if (!pSttIdx)
        return;

    SwPosition aTmpPos(*m_pPaM->GetPoint());

    m_pPaM->GetPoint()->nNode = pSttIdx->GetIndex() + 1;
    m_pPaM->GetPoint()->nContent.Assign(m_pPaM->GetContentNode(), 0);

    SwFlyFrameFormat *pFrame = m_rDoc.MakeFlySection(RndStdIds::FLY_AT_PARA, m_pPaM->GetPoint());

    SwFormatAnchor aAnch( pFrame->GetAnchor() );
    aAnch.SetType( RndStdIds::FLY_AT_PARA );
    pFrame->SetFormatAttr( aAnch );
    SwFormatFrameSize aSz(ATT_MIN_SIZE, nPageWidth, MINLAY);
    SwFrameSize eFrameSize = ATT_MIN_SIZE;
    if( eFrameSize != aSz.GetWidthSizeType() )
        aSz.SetWidthSizeType( eFrameSize );
    pFrame->SetFormatAttr(aSz);
    pFrame->SetFormatAttr(SwFormatSurround(css::text::WrapTextMode_THROUGH));
    pFrame->SetFormatAttr(SwFormatHoriOrient(0, text::HoriOrientation::LEFT)); //iFOO

    // #i43427# - send frame for header/footer into background.
    pFrame->SetFormatAttr( SvxOpaqueItem( RES_OPAQUE, false ) );
    SdrObject* pFrameObj = CreateContactObject( pFrame );
    OSL_ENSURE( pFrameObj,
            "<SwWW8ImplReader::Read_HdFtTextAsHackedFrame(..)> - missing SdrObject instance" );
    if ( pFrameObj )
    {
        pFrameObj->SetOrdNum( 0L );
    }
    MoveInsideFly(pFrame);

    const SwNodeIndex* pHackIdx = pFrame->GetContent().GetContentIdx();

    Read_HdFtFootnoteText(pHackIdx, nStart, nLen - 1, MAN_HDFT);

    MoveOutsideFly(pFrame, aTmpPos);
}

void SwWW8ImplReader::Read_HdFtText(WW8_CP nStart, WW8_CP nLen, SwFrameFormat* pHdFtFormat)
{
    const SwNodeIndex* pSttIdx = pHdFtFormat->GetContent().GetContentIdx();
    if (!pSttIdx)
        return;

    SwPosition aTmpPos( *m_pPaM->GetPoint() ); // Remember old cursor position

    Read_HdFtFootnoteText(pSttIdx, nStart, nLen - 1, MAN_HDFT);

    *m_pPaM->GetPoint() = aTmpPos;
}

bool SwWW8ImplReader::isValid_HdFt_CP(WW8_CP nHeaderCP) const
{
    // Each CP of Plcfhdd MUST be less than FibRgLw97.ccpHdd
    return (nHeaderCP < m_pWwFib->m_ccpHdr && nHeaderCP >= 0);
}

bool SwWW8ImplReader::HasOwnHeaderFooter(sal_uInt8 nWhichItems, sal_uInt8 grpfIhdt,
    int nSect)
{
    if (m_pHdFt)
    {
        WW8_CP nStart, nLen;
        sal_uInt8 nNumber = 5;

        for( sal_uInt8 nI = 0x20; nI; nI >>= 1, nNumber-- )
        {
            if (nI & nWhichItems)
            {
                bool bOk = true;
                if( m_bVer67 )
                    bOk = ( m_pHdFt->GetTextPos(grpfIhdt, nI, nStart, nLen ) && nStart >= 0 && nLen >= 2 );
                else
                {
                    m_pHdFt->GetTextPosExact( static_cast< short >(nNumber + (nSect+1)*6), nStart, nLen);
                    bOk = ( 2 <= nLen ) && isValid_HdFt_CP(nStart);
                }

                if (bOk)
                    return true;
            }
        }
    }
    return false;
}

void SwWW8ImplReader::Read_HdFt(int nSect, const SwPageDesc *pPrev,
    const wwSection &rSection)
{
    sal_uInt8 grpfIhdt = rSection.maSep.grpfIhdt;
    SwPageDesc *pPD = rSection.mpPage;

    if( m_pHdFt )
    {
        WW8_CP nStart, nLen;
        sal_uInt8 nNumber = 5;

        // This loops through the 6 flags WW8_{FOOTER,HEADER}_{ODD,EVEN,FIRST}
        // corresponding to bit fields in grpfIhdt indicating which
        // header/footer(s) are present in this section
        for( sal_uInt8 nI = 0x20; nI; nI >>= 1, nNumber-- )
        {
            if (nI & grpfIhdt)
            {
                bool bOk = true;
                if( m_bVer67 )
                    bOk = ( m_pHdFt->GetTextPos(grpfIhdt, nI, nStart, nLen ) && nLen >= 2 );
                else
                {
                    m_pHdFt->GetTextPosExact( static_cast< short >(nNumber + (nSect+1)*6), nStart, nLen);
                    bOk = ( 2 <= nLen ) && isValid_HdFt_CP(nStart);
                }

                bool bUseLeft
                    = (nI & ( WW8_HEADER_EVEN | WW8_FOOTER_EVEN )) != 0;
                bool bUseFirst
                    = (nI & ( WW8_HEADER_FIRST | WW8_FOOTER_FIRST )) != 0;

                // If we are loading a first-page header/footer which is not
                // actually enabled in this section (it still needs to be
                // loaded as it may be inherited by a later section)
                bool bDisabledFirst = bUseFirst && !rSection.HasTitlePage();

                bool bFooter
                    = (nI & ( WW8_FOOTER_EVEN | WW8_FOOTER_ODD | WW8_FOOTER_FIRST )) != 0;

                SwFrameFormat& rFormat = bUseLeft ? pPD->GetLeft()
                    : bUseFirst ? pPD->GetFirstMaster()
                    : pPD->GetMaster();

                SwFrameFormat* pHdFtFormat;
                // If we have empty first page header and footer.
                bool bNoFirst = !(grpfIhdt & WW8_HEADER_FIRST) && !(grpfIhdt & WW8_FOOTER_FIRST);
                if (bFooter)
                {
                    m_bIsFooter = true;
                    //#i17196# Cannot have left without right
                    if (!bDisabledFirst
                            && !pPD->GetMaster().GetFooter().GetFooterFormat())
                        pPD->GetMaster().SetFormatAttr(SwFormatFooter(true));
                    if (bUseLeft)
                        pPD->GetLeft().SetFormatAttr(SwFormatFooter(true));
                    if (bUseFirst || (rSection.maSep.fTitlePage && bNoFirst))
                        pPD->GetFirstMaster().SetFormatAttr(SwFormatFooter(true));
                    pHdFtFormat = const_cast<SwFrameFormat*>(rFormat.GetFooter().GetFooterFormat());
                }
                else
                {
                    m_bIsHeader = true;
                    //#i17196# Cannot have left without right
                    if (!bDisabledFirst
                            && !pPD->GetMaster().GetHeader().GetHeaderFormat())
                        pPD->GetMaster().SetFormatAttr(SwFormatHeader(true));
                    if (bUseLeft)
                        pPD->GetLeft().SetFormatAttr(SwFormatHeader(true));
                    if (bUseFirst || (rSection.maSep.fTitlePage && bNoFirst))
                        pPD->GetFirstMaster().SetFormatAttr(SwFormatHeader(true));
                    pHdFtFormat = const_cast<SwFrameFormat*>(rFormat.GetHeader().GetHeaderFormat());
                }

                if (bOk)
                {
                    bool bHackRequired = false;
                    if (m_bIsHeader && rSection.IsFixedHeightHeader())
                        bHackRequired = true;
                    else if (m_bIsFooter && rSection.IsFixedHeightFooter())
                        bHackRequired = true;

                    if (bHackRequired)
                    {
                        Read_HdFtTextAsHackedFrame(nStart, nLen, *pHdFtFormat,
                            static_cast< sal_uInt16 >(rSection.GetTextAreaWidth()) );
                    }
                    else
                        Read_HdFtText(nStart, nLen, pHdFtFormat);
                }
                else if (!bOk && pPrev)
                    CopyPageDescHdFt(pPrev, pPD, nI);

                m_bIsHeader = m_bIsFooter = false;
            }
        }
    }
}

bool wwSectionManager::SectionIsProtected(const wwSection &rSection) const
{
    return (mrReader.m_pWwFib->m_fReadOnlyRecommended && !rSection.IsNotProtected());
}

void wwSectionManager::SetHdFt(wwSection &rSection, int nSect,
    const wwSection *pPrevious)
{
    // Header/Footer not present
    if (!rSection.maSep.grpfIhdt)
        return;

    OSL_ENSURE(rSection.mpPage, "makes no sense to call with a main page");
    if (rSection.mpPage)
    {
        mrReader.Read_HdFt(nSect, pPrevious ? pPrevious->mpPage : nullptr,
                rSection);
    }

    // Header/Footer - Update Index
    // So that the index is still valid later on
    if (mrReader.m_pHdFt)
        mrReader.m_pHdFt->UpdateIndex(rSection.maSep.grpfIhdt);

}

void SwWW8ImplReader::AppendTextNode(SwPosition& rPos)
{
    SwTextNode* pText = m_pPaM->GetNode().GetTextNode();

    const SwNumRule* pRule = nullptr;

    if (pText != nullptr)
        pRule = sw::util::GetNumRuleFromTextNode(*pText);

    if (
         pRule && !m_pWDop->fDontUseHTMLAutoSpacing &&
         (m_bParaAutoBefore || m_bParaAutoAfter)
       )
    {
        // If after spacing is set to auto, set the after space to 0
        if (m_bParaAutoAfter)
            SetLowerSpacing(*m_pPaM, 0);

        // If the previous textnode had numbering and
        // and before spacing is set to auto, set before space to 0
        if(m_pPrevNumRule && m_bParaAutoBefore)
            SetUpperSpacing(*m_pPaM, 0);

        // If the previous numbering rule was different we need
        // to insert a space after the previous paragraph
        if((pRule != m_pPrevNumRule) && m_pPreviousNumPaM)
            SetLowerSpacing(*m_pPreviousNumPaM, GetParagraphAutoSpace(m_pWDop->fDontUseHTMLAutoSpacing));

        // cache current paragraph
        if(m_pPreviousNumPaM)
        {
            delete m_pPreviousNumPaM;
            m_pPreviousNumPaM = nullptr;
        }

        m_pPreviousNumPaM = new SwPaM(*m_pPaM, m_pPaM);
        m_pPrevNumRule = pRule;
    }
    else if(!pRule && m_pPreviousNumPaM)
    {
        // If the previous paragraph has numbering but the current one does not
        // we need to add a space after the previous paragraph
        SetLowerSpacing(*m_pPreviousNumPaM, GetParagraphAutoSpace(m_pWDop->fDontUseHTMLAutoSpacing));
        delete m_pPreviousNumPaM;
        m_pPreviousNumPaM = nullptr;
        m_pPrevNumRule = nullptr;
    }
    else
    {
        // clear paragraph cache
        if(m_pPreviousNumPaM)
        {
            delete m_pPreviousNumPaM;
            m_pPreviousNumPaM = nullptr;
        }
        m_pPrevNumRule = pRule;
    }

    // If this is the first paragraph in the document and
    // Auto-spacing before paragraph is set,
    // set the upper spacing value to 0
    if(m_bParaAutoBefore && m_bFirstPara && !m_pWDop->fDontUseHTMLAutoSpacing)
        SetUpperSpacing(*m_pPaM, 0);

    m_bFirstPara = false;

    m_rDoc.getIDocumentContentOperations().AppendTextNode(rPos);

    // We can flush all anchored graphics at the end of a paragraph.
    m_pAnchorStck->Flush();
}

bool SwWW8ImplReader::SetSpacing(SwPaM &rMyPam, int nSpace, bool bIsUpper )
{
        bool bRet = false;
        const SwPosition* pSpacingPos = rMyPam.GetPoint();

        const SvxULSpaceItem* pULSpaceItem = static_cast<const SvxULSpaceItem*>(m_pCtrlStck->GetFormatAttr(*pSpacingPos, RES_UL_SPACE));

        if(pULSpaceItem != nullptr)
        {
            SvxULSpaceItem aUL(*pULSpaceItem);

            if(bIsUpper)
                aUL.SetUpper( static_cast< sal_uInt16 >(nSpace) );
            else
                aUL.SetLower( static_cast< sal_uInt16 >(nSpace) );

            const sal_Int32 nEnd = pSpacingPos->nContent.GetIndex();
            rMyPam.GetPoint()->nContent.Assign(rMyPam.GetContentNode(), 0);
            m_pCtrlStck->NewAttr(*pSpacingPos, aUL);
            rMyPam.GetPoint()->nContent.Assign(rMyPam.GetContentNode(), nEnd);
            m_pCtrlStck->SetAttr(*pSpacingPos, RES_UL_SPACE);
            bRet = true;
        }
        return bRet;
}

bool SwWW8ImplReader::SetLowerSpacing(SwPaM &rMyPam, int nSpace)
{
    return SetSpacing(rMyPam, nSpace, false);
}

bool SwWW8ImplReader::SetUpperSpacing(SwPaM &rMyPam, int nSpace)
{
    return SetSpacing(rMyPam, nSpace, true);
}

sal_uInt16 SwWW8ImplReader::TabRowSprm(int nLevel) const
{
    if (m_bVer67)
        return 25;
    return nLevel ? 0x244C : 0x2417;
}

void SwWW8ImplReader::EndSpecial()
{
    // Frame/Table/Anl
    if (m_bAnl)
        StopAllAnl(); // -> bAnl = false

    while(m_aApos.size() > 1)
    {
        StopTable();
        m_aApos.pop_back();
        --m_nInTable;
        if (m_aApos[m_nInTable])
            StopApo();
    }

    if (m_aApos[0])
        StopApo();

    OSL_ENSURE(!m_nInTable, "unclosed table!");
}

bool SwWW8ImplReader::ProcessSpecial(bool &rbReSync, WW8_CP nStartCp)
{
    // Frame/Table/Anl
    if (m_bInHyperlink)
        return false;

    rbReSync = false;

    OSL_ENSURE(m_nInTable >= 0,"nInTable < 0!");

    // TabRowEnd
    bool bTableRowEnd = (m_pPlcxMan->HasParaSprm(m_bVer67 ? 25 : 0x2417).pSprm != nullptr);

// Unfortunately, for every paragraph we need to check first whether
// they contain a sprm 29 (0x261B), which starts an APO.
// All other sprms then refer to that APO and not to the normal text
// surrounding it.
// The same holds true for a Table (sprm 24 (0x2416)) and Anls (sprm 13).

// WW: Table in APO is possible (Both Start-Ends occur at the same time)
// WW: APO in Table not possible

// This mean that of a Table is the content of a APO, the APO start needs
// to be edited first, so that the Table remains in the APO and not the
// other way around.
// At the End, however, we need to edit the Table End first as the APO
// must end after that Table (or else we never find the APO End).

// The same holds true for Fly / Anl, Tab / Anl, Fly / Tab / Anl.

// If the Table is within an APO the TabRowEnd Area misses the
// APO settings.
// To not end the APO there, we do not call ProcessApo

// KHZ: When there is a table inside the Apo the Apo-flags are also
//      missing for the 2nd, 3rd... paragraphs of each cell.

//  1st look for in-table flag, for 2000+ there is a subtable flag to
//  be considered, the sprm 6649 gives the level of the table
    sal_uInt8 nCellLevel = 0;

    if (m_bVer67)
        nCellLevel = int(nullptr != m_pPlcxMan->HasParaSprm(24).pSprm);
    else
    {
        nCellLevel = int(nullptr != m_pPlcxMan->HasParaSprm(0x2416).pSprm);
        if (!nCellLevel)
            nCellLevel = int(nullptr != m_pPlcxMan->HasParaSprm(0x244B).pSprm);
    }
    do
    {
        WW8_TablePos *pTabPos=nullptr;
        WW8_TablePos aTabPos;
        if(nCellLevel && !m_bVer67)
        {
            WW8PLCFxSave1 aSave;
            m_pPlcxMan->GetPap()->Save( aSave );
            rbReSync = true;
            WW8PLCFx_Cp_FKP* pPap = m_pPlcxMan->GetPapPLCF();
            WW8_CP nMyStartCp=nStartCp;

            SprmResult aLevel = m_pPlcxMan->HasParaSprm(0x6649);
            if (aLevel.pSprm && aLevel.nRemainingData >= 1)
                nCellLevel = *aLevel.pSprm;

            bool bHasRowEnd = SearchRowEnd(pPap, nMyStartCp, (m_nInTable<nCellLevel?m_nInTable:nCellLevel-1));

            // Bad Table, remain unchanged in level, e.g. #i19667#
            if (!bHasRowEnd)
                nCellLevel = static_cast< sal_uInt8 >(m_nInTable);

            if (bHasRowEnd && ParseTabPos(&aTabPos,pPap))
                pTabPos = &aTabPos;

            if (pTabPos && !pTabPos->bNoFly && SearchTableEnd(pPap))
            {
                // Table is considered to be imported into a fly frame and we
                // know where the end of the table is.
                bool bIsUnicode;
                WW8_FC nFc = m_pSBase->WW8Cp2Fc(pPap->Where(), &bIsUnicode);
                sal_uInt64 nPos = m_pStrm->Tell();
                m_pStrm->Seek(nFc);
                sal_uInt16 nUChar = 0;
                if (bIsUnicode)
                    m_pStrm->ReadUInt16(nUChar);
                else
                {
                    sal_uInt8 nChar = 0;
                    m_pStrm->ReadUChar(nChar);
                    nUChar = nChar;
                }
                m_pStrm->Seek(nPos);
                if (nUChar == 0xc)
                    // The pap after the table starts with a page break, so
                    // there will be no wrapping around the float-table.
                    // Request no fly in this case, so the table can properly
                    // be a multi-page one if necessary.
                    pTabPos->bNoFly = true;
            }
            m_pPlcxMan->GetPap()->Restore( aSave );
        }

        // Then look if we are in an Apo

        ApoTestResults aApo = TestApo(nCellLevel, bTableRowEnd, pTabPos);

        // Look to see if we are in a Table, but Table in foot/end note not allowed
        bool bStartTab = (m_nInTable < nCellLevel) && !m_bFootnoteEdn;

        bool bStopTab = m_bWasTabRowEnd && (m_nInTable > nCellLevel) && !m_bFootnoteEdn;

        m_bWasTabRowEnd = false;  // must be deactivated right here to prevent next
                                // WW8TabDesc::TableCellEnd() from making nonsense

        if (m_nInTable && !bTableRowEnd && !bStopTab && (m_nInTable == nCellLevel && aApo.HasStartStop()))
            bStopTab = bStartTab = true; // Required to stop and start table

        //  Test for Anl (Numbering) and process all events in the right order
        if( m_bAnl && !bTableRowEnd )
        {
            SprmResult aSprm13 = m_pPlcxMan->HasParaSprm(13);
            const sal_uInt8* pSprm13 = aSprm13.pSprm;
            if (pSprm13 && aSprm13.nRemainingData >= 1)
            {   // Still Anl left?
                sal_uInt8 nT = static_cast< sal_uInt8 >(GetNumType( *pSprm13 ));
                if( ( nT != WW8_Pause && nT != m_nWwNumType ) // Anl change
                    || aApo.HasStartStop()                  // Forced Anl end
                    || bStopTab || bStartTab )
                {
                    StopAnlToRestart(nT);  // Anl-Restart (= change) over sprms
                }
                else
                {
                    NextAnlLine( pSprm13 ); // Next Anl Line
                }
            }
            else
            {   // Regular Anl end
                StopAllAnl(); // Actual end
            }
        }
        if (bStopTab)
        {
            StopTable();
            m_aApos.pop_back();
            --m_nInTable;
        }
        if (aApo.mbStopApo)
        {
            StopApo();
            m_aApos[m_nInTable] = false;
        }

        if (aApo.mbStartApo)
        {
            m_aApos[m_nInTable] = StartApo(aApo, pTabPos);
            // We need an ReSync after StartApo
            // (actually only if the Apo extends past a FKP border)
            rbReSync = true;
        }
        if (bStartTab)
        {
            WW8PLCFxSave1 aSave;
            m_pPlcxMan->GetPap()->Save( aSave );

           // Numbering for cell borders causes a crash -> no Anls in Tables
           if (m_bAnl)
               StopAllAnl();

            if(m_nInTable < nCellLevel)
            {
                if (StartTable(nStartCp))
                    ++m_nInTable;
                else
                    break;
                m_aApos.push_back(false);
            }

            if(m_nInTable >= nCellLevel)
            {
                // We need an ReSync after StartTable
                // (actually only if the Apo extends past a FKP border)
                rbReSync = true;
                m_pPlcxMan->GetPap()->Restore( aSave );
            }
        }
    } while (!m_bFootnoteEdn && (m_nInTable < nCellLevel));
    return bTableRowEnd;
}

rtl_TextEncoding SwWW8ImplReader::GetCharSetFromLanguage()
{
    /*
     #i22206#/#i52786#
     The (default) character set used for a run of text is the default
     character set for the version of Word that last saved the document.

     This is a bit tentative, more might be required if the concept is correct.
     When later version of word write older 6/95 documents the charset is
     correctly set in the character runs involved, so its hard to reproduce
     documents that require this to be sure of the process involved.
    */
    const SvxLanguageItem *pLang = static_cast<const SvxLanguageItem*>(GetFormatAttr(RES_CHRATR_LANGUAGE));
    LanguageType eLang = pLang ? pLang->GetLanguage() : LANGUAGE_SYSTEM;
    css::lang::Locale aLocale(LanguageTag::convertToLocale(eLang));
    return msfilter::util::getBestTextEncodingFromLocale(aLocale);
}

rtl_TextEncoding SwWW8ImplReader::GetCJKCharSetFromLanguage()
{
    /*
     #i22206#/#i52786#
     The (default) character set used for a run of text is the default
     character set for the version of Word that last saved the document.

     This is a bit tentative, more might be required if the concept is correct.
     When later version of word write older 6/95 documents the charset is
     correctly set in the character runs involved, so its hard to reproduce
     documents that require this to be sure of the process involved.
    */
    const SvxLanguageItem *pLang = static_cast<const SvxLanguageItem*>(GetFormatAttr(RES_CHRATR_CJK_LANGUAGE));
    LanguageType eLang = pLang ? pLang->GetLanguage() : LANGUAGE_SYSTEM;
    css::lang::Locale aLocale(LanguageTag::convertToLocale(eLang));
    return msfilter::util::getBestTextEncodingFromLocale(aLocale);
}

rtl_TextEncoding SwWW8ImplReader::GetCurrentCharSet()
{
    /*
    #i2015
    If the hard charset is set use it, if not see if there is an open
    character run that has set the charset, if not then fallback to the
    current underlying paragraph style.
    */
    rtl_TextEncoding eSrcCharSet = m_eHardCharSet;
    if (eSrcCharSet == RTL_TEXTENCODING_DONTKNOW)
    {
        if (!m_aFontSrcCharSets.empty())
            eSrcCharSet = m_aFontSrcCharSets.top();
        if ((eSrcCharSet == RTL_TEXTENCODING_DONTKNOW) && m_nCharFormat >= 0 && (size_t)m_nCharFormat < m_vColl.size() )
            eSrcCharSet = m_vColl[m_nCharFormat].GetCharSet();
        if ((eSrcCharSet == RTL_TEXTENCODING_DONTKNOW) && StyleExists(m_nAktColl) && m_nAktColl < m_vColl.size())
            eSrcCharSet = m_vColl[m_nAktColl].GetCharSet();
        if (eSrcCharSet == RTL_TEXTENCODING_DONTKNOW)
            eSrcCharSet = GetCharSetFromLanguage();
    }
    return eSrcCharSet;
}

//Takashi Ono for CJK
rtl_TextEncoding SwWW8ImplReader::GetCurrentCJKCharSet()
{
    /*
    #i2015
    If the hard charset is set use it, if not see if there is an open
    character run that has set the charset, if not then fallback to the
    current underlying paragraph style.
    */
    rtl_TextEncoding eSrcCharSet = m_eHardCharSet;
    if (eSrcCharSet == RTL_TEXTENCODING_DONTKNOW)
    {
        if (!m_aFontSrcCJKCharSets.empty())
            eSrcCharSet = m_aFontSrcCJKCharSets.top();
        if ((eSrcCharSet == RTL_TEXTENCODING_DONTKNOW) && m_nCharFormat >= 0 && (size_t)m_nCharFormat < m_vColl.size() )
            eSrcCharSet = m_vColl[m_nCharFormat].GetCJKCharSet();
        if (eSrcCharSet == RTL_TEXTENCODING_DONTKNOW && StyleExists(m_nAktColl) && m_nAktColl < m_vColl.size())
            eSrcCharSet = m_vColl[m_nAktColl].GetCJKCharSet();
        if (eSrcCharSet == RTL_TEXTENCODING_DONTKNOW)
            eSrcCharSet = GetCJKCharSetFromLanguage();
    }
    return eSrcCharSet;
}

void SwWW8ImplReader::PostProcessAttrs()
{
    if (m_pPostProcessAttrsInfo != nullptr)
    {
        SfxItemIter aIter(m_pPostProcessAttrsInfo->mItemSet);

        const SfxPoolItem * pItem = aIter.GetCurItem();
        if (pItem != nullptr)
        {
            do
            {
                m_pCtrlStck->NewAttr(*m_pPostProcessAttrsInfo->mPaM.GetPoint(),
                                   *pItem);
                m_pCtrlStck->SetAttr(*m_pPostProcessAttrsInfo->mPaM.GetMark(),
                                   pItem->Which());
            }
            while (!aIter.IsAtEnd() && nullptr != (pItem = aIter.NextItem()));
        }

        delete m_pPostProcessAttrsInfo;
        m_pPostProcessAttrsInfo = nullptr;
    }
}

/*
 #i9241#
 It appears that some documents that are in a baltic 8 bit encoding which has
 some undefined characters can have use made of those characters, in which
 case they default to CP1252. If not then its perhaps that the font encoding
 is only in use for 6/7 and for 8+ if we are in 8bit mode then the encoding
 is always 1252.

 So a encoding converter that on an undefined character attempts to
 convert from 1252 on the undefined character
*/
std::size_t Custom8BitToUnicode(rtl_TextToUnicodeConverter hConverter,
    sal_Char *pIn, std::size_t nInLen, sal_Unicode *pOut, std::size_t nOutLen)
{
    const sal_uInt32 nFlags =
        RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR |
        RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR |
        RTL_TEXTTOUNICODE_FLAGS_INVALID_IGNORE |
        RTL_TEXTTOUNICODE_FLAGS_FLUSH;

    const sal_uInt32 nFlags2 =
        RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_IGNORE |
        RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_IGNORE |
        RTL_TEXTTOUNICODE_FLAGS_INVALID_IGNORE |
        RTL_TEXTTOUNICODE_FLAGS_FLUSH;

    std::size_t nDestChars=0;
    std::size_t nConverted=0;

    do
    {
        sal_uInt32 nInfo = 0;
        sal_Size nThisConverted=0;

        nDestChars += rtl_convertTextToUnicode(hConverter, nullptr,
            pIn+nConverted, nInLen-nConverted,
            pOut+nDestChars, nOutLen-nDestChars,
            nFlags, &nInfo, &nThisConverted);

        OSL_ENSURE(nInfo == 0, "A character conversion failed!");

        nConverted += nThisConverted;

        if (
            nInfo & RTL_TEXTTOUNICODE_INFO_UNDEFINED ||
            nInfo & RTL_TEXTTOUNICODE_INFO_MBUNDEFINED
           )
        {
            sal_Size nOtherConverted;
            rtl_TextToUnicodeConverter hCP1252Converter =
                rtl_createTextToUnicodeConverter(RTL_TEXTENCODING_MS_1252);
            nDestChars += rtl_convertTextToUnicode(hCP1252Converter, nullptr,
                pIn+nConverted, 1,
                pOut+nDestChars, nOutLen-nDestChars,
                nFlags2, &nInfo, &nOtherConverted);
            rtl_destroyTextToUnicodeConverter(hCP1252Converter);
            nConverted+=1;
        }
    } while (nConverted < nInLen);

    return nDestChars;
}

bool SwWW8ImplReader::LangUsesHindiNumbers(LanguageType nLang)
{
    bool bResult = false;

    switch ((sal_uInt16)nLang)
    {
        case 0x1401: // Arabic(Algeria)
        case 0x3c01: // Arabic(Bahrain)
        case 0xc01: // Arabic(Egypt)
        case 0x801: // Arabic(Iraq)
        case 0x2c01: // Arabic (Jordan)
        case 0x3401: // Arabic(Kuwait)
        case 0x3001: // Arabic(Lebanon)
        case 0x1001: // Arabic(Libya)
        case 0x1801: // Arabic(Morocco)
        case 0x2001: // Arabic(Oman)
        case 0x4001: // Arabic(Qatar)
        case 0x401: // Arabic(Saudi Arabia)
        case 0x2801: // Arabic(Syria)
        case 0x1c01: // Arabic(Tunisia)
        case 0x3801: // Arabic(U.A.E)
        case 0x2401: // Arabic(Yemen)
            bResult = true;
            break;
        default:
            break;
    }

    return bResult;
}

sal_Unicode SwWW8ImplReader::TranslateToHindiNumbers(sal_Unicode nChar)
{
    if (nChar >= 0x0030 && nChar <= 0x0039)
        return nChar + 0x0630;

    return nChar;
}

namespace
{
    OUString makeOUString(rtl_uString *pStr, sal_Int32 nAllocLen)
    {
        //if read len was in or around that of allocated len, just reuse pStr
        if (nAllocLen < pStr->length + 256)
            return OUString(pStr, SAL_NO_ACQUIRE);
        //otherwise copy the shorter used section to release extra mem
        OUString sRet(pStr->buffer, pStr->length);
        rtl_uString_release(pStr);
        return sRet;
    }
}

/**
 * Return value: true for non special chars
 */
bool SwWW8ImplReader::ReadPlainChars(WW8_CP& rPos, sal_Int32 nEnd, sal_Int32 nCpOfs)
{
    sal_Int32 nRequestedStrLen = nEnd - rPos;

    OSL_ENSURE(nRequestedStrLen, "String is 0");
    if (nRequestedStrLen <= 0)
        return true;

    sal_Int32 nRequestedPos = m_pSBase->WW8Cp2Fc(nCpOfs+rPos, &m_bIsUnicode);
    bool bValidPos = checkSeek(*m_pStrm, nRequestedPos);
    OSL_ENSURE(bValidPos, "Document claimed to have more text than available");
    if (!bValidPos)
    {
        // Swallow missing range, e.g. #i95550#
        rPos+=nRequestedStrLen;
        return true;
    }

    std::size_t nAvailableStrLen = m_pStrm->remainingSize() / (m_bIsUnicode ? 2 : 1);
    OSL_ENSURE(nAvailableStrLen, "Document claimed to have more text than available");
    if (!nAvailableStrLen)
    {
        // Swallow missing range, e.g. #i95550#
        rPos+=nRequestedStrLen;
        return true;
    }

    sal_Int32 nValidStrLen = std::min<std::size_t>(nRequestedStrLen, nAvailableStrLen);

    // Reset Unicode flag and correct FilePos if needed.
    // Note: Seek is not expensive, as we're checking inline whether or not
    // the correct FilePos has already been reached.
    const sal_Int32 nStrLen = std::min(nValidStrLen, SAL_MAX_INT32-1);

    rtl_TextEncoding eSrcCharSet = m_bVer67 ? GetCurrentCharSet() :
        RTL_TEXTENCODING_MS_1252;
    if (m_bVer67 && eSrcCharSet == RTL_TEXTENCODING_MS_932)
    {
        /*
         fdo#82904

         Older documents exported as word 95 that use unicode aware fonts will
         have the charset of those fonts set to RTL_TEXTENCODING_MS_932 on
         export as the conversion from RTL_TEXTENCODING_UNICODE. This is a serious
         pain.

         We will try and use a fallback encoding if the conversion from
         RTL_TEXTENCODING_MS_932 fails, but you can get unlucky and get a document
         which isn't really in RTL_TEXTENCODING_MS_932 but parts of it form
         valid RTL_TEXTENCODING_MS_932 by chance :-(

         We're not the only ones that struggle with this: Here's the help from
         MSOffice 2003 on the topic:

         <<
          Earlier versions of Microsoft Word were sometimes used in conjunction with
          third-party language-processing add-in programs designed to support Chinese or
          Korean on English versions of Microsoft Windows. Use of these add-ins sometimes
          results in incorrect text display in more recent versions of Word.

          However, you can set options to convert these documents so that text is
          displayed correctly. On the Tools menu, click Options, and then click the
          General tab. In the English Word 6.0/95 documents list, select Contain Asian
          text (to have Word interpret the text as Asian code page data, regardless of
          its font) or Automatically detect Asian text (to have Word attempt to determine
          which parts of the text are meant to be Asian).
        >>

        What we can try here is to ignore a RTL_TEXTENCODING_MS_932 codepage if
        the language is not Japanese
        */

        const SfxPoolItem * pItem = GetFormatAttr(RES_CHRATR_CJK_LANGUAGE);
        if (pItem != nullptr && LANGUAGE_JAPANESE != static_cast<const SvxLanguageItem *>(pItem)->GetLanguage())
        {
            SAL_WARN("sw.ww8", "discarding word95 RTL_TEXTENCODING_MS_932 encoding");
            eSrcCharSet = GetCharSetFromLanguage();
        }
    }
    const rtl_TextEncoding eSrcCJKCharSet = m_bVer67 ? GetCurrentCJKCharSet() :
        RTL_TEXTENCODING_MS_1252;

    // allocate unicode string data
    rtl_uString *pStr = rtl_uString_alloc(nStrLen);
    sal_Unicode* pBuffer = pStr->buffer;
    sal_Unicode* pWork = pBuffer;

    sal_Char* p8Bits = nullptr;

    rtl_TextToUnicodeConverter hConverter = nullptr;
    if (!m_bIsUnicode || m_bVer67)
        hConverter = rtl_createTextToUnicodeConverter(eSrcCharSet);

    if (!m_bIsUnicode)
        p8Bits = new sal_Char[nStrLen];

    // read the stream data
    sal_uInt8   nBCode = 0;
    sal_uInt16 nUCode;

    LanguageType nCTLLang = LANGUAGE_SYSTEM;
    const SfxPoolItem * pItem = GetFormatAttr(RES_CHRATR_CTL_LANGUAGE);
    if (pItem != nullptr)
        nCTLLang = static_cast<const SvxLanguageItem *>(pItem)->GetLanguage();

    sal_Int32 nL2;
    for (nL2 = 0; nL2 < nStrLen; ++nL2)
    {
        if (m_bIsUnicode)
            m_pStrm->ReadUInt16( nUCode ); // unicode  --> read 2 bytes
        else
        {
            m_pStrm->ReadUChar( nBCode ); // old code --> read 1 byte
            nUCode = nBCode;
        }

        if (m_pStrm->GetError())
        {
            rPos = WW8_CP_MAX-10; // -> eof or other error
            rtl_freeMemory(pStr);
            delete [] p8Bits;
            return true;
        }

        if ((32 > nUCode) || (0xa0 == nUCode))
        {
            m_pStrm->SeekRel( m_bIsUnicode ? -2 : -1 );
            break; // Special character < 32, == 0xa0 found
        }

        if (m_bIsUnicode)
        {
            if (!m_bVer67)
                *pWork++ = nUCode;
            else
            {
                if (nUCode >= 0x3000) //0x8000 ?
                {
                    sal_Char aTest[2];
                    aTest[0] = static_cast< sal_Char >((nUCode & 0xFF00) >> 8);
                    aTest[1] = static_cast< sal_Char >(nUCode & 0x00FF);
                    OUString aTemp(aTest, 2, eSrcCJKCharSet);
                    OSL_ENSURE(aTemp.getLength() == 1, "so much for that theory");
                    *pWork++ = aTemp[0];
                }
                else
                {
                    sal_Char cTest = static_cast< sal_Char >(nUCode & 0x00FF);
                    pWork += Custom8BitToUnicode(hConverter, &cTest, 1, pWork, 1);
                }
            }
        }
        else
            p8Bits[nL2] = nBCode;
    }

    if (nL2)
    {
        const sal_Int32 nEndUsed = !m_bIsUnicode
            ? Custom8BitToUnicode(hConverter, p8Bits, nL2, pBuffer, nStrLen)
            : pWork - pBuffer;

        if (m_bRegardHindiDigits && m_bBidi && LangUsesHindiNumbers(nCTLLang))
        {
            for (sal_Int32 nI = 0; nI < nEndUsed; ++nI, ++pBuffer)
                *pBuffer = TranslateToHindiNumbers(*pBuffer);
        }

        pStr->buffer[nEndUsed] = 0;
        pStr->length = nEndUsed;

        emulateMSWordAddTextToParagraph(makeOUString(pStr, nStrLen));
        pStr = nullptr;
        rPos += nL2;
        if (!m_aApos.back()) // a para end in apo doesn't count
            m_bWasParaEnd = false; // No CR
    }

    if (hConverter)
        rtl_destroyTextToUnicodeConverter(hConverter);
    if (pStr)
        rtl_uString_release(pStr);
    delete [] p8Bits;
    return nL2 >= nStrLen;
}

#define MSASCII SAL_MAX_INT16

namespace
{
    // We want to force weak chars inside 0x0020 to 0x007F to LATIN
    sal_Int16 lcl_getScriptType(
        const uno::Reference<i18n::XBreakIterator>& rBI,
        const OUString &rString, sal_Int32 nPos)
    {
        sal_Int16 nScript = rBI->getScriptType(rString, nPos);
        if (nScript == i18n::ScriptType::WEAK && rString[nPos] >= 0x0020 && rString[nPos] <= 0x007F)
            nScript = MSASCII;
        return nScript;
    }

    // We want to know about WEAK segments, so endOfScript isn't
    // useful, and see lcl_getScriptType anyway
    sal_Int32 lcl_endOfScript(
        const uno::Reference<i18n::XBreakIterator>& rBI,
        const OUString &rString, sal_Int32 nPos, sal_Int16 nScript)
    {
        while (nPos < rString.getLength())
        {
            sal_Int16 nNewScript = lcl_getScriptType(rBI, rString, nPos);
            if (nScript != nNewScript)
                break;
            ++nPos;
        }
        return nPos;
    }

    sal_Int32 lcl_getWriterScriptType(
        const uno::Reference<i18n::XBreakIterator>& rBI,
        const OUString &rString, sal_Int32 nPos)
    {
        sal_Int16 nScript = i18n::ScriptType::WEAK;

        if (rString.isEmpty())
            return nScript;

        while (nPos >= 0)
        {
            nScript = rBI->getScriptType(rString, nPos);
            if (nScript != i18n::ScriptType::WEAK)
                break;
            --nPos;
        }

        return nScript;
    }

    bool samePitchIgnoreUnknown(FontPitch eA, FontPitch eB)
    {
        return (eA == eB || eA == PITCH_DONTKNOW || eB == PITCH_DONTKNOW);
    }

    bool sameFontIgnoringIrrelevantFields(const SvxFontItem &rA, const SvxFontItem &rB)
    {
        // Ignoring CharSet, and ignoring unknown pitch
        return rA.GetFamilyName() == rB.GetFamilyName() &&
            rA.GetStyleName() == rB.GetStyleName() &&
            rA.GetFamily() == rB.GetFamily() &&
            samePitchIgnoreUnknown(rA.GetPitch(), rB.GetPitch());
    }
}

// In writer we categorize text into CJK, CTL and "Western" for everything else.
// Microsoft Word basically categorizes text into East Asian, Complex, ASCII,
// NonEastAsian/HighAnsi, with some shared characters and some properties to
// hint as to which way to bias those shared characters.

// That's four categories, we however have three categories. Given that problem
// here we would ideally find out "what would word do" to see what font/language
// word would assign to characters based on the unicode range they fall into and
// hack the word one onto the range we use. However it's unclear what word's
// categorization is. So we don't do that here yet.

// Additional to the categorization, when word encounters weak text for ambiguous
// chars it uses idcthint to indicate which way to bias. We don't have a idcthint
// feature in writer.

// So what we currently do here then is to split our text into non-weak/weak
// sections and uses word's idcthint to determine what font it would use and
// force that on for the segment. Following what we *do* know about word's
// categorization, we know that the range 0x0020 and 0x007F is sprmCRgFtc0 in
// word, something we map to LATIN, so we consider all weaks chars in that range
// to auto-bias to LATIN.

// See https://bugs.libreoffice.org/show_bug.cgi?id=34319 for an example
void SwWW8ImplReader::emulateMSWordAddTextToParagraph(const OUString& rAddString)
{
    if (rAddString.isEmpty())
        return;

    uno::Reference<i18n::XBreakIterator> xBI(g_pBreakIt->GetBreakIter());
    assert(xBI.is());

    sal_Int16 nScript = lcl_getScriptType(xBI, rAddString, 0);
    sal_Int32 nLen = rAddString.getLength();

    OUString sParagraphText;
    const SwContentNode *pCntNd = m_pPaM->GetContentNode();
    const SwTextNode* pNd = pCntNd ? pCntNd->GetTextNode() : nullptr;
    if (pNd)
        sParagraphText = pNd->GetText();
    sal_Int32 nParaOffset = sParagraphText.getLength();
    sParagraphText = sParagraphText + rAddString;

    sal_Int32 nPos = 0;
    while (nPos < nLen)
    {
        sal_Int32 nEnd = lcl_endOfScript(xBI, rAddString, nPos, nScript);
        if (nEnd < 0)
            break;

        OUString sChunk(rAddString.copy(nPos, nEnd-nPos));
        const sal_uInt16 aIds[] = {RES_CHRATR_FONT, RES_CHRATR_CJK_FONT, RES_CHRATR_CTL_FONT};
        const SvxFontItem *pOverriddenItems[] = {nullptr, nullptr, nullptr};
        bool aForced[] = {false, false, false};

        int nLclIdctHint = 0xFF;
        if (nScript == i18n::ScriptType::WEAK)
        {
            const SfxInt16Item *pIdctHint = static_cast<const SfxInt16Item*>(GetFormatAttr(RES_CHRATR_IDCTHINT));
            nLclIdctHint = pIdctHint->GetValue();
        }
        else if (nScript == MSASCII) // Force weak chars in ascii range to use LATIN font
            nLclIdctHint = 0;

        sal_uInt16 nForceFromFontId = 0;
        if (nLclIdctHint != 0xFF)
        {
            switch (nLclIdctHint)
            {
                case 0:
                    nForceFromFontId = RES_CHRATR_FONT;
                    break;
                case 1:
                    nForceFromFontId = RES_CHRATR_CJK_FONT;
                    break;
                case 2:
                    nForceFromFontId = RES_CHRATR_CTL_FONT;
                    break;
                default:
                    break;
            }
        }

        if (nForceFromFontId != 0)
        {
            // Now we know that word would use the nForceFromFontId font for this range
            // Try and determine what script writer would assign this range to

            sal_Int32 nWriterScript = lcl_getWriterScriptType(xBI, sParagraphText,
                nPos + nParaOffset);

            bool bWriterWillUseSameFontAsWordAutomatically = false;

            if (nWriterScript != i18n::ScriptType::WEAK)
            {
                if (
                     (nWriterScript == i18n::ScriptType::ASIAN && nForceFromFontId == RES_CHRATR_CJK_FONT) ||
                     (nWriterScript == i18n::ScriptType::COMPLEX && nForceFromFontId == RES_CHRATR_CTL_FONT) ||
                     (nWriterScript == i18n::ScriptType::LATIN && nForceFromFontId == RES_CHRATR_FONT)
                   )
                {
                    bWriterWillUseSameFontAsWordAutomatically = true;
                }
                else
                {
                    const SvxFontItem *pSourceFont = static_cast<const SvxFontItem*>(GetFormatAttr(nForceFromFontId));
                    sal_uInt16 nDestId = aIds[nWriterScript-1];
                    const SvxFontItem *pDestFont = static_cast<const SvxFontItem*>(GetFormatAttr(nDestId));
                    bWriterWillUseSameFontAsWordAutomatically = sameFontIgnoringIrrelevantFields(*pSourceFont, *pDestFont);
                }
            }

            // Writer won't use the same font as word, so force the issue
            if (!bWriterWillUseSameFontAsWordAutomatically)
            {
                const SvxFontItem *pSourceFont = static_cast<const SvxFontItem*>(GetFormatAttr(nForceFromFontId));

                for (size_t i = 0; i < SAL_N_ELEMENTS(aIds); ++i)
                {
                    const SvxFontItem *pDestFont = static_cast<const SvxFontItem*>(GetFormatAttr(aIds[i]));
                    aForced[i] = aIds[i] != nForceFromFontId && *pSourceFont != *pDestFont;
                    if (aForced[i])
                    {
                        pOverriddenItems[i] =
                            static_cast<const SvxFontItem*>(m_pCtrlStck->GetStackAttr(*m_pPaM->GetPoint(), aIds[i]));

                        SvxFontItem aForceFont(*pSourceFont);
                        aForceFont.SetWhich(aIds[i]);
                        m_pCtrlStck->NewAttr(*m_pPaM->GetPoint(), aForceFont);
                    }
                }
            }
        }

        simpleAddTextToParagraph(sChunk);

        for (size_t i = 0; i < SAL_N_ELEMENTS(aIds); ++i)
        {
            if (aForced[i])
            {
                m_pCtrlStck->SetAttr(*m_pPaM->GetPoint(), aIds[i]);
                if (pOverriddenItems[i])
                    m_pCtrlStck->NewAttr(*m_pPaM->GetPoint(), *(pOverriddenItems[i]));
            }
        }

        nPos = nEnd;
        if (nPos < nLen)
            nScript = lcl_getScriptType(xBI, rAddString, nPos);
    }
}

void SwWW8ImplReader::simpleAddTextToParagraph(const OUString& rAddString)
{
    if (rAddString.isEmpty())
        return;

#if OSL_DEBUG_LEVEL > 1
        {
            OString sText(OUStringToOString(rAddString, RTL_TEXTENCODING_UTF8));
            SAL_INFO("sw.ww8", "<addTextToParagraph>" << sText.getStr() << "</addTextToParagraph>");
        }
#endif

    const SwContentNode *pCntNd = m_pPaM->GetContentNode();
    const SwTextNode* pNd = pCntNd ? pCntNd->GetTextNode() : nullptr;

    OSL_ENSURE(pNd, "What the hell, where's my text node");

    if (!pNd)
        return;

    const sal_Int32 nCharsLeft = SAL_MAX_INT32 - pNd->GetText().getLength();
    if (nCharsLeft > 0)
    {
        if (rAddString.getLength() <= nCharsLeft)
        {
            m_rDoc.getIDocumentContentOperations().InsertString(*m_pPaM, rAddString);
        }
        else
        {
            m_rDoc.getIDocumentContentOperations().InsertString(*m_pPaM, rAddString.copy(0, nCharsLeft));
            AppendTextNode(*m_pPaM->GetPoint());
            m_rDoc.getIDocumentContentOperations().InsertString(*m_pPaM, rAddString.copy(nCharsLeft));
        }
    }
    else
    {
        AppendTextNode(*m_pPaM->GetPoint());
        m_rDoc.getIDocumentContentOperations().InsertString(*m_pPaM, rAddString);
    }

    m_bReadTable = false;
}

/**
 * Return value: true for para end
 */
bool SwWW8ImplReader::ReadChars(WW8_CP& rPos, WW8_CP nNextAttr, long nTextEnd,
    long nCpOfs)
{
    long nEnd = ( nNextAttr < nTextEnd ) ? nNextAttr : nTextEnd;

    if (m_bSymbol || m_bIgnoreText)
    {
        WW8_CP nRequested = nEnd - rPos;
        if (m_bSymbol) // Insert special chars
        {
            sal_uInt64 nMaxPossible = m_pStrm->remainingSize();
            if (static_cast<sal_uInt64>(nRequested) > nMaxPossible)
            {
                SAL_WARN("sw.ww8", "document claims to have more characters, " << nRequested << " than remaining, " << nMaxPossible);
                nRequested = nMaxPossible;
            }

            for (WW8_CP nCh = 0; nCh < nRequested; ++nCh)
            {
                m_rDoc.getIDocumentContentOperations().InsertString( *m_pPaM, OUString(m_cSymbol) );
            }
            m_pCtrlStck->SetAttr( *m_pPaM->GetPoint(), RES_CHRATR_FONT );
            m_pCtrlStck->SetAttr( *m_pPaM->GetPoint(), RES_CHRATR_CJK_FONT );
            m_pCtrlStck->SetAttr( *m_pPaM->GetPoint(), RES_CHRATR_CTL_FONT );
        }
        m_pStrm->SeekRel(nRequested);
        rPos = nEnd; // Ignore until attribute end
        return false;
    }

    while (true)
    {
        if (ReadPlainChars(rPos, nEnd, nCpOfs))
            return false; // Done

        bool bStartLine = ReadChar(rPos, nCpOfs);
        rPos++;
        if (m_bPgSecBreak || bStartLine || rPos == nEnd) // CR or Done
        {
            return bStartLine;
        }
    }
}

bool SwWW8ImplReader::HandlePageBreakChar()
{
    bool bParaEndAdded = false;
    // #i1909# section/page breaks should not occur in tables, word
    // itself ignores them in this case.
    if (!m_nInTable)
    {
        bool IsTemp=true;
        SwTextNode* pTemp = m_pPaM->GetNode().GetTextNode();
        if (pTemp && pTemp->GetText().isEmpty()
                && (m_bFirstPara || m_bFirstParaOfPage))
        {
            IsTemp = false;
            AppendTextNode(*m_pPaM->GetPoint());
            pTemp->SetAttr(*GetDfltAttr(RES_PARATR_NUMRULE));
        }

        m_bPgSecBreak = true;
        m_pCtrlStck->KillUnlockedAttrs(*m_pPaM->GetPoint());
        /*
        If it's a 0x0c without a paragraph end before it, act like a
        paragraph end, but nevertheless, numbering (and perhaps other
        similar constructs) do not exist on the para.
        */
        if (!m_bWasParaEnd && IsTemp)
        {
            bParaEndAdded = true;
            if (0 >= m_pPaM->GetPoint()->nContent.GetIndex())
            {
                if (SwTextNode* pTextNode = m_pPaM->GetNode().GetTextNode())
                {
                    pTextNode->SetAttr(
                        *GetDfltAttr(RES_PARATR_NUMRULE));
                }
            }
        }
    }
    return bParaEndAdded;
}

bool SwWW8ImplReader::ReadChar(long nPosCp, long nCpOfs)
{
    bool bNewParaEnd = false;
    // Reset Unicode flag and correct FilePos if needed.
    // Note: Seek is not expensive, as we're checking inline whether or not
    // the correct FilePos has already been reached.
    std::size_t nRequestedPos = m_pSBase->WW8Cp2Fc(nCpOfs+nPosCp, &m_bIsUnicode);
    if (!checkSeek(*m_pStrm, nRequestedPos))
        return false;

    sal_uInt8 nBCode(0);
    sal_uInt16 nWCharVal(0);
    if( m_bIsUnicode )
        m_pStrm->ReadUInt16( nWCharVal ); // unicode  --> read 2 bytes
    else
    {
        m_pStrm -> ReadUChar( nBCode ); // old code --> read 1 byte
        nWCharVal = nBCode;
    }

    sal_Unicode cInsert = '\x0';
    bool bParaMark = false;

    if ( 0xc != nWCharVal )
        m_bFirstParaOfPage = false;

    switch (nWCharVal)
    {
        case 0:
            {
                // Page number
                SwPageNumberField aField(
                    static_cast<SwPageNumberFieldType*>(m_rDoc.getIDocumentFieldsAccess().GetSysFieldType(
                    SwFieldIds::PageNumber )), PG_RANDOM, SVX_NUM_ARABIC);
                m_rDoc.getIDocumentContentOperations().InsertPoolItem(*m_pPaM, SwFormatField(aField));
            }
            break;
        case 0xe:
            // if there is only one column word treats a column break like a pagebreak.
            if (m_aSectionManager.CurrentSectionColCount() < 2)
                bParaMark = HandlePageBreakChar();
            else if (!m_nInTable)
            {
                // Always insert a txtnode for a column break, e.g. ##
                SwContentNode *pCntNd=m_pPaM->GetContentNode();
                if (pCntNd!=nullptr && pCntNd->Len()>0) // if par is empty not break is needed
                    AppendTextNode(*m_pPaM->GetPoint());
                m_rDoc.getIDocumentContentOperations().InsertPoolItem(*m_pPaM, SvxFormatBreakItem(SvxBreak::ColumnBefore, RES_BREAK));
            }
            break;
        case 0x7:
            {
                bNewParaEnd = true;
                WW8PLCFxDesc* pPap = m_pPlcxMan->GetPap();
                //The last paragraph of each cell is terminated by a special
                //paragraph mark called a cell mark. Following the cell mark
                //that ends the last cell of a table row, the table row is
                //terminated by a special paragraph mark called a row mark
                //
                //So the 0x7 should be right at the end of the previous
                //range to be a real cell-end.
                if (pPap->nOrigStartPos == nPosCp+1 ||
                    pPap->nOrigStartPos == WW8_CP_MAX)
                {
                    TabCellEnd();       // Table cell/row end
                }
                else
                    bParaMark = true;
            }
            break;
        case 0xf:
            if( !m_bSpec )        // "Satellite"
                cInsert = u'\x00a4';
            break;
        case 0x14:
            if( !m_bSpec )        // "Para End" char
                cInsert = u'\x00b5';
                    //TODO: should this be U+00B6 PILCROW SIGN rather than
                    // U+00B5 MICRO SIGN?
            break;
        case 0x15:
            if( !m_bSpec )        // Juristenparagraph
            {
                cp_set::iterator aItr = m_aTOXEndCps.find((WW8_CP)nPosCp);
                if (aItr == m_aTOXEndCps.end())
                    cInsert = u'\x00a7';
                else
                    m_aTOXEndCps.erase(aItr);
            }
            break;
        case 0x9:
            cInsert = '\x9';    // Tab
            break;
        case 0xb:
            cInsert = '\xa';    // Hard NewLine
            break;
        case 0xc:
            bParaMark = HandlePageBreakChar();
            break;
        case 0x1e:              // Non-breaking hyphen
            m_rDoc.getIDocumentContentOperations().InsertString( *m_pPaM, OUString(CHAR_HARDHYPHEN) );
            break;
        case 0x1f:              // Non-required hyphens
            m_rDoc.getIDocumentContentOperations().InsertString( *m_pPaM, OUString(CHAR_SOFTHYPHEN) );
            break;
        case 0xa0:              // Non-breaking spaces
            m_rDoc.getIDocumentContentOperations().InsertString( *m_pPaM, OUString(CHAR_HARDBLANK)  );
            break;
        case 0x1:
            /*
            Current thinking is that if bObj is set then we have a
            straightforward "traditional" ole object, otherwise we have a
            graphic preview of an associated ole2 object (or a simple
            graphic of course)

            normally in the canvas field, the code is 0x8 0x1.
            in a special case, the code is 0x1 0x1, which yields a simple picture
            */
            {
                bool bReadObj = IsInlineEscherHack();
                if( bReadObj )
                {
                    long nCurPos = m_pStrm->Tell();
                    sal_uInt16 nWordCode(0);

                    if( m_bIsUnicode )
                        m_pStrm->ReadUInt16( nWordCode );
                    else
                    {
                        sal_uInt8 nByteCode(0);
                        m_pStrm->ReadUChar( nByteCode );
                        nWordCode = nByteCode;
                    }
                    if( nWordCode == 0x1 )
                        bReadObj = false;
                    m_pStrm->Seek( nCurPos );
                }
                if( !bReadObj )
                {
                    SwFrameFormat *pResult = nullptr;
                    if (m_bObj)
                        pResult = ImportOle();
                    else if (m_bSpec)
                        pResult = ImportGraf();

                    // If we have a bad 0x1 insert a space instead.
                    if (!pResult)
                    {
                        cInsert = ' ';
                        OSL_ENSURE(!m_bObj && !m_bEmbeddObj && !m_nObjLocFc,
                            "WW8: Please report this document, it may have a "
                            "missing graphic");
                    }
                    else
                    {
                        // reset the flags.
                        m_bObj = m_bEmbeddObj = false;
                        m_nObjLocFc = 0;
                    }
                }
            }
            break;
        case 0x8:
            if( !m_bObj )
                Read_GrafLayer( nPosCp );
            break;
        case 0xd:
            bNewParaEnd = bParaMark = true;
            if (m_nInTable > 1)
            {
                /*
                #i9666#/#i23161#
                Yes complex, if there is an entry in the undocumented PLCF
                which I believe to be a record of cell and row boundaries
                see if the magic bit which I believe to mean cell end is
                set. I also think btw that the third byte of the 4 byte
                value is the level of the cell
                */
                WW8PLCFspecial* pTest = m_pPlcxMan->GetMagicTables();
                if (pTest && pTest->SeekPosExact(nPosCp+1+nCpOfs) &&
                    pTest->Where() == nPosCp+1+nCpOfs)
                {
                    WW8_FC nPos;
                    void *pData;
                    sal_uInt32 nData = pTest->Get(nPos, pData) ? SVBT32ToUInt32(*static_cast<SVBT32*>(pData))
                                                               : 0;
                    if (nData & 0x2) // Might be how it works
                    {
                        TabCellEnd();
                        bParaMark = false;
                    }
                }
                // tdf#106799: We expect TTP marks to be also cell marks,
                // but sometimes sprmPFInnerTtp comes without sprmPFInnerTableCell
                else if (m_bWasTabCellEnd || m_bWasTabRowEnd)
                {
                    TabCellEnd();
                    bParaMark = false;
                }
            }

            m_bWasTabCellEnd = false;

            break;              // line end
        case 0x5:               // Annotation reference
        case 0x13:
            break;
        case 0x2:               // TODO: Auto-Footnote-Number, should be replaced by SwWW8ImplReader::End_Footnote later
            if (!m_aFootnoteStack.empty())
                cInsert = 0x2;
            break;
        default:
            SAL_INFO( "sw.ww8.level2", "<unknownValue val=\"" << nWCharVal << "\">" );
            break;
    }

    if( '\x0' != cInsert )
    {
        OUString sInsert(cInsert);
        emulateMSWordAddTextToParagraph(sInsert);
    }
    if (!m_aApos.back()) // a para end in apo doesn't count
        m_bWasParaEnd = bNewParaEnd;
    return bParaMark;
}

void SwWW8ImplReader::ProcessAktCollChange(WW8PLCFManResult& rRes,
    bool* pStartAttr, bool bCallProcessSpecial)
{
    sal_uInt16 nOldColl = m_nAktColl;
    m_nAktColl = m_pPlcxMan->GetColl();

    // Invalid Style-Id
    if (m_nAktColl >= m_vColl.size() || !m_vColl[m_nAktColl].m_pFormat || !m_vColl[m_nAktColl].m_bColl)
    {
        m_nAktColl = 0;
        m_bParaAutoBefore = false;
        m_bParaAutoAfter = false;
    }
    else
    {
        m_bParaAutoBefore = m_vColl[m_nAktColl].m_bParaAutoBefore;
        m_bParaAutoAfter = m_vColl[m_nAktColl].m_bParaAutoAfter;
    }

    if (nOldColl >= m_vColl.size())
        nOldColl = 0; // guess! TODO make sure this is what we want

    bool bTabRowEnd = false;
    if( pStartAttr && bCallProcessSpecial && !m_bInHyperlink )
    {
        bool bReSync;
        // Frame/Table/Autonumbering List Level
        bTabRowEnd = ProcessSpecial(bReSync, rRes.nAktCp+m_pPlcxMan->GetCpOfs());
        if( bReSync )
            *pStartAttr = m_pPlcxMan->Get( &rRes ); // Get Attribut-Pos again
    }

    if (!bTabRowEnd && StyleExists(m_nAktColl))
    {
        SetTextFormatCollAndListLevel( *m_pPaM, m_vColl[ m_nAktColl ]);
        ChkToggleAttr(m_vColl[ nOldColl ].m_n81Flags, m_vColl[ m_nAktColl ].m_n81Flags);
        ChkToggleBiDiAttr(m_vColl[nOldColl].m_n81BiDiFlags,
            m_vColl[m_nAktColl].m_n81BiDiFlags);
    }
}

long SwWW8ImplReader::ReadTextAttr(WW8_CP& rTextPos, long nTextEnd, bool& rbStartLine)
{
    long nSkipChars = 0;
    WW8PLCFManResult aRes;

    OSL_ENSURE(m_pPaM->GetNode().GetTextNode(), "Missing txtnode");
    bool bStartAttr = m_pPlcxMan->Get(&aRes); // Get Attribute position again
    aRes.nAktCp = rTextPos;                  // Current Cp position

    bool bNewSection = (aRes.nFlags & MAN_MASK_NEW_SEP) && !m_bIgnoreText;
    if ( bNewSection ) // New Section
    {
        OSL_ENSURE(m_pPaM->GetNode().GetTextNode(), "Missing txtnode");
        // Create PageDesc and fill it
        m_aSectionManager.CreateSep(rTextPos);
        // -> 0xc was a Sectionbreak, but not a Pagebreak;
        // Create PageDesc and fill it
        m_bPgSecBreak = false;
        OSL_ENSURE(m_pPaM->GetNode().GetTextNode(), "Missing txtnode");
    }

    // New paragraph over Plcx.Fkp.papx
    if ( (aRes.nFlags & MAN_MASK_NEW_PAP)|| rbStartLine )
    {
        ProcessAktCollChange( aRes, &bStartAttr,
            MAN_MASK_NEW_PAP == (aRes.nFlags & MAN_MASK_NEW_PAP) &&
            !m_bIgnoreText );
        rbStartLine = false;
    }

    // position of last CP that's to be ignored
    long nSkipPos = -1;

    if( 0 < aRes.nSprmId ) // Ignore empty Attrs
    {
        if( ( eFTN > aRes.nSprmId ) || ( 0x0800 <= aRes.nSprmId ) )
        {
            if( bStartAttr ) // WW attributes
            {
                if( aRes.nMemLen >= 0 )
                    ImportSprm(aRes.pMemPos, aRes.nMemLen, aRes.nSprmId);
            }
            else
                EndSprm( aRes.nSprmId ); // Switch off Attr
        }
        else if( aRes.nSprmId < 0x800 ) // Own helper attributes
        {
            if (bStartAttr)
            {
                nSkipChars = ImportExtSprm(&aRes);
                if (
                    (aRes.nSprmId == eFTN) || (aRes.nSprmId == eEDN) ||
                    (aRes.nSprmId == eFLD) || (aRes.nSprmId == eAND)
                   )
                {
                    WW8_CP nMaxLegalSkip = nTextEnd - rTextPos;
                    // Skip Field/Footnote-/End-Note here
                    rTextPos += std::min<WW8_CP>(nSkipChars, nMaxLegalSkip);
                    nSkipPos = rTextPos-1;
                }
            }
            else
                EndExtSprm( aRes.nSprmId );
        }
    }

    sal_Int32 nRequestedPos = m_pSBase->WW8Cp2Fc(m_pPlcxMan->GetCpOfs() + rTextPos, &m_bIsUnicode);
    bool bValidPos = checkSeek(*m_pStrm, nRequestedPos);
    SAL_WARN_IF(!bValidPos, "sw.ww8", "Document claimed to have text at an invalid position, skip attributes for region");

    // Find next Attr position (and Skip attributes of field contents if needed)
    if (nSkipChars && !m_bIgnoreText)
        m_pCtrlStck->MarkAllAttrsOld();
    bool bOldIgnoreText = m_bIgnoreText;
    m_bIgnoreText = true;
    sal_uInt16 nOldColl = m_nAktColl;
    bool bDoPlcxManPlusPLus = true;
    long nNext;
    do
    {
        if( bDoPlcxManPlusPLus )
            m_pPlcxMan->advance();
        nNext = bValidPos ? m_pPlcxMan->Where() : nTextEnd;

        if (m_pPostProcessAttrsInfo &&
            m_pPostProcessAttrsInfo->mnCpStart == nNext)
        {
            m_pPostProcessAttrsInfo->mbCopy = true;
        }

        if( (0 <= nNext) && (nSkipPos >= nNext) )
        {
            nNext = ReadTextAttr(rTextPos, nTextEnd, rbStartLine);
            bDoPlcxManPlusPLus = false;
            m_bIgnoreText = true;
        }

        if (m_pPostProcessAttrsInfo &&
            nNext > m_pPostProcessAttrsInfo->mnCpEnd)
        {
            m_pPostProcessAttrsInfo->mbCopy = false;
        }
    }
    while( nSkipPos >= nNext );
    m_bIgnoreText    = bOldIgnoreText;
    if( nSkipChars )
    {
        m_pCtrlStck->KillUnlockedAttrs( *m_pPaM->GetPoint() );
        if( nOldColl != m_pPlcxMan->GetColl() )
            ProcessAktCollChange(aRes, nullptr, false);
    }

    return nNext;
}

//Revised 2012.8.16 for the complex attribute presentation of 0x0D in MS
bool SwWW8ImplReader::IsParaEndInCPs(sal_Int32 nStart, sal_Int32 nEnd,bool bSdOD) const
{
    //Revised for performance consideration
    if (nStart == -1 || nEnd == -1 || nEnd < nStart )
        return false;

    for (cp_vector::const_reverse_iterator aItr = m_aEndParaPos.rbegin(); aItr!= m_aEndParaPos.rend(); ++aItr)
    {
        //Revised 2012.8.16,to the 0x0D,the attribute will have two situations
        //*********within***********exact******
        //*********but also sample with only left and the position of 0x0d is the edge of the right side***********
        if ( bSdOD && ( (nStart < *aItr && nEnd > *aItr) || ( nStart == nEnd && *aItr == nStart)) )
            return true;
        else if ( !bSdOD &&  (nStart < *aItr && nEnd >= *aItr) )
            return true;
    }

    return false;
}

//Clear the para end position recorded in reader intermittently for the least impact on loading performance
void SwWW8ImplReader::ClearParaEndPosition()
{
    if ( m_aEndParaPos.size() > 0 )
        m_aEndParaPos.clear();
}

void SwWW8ImplReader::ReadAttrs(WW8_CP& rTextPos, WW8_CP& rNext, long nTextEnd, bool& rbStartLine)
{
    // Dow we have attributes?
    if( rTextPos >= rNext )
    {
        do
        {
            m_aCurrAttrCP = rTextPos;
            rNext = ReadTextAttr(rTextPos, nTextEnd, rbStartLine);
            if (rTextPos == rNext && rTextPos >= nTextEnd)
                break;
        }
        while( rTextPos >= rNext );

    }
    else if ( rbStartLine )
    {
    /* No attributes, but still a new line.
     * If a line ends with a line break and paragraph attributes or paragraph templates
     * do NOT change the line end was not added to the Plcx.Fkp.papx i.e. (nFlags & MAN_MASK_NEW_PAP)
     * is false.
     * Due to this we need to set the template here as a kind of special treatment.
     */
    if (!m_bCpxStyle && m_nAktColl < m_vColl.size())
            SetTextFormatCollAndListLevel(*m_pPaM, m_vColl[m_nAktColl]);
        rbStartLine = false;
    }
}

/**
 * CloseAttrEnds to only read the attribute ends at the end of a text or a
 * text area (Header, Footnote, ...).
 * We ignore attribute starts and fields.
 */
void SwWW8ImplReader::CloseAttrEnds()
{
    // If there are any unclosed sprms then copy them to
    // another stack and close the ones that must be closed
    std::stack<sal_uInt16> aStack;
    m_pPlcxMan->TransferOpenSprms(aStack);

    while (!aStack.empty())
    {
        sal_uInt16 nSprmId = aStack.top();
        if ((0 < nSprmId) && (( eFTN > nSprmId) || (0x0800 <= nSprmId)))
            EndSprm(nSprmId);
        aStack.pop();
    }

    EndSpecial();
}

bool SwWW8ImplReader::ReadText(WW8_CP nStartCp, WW8_CP nTextLen, ManTypes nType)
{
    bool bJoined=false;

    bool bStartLine = true;
    short nCrCount = 0;
    short nDistance = 0;

    m_bWasParaEnd = false;
    m_nAktColl    =  0;
    m_pAktItemSet =  nullptr;
    m_nCharFormat    = -1;
    m_bSpec = false;
    m_bPgSecBreak = false;

    m_pPlcxMan = new WW8PLCFMan( m_pSBase, nType, nStartCp );
    long nCpOfs = m_pPlcxMan->GetCpOfs(); // Offset for Header/Footer, Footnote

    WW8_CP nNext = m_pPlcxMan->Where();
    SwTextNode* pPreviousNode = nullptr;
    sal_uInt8 nDropLines = 0;
    SwCharFormat* pNewSwCharFormat = nullptr;
    const SwCharFormat* pFormat = nullptr;
    m_pStrm->Seek( m_pSBase->WW8Cp2Fc( nStartCp + nCpOfs, &m_bIsUnicode ) );

    WW8_CP l = nStartCp;
    const WW8_CP nMaxPossible = WW8_CP_MAX-nStartCp;
    if (nTextLen > nMaxPossible)
    {
        SAL_WARN_IF(nTextLen > nMaxPossible, "sw.ww8", "TextLen too long");
        nTextLen = nMaxPossible;
    }
    WW8_CP nTextEnd = nStartCp+nTextLen;
    while (l < nTextEnd)
    {
        ReadAttrs( l, nNext, nTextEnd, bStartLine );// Takes SectionBreaks into account, too
        OSL_ENSURE(m_pPaM->GetNode().GetTextNode(), "Missing txtnode");

        if (m_pPostProcessAttrsInfo != nullptr)
            PostProcessAttrs();

        if (l >= nTextEnd)
            break;

        bStartLine = ReadChars(l, nNext, nTextEnd, nCpOfs);

        // If the previous paragraph was a dropcap then do not
        // create a new txtnode and join the two paragraphs together
        if (bStartLine && !pPreviousNode) // Line end
        {
            bool bSplit = true;
            if (m_bCareFirstParaEndInToc)
            {
                m_bCareFirstParaEndInToc = false;
                if (m_pPaM->End() && m_pPaM->End()->nNode.GetNode().GetTextNode() &&  m_pPaM->End()->nNode.GetNode().GetTextNode()->Len() == 0)
                    bSplit = false;
            }
            if (m_bCareLastParaEndInToc)
            {
                m_bCareLastParaEndInToc = false;
                if (m_pPaM->End() && m_pPaM->End()->nNode.GetNode().GetTextNode() &&  m_pPaM->End()->nNode.GetNode().GetTextNode()->Len() == 0)
                    bSplit = false;
            }
            if (bSplit)
            {
                // We will record the CP of a paragraph end ('0x0D'), if current loading contents is from main stream;
                if (m_bOnLoadingMain)
                    m_aEndParaPos.push_back(l-1);
                AppendTextNode(*m_pPaM->GetPoint());
            }
        }

        if (pPreviousNode && bStartLine)
        {
            SwTextNode* pEndNd = m_pPaM->GetNode().GetTextNode();
            const sal_Int32 nDropCapLen = pPreviousNode->GetText().getLength();

            // Need to reset the font size and text position for the dropcap
            {
                SwPaM aTmp(*pEndNd, 0, *pEndNd, nDropCapLen+1);
                m_pCtrlStck->Delete(aTmp);
            }

            // Get the default document dropcap which we can use as our template
            const SwFormatDrop* defaultDrop =
                static_cast<const SwFormatDrop*>( GetFormatAttr(RES_PARATR_DROP));
            SwFormatDrop aDrop(*defaultDrop);

            aDrop.GetLines() = nDropLines;
            aDrop.GetDistance() = nDistance;
            aDrop.GetChars() = writer_cast<sal_uInt8>(nDropCapLen);
            // Word has no concept of a "whole word dropcap"
            aDrop.GetWholeWord() = false;

            if (pFormat)
                aDrop.SetCharFormat(const_cast<SwCharFormat*>(pFormat));
            else if(pNewSwCharFormat)
                aDrop.SetCharFormat(pNewSwCharFormat);

            SwPosition aStart(*pEndNd);
            m_pCtrlStck->NewAttr(aStart, aDrop);
            m_pCtrlStck->SetAttr(*m_pPaM->GetPoint(), RES_PARATR_DROP);
            pPreviousNode = nullptr;
        }
        else if (m_bDropCap)
        {
            // If we have found a dropcap store the textnode
            pPreviousNode = m_pPaM->GetNode().GetTextNode();

            SprmResult aDCS;
            if (m_bVer67)
                aDCS = m_pPlcxMan->GetPapPLCF()->HasSprm(46);
            else
                aDCS = m_pPlcxMan->GetPapPLCF()->HasSprm(0x442C);

            if (aDCS.pSprm && aDCS.nRemainingData >= 1)
                nDropLines = (*aDCS.pSprm) >> 3;
            else    // There is no Drop Cap Specifier hence no dropcap
                pPreviousNode = nullptr;

            SprmResult aDistance = m_pPlcxMan->GetPapPLCF()->HasSprm(0x842F);
            if (aDistance.pSprm && aDistance.nRemainingData >= 2)
                nDistance = SVBT16ToShort(aDistance.pSprm);
            else
                nDistance = 0;

            const SwFormatCharFormat *pSwFormatCharFormat = nullptr;

            if(m_pAktItemSet)
                pSwFormatCharFormat = &(ItemGet<SwFormatCharFormat>(*m_pAktItemSet, RES_TXTATR_CHARFMT));

            if(pSwFormatCharFormat)
                pFormat = pSwFormatCharFormat->GetCharFormat();

            if(m_pAktItemSet && !pFormat)
            {
                OUString sPrefix(OUStringBuffer("WW8Dropcap").append(m_nDropCap++).makeStringAndClear());
                pNewSwCharFormat = m_rDoc.MakeCharFormat(sPrefix, m_rDoc.GetDfltCharFormat());
                 m_pAktItemSet->ClearItem(RES_CHRATR_ESCAPEMENT);
                pNewSwCharFormat->SetFormatAttr( *m_pAktItemSet );
            }

            delete m_pAktItemSet;
            m_pAktItemSet = nullptr;
            m_bDropCap=false;
        }

        if (bStartLine || m_bWasTabRowEnd)
        {
            // Call all 64 CRs; not for Header and the like
            if ((nCrCount++ & 0x40) == 0 && nType == MAN_MAINTEXT)
            {
                m_nProgress = (sal_uInt16)( l * 100 / nTextLen );
                ::SetProgressState(m_nProgress, m_pDocShell); // Update
            }
        }

        // If we have encountered a 0x0c which indicates either section of
        // pagebreak then look it up to see if it is a section break, and
        // if it is not then insert a page break. If it is a section break
        // it will be handled as such in the ReadAttrs of the next loop
        if (m_bPgSecBreak)
        {
            // We need only to see if a section is ending at this cp,
            // the plcf will already be sitting on the correct location
            // if it is there.
            WW8PLCFxDesc aTemp;
            aTemp.nStartPos = aTemp.nEndPos = WW8_CP_MAX;
            if (m_pPlcxMan->GetSepPLCF())
                m_pPlcxMan->GetSepPLCF()->GetSprms(&aTemp);
            if ((aTemp.nStartPos != l) && (aTemp.nEndPos != l))
            {
                // #i39251# - insert text node for page break, if no one inserted.
                // #i43118# - refine condition: the anchor
                // control stack has to have entries, otherwise it's not needed
                // to insert a text node.
                if (!bStartLine && !m_pAnchorStck->empty())
                {
                    AppendTextNode(*m_pPaM->GetPoint());
                }
                m_rDoc.getIDocumentContentOperations().InsertPoolItem(*m_pPaM,
                    SvxFormatBreakItem(SvxBreak::PageBefore, RES_BREAK));
                m_bFirstParaOfPage = true;
                m_bPgSecBreak = false;
            }
        }
    }

    if (m_pPaM->GetPoint()->nContent.GetIndex())
        AppendTextNode(*m_pPaM->GetPoint());

    if (!m_bInHyperlink)
        bJoined = JoinNode(*m_pPaM);

    CloseAttrEnds();

    delete m_pPlcxMan;
    m_pPlcxMan = nullptr;
    return bJoined;
}

SwWW8ImplReader::SwWW8ImplReader(sal_uInt8 nVersionPara, SotStorage* pStorage,
    SvStream* pSt, SwDoc& rD, const OUString& rBaseURL, bool bNewDoc, bool bSkipImages, SwPosition &rPos)
    : m_pDocShell(rD.GetDocShell())
    , m_pStg(pStorage)
    , m_pStrm(pSt)
    , m_pTableStream(nullptr)
    , m_pDataStream(nullptr)
    , m_rDoc(rD)
    , m_pPaM(nullptr)
    , m_pCtrlStck(nullptr)
    , m_pRedlineStack(nullptr)
    , m_pReffedStck(nullptr)
    , m_pReffingStck(nullptr)
    , m_pAnchorStck(nullptr)
    , m_aSectionManager(*this)
    , m_aExtraneousParas(rD)
    , m_aInsertedTables(rD)
    , m_aSectionNameGenerator(rD, "WW")
    , m_pSprmParser(nullptr)
    , m_aGrfNameGenerator(bNewDoc, OUString('G'))
    , m_aParaStyleMapper(rD)
    , m_aCharStyleMapper(rD)
    , m_pFormImpl(nullptr)
    , m_pFlyFormatOfJustInsertedGraphic(nullptr)
    , m_pFormatOfJustInsertedApo(nullptr)
    , m_pPreviousNumPaM(nullptr)
    , m_pPrevNumRule(nullptr)
    , m_pPostProcessAttrsInfo(nullptr)
    , m_pWwFib(nullptr)
    , m_pFonts(nullptr)
    , m_pWDop(nullptr)
    , m_pLstManager(nullptr)
    , m_pSBase(nullptr)
    , m_pPlcxMan(nullptr)
    , m_aTextNodesHavingFirstLineOfstSet()
    , m_aTextNodesHavingLeftIndentSet()
    , m_pStyles(nullptr)
    , m_pAktColl(nullptr)
    , m_pAktItemSet(nullptr)
    , m_pDfltTextFormatColl(nullptr)
    , m_pStandardFormatColl(nullptr)
    , m_pHdFt(nullptr)
    , m_pTableDesc(nullptr)
    , m_pNumOlst(nullptr)
    , m_pDrawModel(nullptr)
    , m_pDrawPg(nullptr)
    , m_pDrawEditEngine(nullptr)
    , m_pWWZOrder(nullptr)
    , m_pNumFieldType(nullptr)
    , m_pMSDffManager(nullptr)
    , m_pAtnNames(nullptr)
    , m_sBaseURL(rBaseURL)
    , m_nIniFlags(0)
    , m_nIniFlags1(0)
    , m_nFieldFlags(0)
    , m_bRegardHindiDigits( false )
    , m_bDrawCpOValid( false )
    , m_nDrawCpO(0)
    , m_nPicLocFc(0)
    , m_nObjLocFc(0)
    , m_nIniFlyDx(0)
    , m_nIniFlyDy(0)
    , m_eTextCharSet(RTL_TEXTENCODING_ASCII_US)
    , m_eStructCharSet(RTL_TEXTENCODING_ASCII_US)
    , m_eHardCharSet(RTL_TEXTENCODING_DONTKNOW)
    , m_nProgress(0)
    , m_nAktColl(0)
    , m_nFieldNum(0)
    , m_nLFOPosition(USHRT_MAX)
    , m_nCharFormat(0)
    , m_nDrawXOfs(0)
    , m_nDrawYOfs(0)
    , m_nDrawXOfs2(0)
    , m_nDrawYOfs2(0)
    , m_cSymbol(0)
    , m_nWantedVersion(nVersionPara)
    , m_nSwNumLevel(0xff)
    , m_nWwNumType(0xff)
    , m_nListLevel(WW8ListManager::nMaxLevel)
    , m_bNewDoc(bNewDoc)
    , m_bSkipImages(bSkipImages)
    , m_bReadNoTable(false)
    , m_bPgSecBreak(false)
    , m_bSpec(false)
    , m_bObj(false)
    , m_bTxbxFlySection(false)
    , m_bHasBorder(false)
    , m_bSymbol(false)
    , m_bIgnoreText(false)
    , m_nInTable(0)
    , m_bWasTabRowEnd(false)
    , m_bWasTabCellEnd(false)
    , m_bAnl(false)
    , m_bHdFtFootnoteEdn(false)
    , m_bFootnoteEdn(false)
    , m_bIsHeader(false)
    , m_bIsFooter(false)
    , m_bIsUnicode(false)
    , m_bCpxStyle(false)
    , m_bStyNormal(false)
    , m_bWWBugNormal(false)
    , m_bNoAttrImport(false)
    , m_bInHyperlink(false)
    , m_bWasParaEnd(false)
    , m_bVer67(false)
    , m_bVer6(false)
    , m_bVer7(false)
    , m_bVer8(false)
    , m_bEmbeddObj(false)
    , m_bAktAND_fNumberAcross(false)
    , m_bNoLnNumYet(true)
    , m_bFirstPara(true)
    , m_bFirstParaOfPage(false)
    , m_bParaAutoBefore(false)
    , m_bParaAutoAfter(false)
    , m_bDropCap(false)
    , m_nDropCap(0)
    , m_bBidi(false)
    , m_bReadTable(false)
    , m_bLoadingTOXCache(false)
    , m_nEmbeddedTOXLevel(0)
    , m_bLoadingTOXHyperlink(false)
    , m_pPosAfterTOC(nullptr)
    , m_bCareFirstParaEndInToc(false)
    , m_bCareLastParaEndInToc(false)
    , m_aTOXEndCps()
    , m_aCurrAttrCP(-1)
    , m_bOnLoadingMain(false)
{
    m_pStrm->SetEndian( SvStreamEndian::LITTLE );
    m_aApos.push_back(false);

    mpCursor = m_rDoc.CreateUnoCursor(rPos);
}

void SwWW8ImplReader::DeleteStack(SwFltControlStack* pStck)
{
    if( pStck )
    {
        pStck->SetAttr( *m_pPaM->GetPoint(), 0, false);
        pStck->SetAttr( *m_pPaM->GetPoint(), 0, false);
        delete pStck;
    }
    else
    {
        OSL_ENSURE( false, "WW-Stack bereits geloescht" );
    }
}

void wwSectionManager::SetSegmentToPageDesc(const wwSection &rSection,
    bool bIgnoreCols)
{
    SwPageDesc &rPage = *rSection.mpPage;

    SetNumberingType(rSection, rPage);

    SwFrameFormat &rFormat = rPage.GetMaster();

    if(mrReader.m_pWDop->fUseBackGroundInAllmodes) // #i56806# Make sure mrReader is initialized
        mrReader.GrafikCtor();

    if (mrReader.m_pWDop->fUseBackGroundInAllmodes && mrReader.m_pMSDffManager)
    {
        tools::Rectangle aRect(0, 0, 100, 100); // A dummy, we don't care about the size
        SvxMSDffImportData aData(aRect);
        SdrObject* pObject = nullptr;
        if (mrReader.m_pMSDffManager->GetShape(0x401, pObject, aData))
        {
            // Only handle shape if it is a background shape
            if (((*aData.begin())->nFlags & 0x400) != 0)
            {
                SfxItemSet aSet(rFormat.GetAttrSet());
                mrReader.MatchSdrItemsIntoFlySet(pObject, aSet, mso_lineSimple,
                                                 mso_lineSolid, mso_sptRectangle, aRect);
                rFormat.SetFormatAttr(aSet.Get(RES_BACKGROUND));
            }
        }
        SdrObject::Free(pObject);
    }
    wwULSpaceData aULData;
    GetPageULData(rSection, aULData);
    SetPageULSpaceItems(rFormat, aULData, rSection);

    rPage.SetVerticalAdjustment( rSection.mnVerticalAdjustment );

    SetPage(rPage, rFormat, rSection, bIgnoreCols);

    if (!(rSection.maSep.pgbApplyTo & 1))
        SwWW8ImplReader::SetPageBorder(rFormat, rSection);
    if (!(rSection.maSep.pgbApplyTo & 2))
        SwWW8ImplReader::SetPageBorder(rPage.GetFirstMaster(), rSection);

    mrReader.SetDocumentGrid(rFormat, rSection);
}

void wwSectionManager::SetUseOn(wwSection &rSection)
{
    bool bMirror = mrReader.m_pWDop->fMirrorMargins ||
        mrReader.m_pWDop->doptypography.f2on1;

    UseOnPage eUseBase = bMirror ? UseOnPage::Mirror : UseOnPage::All;
    UseOnPage eUse = eUseBase;
    if (!mrReader.m_pWDop->fFacingPages)
        eUse |= UseOnPage::HeaderShare | UseOnPage::FooterShare;
    if (!rSection.HasTitlePage())
        eUse |= UseOnPage::FirstShare;

    OSL_ENSURE(rSection.mpPage, "Makes no sense to call me with no pages to set");
    if (rSection.mpPage)
        rSection.mpPage->WriteUseOn(eUse);
}

/**
 * Set the page descriptor on this node, handle the different cases for a text
 * node or a table
 */
void GiveNodePageDesc(SwNodeIndex &rIdx, const SwFormatPageDesc &rPgDesc,
    SwDoc &rDoc)
{
    /*
    If it's a table here, apply the pagebreak to the table
    properties, otherwise we add it to the para at this
    position
    */
    if (rIdx.GetNode().IsTableNode())
    {
        SwTable& rTable =
            rIdx.GetNode().GetTableNode()->GetTable();
        SwFrameFormat* pApply = rTable.GetFrameFormat();
        OSL_ENSURE(pApply, "impossible");
        if (pApply)
            pApply->SetFormatAttr(rPgDesc);
    }
    else
    {
        SwPosition aPamStart(rIdx);
        aPamStart.nContent.Assign(
            rIdx.GetNode().GetContentNode(), 0);
        SwPaM aPage(aPamStart);

        rDoc.getIDocumentContentOperations().InsertPoolItem(aPage, rPgDesc);
    }
}

/**
 * Map a word section to a writer page descriptor
 */
SwFormatPageDesc wwSectionManager::SetSwFormatPageDesc(mySegIter &rIter,
    mySegIter &rStart, bool bIgnoreCols)
{
    if (mrReader.m_bNewDoc && rIter == rStart)
    {
        rIter->mpPage =
            mrReader.m_rDoc.getIDocumentStylePoolAccess().GetPageDescFromPool(RES_POOLPAGE_STANDARD);
    }
    else
    {
        rIter->mpPage = mrReader.m_rDoc.MakePageDesc(
            SwViewShell::GetShellRes()->GetPageDescName(mnDesc, ShellResource::NORMAL_PAGE),
            nullptr, false);
    }
    OSL_ENSURE(rIter->mpPage, "no page!");
    if (!rIter->mpPage)
        return SwFormatPageDesc();

    // Set page before hd/ft
    const wwSection *pPrevious = nullptr;
    if (rIter != rStart)
        pPrevious = &(*(rIter-1));
    SetHdFt(*rIter, std::distance(rStart, rIter), pPrevious);
    SetUseOn(*rIter);

    // Set hd/ft after set page
    SetSegmentToPageDesc(*rIter, bIgnoreCols);

    SwFormatPageDesc aRet(rIter->mpPage);

    rIter->mpPage->SetFollow(rIter->mpPage);

    if (rIter->PageRestartNo())
        aRet.SetNumOffset(rIter->PageStartAt());

    ++mnDesc;
    return aRet;
}

void wwSectionManager::InsertSegments()
{
    const SvtFilterOptions& rOpt = SvtFilterOptions::Get();
    bool bUseEnhFields = rOpt.IsUseEnhancedFields();
    mySegIter aEnd = maSegments.end();
    mySegIter aStart = maSegments.begin();
    for (mySegIter aIter = aStart; aIter != aEnd; ++aIter)
    {
        // If the section is of type "New column" (0x01), then simply insert a column break.
        // But only if there actually are columns on the page, otherwise a column break
        // seems to be handled like a page break by MSO.
        if ( aIter->maSep.bkc == 1 && aIter->maSep.ccolM1 > 0 )
        {
            SwPaM start( aIter->maStart );
            mrReader.m_rDoc.getIDocumentContentOperations().InsertPoolItem( start, SvxFormatBreakItem(SvxBreak::ColumnBefore, RES_BREAK));
            continue;
        }

        mySegIter aNext = aIter+1;
        mySegIter aPrev = (aIter == aStart) ? aIter : aIter-1;

        // If two following sections are different in following properties, Word will interprete a continuous
        // section break between them as if it was a section break next page.
        bool bThisAndPreviousAreCompatible = ((aIter->GetPageWidth() == aPrev->GetPageWidth()) &&
            (aIter->GetPageHeight() == aPrev->GetPageHeight()) && (aIter->IsLandScape() == aPrev->IsLandScape()));

        bool bInsertSection = (aIter != aStart) && aIter->IsContinuous() &&  bThisAndPreviousAreCompatible;
        bool bInsertPageDesc = !bInsertSection;
        // HACK Force new pagedesc if margins change, otherwise e.g. floating tables may be anchored improperly.
        if( aIter->maSep.dyaTop != aPrev->maSep.dyaTop || aIter->maSep.dyaBottom != aPrev->maSep.dyaBottom
            || aIter->maSep.dxaLeft != aPrev->maSep.dxaLeft || aIter->maSep.dxaRight != aPrev->maSep.dxaRight )
            bInsertPageDesc = true;
        bool bProtected = SectionIsProtected(*aIter); // do we really  need this ?? I guess I have a different logic in editshell which disables this...
        if (bUseEnhFields && mrReader.m_pWDop->fProtEnabled && aIter->IsNotProtected())
        {
            // here we have the special case that the whole document is protected, with the exception of this section.
            // I want to address this when I do the section rework, so for the moment we disable the overall protection then...
            mrReader.m_rDoc.getIDocumentSettingAccess().set(DocumentSettingId::PROTECT_FORM, false );
        }

        if (bInsertPageDesc)
        {
            /*
             If a cont section follows this section then we won't be
             creating a page desc with 2+ cols as we cannot host a one
             col section in a 2+ col pagedesc and make it look like
             word. But if the current section actually has columns then
             we are forced to insert a section here as well as a page
             descriptor.
            */

            bool bIgnoreCols = false;
            bool bThisAndNextAreCompatible = (aNext == aEnd) ||
                ((aIter->GetPageWidth() == aNext->GetPageWidth()) &&
                 (aIter->GetPageHeight() == aNext->GetPageHeight()) &&
                 (aIter->IsLandScape() == aNext->IsLandScape()));

            if (((aNext != aEnd && aNext->IsContinuous() && bThisAndNextAreCompatible) || bProtected))
            {
                bIgnoreCols = true;
                if ((aIter->NoCols() > 1) || bProtected)
                    bInsertSection = true;
            }

            SwFormatPageDesc aDesc(SetSwFormatPageDesc(aIter, aStart, bIgnoreCols));
            if (!aDesc.GetPageDesc())
                continue;

            // special case handling for odd/even section break
            // a) as before create a new page style for the section break
            // b) set Layout of generated page style to right/left ( according
            //    to section break odd/even )
            // c) create a new style to follow the break page style
            if ( aIter->maSep.bkc == 3 || aIter->maSep.bkc == 4 )
            {
                // SetSwFormatPageDesc calls some methods that could
                // modify aIter (e.g. wwSection ).
                // Since  we call SetSwFormatPageDesc below to generate the
                // 'Following' style of the Break style, it is safer
                // to take  a copy of the contents of aIter.
                wwSection aTmpSection = *aIter;
                // create a new following page style
                SwFormatPageDesc aFollow(SetSwFormatPageDesc(aIter, aStart, bIgnoreCols));
                // restore any contents of aIter trashed by SetSwFormatPageDesc
                *aIter = aTmpSection;

                // Handle the section break
                UseOnPage eUseOnPage = UseOnPage::Left;
                if ( aIter->maSep.bkc == 4 ) // Odd ( right ) Section break
                    eUseOnPage = UseOnPage::Right;

                // Keep the share flags.
                aDesc.GetPageDesc()->SetUseOn( eUseOnPage );
                aDesc.GetPageDesc()->SetFollow( aFollow.GetPageDesc() );
            }

            GiveNodePageDesc(aIter->maStart, aDesc, mrReader.m_rDoc);
        }

        SwTextNode* pTextNd = nullptr;
        if (bInsertSection)
        {
            // Start getting the bounds of this section
            SwPaM aSectPaM(*mrReader.m_pPaM, mrReader.m_pPaM);
            SwNodeIndex aAnchor(aSectPaM.GetPoint()->nNode);
            if (aNext != aEnd)
            {
                aAnchor = aNext->maStart;
                aSectPaM.GetPoint()->nNode = aAnchor;
                aSectPaM.GetPoint()->nContent.Assign(
                    aNext->maStart.GetNode().GetContentNode(), 0);
                aSectPaM.Move(fnMoveBackward);
            }

            const SwPosition* pPos  = aSectPaM.GetPoint();
            SwTextNode const*const pSttNd = pPos->nNode.GetNode().GetTextNode();
            const SwTableNode* pTableNd = pSttNd ? pSttNd->FindTableNode() : nullptr;
            if (pTableNd)
            {
                pTextNd =
                    mrReader.m_rDoc.GetNodes().MakeTextNode(aAnchor,
                    mrReader.m_rDoc.getIDocumentStylePoolAccess().GetTextCollFromPool( RES_POOLCOLL_TEXT ));

                aSectPaM.GetPoint()->nNode.Assign(*pTextNd);
                aSectPaM.GetPoint()->nContent.Assign(
                    aSectPaM.GetContentNode(), 0);
            }

            aSectPaM.SetMark();

            aSectPaM.GetPoint()->nNode = aIter->maStart;
            aSectPaM.GetPoint()->nContent.Assign(
                aSectPaM.GetContentNode(), 0);

            bool bHasOwnHdFt = false;
            /*
             In this nightmare scenario the continuous section has its own
             headers and footers so we will try and find a hard page break
             between here and the end of the section and put the headers and
             footers there.
            */
            if (!bInsertPageDesc)
            {
               bHasOwnHdFt =
                mrReader.HasOwnHeaderFooter(
                 aIter->maSep.grpfIhdt & ~(WW8_HEADER_FIRST | WW8_FOOTER_FIRST),
                 aIter->maSep.grpfIhdt, std::distance(aStart, aIter)
                );
            }
            if (bHasOwnHdFt)
            {
                // #i40766# Need to cache the page descriptor in case there is
                // no page break in the section
                SwPageDesc *pOrig = aIter->mpPage;
                bool bFailed = true;
                SwFormatPageDesc aDesc(SetSwFormatPageDesc(aIter, aStart, true));
                if (aDesc.GetPageDesc())
                {
                    sal_uLong nStart = aSectPaM.Start()->nNode.GetIndex();
                    sal_uLong nEnd   = aSectPaM.End()->nNode.GetIndex();
                    for(; nStart <= nEnd; ++nStart)
                    {
                        SwNode* pNode = mrReader.m_rDoc.GetNodes()[nStart];
                        if (!pNode)
                            continue;
                        if (sw::util::HasPageBreak(*pNode))
                        {
                            SwNodeIndex aIdx(*pNode);
                            GiveNodePageDesc(aIdx, aDesc, mrReader.m_rDoc);
                            bFailed = false;
                            break;
                        }
                    }
                }
                if(bFailed)
                {
                    aIter->mpPage = pOrig;
                }
            }

            // End getting the bounds of this section, quite a job eh?
            SwSectionFormat *pRet = InsertSection(aSectPaM, *aIter);
            // The last section if continuous is always unbalanced
            if (pRet)
            {
                // Set the columns to be UnBalanced if that compatibility option is set
                if (mrReader.m_pWDop->fNoColumnBalance)
                    pRet->SetFormatAttr(SwFormatNoBalancedColumns(true));
                else
                {
                    // Otherwise set to unbalanced if the following section is
                    // not continuous, (which also means that the last section
                    // is unbalanced)
                    if (aNext == aEnd || !aNext->IsContinuous())
                        pRet->SetFormatAttr(SwFormatNoBalancedColumns(true));
                }
            }
        }

        if (pTextNd)
        {
            SwNodeIndex aIdx(*pTextNd);
            SwPaM aTest(aIdx);
            mrReader.m_rDoc.getIDocumentContentOperations().DelFullPara(aTest);
            pTextNd = nullptr;
        }
    }
}

void wwExtraneousParas::delete_all_from_doc()
{
    auto aEnd = m_aTextNodes.rend();
    for (auto aI = m_aTextNodes.rbegin(); aI != aEnd; ++aI)
    {
        SwTextNode *pTextNode = *aI;
        SwNodeIndex aIdx(*pTextNode);
        SwPaM aTest(aIdx);
        m_rDoc.getIDocumentContentOperations().DelFullPara(aTest);
    }
    m_aTextNodes.clear();
}

void SwWW8ImplReader::StoreMacroCmds()
{
    if (m_pWwFib->m_lcbCmds)
    {
        m_pTableStream->Seek(m_pWwFib->m_fcCmds);

        uno::Reference < embed::XStorage > xRoot(m_pDocShell->GetStorage());

        if (!xRoot.is())
            return;

        try
        {
            uno::Reference < io::XStream > xStream =
                    xRoot->openStreamElement( SL::aMSMacroCmds, embed::ElementModes::READWRITE );
            std::unique_ptr<SvStream> xOutStream(::utl::UcbStreamHelper::CreateStream(xStream));

            sal_uInt32 lcbCmds = std::min<sal_uInt32>(m_pWwFib->m_lcbCmds, m_pTableStream->remainingSize());
            std::unique_ptr<sal_uInt8[]> xBuffer(new sal_uInt8[lcbCmds]);
            m_pWwFib->m_lcbCmds = m_pTableStream->ReadBytes(xBuffer.get(), lcbCmds);
            xOutStream->WriteBytes(xBuffer.get(), m_pWwFib->m_lcbCmds);
        }
        catch (...)
        {
        }
    }
}

void SwWW8ImplReader::ReadDocVars()
{
    std::vector<OUString> aDocVarStrings;
    std::vector<ww::bytes> aDocVarStringIds;
    std::vector<OUString> aDocValueStrings;
    WW8ReadSTTBF(!m_bVer67, *m_pTableStream, m_pWwFib->m_fcStwUser,
        m_pWwFib->m_lcbStwUser, m_bVer67 ? 2 : 0, m_eStructCharSet,
        aDocVarStrings, &aDocVarStringIds, &aDocValueStrings);
    if (!m_bVer67) {
        using namespace ::com::sun::star;

        uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
            m_pDocShell->GetModel(), uno::UNO_QUERY_THROW);
        uno::Reference<document::XDocumentProperties> xDocProps(
            xDPS->getDocumentProperties());
        OSL_ENSURE(xDocProps.is(), "DocumentProperties is null");
        uno::Reference<beans::XPropertyContainer> xUserDefinedProps =
            xDocProps->getUserDefinedProperties();
        OSL_ENSURE(xUserDefinedProps.is(), "UserDefinedProperties is null");

        for(size_t i=0; i<aDocVarStrings.size(); i++)
        {
            const OUString &rName = aDocVarStrings[i];
            uno::Any aValue;
            aValue <<= rName;
            try {
                xUserDefinedProps->addProperty( rName,
                    beans::PropertyAttribute::REMOVABLE,
                    aValue );
            } catch (const uno::Exception &) {
                // ignore
            }
        }
    }
}

/**
 * Document Info
 */
void SwWW8ImplReader::ReadDocInfo()
{
    if( m_pStg )
    {
        uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
            m_pDocShell->GetModel(), uno::UNO_QUERY_THROW);
        uno::Reference<document::XDocumentProperties> xDocProps(
            xDPS->getDocumentProperties());
        OSL_ENSURE(xDocProps.is(), "DocumentProperties is null");

        if (xDocProps.is()) {
            if ( m_pWwFib->m_fDot )
            {
                OUString sTemplateURL;
                SfxMedium* pMedium = m_pDocShell->GetMedium();
                if ( pMedium )
                {
                    OUString aName = pMedium->GetName();
                    INetURLObject aURL( aName );
                    sTemplateURL = aURL.GetMainURL(INetURLObject::DecodeMechanism::ToIUri);
                    if ( !sTemplateURL.isEmpty() )
                        xDocProps->setTemplateURL( sTemplateURL );
                }
            }
            else if (m_pWwFib->m_lcbSttbfAssoc) // not a template, and has a SttbfAssoc
            {
                long nCur = m_pTableStream->Tell();
                Sttb aSttb;
                m_pTableStream->Seek( m_pWwFib->m_fcSttbfAssoc ); // point at tgc record
                if (!aSttb.Read( *m_pTableStream ) )
                    SAL_WARN("sw.ww8", "** Read of SttbAssoc data failed!!!! ");
                m_pTableStream->Seek( nCur ); // return to previous position, is that necessary?
#if OSL_DEBUG_LEVEL > 1
                aSttb.Print( stderr );
#endif
                OUString sPath = aSttb.getStringAtIndex( 0x1 );
                OUString aURL;
                // attempt to convert to url (won't work for obvious reasons on linux)
                if ( !sPath.isEmpty() )
                    osl::FileBase::getFileURLFromSystemPath( sPath, aURL );
                if (aURL.isEmpty())
                    xDocProps->setTemplateURL( aURL );
                else
                    xDocProps->setTemplateURL( sPath );

            }
            sfx2::LoadOlePropertySet(xDocProps, m_pStg);
        }
    }
}

static void lcl_createTemplateToProjectEntry( const uno::Reference< container::XNameContainer >& xPrjNameCache, const OUString& sTemplatePathOrURL, const OUString& sVBAProjName )
{
    if ( xPrjNameCache.is() )
    {
        INetURLObject aObj;
        aObj.SetURL( sTemplatePathOrURL );
        bool bIsURL = aObj.GetProtocol() != INetProtocol::NotValid;
        OUString aURL;
        if ( bIsURL )
            aURL = sTemplatePathOrURL;
        else
        {
            osl::FileBase::getFileURLFromSystemPath( sTemplatePathOrURL, aURL );
            aObj.SetURL( aURL );
        }
        try
        {
            OUString templateNameWithExt = aObj.GetLastName();
            OUString templateName;
            sal_Int32 nIndex =  templateNameWithExt.lastIndexOf( '.' );
            if ( nIndex != -1 )
            {
                templateName = templateNameWithExt.copy( 0, nIndex );
                xPrjNameCache->insertByName( templateName, uno::makeAny( sVBAProjName ) );
            }
        }
        catch( const uno::Exception& )
        {
        }
    }
}

class WW8Customizations
{
    SvStream* mpTableStream;
    WW8Fib mWw8Fib;
public:
    WW8Customizations( SvStream*, WW8Fib& );
    void  Import( SwDocShell* pShell );
};

WW8Customizations::WW8Customizations( SvStream* pTableStream, WW8Fib& rFib ) : mpTableStream(pTableStream), mWw8Fib( rFib )
{
}

void WW8Customizations::Import( SwDocShell* pShell )
{
    if ( mWw8Fib.m_lcbCmds == 0 || !IsEightPlus(mWw8Fib.GetFIBVersion()) )
        return;
    try
    {
        Tcg aTCG;
        long nCur = mpTableStream->Tell();
        mpTableStream->Seek( mWw8Fib.m_fcCmds ); // point at tgc record
        bool bReadResult = aTCG.Read( *mpTableStream );
        mpTableStream->Seek( nCur ); // return to previous position, is that necessary?
        if ( !bReadResult )
        {
            SAL_WARN("sw.ww8", "** Read of Customization data failed!!!! ");
            return;
        }
#if OSL_DEBUG_LEVEL > 1
        aTCG.Print( stderr );
#endif
        aTCG.ImportCustomToolBar( *pShell );
    }
    catch(...)
    {
        SAL_WARN("sw.ww8", "** Read of Customization data failed!!!! epically");
    }
}

void SwWW8ImplReader::ReadGlobalTemplateSettings( const OUString& sCreatedFrom, const uno::Reference< container::XNameContainer >& xPrjNameCache )
{
    if (utl::ConfigManager::IsAvoidConfig())
        return;

    SvtPathOptions aPathOpt;
    OUString aAddinPath = aPathOpt.GetAddinPath();
    uno::Sequence< OUString > sGlobalTemplates;

    // first get the autoload addins in the directory STARTUP
    uno::Reference<ucb::XSimpleFileAccess3> xSFA(ucb::SimpleFileAccess::create(::comphelper::getProcessComponentContext()));

    if( xSFA->isFolder( aAddinPath ) )
        sGlobalTemplates = xSFA->getFolderContents( aAddinPath, false );

    sal_Int32 nEntries = sGlobalTemplates.getLength();
    for ( sal_Int32 i=0; i<nEntries; ++i )
    {
        INetURLObject aObj;
        aObj.SetURL( sGlobalTemplates[ i ] );
        bool bIsURL = aObj.GetProtocol() != INetProtocol::NotValid;
        OUString aURL;
        if ( bIsURL )
                aURL = sGlobalTemplates[ i ];
        else
                osl::FileBase::getFileURLFromSystemPath( sGlobalTemplates[ i ], aURL );
        if ( !aURL.endsWithIgnoreAsciiCase( ".dot" ) || ( !sCreatedFrom.isEmpty() && sCreatedFrom.equals( aURL ) ) )
            continue; // don't try and read the same document as ourselves

        tools::SvRef<SotStorage> rRoot = new SotStorage( aURL, StreamMode::STD_READWRITE );

        BasicProjImportHelper aBasicImporter( *m_pDocShell );
        // Import vba via oox filter
        aBasicImporter.import( m_pDocShell->GetMedium()->GetInputStream() );
        lcl_createTemplateToProjectEntry( xPrjNameCache, aURL, aBasicImporter.getProjectName() );
        // Read toolbars & menus
        tools::SvRef<SotStorageStream> refMainStream = rRoot->OpenSotStream( "WordDocument");
        refMainStream->SetEndian(SvStreamEndian::LITTLE);
        WW8Fib aWwFib( *refMainStream, 8 );
        tools::SvRef<SotStorageStream> xTableStream =
                rRoot->OpenSotStream(aWwFib.m_fWhichTableStm ? SL::a1Table : SL::a0Table, StreamMode::STD_READ);

        if (xTableStream.is() && SVSTREAM_OK == xTableStream->GetError())
        {
            xTableStream->SetEndian(SvStreamEndian::LITTLE);
            WW8Customizations aGblCustomisations( xTableStream.get(), aWwFib );
            aGblCustomisations.Import( m_pDocShell );
        }
    }
}

sal_uLong SwWW8ImplReader::CoreLoad(WW8Glossary *pGloss)
{
    sal_uLong nErrRet = 0;

    m_rDoc.SetDocumentType( SwDoc::DOCTYPE_MSWORD );
    if (m_bNewDoc && m_pStg && !pGloss)
    {
        // Initialize RDF metadata, to be able to add statements during the import.
        try
        {
            uno::Reference<rdf::XDocumentMetadataAccess> xDocumentMetadataAccess(m_rDoc.GetDocShell()->GetBaseModel(), uno::UNO_QUERY_THROW);
            uno::Reference<uno::XComponentContext> xComponentContext(comphelper::getProcessComponentContext());
            uno::Reference<embed::XStorage> xStorage = comphelper::OStorageHelper::GetTemporaryStorage();
            const uno::Reference<rdf::XURI> xBaseURI(sfx2::createBaseURI(xComponentContext, xStorage, m_sBaseURL));
            uno::Reference<task::XInteractionHandler> xHandler;
            xDocumentMetadataAccess->loadMetadataFromStorage(xStorage, xBaseURI, xHandler);
        }
        catch (const uno::Exception& rException)
        {
            SAL_WARN("sw.ww8", "SwWW8ImplReader::CoreLoad: failed to initialize RDF metadata: " << rException.Message);
        }
        ReadDocInfo();
    }

    ::ww8::WW8FibData * pFibData = new ::ww8::WW8FibData();

    if (m_pWwFib->m_fReadOnlyRecommended)
        pFibData->setReadOnlyRecommended(true);
    else
        pFibData->setReadOnlyRecommended(false);

    if (m_pWwFib->m_fWriteReservation)
        pFibData->setWriteReservation(true);
    else
        pFibData->setWriteReservation(false);

    ::sw::tExternalDataPointer pExternalFibData(pFibData);

    m_rDoc.getIDocumentExternalData().setExternalData(::sw::tExternalDataType::FIB, pExternalFibData);

    ::sw::tExternalDataPointer pSttbfAsoc
          (new ::ww8::WW8Sttb<ww8::WW8Struct>(*m_pTableStream, m_pWwFib->m_fcSttbfAssoc, m_pWwFib->m_lcbSttbfAssoc));

    m_rDoc.getIDocumentExternalData().setExternalData(::sw::tExternalDataType::STTBF_ASSOC, pSttbfAsoc);

    if (m_pWwFib->m_fWriteReservation || m_pWwFib->m_fReadOnlyRecommended)
    {
        SwDocShell * pDocShell = m_rDoc.GetDocShell();
        if (pDocShell)
            pDocShell->SetReadOnlyUI();
    }

    m_pPaM = mpCursor.get();

    m_pCtrlStck = new SwWW8FltControlStack( &m_rDoc, m_nFieldFlags, *this );

    m_pRedlineStack = new sw::util::RedlineStack(m_rDoc);

    /*
        RefFieldStck: Keeps track of bookmarks which may be inserted as
        variables instead.
    */
    m_pReffedStck = new SwWW8ReferencedFltEndStack(&m_rDoc, m_nFieldFlags);
    m_pReffingStck = new SwWW8FltRefStack(&m_rDoc, m_nFieldFlags);

    m_pAnchorStck = new SwWW8FltAnchorStack(&m_rDoc, m_nFieldFlags);

    size_t nPageDescOffset = m_rDoc.GetPageDescCnt();

    SwNodeIndex aSttNdIdx( m_rDoc.GetNodes() );
    SwRelNumRuleSpaces aRelNumRule(m_rDoc, m_bNewDoc);

    RedlineFlags eMode = RedlineFlags::ShowInsert;

    m_pSprmParser = new wwSprmParser(*m_pWwFib);

    // Set handy helper variables
    m_bVer6  = (6 == m_pWwFib->m_nVersion);
    m_bVer7  = (7 == m_pWwFib->m_nVersion);
    m_bVer67 = m_bVer6 || m_bVer7;
    m_bVer8  = (8 == m_pWwFib->m_nVersion);

    m_eTextCharSet = WW8Fib::GetFIBCharset(m_pWwFib->m_chse, m_pWwFib->m_lid);
    m_eStructCharSet = WW8Fib::GetFIBCharset(m_pWwFib->m_chseTables, m_pWwFib->m_lid);

    m_bWWBugNormal = m_pWwFib->m_nProduct == 0xc03d;

    if (!m_bNewDoc)
        aSttNdIdx = m_pPaM->GetPoint()->nNode;

    ::StartProgress(STR_STATSTR_W4WREAD, 0, 100, m_pDocShell);

    // read Font Table
    m_pFonts = new WW8Fonts( *m_pTableStream, *m_pWwFib );

    // Document Properties
    m_pWDop = new WW8Dop( *m_pTableStream, m_pWwFib->m_nFib, m_pWwFib->m_fcDop,
        m_pWwFib->m_lcbDop );

    if (m_bNewDoc)
        ImportDop();

    /*
        Import revisioning data: author names
    */
    if( m_pWwFib->m_lcbSttbfRMark )
    {
        ReadRevMarkAuthorStrTabl( *m_pTableStream,
                                    m_pWwFib->m_fcSttbfRMark,
                                    m_pWwFib->m_lcbSttbfRMark, m_rDoc );
    }

    // Initialize our String/ID map for Linked Sections
    std::vector<OUString> aLinkStrings;
    std::vector<ww::bytes> aStringIds;

    WW8ReadSTTBF(!m_bVer67, *m_pTableStream, m_pWwFib->m_fcSttbFnm,
        m_pWwFib->m_lcbSttbFnm, m_bVer67 ? 2 : 0, m_eStructCharSet,
        aLinkStrings, &aStringIds);

    for (size_t i=0; i < aLinkStrings.size() && i < aStringIds.size(); ++i)
    {
        const ww::bytes& stringId = aStringIds[i];
        if (stringId.size() < sizeof(WW8_STRINGID))
        {
            SAL_WARN("sw.ww8", "SwWW8ImplReader::CoreLoad: WW8_STRINGID is too short");
            continue;
        }
        const WW8_STRINGID *stringIdStruct = reinterpret_cast<const WW8_STRINGID*>(stringId.data());
        m_aLinkStringMap[SVBT16ToShort(stringIdStruct->nStringId)] = aLinkStrings[i];
    }

    ReadDocVars(); // import document variables as meta information.

    ::SetProgressState(m_nProgress, m_pDocShell);    // Update

    m_pLstManager = new WW8ListManager( *m_pTableStream, *this );

    /*
        first (1) import all styles (see WW8PAR2.CXX)
            BEFORE the import of the lists !!
    */
    ::SetProgressState(m_nProgress, m_pDocShell);    // Update
    m_pStyles = new WW8RStyle( *m_pWwFib, this );     // Styles
    m_pStyles->Import();

    /*
        In the end: (also see WW8PAR3.CXX)

        Go through all Styles and attach respective List Format
        AFTER we imported the Styles and AFTER we imported the Lists!
    */
    ::SetProgressState(m_nProgress, m_pDocShell); // Update
    m_pStyles->PostProcessStyles();

    if (!m_vColl.empty())
        SetOutlineStyles();

    m_pSBase = new WW8ScannerBase(m_pStrm,m_pTableStream,m_pDataStream,m_pWwFib);

    static const SvxNumType eNumTA[16] =
    {
        SVX_NUM_ARABIC, SVX_NUM_ROMAN_UPPER, SVX_NUM_ROMAN_LOWER,
        SVX_NUM_CHARS_UPPER_LETTER_N, SVX_NUM_CHARS_LOWER_LETTER_N,
        SVX_NUM_ARABIC, SVX_NUM_ARABIC, SVX_NUM_ARABIC,
        SVX_NUM_ARABIC, SVX_NUM_ARABIC, SVX_NUM_ARABIC,
        SVX_NUM_ARABIC, SVX_NUM_ARABIC, SVX_NUM_ARABIC,
        SVX_NUM_ARABIC, SVX_NUM_ARABIC
    };

    if (m_pSBase->AreThereFootnotes())
    {
        static const SwFootnoteNum eNumA[4] =
        {
            FTNNUM_DOC, FTNNUM_CHAPTER, FTNNUM_PAGE, FTNNUM_DOC
        };

        SwFootnoteInfo aInfo;
        aInfo = m_rDoc.GetFootnoteInfo(); // Copy-Ctor private

        aInfo.ePos = FTNPOS_PAGE;
        aInfo.eNum = eNumA[m_pWDop->rncFootnote];
        sal_uInt16 nfcFootnoteRef = m_pWDop->nfcFootnoteRef & 0xF;
        aInfo.aFormat.SetNumberingType( eNumTA[nfcFootnoteRef] );
        if( m_pWDop->nFootnote )
            aInfo.nFootnoteOffset = m_pWDop->nFootnote - 1;
        m_rDoc.SetFootnoteInfo( aInfo );
    }
    if( m_pSBase->AreThereEndnotes() )
    {
        SwEndNoteInfo aInfo;
        aInfo = m_rDoc.GetEndNoteInfo(); // Same as for Footnote
        sal_uInt16 nfcEdnRef = m_pWDop->nfcEdnRef & 0xF;
        aInfo.aFormat.SetNumberingType( eNumTA[nfcEdnRef] );
        if( m_pWDop->nEdn )
            aInfo.nFootnoteOffset = m_pWDop->nEdn - 1;
        m_rDoc.SetEndNoteInfo( aInfo );
    }

    if( m_pWwFib->m_lcbPlcfhdd )
        m_pHdFt = new WW8PLCF_HdFt( m_pTableStream, *m_pWwFib, *m_pWDop );

    if (!m_bNewDoc)
    {
        // inserting into an existing document:
        // As only complete paragraphs are inserted, the current one
        // needs to be splitted - once or even twice.
        const SwPosition* pPos = m_pPaM->GetPoint();

        // split current paragraph to get new paragraph for the insertion
        m_rDoc.getIDocumentContentOperations().SplitNode( *pPos, false );

        // another split, if insertion position was not at the end of the current paragraph.
        SwTextNode const*const pTextNd = pPos->nNode.GetNode().GetTextNode();
        if ( pTextNd->GetText().getLength() )
        {
            m_rDoc.getIDocumentContentOperations().SplitNode( *pPos, false );
            // move PaM back to the newly empty paragraph
            m_pPaM->Move( fnMoveBackward );
        }

        // suppress insertion of tables inside footnotes.
        const sal_uLong nNd = pPos->nNode.GetIndex();
        m_bReadNoTable = ( nNd < m_rDoc.GetNodes().GetEndOfInserts().GetIndex() &&
                       m_rDoc.GetNodes().GetEndOfInserts().StartOfSectionIndex() < nNd );
    }

    ::SetProgressState(m_nProgress, m_pDocShell); // Update

    // loop for each glossary entry and add dummy section node
    if (pGloss)
    {
        WW8PLCF aPlc(*m_pTableStream, m_pWwFib->m_fcPlcfglsy, m_pWwFib->m_lcbPlcfglsy, 0);

        WW8_CP nStart, nEnd;
        void* pDummy;

        for (int i = 0; i < pGloss->GetNoStrings(); ++i, aPlc.advance())
        {
            SwNodeIndex aIdx( m_rDoc.GetNodes().GetEndOfContent());
            SwTextFormatColl* pColl =
                m_rDoc.getIDocumentStylePoolAccess().GetTextCollFromPool(RES_POOLCOLL_STANDARD,
                false);
            SwStartNode *pNode =
                m_rDoc.GetNodes().MakeTextSection(aIdx,
                SwNormalStartNode,pColl);
            m_pPaM->GetPoint()->nNode = pNode->GetIndex()+1;
            m_pPaM->GetPoint()->nContent.Assign(m_pPaM->GetContentNode(),0);
            aPlc.Get( nStart, nEnd, pDummy );
            ReadText(nStart,nEnd-nStart-1,MAN_MAINTEXT);
        }
    }
    else // ordinary case
    {
        if (m_bNewDoc && m_pStg && !pGloss) /*meaningless for a glossary */
        {
            m_pDocShell->SetIsTemplate( m_pWwFib->m_fDot ); // point at tgc record
            uno::Reference<document::XDocumentPropertiesSupplier> const
                xDocPropSupp(m_pDocShell->GetModel(), uno::UNO_QUERY_THROW);
            uno::Reference< document::XDocumentProperties > xDocProps( xDocPropSupp->getDocumentProperties(), uno::UNO_QUERY_THROW );

            OUString sCreatedFrom = xDocProps->getTemplateURL();
            uno::Reference< container::XNameContainer > xPrjNameCache;
            uno::Reference< lang::XMultiServiceFactory> xSF(m_pDocShell->GetModel(), uno::UNO_QUERY);
            if ( xSF.is() )
                xPrjNameCache.set( xSF->createInstance( "ooo.vba.VBAProjectNameProvider" ), uno::UNO_QUERY );

            // Read Global templates
            ReadGlobalTemplateSettings( sCreatedFrom, xPrjNameCache );

            // Create and insert Word vba Globals
            uno::Any aGlobs;
            uno::Sequence< uno::Any > aArgs(1);
            aArgs[ 0 ] <<= m_pDocShell->GetModel();
            try
            {
                aGlobs <<= ::comphelper::getProcessServiceFactory()->createInstanceWithArguments( "ooo.vba.word.Globals", aArgs );
            }
            catch (const uno::Exception&)
            {
                SAL_WARN("sw.ww8", "SwWW8ImplReader::CoreLoad: ooo.vba.word.Globals is not available");
            }

#if HAVE_FEATURE_SCRIPTING
            if (!utl::ConfigManager::IsAvoidConfig())
            {
                BasicManager *pBasicMan = m_pDocShell->GetBasicManager();
                if (pBasicMan)
                    pBasicMan->SetGlobalUNOConstant( "VBAGlobals", aGlobs );
            }
#endif
            BasicProjImportHelper aBasicImporter( *m_pDocShell );
            // Import vba via oox filter
            bool bRet = aBasicImporter.import( m_pDocShell->GetMedium()->GetInputStream() );

            lcl_createTemplateToProjectEntry( xPrjNameCache, sCreatedFrom, aBasicImporter.getProjectName() );
            WW8Customizations aCustomisations( m_pTableStream, *m_pWwFib );
            aCustomisations.Import( m_pDocShell );

            if( bRet )
                m_rDoc.SetContainsMSVBasic(true);

            StoreMacroCmds();
        }
        m_bOnLoadingMain = true;
        ReadText(0, m_pWwFib->m_ccpText, MAN_MAINTEXT);
        m_bOnLoadingMain = false;
    }

    ::SetProgressState(m_nProgress, m_pDocShell); // Update

    if (m_pDrawPg && m_pMSDffManager && m_pMSDffManager->GetShapeOrders())
    {
        // Helper array to chain the inserted frames (instead of SdrTextObj)
        SvxMSDffShapeTxBxSort aTxBxSort;

        // Ensure correct z-order of read Escher objects
        sal_uInt16 nShapeCount = m_pMSDffManager->GetShapeOrders()->size();

        for (sal_uInt16 nShapeNum=0; nShapeNum < nShapeCount; nShapeNum++)
        {
            SvxMSDffShapeOrder *pOrder =
                (*m_pMSDffManager->GetShapeOrders())[nShapeNum].get();
            // Insert Pointer into new Sort array
            if (pOrder->nTxBxComp && pOrder->pFly)
                aTxBxSort.insert(pOrder);
        }
        // Chain Frames
        if( !aTxBxSort.empty() )
        {
            SwFormatChain aChain;
            for( SvxMSDffShapeTxBxSort::iterator it = aTxBxSort.begin(); it != aTxBxSort.end(); ++it )
            {
                SvxMSDffShapeOrder *pOrder = *it;

                // Initialize FlyFrame Formats
                SwFlyFrameFormat* pFlyFormat     = pOrder->pFly;
                SwFlyFrameFormat* pNextFlyFormat = nullptr;
                SwFlyFrameFormat* pPrevFlyFormat = nullptr;

                // Determine successor, if we can
                SvxMSDffShapeTxBxSort::iterator tmpIter1 = it;
                ++tmpIter1;
                if( tmpIter1 != aTxBxSort.end() )
                {
                    SvxMSDffShapeOrder *pNextOrder = *tmpIter1;
                    if ((0xFFFF0000 & pOrder->nTxBxComp)
                           == (0xFFFF0000 & pNextOrder->nTxBxComp))
                        pNextFlyFormat = pNextOrder->pFly;
                }
                // Determine predecessor, if we can
                if( it != aTxBxSort.begin() )
                {
                    SvxMSDffShapeTxBxSort::iterator tmpIter2 = it;
                    --tmpIter2;
                    SvxMSDffShapeOrder *pPrevOrder = *tmpIter2;
                    if ((0xFFFF0000 & pOrder->nTxBxComp)
                           == (0xFFFF0000 & pPrevOrder->nTxBxComp))
                        pPrevFlyFormat = pPrevOrder->pFly;
                }
                // If successor or predecessor present, insert the
                // chain at the FlyFrame Format
                if (pNextFlyFormat || pPrevFlyFormat)
                {
                    aChain.SetNext( pNextFlyFormat );
                    aChain.SetPrev( pPrevFlyFormat );
                    pFlyFormat->SetFormatAttr( aChain );
                }
            }
        }
    }

    if (m_bNewDoc)
    {
        if( m_pWDop->fRevMarking )
            eMode |= RedlineFlags::On;
        if( m_pWDop->fRMView )
            eMode |= RedlineFlags::ShowDelete;
    }

    m_aInsertedTables.DelAndMakeTableFrames();
    m_aSectionManager.InsertSegments();

    m_vColl.clear();

    DELETEZ( m_pStyles );

    if( m_pFormImpl )
        DeleteFormImpl();
    GrafikDtor();
    DELETEZ( m_pMSDffManager );
    DELETEZ( m_pHdFt );
    DELETEZ( m_pSBase );
    delete m_pWDop;
    DELETEZ( m_pFonts );
    delete m_pAtnNames;
    delete m_pSprmParser;
    ::EndProgress(m_pDocShell);

    m_pDataStream = nullptr;
    m_pTableStream = nullptr;

    DeleteCtrlStack();
    m_pRedlineStack->closeall(*m_pPaM->GetPoint());
    delete m_pRedlineStack;
    DeleteAnchorStack();
    DeleteRefStacks();

    // For i120928,achieve the graphics from the special bookmark with is for graphic bullet
    {
        std::vector<const SwGrfNode*> vecBulletGrf;
        std::vector<SwFrameFormat*> vecFrameFormat;

        IDocumentMarkAccess* const pMarkAccess = m_rDoc.getIDocumentMarkAccess();
        if ( pMarkAccess )
        {
            IDocumentMarkAccess::const_iterator_t ppBkmk = pMarkAccess->findBookmark( "_PictureBullets" );
            if ( ppBkmk != pMarkAccess->getBookmarksEnd() &&
                       IDocumentMarkAccess::GetType( *(ppBkmk->get()) ) == IDocumentMarkAccess::MarkType::BOOKMARK )
            {
                SwTextNode* pTextNode = ppBkmk->get()->GetMarkStart().nNode.GetNode().GetTextNode();

                if ( pTextNode )
                {
                    const SwpHints* pHints = pTextNode->GetpSwpHints();
                    for( size_t nHintPos = 0; pHints && nHintPos < pHints->Count(); ++nHintPos)
                    {
                        const SwTextAttr *pHt = pHints->Get(nHintPos);
                        const sal_Int32 st = pHt->GetStart();
                        if( pHt
                            && pHt->Which() == RES_TXTATR_FLYCNT
                            && (st >= ppBkmk->get()->GetMarkStart().nContent.GetIndex()) )
                        {
                            SwFrameFormat* pFrameFormat = pHt->GetFlyCnt().GetFrameFormat();
                            vecFrameFormat.push_back(pFrameFormat);
                            const SwNodeIndex* pNdIdx = pFrameFormat->GetContent().GetContentIdx();
                            const SwNodes* pNodesArray = (pNdIdx != nullptr)
                                                         ? &(pNdIdx->GetNodes())
                                                         : nullptr;
                            const SwGrfNode *pGrf = (pNodesArray != nullptr)
                                                    ? dynamic_cast<const SwGrfNode*>((*pNodesArray)[pNdIdx->GetIndex() + 1])
                                                    : nullptr;
                            vecBulletGrf.push_back(pGrf);
                        }
                    }
                    // update graphic bullet information
                    size_t nCount = m_pLstManager->GetWW8LSTInfoNum();
                    for (size_t i = 0; i < nCount; ++i)
                    {
                        SwNumRule* pRule = m_pLstManager->GetNumRule(i);
                        for (sal_uInt16 j = 0; j < MAXLEVEL; ++j)
                        {
                            SwNumFormat aNumFormat(pRule->Get(j));
                            const sal_Int16 nType = aNumFormat.GetNumberingType();
                            const sal_uInt16 nGrfBulletCP = aNumFormat.GetGrfBulletCP();
                            if ( nType == SVX_NUM_BITMAP
                                 && vecBulletGrf.size() > nGrfBulletCP
                                 && vecBulletGrf[nGrfBulletCP] != nullptr )
                            {
                                Graphic aGraphic = vecBulletGrf[nGrfBulletCP]->GetGrf();
                                SvxBrushItem aBrush(aGraphic, GPOS_AREA, SID_ATTR_BRUSH);
                                const vcl::Font& aFont = numfunc::GetDefBulletFont();
                                int nHeight = aFont.GetFontHeight() * 12;
                                Size aPrefSize( aGraphic.GetPrefSize());
                                if (aPrefSize.Height() * aPrefSize.Width() != 0 )
                                {
                                    int nWidth = (nHeight * aPrefSize.Width()) / aPrefSize.Height();
                                    Size aSize(nWidth, nHeight);
                                    aNumFormat.SetGraphicBrush(&aBrush, &aSize);
                                }
                                else
                                {
                                    aNumFormat.SetNumberingType(SVX_NUM_CHAR_SPECIAL);
                                    aNumFormat.SetBulletChar(0x2190);
                                }
                                pRule->Set( j, aNumFormat );
                            }
                        }
                    }
                    // Remove additional pictures
                    for (SwFrameFormat* p : vecFrameFormat)
                    {
                        m_rDoc.getIDocumentLayoutAccess().DelLayoutFormat(p);
                    }
                }
            }
        }
        DELETEZ( m_pLstManager );
    }

    SAL_WARN_IF(m_pTableEndPaM, "sw.ww8", "document ended without table ending");
    m_pTableEndPaM.reset();  //ensure this is deleted before pPaM
    mpCursor.reset();
    m_pPaM = nullptr;
    m_pLastAnchorPos.reset();//ensure this is deleted before UpdatePageDescs

    // remove extra paragraphs after attribute ctrl
    // stacks etc. are destroyed, and before fields
    // are updated
    m_aExtraneousParas.delete_all_from_doc();

    UpdateFields();

    // delete the pam before the call for hide all redlines (Bug 73683)
    if (m_bNewDoc)
      m_rDoc.getIDocumentRedlineAccess().SetRedlineFlags(eMode);

    UpdatePageDescs(m_rDoc, nPageDescOffset);

    return nErrRet;
}

sal_uLong SwWW8ImplReader::SetSubStreams(tools::SvRef<SotStorageStream> &rTableStream,
    tools::SvRef<SotStorageStream> &rDataStream)
{
    sal_uLong nErrRet = 0;
    // 6 stands for "6 OR 7", 7 stands for "ONLY 7"
    switch (m_pWwFib->m_nVersion)
    {
        case 6:
        case 7:
            m_pTableStream = m_pStrm;
            m_pDataStream = m_pStrm;
            break;
        case 8:
            if(!m_pStg)
            {
                OSL_ENSURE( m_pStg, "Version 8 always needs to have a Storage!!" );
                nErrRet = ERR_SWG_READ_ERROR;
                break;
            }

            rTableStream = m_pStg->OpenSotStream(
                m_pWwFib->m_fWhichTableStm ? SL::a1Table : SL::a0Table,
                StreamMode::STD_READ);

            m_pTableStream = rTableStream.get();
            m_pTableStream->SetEndian( SvStreamEndian::LITTLE );

            rDataStream = m_pStg->OpenSotStream(SL::aData, StreamMode::STD_READ);

            if (rDataStream.is() && SVSTREAM_OK == rDataStream->GetError())
            {
                m_pDataStream = rDataStream.get();
                m_pDataStream->SetEndian(SvStreamEndian::LITTLE);
            }
            else
                m_pDataStream = m_pStrm;
            break;
        default:
            // Program error!
            OSL_ENSURE( false, "We forgot to encode nVersion!" );
            nErrRet = ERR_SWG_READ_ERROR;
            break;
    }
    return nErrRet;
}

namespace
{
    utl::TempFile *MakeTemp(SvFileStream &rSt)
    {
        utl::TempFile *pT = new utl::TempFile;
        pT->EnableKillingFile();
        rSt.Open(pT->GetFileName(), StreamMode::READWRITE | StreamMode::SHARE_DENYWRITE);
        return pT;
    }

#define WW_BLOCKSIZE 0x200

    void DecryptRC4(msfilter::MSCodec97& rCtx, SvStream &rIn, SvStream &rOut)
    {
        rIn.Seek(STREAM_SEEK_TO_END);
        const std::size_t nLen = rIn.Tell();
        rIn.Seek(0);

        sal_uInt8 in[WW_BLOCKSIZE];
        for (std::size_t nI = 0, nBlock = 0; nI < nLen; nI += WW_BLOCKSIZE, ++nBlock)
        {
            std::size_t nBS = (nLen - nI > WW_BLOCKSIZE) ? WW_BLOCKSIZE : nLen - nI;
            nBS = rIn.ReadBytes(in, nBS);
            rCtx.InitCipher(nBlock);
            rCtx.Decode(in, nBS, in, nBS);
            rOut.WriteBytes(in, nBS);
        }
    }

    void DecryptXOR(msfilter::MSCodec_XorWord95 &rCtx, SvStream &rIn, SvStream &rOut)
    {
        std::size_t nSt = rIn.Tell();
        rIn.Seek(STREAM_SEEK_TO_END);
        std::size_t nLen = rIn.Tell();
        rIn.Seek(nSt);

        rCtx.InitCipher();
        rCtx.Skip(nSt);

        sal_uInt8 in[0x4096];
        for (std::size_t nI = nSt; nI < nLen; nI += 0x4096)
        {
            std::size_t nBS = (nLen - nI > 0x4096 ) ? 0x4096 : nLen - nI;
            nBS = rIn.ReadBytes(in, nBS);
            rCtx.Decode(in, nBS);
            rOut.WriteBytes(in, nBS);
        }
    }

    // moan, copy and paste :-(
    OUString QueryPasswordForMedium(SfxMedium& rMedium)
    {
        OUString aPassw;

        using namespace com::sun::star;

        const SfxItemSet* pSet = rMedium.GetItemSet();
        const SfxPoolItem *pPasswordItem;

        if(pSet && SfxItemState::SET == pSet->GetItemState(SID_PASSWORD, true, &pPasswordItem))
            aPassw = static_cast<const SfxStringItem *>(pPasswordItem)->GetValue();
        else
        {
            try
            {
                uno::Reference< task::XInteractionHandler > xHandler( rMedium.GetInteractionHandler() );
                if( xHandler.is() )
                {
                    ::comphelper::DocPasswordRequest* pRequest = new ::comphelper::DocPasswordRequest(
                        ::comphelper::DocPasswordRequestType::MS, task::PasswordRequestMode_PASSWORD_ENTER,
                        INetURLObject( rMedium.GetOrigURL() ).GetName( INetURLObject::DecodeMechanism::WithCharset ) );
                    uno::Reference< task::XInteractionRequest > xRequest( pRequest );

                    xHandler->handle( xRequest );

                    if( pRequest->isPassword() )
                        aPassw = pRequest->getPassword();
                }
            }
            catch( const uno::Exception& )
            {
            }
        }

        return aPassw;
    }

    uno::Sequence< beans::NamedValue > InitXorWord95Codec( ::msfilter::MSCodec_XorWord95& rCodec, SfxMedium& rMedium, WW8Fib* pWwFib )
    {
        uno::Sequence< beans::NamedValue > aEncryptionData;
        const SfxUnoAnyItem* pEncryptionData = SfxItemSet::GetItem<SfxUnoAnyItem>(rMedium.GetItemSet(), SID_ENCRYPTIONDATA, false);
        if ( pEncryptionData && ( pEncryptionData->GetValue() >>= aEncryptionData ) && !rCodec.InitCodec( aEncryptionData ) )
            aEncryptionData.realloc( 0 );

        if ( !aEncryptionData.getLength() )
        {
            OUString sUniPassword = QueryPasswordForMedium( rMedium );

            OString sPassword(OUStringToOString(sUniPassword,
                WW8Fib::GetFIBCharset(pWwFib->m_chseTables, pWwFib->m_lid)));

            sal_Int32 nLen = sPassword.getLength();
            if( nLen <= 15 )
            {
                sal_uInt8 pPassword[16];
                memcpy(pPassword, sPassword.getStr(), nLen);
                memset(pPassword+nLen, 0, sizeof(pPassword)-nLen);

                rCodec.InitKey( pPassword );
                aEncryptionData = rCodec.GetEncryptionData();

                // the export supports RC4 algorithm only, so we have to
                // generate the related EncryptionData as well, so that Save
                // can export the document without asking for a password;
                // as result there will be EncryptionData for both algorithms
                // in the MediaDescriptor
                ::msfilter::MSCodec_Std97 aCodec97;

                // Generate random number with a seed of time as salt.
                TimeValue aTime;
                osl_getSystemTime( &aTime );
                rtlRandomPool aRandomPool = rtl_random_createPool();
                rtl_random_addBytes ( aRandomPool, &aTime, 8 );

                sal_uInt8 pDocId[ 16 ];
                rtl_random_getBytes( aRandomPool, pDocId, 16 );

                rtl_random_destroyPool( aRandomPool );

                sal_uInt16 pStd97Pass[16];
                memset( pStd97Pass, 0, sizeof( pStd97Pass ) );
                for( sal_Int32 nChar = 0; nChar < nLen; ++nChar )
                    pStd97Pass[nChar] = sUniPassword[nChar];

                aCodec97.InitKey( pStd97Pass, pDocId );

                // merge the EncryptionData, there should be no conflicts
                ::comphelper::SequenceAsHashMap aEncryptionHash( aEncryptionData );
                aEncryptionHash.update( ::comphelper::SequenceAsHashMap( aCodec97.GetEncryptionData() ) );
                aEncryptionHash >> aEncryptionData;
            }
        }

        return aEncryptionData;
    }

    uno::Sequence< beans::NamedValue > Init97Codec(msfilter::MSCodec97& rCodec, sal_uInt8 pDocId[16], SfxMedium& rMedium)
    {
        uno::Sequence< beans::NamedValue > aEncryptionData;
        const SfxUnoAnyItem* pEncryptionData = SfxItemSet::GetItem<SfxUnoAnyItem>(rMedium.GetItemSet(), SID_ENCRYPTIONDATA, false);
        if ( pEncryptionData && ( pEncryptionData->GetValue() >>= aEncryptionData ) && !rCodec.InitCodec( aEncryptionData ) )
            aEncryptionData.realloc( 0 );

        if ( !aEncryptionData.getLength() )
        {
            OUString sUniPassword = QueryPasswordForMedium( rMedium );

            sal_Int32 nLen = sUniPassword.getLength();
            if ( nLen <= 15 )
            {
                sal_uInt16 pPassword[16];
                memset( pPassword, 0, sizeof( pPassword ) );
                for( sal_Int32 nChar = 0; nChar < nLen; ++nChar )
                    pPassword[nChar] = sUniPassword[nChar];

                rCodec.InitKey( pPassword, pDocId );
                aEncryptionData = rCodec.GetEncryptionData();
            }
        }

        return aEncryptionData;
    }
}

//TO-DO: merge this with lclReadFilepass8_Strong in sc which uses a different
//stream thing
static bool lclReadCryptoAPIHeader(msfilter::RC4EncryptionInfo &info, SvStream &rStream)
{
    //It is possible there are other variants in existence but these
    //are the defaults I get with Word 2013

    rStream.ReadUInt32(info.header.flags);
    if (oox::getFlag( info.header.flags, msfilter::ENCRYPTINFO_EXTERNAL))
        return false;

    sal_uInt32 nHeaderSize(0);
    rStream.ReadUInt32(nHeaderSize);
    sal_uInt32 actualHeaderSize = sizeof(info.header);

    if (nHeaderSize < actualHeaderSize)
        return false;

    rStream.ReadUInt32(info.header.flags);
    rStream.ReadUInt32(info.header.sizeExtra);
    rStream.ReadUInt32(info.header.algId);
    rStream.ReadUInt32(info.header.algIdHash);
    rStream.ReadUInt32(info.header.keyBits);
    rStream.ReadUInt32(info.header.providedType);
    rStream.ReadUInt32(info.header.reserved1);
    rStream.ReadUInt32(info.header.reserved2);

    rStream.SeekRel(nHeaderSize - actualHeaderSize);

    rStream.ReadUInt32(info.verifier.saltSize);
    if (info.verifier.saltSize != msfilter::SALT_LENGTH)
        return false;
    rStream.ReadBytes(&info.verifier.salt, sizeof(info.verifier.salt));
    rStream.ReadBytes(&info.verifier.encryptedVerifier, sizeof(info.verifier.encryptedVerifier));

    rStream.ReadUInt32(info.verifier.encryptedVerifierHashSize);
    if (info.verifier.encryptedVerifierHashSize != RTL_DIGEST_LENGTH_SHA1)
        return false;
    rStream.ReadBytes(&info.verifier.encryptedVerifierHash, info.verifier.encryptedVerifierHashSize);

    // check flags and algorithm IDs, required are AES128 and SHA-1
    if (!oox::getFlag(info.header.flags, msfilter::ENCRYPTINFO_CRYPTOAPI))
        return false;

    if (oox::getFlag(info.header.flags, msfilter::ENCRYPTINFO_AES))
        return false;

    if (info.header.algId != msfilter::ENCRYPT_ALGO_RC4)
        return false;

    // hash algorithm ID 0 defaults to SHA-1 too
    if (info.header.algIdHash != 0 && info.header.algIdHash != msfilter::ENCRYPT_HASH_SHA1)
        return false;

    return true;
}

sal_uLong SwWW8ImplReader::LoadThroughDecryption(WW8Glossary *pGloss)
{
    sal_uLong nErrRet = 0;
    if (pGloss)
        m_pWwFib = pGloss->GetFib();
    else
        m_pWwFib = new WW8Fib(*m_pStrm, m_nWantedVersion);

    if (m_pWwFib->m_nFibError)
        nErrRet = ERR_SWG_READ_ERROR;

    tools::SvRef<SotStorageStream> xTableStream, xDataStream;

    if (!nErrRet)
        nErrRet = SetSubStreams(xTableStream, xDataStream);

    utl::TempFile *pTempMain = nullptr;
    utl::TempFile *pTempTable = nullptr;
    utl::TempFile *pTempData = nullptr;
    SvFileStream aDecryptMain;
    SvFileStream aDecryptTable;
    SvFileStream aDecryptData;

    bool bDecrypt = false;
    enum {RC4CryptoAPI, RC4, XOR, Other} eAlgo = Other;
    if (m_pWwFib->m_fEncrypted && !nErrRet)
    {
        if (!pGloss)
        {
            bDecrypt = true;
            if (8 != m_pWwFib->m_nVersion)
                eAlgo = XOR;
            else
            {
                if (m_pWwFib->m_nKey != 0)
                    eAlgo = XOR;
                else
                {
                    m_pTableStream->Seek(0);
                    sal_uInt32 nEncType(0);
                    m_pTableStream->ReadUInt32(nEncType);
                    if (nEncType == msfilter::VERSION_INFO_1997_FORMAT)
                        eAlgo = RC4;
                    else if (nEncType == msfilter::VERSION_INFO_2007_FORMAT || nEncType == msfilter::VERSION_INFO_2007_FORMAT_SP2)
                        eAlgo = RC4CryptoAPI;
                }
            }
        }
    }

    if (bDecrypt)
    {
        nErrRet = ERRCODE_SVX_WRONGPASS;
        SfxMedium* pMedium = m_pDocShell->GetMedium();

        if ( pMedium )
        {
            switch (eAlgo)
            {
                default:
                    nErrRet = ERRCODE_SVX_READ_FILTER_CRYPT;
                    break;
                case XOR:
                {
                    msfilter::MSCodec_XorWord95 aCtx;
                    uno::Sequence< beans::NamedValue > aEncryptionData = InitXorWord95Codec( aCtx, *pMedium, m_pWwFib );

                    // if initialization has failed the EncryptionData should be empty
                    if ( aEncryptionData.getLength() && aCtx.VerifyKey( m_pWwFib->m_nKey, m_pWwFib->m_nHash ) )
                    {
                        nErrRet = 0;
                        pTempMain = MakeTemp(aDecryptMain);

                        m_pStrm->Seek(0);
                        size_t nUnencryptedHdr =
                            (8 == m_pWwFib->m_nVersion) ? 0x44 : 0x34;
                        sal_uInt8 *pIn = new sal_uInt8[nUnencryptedHdr];
                        nUnencryptedHdr = m_pStrm->ReadBytes(pIn, nUnencryptedHdr);
                        aDecryptMain.WriteBytes(pIn, nUnencryptedHdr);
                        delete [] pIn;

                        DecryptXOR(aCtx, *m_pStrm, aDecryptMain);

                        if (!m_pTableStream || m_pTableStream == m_pStrm)
                            m_pTableStream = &aDecryptMain;
                        else
                        {
                            pTempTable = MakeTemp(aDecryptTable);
                            DecryptXOR(aCtx, *m_pTableStream, aDecryptTable);
                            m_pTableStream = &aDecryptTable;
                        }

                        if (!m_pDataStream || m_pDataStream == m_pStrm)
                            m_pDataStream = &aDecryptMain;
                        else
                        {
                            pTempData = MakeTemp(aDecryptData);
                            DecryptXOR(aCtx, *m_pDataStream, aDecryptData);
                            m_pDataStream = &aDecryptData;
                        }

                        pMedium->GetItemSet()->ClearItem( SID_PASSWORD );
                        pMedium->GetItemSet()->Put( SfxUnoAnyItem( SID_ENCRYPTIONDATA, uno::makeAny( aEncryptionData ) ) );
                    }
                }
                break;
                case RC4:
                case RC4CryptoAPI:
                {
                    std::unique_ptr<msfilter::MSCodec97> xCtx;
                    msfilter::RC4EncryptionInfo info;
                    bool bCouldReadHeaders;

                    if (eAlgo == RC4)
                    {
                        xCtx.reset(new msfilter::MSCodec_Std97);
                        assert(sizeof(info.verifier.encryptedVerifierHash) >= RTL_DIGEST_LENGTH_MD5);
                        bCouldReadHeaders =
                            checkRead(*m_pTableStream, info.verifier.salt, sizeof(info.verifier.salt)) &&
                            checkRead(*m_pTableStream, info.verifier.encryptedVerifier, sizeof(info.verifier.encryptedVerifier)) &&
                            checkRead(*m_pTableStream, info.verifier.encryptedVerifierHash, RTL_DIGEST_LENGTH_MD5);
                    }
                    else
                    {
                        xCtx.reset(new msfilter::MSCodec_CryptoAPI);
                        bCouldReadHeaders = lclReadCryptoAPIHeader(info, *m_pTableStream);
                    }

                    // if initialization has failed the EncryptionData should be empty
                    uno::Sequence< beans::NamedValue > aEncryptionData;
                    if (bCouldReadHeaders)
                        aEncryptionData = Init97Codec(*xCtx, info.verifier.salt, *pMedium);
                    else
                        nErrRet = ERRCODE_SVX_READ_FILTER_CRYPT;
                    if (aEncryptionData.getLength() && xCtx->VerifyKey(info.verifier.encryptedVerifier,
                                                                       info.verifier.encryptedVerifierHash))
                    {
                        nErrRet = 0;

                        pTempMain = MakeTemp(aDecryptMain);

                        m_pStrm->Seek(0);
                        std::size_t nUnencryptedHdr = 0x44;
                        sal_uInt8 *pIn = new sal_uInt8[nUnencryptedHdr];
                        nUnencryptedHdr = m_pStrm->ReadBytes(pIn, nUnencryptedHdr);

                        DecryptRC4(*xCtx, *m_pStrm, aDecryptMain);

                        aDecryptMain.Seek(0);
                        aDecryptMain.WriteBytes(pIn, nUnencryptedHdr);
                        delete [] pIn;

                        pTempTable = MakeTemp(aDecryptTable);
                        DecryptRC4(*xCtx, *m_pTableStream, aDecryptTable);
                        m_pTableStream = &aDecryptTable;

                        if (!m_pDataStream || m_pDataStream == m_pStrm)
                            m_pDataStream = &aDecryptMain;
                        else
                        {
                            pTempData = MakeTemp(aDecryptData);
                            DecryptRC4(*xCtx, *m_pDataStream, aDecryptData);
                            m_pDataStream = &aDecryptData;
                        }

                        pMedium->GetItemSet()->ClearItem( SID_PASSWORD );
                        pMedium->GetItemSet()->Put( SfxUnoAnyItem( SID_ENCRYPTIONDATA, uno::makeAny( aEncryptionData ) ) );
                    }
                }
                break;
            }
        }

        if (nErrRet == 0)
        {
            m_pStrm = &aDecryptMain;

            delete m_pWwFib;
            m_pWwFib = new WW8Fib(*m_pStrm, m_nWantedVersion);
            if (m_pWwFib->m_nFibError)
                nErrRet = ERR_SWG_READ_ERROR;
        }
    }

    if (!nErrRet)
        nErrRet = CoreLoad(pGloss);

    delete pTempMain;
    delete pTempTable;
    delete pTempData;

    if (!pGloss)
        delete m_pWwFib;
    return nErrRet;
}

void SwWW8ImplReader::SetOutlineStyles()
{
    // If we are inserted into a document then don't clobber existing outline
    // levels.
    sal_uInt16 nOutlineStyleListLevelWithAssignment = 0;
    if (!m_bNewDoc)
    {
        ww8::ParaStyles aOutLined(sw::util::GetParaStyles(m_rDoc));
        sw::util::SortByAssignedOutlineStyleListLevel(aOutLined);
        ww8::ParaStyles::reverse_iterator aEnd = aOutLined.rend();
        for ( ww8::ParaStyles::reverse_iterator aIter = aOutLined.rbegin(); aIter < aEnd; ++aIter)
        {
            if ((*aIter)->IsAssignedToListLevelOfOutlineStyle())
                nOutlineStyleListLevelWithAssignment |= 1 << (*aIter)->GetAssignedOutlineStyleLevel();
            else
                break;
        }
    }

    // Check applied WW8 list styles at WW8 Built-In Heading Styles
    // - Choose the list style which occurs most often as the one which provides
    //   the list level properties for the Outline Style.
    // - Populate temporary list of WW8 Built-In Heading Styles for further
    // iteration
    std::vector<SwWW8StyInf*> aWW8BuiltInHeadingStyles;
    const SwNumRule* pChosenWW8ListStyle = nullptr;
    {
        std::map<const SwNumRule*, int> aWW8ListStyleCounts;
        for (SwWW8StyInf & rSI : m_vColl)
        {
            if (!rSI.IsWW8BuiltInHeadingStyle() || !rSI.HasWW8OutlineLevel())
            {
                continue;
            }

            aWW8BuiltInHeadingStyles.push_back(&rSI);

            const SwNumRule* pWW8ListStyle = rSI.GetOutlineNumrule();
            if (pWW8ListStyle != nullptr)
            {
                std::map<const SwNumRule*, int>::iterator aCountIter
                    = aWW8ListStyleCounts.find(pWW8ListStyle);
                if (aCountIter == aWW8ListStyleCounts.end())
                {
                    aWW8ListStyleCounts[pWW8ListStyle] = 1;
                }
                else
                {
                    ++(aCountIter->second);
                }
            }
        }

        int nCurrentMaxCount = 0;
        std::map<const SwNumRule*, int>::iterator aCountIterEnd
            = aWW8ListStyleCounts.end();
        for (std::map<const SwNumRule*, int>::iterator aIter
             = aWW8ListStyleCounts.begin();
             aIter != aCountIterEnd; ++aIter)
        {
            if (aIter->second > nCurrentMaxCount)
            {
                nCurrentMaxCount = aIter->second;
                pChosenWW8ListStyle = aIter->first;
            }
        }
    }

    // - set list level properties of Outline Style - ODF's list style applied
    // by default to headings
    // - assign corresponding Heading Paragraph Styles to the Outline Style
    // - If a heading Paragraph Styles is not applying the WW8 list style which
    // had been chosen as
    //   the one which provides the list level properties for the Outline Style,
    // its assignment to
    //   the Outline Style is removed. A potential applied WW8 list style is
    // assigned directly and
    //   its default outline level is applied.
    SwNumRule aOutlineRule(*m_rDoc.GetOutlineNumRule());
    bool bAppliedChangedOutlineStyle = false;
    std::vector<SwWW8StyInf*>::iterator aStylesIterEnd
        = aWW8BuiltInHeadingStyles.end();
    for (std::vector<SwWW8StyInf*>::iterator aStyleIter
         = aWW8BuiltInHeadingStyles.begin();
         aStyleIter != aStylesIterEnd; ++aStyleIter)
    {
        SwWW8StyInf* pStyleInf = (*aStyleIter);

        if (!pStyleInf->m_bColl) //Character Style
            continue;

        const sal_uInt16 nOutlineStyleListLevelOfWW8BuiltInHeadingStyle
            = 1 << pStyleInf->mnWW8OutlineLevel;
        if (nOutlineStyleListLevelOfWW8BuiltInHeadingStyle
            & nOutlineStyleListLevelWithAssignment)
        {
            continue;
        }

        if (pChosenWW8ListStyle != nullptr && pStyleInf->mnWW8OutlineLevel
                                           == pStyleInf->m_nListLevel)
        {
            const SwNumFormat& rRule
                = pChosenWW8ListStyle->Get(pStyleInf->mnWW8OutlineLevel);
            aOutlineRule.Set(pStyleInf->mnWW8OutlineLevel, rRule);
            bAppliedChangedOutlineStyle = true;
        }

        // in case that there are more styles on this level ignore them
        nOutlineStyleListLevelWithAssignment
            |= nOutlineStyleListLevelOfWW8BuiltInHeadingStyle;

        SwTextFormatColl* pTextFormatColl = static_cast<SwTextFormatColl*>(pStyleInf->m_pFormat);
        if (pStyleInf->GetOutlineNumrule() != pChosenWW8ListStyle
            || (pStyleInf->m_nListLevel < WW8ListManager::nMaxLevel
                && pStyleInf->mnWW8OutlineLevel != pStyleInf->m_nListLevel))
        {
            // WW8 Built-In Heading Style does not apply the chosen one.
            // --> delete assignment to OutlineStyle, but keep its current
            // outline level
            pTextFormatColl->DeleteAssignmentToListLevelOfOutlineStyle();
            // Apply existing WW8 list style a normal list style at the
            // Paragraph Style
            if (pStyleInf->GetOutlineNumrule() != nullptr)
            {
                pTextFormatColl->SetFormatAttr(
                    SwNumRuleItem(pStyleInf->GetOutlineNumrule()->GetName()));
            }
            // apply default outline level of WW8 Built-in Heading Style
            const sal_uInt8 nOutlineLevel
                = SwWW8StyInf::WW8OutlineLevelToOutlinelevel(
                    pStyleInf->mnWW8OutlineLevel);
            pTextFormatColl->SetFormatAttr(
                SfxUInt16Item(RES_PARATR_OUTLINELEVEL, nOutlineLevel));
        }
        else
        {
            pTextFormatColl->AssignToListLevelOfOutlineStyle(
                pStyleInf->mnWW8OutlineLevel);
        }
    }

    if (bAppliedChangedOutlineStyle)
    {
        m_rDoc.SetOutlineNumRule(aOutlineRule);
    }
}

const OUString* SwWW8ImplReader::GetAnnotationAuthor(sal_uInt16 nIdx)
{
    if (!m_pAtnNames && m_pWwFib->m_lcbGrpStAtnOwners)
    {
        // Determine authors: can be found in the TableStream
        m_pAtnNames = new std::vector<OUString>;
        SvStream& rStrm = *m_pTableStream;

        long nOldPos = rStrm.Tell();
        rStrm.Seek( m_pWwFib->m_fcGrpStAtnOwners );

        long nRead = 0, nCount = m_pWwFib->m_lcbGrpStAtnOwners;
        while (nRead < nCount && rStrm.good())
        {
            if( m_bVer67 )
            {
                m_pAtnNames->push_back(read_uInt8_PascalString(rStrm,
                    RTL_TEXTENCODING_MS_1252));
                nRead += m_pAtnNames->rbegin()->getLength() + 1; // Length + sal_uInt8 count
            }
            else
            {
                m_pAtnNames->push_back(read_uInt16_PascalString(rStrm));
                // Unicode: double the length + sal_uInt16 count
                nRead += (m_pAtnNames->rbegin()->getLength() + 1)*2;
            }
        }
        rStrm.Seek( nOldPos );
    }

    const OUString *pRet = nullptr;
    if (m_pAtnNames && nIdx < m_pAtnNames->size())
        pRet = &((*m_pAtnNames)[nIdx]);
    return pRet;
}

void SwWW8ImplReader::GetSmartTagInfo(SwFltRDFMark& rMark)
{
    if (!m_pSmartTagData && m_pWwFib->m_lcbFactoidData)
    {
        m_pSmartTagData.reset(new WW8SmartTagData);
        m_pSmartTagData->Read(*m_pTableStream, m_pWwFib->m_fcFactoidData, m_pWwFib->m_lcbFactoidData);
    }

    if (!m_pSmartTagData)
        return;

    // Check if the handle is a valid smart tag bookmark index.
    size_t nIndex = rMark.GetHandle();
    if (nIndex >= m_pSmartTagData->m_aPropBags.size())
        return;

    // Check if the smart tag bookmark refers to a valid factoid type.
    const MSOPropertyBag& rPropertyBag = m_pSmartTagData->m_aPropBags[rMark.GetHandle()];
    auto itPropertyBag = m_pSmartTagData->m_aPropBagStore.m_aFactoidTypes.begin();
    for (; itPropertyBag != m_pSmartTagData->m_aPropBagStore.m_aFactoidTypes.end(); ++itPropertyBag)
        if (itPropertyBag->m_nId == rPropertyBag.m_nId)
            break;
    if (itPropertyBag == m_pSmartTagData->m_aPropBagStore.m_aFactoidTypes.end())
        return;

    // Check if the factoid is an RDF one.
    const MSOFactoidType& rFactoidType = *itPropertyBag;
    if (rFactoidType.m_aUri != "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
        return;

    // Finally put the relevant attributes to the mark.
    std::vector< std::pair<OUString, OUString> > aAttributes;
    for (const MSOProperty& rProperty : rPropertyBag.m_aProperties)
    {
        OUString aKey;
        OUString aValue;
        if (rProperty.m_nKey < m_pSmartTagData->m_aPropBagStore.m_aStringTable.size())
            aKey = m_pSmartTagData->m_aPropBagStore.m_aStringTable[rProperty.m_nKey];
        if (rProperty.m_nValue < m_pSmartTagData->m_aPropBagStore.m_aStringTable.size())
            aValue = m_pSmartTagData->m_aPropBagStore.m_aStringTable[rProperty.m_nValue];
        if (!aKey.isEmpty() && !aValue.isEmpty())
            aAttributes.push_back(std::make_pair(aKey, aValue));
    }
    rMark.SetAttributes(aAttributes);
}

sal_uLong SwWW8ImplReader::LoadDoc(WW8Glossary *pGloss)
{
    sal_uLong nErrRet = 0;

    {
        static const sal_Char* aNames[ 13 ] = {
            "WinWord/WW", "WinWord/WW8", "WinWord/WWFT",
            "WinWord/WWFLX", "WinWord/WWFLY",
            "WinWord/WWF",
            "WinWord/WWFA0", "WinWord/WWFA1", "WinWord/WWFA2",
            "WinWord/WWFB0", "WinWord/WWFB1", "WinWord/WWFB2",
            "WinWord/RegardHindiDigits"
        };
        sal_uInt64 aVal[ 13 ];

        SwFilterOptions aOpt( 13, aNames, aVal );

        m_nIniFlags = aVal[ 0 ];
        m_nIniFlags1= aVal[ 1 ];
        // Moves Flys by x twips to the right or left
        m_nIniFlyDx = aVal[ 3 ];
        m_nIniFlyDy = aVal[ 4 ];

        m_nFieldFlags = aVal[ 5 ];
        m_nFieldTagAlways[0] = aVal[ 6 ];
        m_nFieldTagAlways[1] = aVal[ 7 ];
        m_nFieldTagAlways[2] = aVal[ 8 ];
        m_nFieldTagBad[0] = aVal[ 9 ];
        m_nFieldTagBad[1] = aVal[ 10 ];
        m_nFieldTagBad[2] = aVal[ 11 ];
        m_bRegardHindiDigits = aVal[ 12 ] > 0;
    }

    sal_uInt16 nMagic(0);
    m_pStrm->ReadUInt16( nMagic );

    // Remember: 6 means "6 OR 7", 7 means "JUST 7"
    switch (m_nWantedVersion)
    {
        case 6:
        case 7:
            if (
                 0xa59b != nMagic && 0xa59c != nMagic &&
                 0xa5dc != nMagic && 0xa5db != nMagic &&
                 (nMagic < 0xa697 || nMagic > 0xa699)
               )
            {
                // Test for own 97 fake!
                if (m_pStg && 0xa5ec == nMagic)
                {
                    sal_uLong nCurPos = m_pStrm->Tell();
                    if (m_pStrm->Seek(nCurPos + 22))
                    {
                        sal_uInt32 nfcMin;
                        m_pStrm->ReadUInt32( nfcMin );
                        if (0x300 != nfcMin)
                            nErrRet = ERR_WW6_NO_WW6_FILE_ERR;
                    }
                    m_pStrm->Seek( nCurPos );
                }
                else
                    nErrRet = ERR_WW6_NO_WW6_FILE_ERR;
            }
            break;
        case 8:
            if (0xa5ec != nMagic)
                nErrRet = ERR_WW8_NO_WW8_FILE_ERR;
            break;
        default:
            nErrRet = ERR_WW8_NO_WW8_FILE_ERR;
            OSL_ENSURE( false, "We forgot to encode nVersion!" );
            break;
    }

    if (!nErrRet)
        nErrRet = LoadThroughDecryption(pGloss);

    m_rDoc.PropagateOutlineRule();

    return nErrRet;
}

extern "C" SAL_DLLPUBLIC_EXPORT Reader* SAL_CALL ImportDOC()
{
    return new WW8Reader;
}

bool SAL_CALL TestImportDOC(SvStream &rStream, const OUString &rFltName)
{
    Reader *pReader = ImportDOC();

    tools::SvRef<SotStorage> xStorage;
    pReader->pStrm = &rStream;
    if (rFltName != "WW6")
    {
        xStorage = tools::SvRef<SotStorage>(new SotStorage(rStream));
        pReader->pStg = xStorage.get();
    }
    pReader->SetFltName(rFltName);

    SwGlobals::ensure();

    SfxObjectShellLock xDocSh(new SwDocShell(SfxObjectCreateMode::INTERNAL));
    xDocSh->DoInitNew();
    SwDoc *pD =  static_cast<SwDocShell*>((&xDocSh))->GetDoc();

    SwNodeIndex aIdx(
        *pD->GetNodes().GetEndOfContent().StartOfSectionNode(), 1);
    if( !aIdx.GetNode().IsTextNode() )
    {
        pD->GetNodes().GoNext( &aIdx );
    }
    SwPaM aPaM( aIdx );
    aPaM.GetPoint()->nContent.Assign(aIdx.GetNode().GetContentNode(), 0);
    pD->SetInReading(true);
    bool bRet = pReader->Read(*pD, OUString(), aPaM, OUString()) == 0;
    pD->SetInReading(false);
    delete pReader;

    FlushFontCache();

    return bRet;
}

extern "C" SAL_DLLPUBLIC_EXPORT bool SAL_CALL TestImportWW8(SvStream &rStream)
{
    return TestImportDOC(rStream, "CWW8");
}

extern "C" SAL_DLLPUBLIC_EXPORT bool SAL_CALL TestImportWW6(SvStream &rStream)
{
    return TestImportDOC(rStream, "CWW6");
}

extern "C" SAL_DLLPUBLIC_EXPORT bool SAL_CALL TestImportWW2(SvStream &rStream)
{
    return TestImportDOC(rStream, "WW6");
}

sal_uLong WW8Reader::OpenMainStream( tools::SvRef<SotStorageStream>& rRef, sal_uInt16& rBuffSize )
{
    sal_uLong nRet = ERR_SWG_READ_ERROR;
    OSL_ENSURE( pStg.get(), "Where is my Storage?" );
    rRef = pStg->OpenSotStream( "WordDocument", StreamMode::READ | StreamMode::SHARE_DENYALL);

    if( rRef.is() )
    {
        if( SVSTREAM_OK == rRef->GetError() )
        {
            sal_uInt16 nOld = rRef->GetBufferSize();
            rRef->SetBufferSize( rBuffSize );
            rBuffSize = nOld;
            nRet = 0;
        }
        else
            nRet = rRef->GetError();
    }
    return nRet;
}

sal_uLong WW8Reader::Read(SwDoc &rDoc, const OUString& rBaseURL, SwPaM &rPaM, const OUString & /* FileName */)
{
    sal_uInt16 nOldBuffSize = 32768;
    bool bNew = !bInsertMode; // New Doc (no inserting)

    tools::SvRef<SotStorageStream> refStrm; // So that no one else can steal the Stream
    SvStream* pIn = pStrm;

    sal_uLong nRet = 0;
    sal_uInt8 nVersion = 8;

    const OUString sFltName = GetFltName();
    if ( sFltName=="WW6" )
    {
        if (pStrm)
            nVersion = 6;
        else
        {
            OSL_ENSURE(false, "WinWord 95 Reader-Read without Stream");
            nRet = ERR_SWG_READ_ERROR;
        }
    }
    else
    {
        if ( sFltName=="CWW6" )
            nVersion = 6;
        else if ( sFltName=="CWW7" )
            nVersion = 7;

        if( pStg.is() )
        {
            nRet = OpenMainStream( refStrm, nOldBuffSize );
            pIn = refStrm.get();
        }
        else
        {
            OSL_ENSURE(false, "WinWord 95/97 Reader-Read without Storage");
            nRet = ERR_SWG_READ_ERROR;
        }
    }

    if( !nRet )
    {
        std::unique_ptr<SwWW8ImplReader> pRdr(new SwWW8ImplReader(nVersion, pStg.get(), pIn, rDoc,
            rBaseURL, bNew, bSkipImages, *rPaM.GetPoint()));
        if (bNew)
        {
            // Remove Frame and offsets from Frame Template
            Reader::ResetFrameFormats( rDoc );

            rPaM.GetBound().nContent.Assign(nullptr, 0);
            rPaM.GetBound(false).nContent.Assign(nullptr, 0);

        }
        try
        {
            nRet = pRdr->LoadDoc();
        }
        catch( const std::exception& )
        {
            nRet = ERR_WW8_NO_WW8_FILE_ERR;
        }

        if( refStrm.is() )
        {
            refStrm->SetBufferSize( nOldBuffSize );
            refStrm.clear();
        }
        else
        {
            pIn->ResetError();
        }

    }
    return nRet;
}

int WW8Reader::GetReaderType()
{
    return SW_STORAGE_READER | SW_STREAM_READER;
}

bool WW8Reader::HasGlossaries() const
{
    return true;
}

bool WW8Reader::ReadGlossaries(SwTextBlocks& rBlocks, bool bSaveRelFiles) const
{
    bool bRet=false;

    WW8Reader *pThis = const_cast<WW8Reader *>(this);

    sal_uInt16 nOldBuffSize = 32768;
    tools::SvRef<SotStorageStream> refStrm;
    if (!pThis->OpenMainStream(refStrm, nOldBuffSize))
    {
        WW8Glossary aGloss( refStrm, 8, pStg.get() );
        bRet = aGloss.Load( rBlocks, bSaveRelFiles );
    }
    return bRet;
}

bool SwMSDffManager::GetOLEStorageName(sal_uInt32 nOLEId, OUString& rStorageName,
    tools::SvRef<SotStorage>& rSrcStorage, uno::Reference < embed::XStorage >& rDestStorage) const
{
    bool bRet = false;

    sal_Int32 nPictureId = 0;
    if (rReader.m_pStg)
    {
        // Via the TextBox-PLCF we get the right char Start-End positions
        // We should then find the EmbeddedField and the corresponding Sprms
        // in that Area.
        // We only need the Sprm for the Picture Id.
        long nOldPos = rReader.m_pStrm->Tell();
        {
            // #i32596# - consider return value of method
            // <rReader.GetTxbxTextSttEndCp(..)>. If it returns false, method
            // wasn't successful. Thus, continue in this case.
            // Note: Ask MM for initialization of <nStartCp> and <nEndCp>.
            // Note: Ask MM about assertions in method <rReader.GetTxbxTextSttEndCp(..)>.
            WW8_CP nStartCp, nEndCp;
            if ( rReader.m_bDrawCpOValid && rReader.GetTxbxTextSttEndCp(nStartCp, nEndCp,
                            static_cast<sal_uInt16>((nOLEId >> 16) & 0xFFFF),
                            static_cast<sal_uInt16>(nOLEId & 0xFFFF)) )
            {
                WW8PLCFxSaveAll aSave;
                memset( &aSave, 0, sizeof( aSave ) );
                rReader.m_pPlcxMan->SaveAllPLCFx( aSave );

                nStartCp += rReader.m_nDrawCpO;
                nEndCp   += rReader.m_nDrawCpO;
                WW8PLCFx_Cp_FKP* pChp = rReader.m_pPlcxMan->GetChpPLCF();
                wwSprmParser aSprmParser(*rReader.m_pWwFib);
                while (nStartCp <= nEndCp && !nPictureId)
                {
                    if (!pChp->SeekPos( nStartCp))
                        break;
                    WW8PLCFxDesc aDesc;
                    pChp->GetSprms( &aDesc );

                    if (aDesc.nSprmsLen && aDesc.pMemPos) // Attributes present
                    {
                        long nLen = aDesc.nSprmsLen;
                        const sal_uInt8* pSprm = aDesc.pMemPos;

                        while (nLen >= 2 && !nPictureId)
                        {
                            sal_uInt16 nId = aSprmParser.GetSprmId(pSprm);
                            sal_uInt16 nSL = aSprmParser.GetSprmSize(nId, pSprm, nLen);

                            if( nLen < nSL )
                                break; // Not enough Bytes left

                            if( 0x6A03 == nId && 0 < nLen )
                            {
                                nPictureId = SVBT32ToUInt32(pSprm +
                                    aSprmParser.DistanceToData(nId));
                                bRet = true;
                            }
                            pSprm += nSL;
                            nLen -= nSL;
                        }
                    }
                    nStartCp = aDesc.nEndPos;
                }

                rReader.m_pPlcxMan->RestoreAllPLCFx( aSave );
            }
        }
        rReader.m_pStrm->Seek( nOldPos );
    }

    if( bRet )
    {
        rStorageName = "_";
        rStorageName += OUString::number(nPictureId);
        rSrcStorage = rReader.m_pStg->OpenSotStorage(SL::aObjectPool);
        if (!rReader.m_pDocShell)
            bRet=false;
        else
            rDestStorage = rReader.m_pDocShell->GetStorage();
    }
    return bRet;
}

/**
 * When reading a single Box (which possibly is part of a group), we do
 * not yet have enough information to decide whether we need it as a TextField
 * or not.
 * So convert all of them as a precaution.
 * FIXME: Actually implement this!
 */
bool SwMSDffManager::ShapeHasText(sal_uLong, sal_uLong) const
{
    return true;
}

bool SwWW8ImplReader::InEqualOrHigherApo(int nLvl) const
{
    if (nLvl)
        --nLvl;
    // #i60827# - check size of <maApos> to assure that <maApos.begin() + nLvl> can be performed.
    if ( sal::static_int_cast< sal_Int32>(nLvl) >= sal::static_int_cast< sal_Int32>(m_aApos.size()) )
    {
        return false;
    }
    mycApoIter aIter = std::find(m_aApos.begin() + nLvl, m_aApos.end(), true);
    return aIter != m_aApos.end();
}

bool SwWW8ImplReader::InEqualApo(int nLvl) const
{
    // If we are in a table, see if an apo was inserted at the level below the table.
    if (nLvl)
        --nLvl;
    if (nLvl < 0 || static_cast<size_t>(nLvl) >= m_aApos.size())
        return false;
    return m_aApos[nLvl];
}

namespace sw
{
    namespace hack
    {
        Position::Position(const SwPosition &rPos)
            : maPtNode(rPos.nNode), mnPtContent(rPos.nContent.GetIndex())
        {
        }

        Position::Position(const Position &rPos)
            : maPtNode(rPos.maPtNode), mnPtContent(rPos.mnPtContent)
        {
        }

        Position::operator SwPosition() const
        {
            SwPosition aRet(maPtNode);
            aRet.nContent.Assign(maPtNode.GetNode().GetContentNode(), mnPtContent);
            return aRet;
        }
    }
}

SwMacroInfo::SwMacroInfo()
    : SdrObjUserData( SdrInventor::ScOrSwDraw, SW_UD_IMAPDATA )
    , mnShapeId(-1)
{
}

SwMacroInfo::~SwMacroInfo()
{
}

SdrObjUserData* SwMacroInfo::Clone( SdrObject* /*pObj*/ ) const
{
   return new SwMacroInfo( *this );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */