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
/* -*- 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_extensions.h>
#include <config_folders.h>

#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/container/XContainer.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/embed/XTransactedObject.hpp>
#include <com/sun/star/io/IOException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/ucb/ContentCreationException.hpp>
#include <com/sun/star/xml/sax/SAXException.hpp>
#include <vcl/svapp.hxx>
#include <osl/mutex.hxx>
#include <vcl/errinf.hxx>
#include <rtl/ustring.hxx>
#include <sal/log.hxx>
#include <sot/storage.hxx>
#include <comphelper/getexpandeduri.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/sequence.hxx>

#include <namecont.hxx>
#include <basic/basicmanagerrepository.hxx>
#include <tools/diagnose_ex.h>
#include <tools/urlobj.hxx>
#include <unotools/pathoptions.hxx>
#include <svtools/sfxecode.hxx>
#include <svtools/ehdl.hxx>
#include <basic/basmgr.hxx>
#include <com/sun/star/xml/sax/Parser.hpp>
#include <com/sun/star/xml/sax/InputSource.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/xml/sax/Writer.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/uno/DeploymentException.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/script/LibraryNotLoadedException.hpp>
#include <com/sun/star/script/vba/VBAScriptEventId.hpp>
#include <com/sun/star/ucb/SimpleFileAccess.hpp>
#include <com/sun/star/util/PathSubstitution.hpp>
#include <com/sun/star/deployment/ExtensionManager.hpp>
#include <comphelper/storagehelper.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <cppuhelper/queryinterface.hxx>
#include <cppuhelper/supportsservice.hxx>
#include <cppuhelper/typeprovider.hxx>
#include <memory>

namespace basic
{

using namespace com::sun::star::document;
using namespace com::sun::star::container;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::io;
using namespace com::sun::star::ucb;
using namespace com::sun::star::script;
using namespace com::sun::star::beans;
using namespace com::sun::star::xml::sax;
using namespace com::sun::star::util;
using namespace com::sun::star::task;
using namespace com::sun::star::embed;
using namespace com::sun::star::frame;
using namespace com::sun::star::deployment;
using namespace com::sun::star;
using namespace cppu;
using namespace osl;

using com::sun::star::uno::Reference;

// #i34411: Flag for error handling during migration
static bool GbMigrationSuppressErrors = false;


// Implementation class NameContainer

// Methods XElementAccess
Type NameContainer::getElementType()
{
    return mType;
}

sal_Bool NameContainer::hasElements()
{
    bool bRet = (mnElementCount > 0);
    return bRet;
}

// Methods XNameAccess
Any NameContainer::getByName( const OUString& aName )
{
    NameContainerNameMap::iterator aIt = mHashMap.find( aName );
    if( aIt == mHashMap.end() )
    {
        throw NoSuchElementException();
    }
    sal_Int32 iHashResult = (*aIt).second;
    Any aRetAny = mValues[ iHashResult ];
    return aRetAny;
}

Sequence< OUString > NameContainer::getElementNames()
{
    return comphelper::containerToSequence(mNames);
}

sal_Bool NameContainer::hasByName( const OUString& aName )
{
    NameContainerNameMap::iterator aIt = mHashMap.find( aName );
    bool bRet = ( aIt != mHashMap.end() );
    return bRet;
}


// Methods XNameReplace
void NameContainer::replaceByName( const OUString& aName, const Any& aElement )
{
    const Type& aAnyType = aElement.getValueType();
    if( mType != aAnyType )
    {
        throw IllegalArgumentException();
    }
    NameContainerNameMap::iterator aIt = mHashMap.find( aName );
    if( aIt == mHashMap.end() )
    {
        throw NoSuchElementException();
    }
    sal_Int32 iHashResult = (*aIt).second;
    Any aOldElement = mValues[ iHashResult ];
    mValues[ iHashResult ] = aElement;


    // Fire event
    if( maContainerListeners.getLength() > 0 )
    {
        ContainerEvent aEvent;
        aEvent.Source = mpxEventSource;
        aEvent.Accessor <<= aName;
        aEvent.Element = aElement;
        aEvent.ReplacedElement = aOldElement;
        maContainerListeners.notifyEach( &XContainerListener::elementReplaced, aEvent );
    }

    /*  After the container event has been fired (one listener will update the
        core Basic manager), fire change event. Listeners can rely on that the
        Basic source code of the core Basic manager is up-to-date. */
    if( maChangesListeners.getLength() > 0 )
    {
        ChangesEvent aEvent;
        aEvent.Source = mpxEventSource;
        aEvent.Base <<= aEvent.Source;
        aEvent.Changes.realloc( 1 );
        aEvent.Changes[ 0 ].Accessor <<= aName;
        aEvent.Changes[ 0 ].Element = aElement;
        aEvent.Changes[ 0 ].ReplacedElement = aOldElement;
        maChangesListeners.notifyEach( &XChangesListener::changesOccurred, aEvent );
    }
}

void NameContainer::insertCheck(const OUString& aName, const Any& aElement)
{
    NameContainerNameMap::iterator aIt = mHashMap.find(aName);
    if( aIt != mHashMap.end() )
    {
        throw ElementExistException();
    }
    insertNoCheck(aName, aElement);
}

void NameContainer::insertNoCheck(const OUString& aName, const Any& aElement)
{
    const Type& aAnyType = aElement.getValueType();
    if( mType != aAnyType )
    {
        throw IllegalArgumentException();
    }

    sal_Int32 nCount = mNames.size();
    mNames.push_back( aName );
    mValues.push_back( aElement );

    mHashMap[ aName ] = nCount;
    mnElementCount++;

    // Fire event
    if( maContainerListeners.getLength() > 0 )
    {
        ContainerEvent aEvent;
        aEvent.Source = mpxEventSource;
        aEvent.Accessor <<= aName;
        aEvent.Element = aElement;
        maContainerListeners.notifyEach( &XContainerListener::elementInserted, aEvent );
    }

    /*  After the container event has been fired (one listener will update the
        core Basic manager), fire change event. Listeners can rely on that the
        Basic source code of the core Basic manager is up-to-date. */
    if( maChangesListeners.getLength() > 0 )
    {
        ChangesEvent aEvent;
        aEvent.Source = mpxEventSource;
        aEvent.Base <<= aEvent.Source;
        aEvent.Changes.realloc( 1 );
        aEvent.Changes[ 0 ].Accessor <<= aName;
        aEvent.Changes[ 0 ].Element = aElement;
        maChangesListeners.notifyEach( &XChangesListener::changesOccurred, aEvent );
    }
}

// Methods XNameContainer
void NameContainer::insertByName( const OUString& aName, const Any& aElement )
{
    insertCheck(aName, aElement);
}

void NameContainer::removeByName( const OUString& aName )
{
    NameContainerNameMap::iterator aIt = mHashMap.find( aName );
    if( aIt == mHashMap.end() )
    {
        OUString sMessage = "\"" + aName + "\" not found";
        throw NoSuchElementException(sMessage);
    }

    sal_Int32 iHashResult = (*aIt).second;
    Any aOldElement = mValues[ iHashResult ];
    mHashMap.erase( aIt );
    sal_Int32 iLast = mNames.size() - 1;
    if( iLast != iHashResult )
    {
        mNames[ iHashResult ] = mNames[ iLast ];
        mValues[ iHashResult ] = mValues[ iLast ];
        mHashMap[ mNames[ iHashResult ] ] = iHashResult;
    }
    mNames.resize( iLast );
    mValues.resize( iLast );
    mnElementCount--;

    // Fire event
    if( maContainerListeners.getLength() > 0 )
    {
        ContainerEvent aEvent;
        aEvent.Source = mpxEventSource;
        aEvent.Accessor <<= aName;
        aEvent.Element = aOldElement;
        maContainerListeners.notifyEach( &XContainerListener::elementRemoved, aEvent );
    }

    /*  After the container event has been fired (one listener will update the
        core Basic manager), fire change event. Listeners can rely on that the
        Basic source code of the core Basic manager is up-to-date. */
    if( maChangesListeners.getLength() > 0 )
    {
        ChangesEvent aEvent;
        aEvent.Source = mpxEventSource;
        aEvent.Base <<= aEvent.Source;
        aEvent.Changes.realloc( 1 );
        aEvent.Changes[ 0 ].Accessor <<= aName;
        // aEvent.Changes[ 0 ].Element remains empty (meaning "replaced with nothing")
        aEvent.Changes[ 0 ].ReplacedElement = aOldElement;
        maChangesListeners.notifyEach( &XChangesListener::changesOccurred, aEvent );
    }
}


// Methods XContainer
void SAL_CALL NameContainer::addContainerListener( const Reference< XContainerListener >& xListener )
{
    if( !xListener.is() )
    {
        throw RuntimeException("addContainerListener called with null xListener");
    }
    maContainerListeners.addInterface( Reference<XInterface>(xListener, UNO_QUERY) );
}

void SAL_CALL NameContainer::removeContainerListener( const Reference< XContainerListener >& xListener )
{
    if( !xListener.is() )
    {
        throw RuntimeException("removeContainerListener called with null xListener");
    }
    maContainerListeners.removeInterface( Reference<XInterface>(xListener, UNO_QUERY) );
}

// Methods XChangesNotifier
void SAL_CALL NameContainer::addChangesListener( const Reference< XChangesListener >& xListener )
{
    if( !xListener.is() )
    {
        throw RuntimeException("addChangesListener called with null xListener");
    }
    maChangesListeners.addInterface( Reference<XInterface>(xListener, UNO_QUERY) );
}

void SAL_CALL NameContainer::removeChangesListener( const Reference< XChangesListener >& xListener )
{
    if( !xListener.is() )
    {
        throw RuntimeException("removeChangesListener called with null xListener");
    }
    maChangesListeners.removeInterface( Reference<XInterface>(xListener, UNO_QUERY) );
}


// ModifiableHelper

void ModifiableHelper::setModified( bool _bModified )
{
    if ( _bModified == mbModified )
    {
        return;
    }
    mbModified = _bModified;

    if ( m_aModifyListeners.getLength() == 0 )
    {
        return;
    }
    EventObject aModifyEvent( m_rEventSource );
    m_aModifyListeners.notifyEach( &XModifyListener::modified, aModifyEvent );
}


VBAScriptListenerContainer::VBAScriptListenerContainer( ::osl::Mutex& rMutex ) :
    VBAScriptListenerContainer_BASE( rMutex )
{
}

bool VBAScriptListenerContainer::implTypedNotify( const Reference< vba::XVBAScriptListener >& rxListener, const vba::VBAScriptEvent& rEvent )
{
    rxListener->notifyVBAScriptEvent( rEvent );
    return true;    // notify all other listeners too
}

// Ctor
SfxLibraryContainer::SfxLibraryContainer()
    : SfxLibraryContainer_BASE( m_aMutex )
    , maVBAScriptListeners( m_aMutex )
    , mnRunningVBAScripts( 0 )
    , mbVBACompat( false )
    , maModifiable( *this, m_aMutex )
    , maNameContainer( new NameContainer(cppu::UnoType<XNameAccess>::get()) )
    , mbOldInfoFormat( false )
    , mbOasis2OOoFormat( false )
    , mpBasMgr( nullptr )
    , mbOwnBasMgr( false )
    , meInitMode(DEFAULT)
{
    mxContext = comphelper::getProcessComponentContext();

    mxSFI = ucb::SimpleFileAccess::create( mxContext );

    mxStringSubstitution = util::PathSubstitution::create( mxContext );
}

SfxLibraryContainer::~SfxLibraryContainer()
{
    if( mbOwnBasMgr )
    {
        delete mpBasMgr;
    }
}

void SfxLibraryContainer::enterMethod()
{
    Application::GetSolarMutex().acquire();
    if ( rBHelper.bInDispose || rBHelper.bDisposed )
    {
        throw DisposedException( OUString(), *this );
    }
}

void SfxLibraryContainer::leaveMethod()
{
    Application::GetSolarMutex().release();
}

BasicManager* SfxLibraryContainer::getBasicManager()
{
    try
    {
        if ( mpBasMgr )
        {
            return mpBasMgr;
        }
        Reference< XModel > xDocument( mxOwnerDocument.get(), UNO_QUERY );
        SAL_WARN_IF(
            !xDocument.is(), "basic",
            ("SfxLibraryContainer::getBasicManager: cannot obtain a BasicManager"
             " without document!"));
        if ( xDocument.is() )
        {
            mpBasMgr = BasicManagerRepository::getDocumentBasicManager( xDocument );
        }
    }
    catch (const css::ucb::ContentCreationException&)
    {
        TOOLS_WARN_EXCEPTION( "basic", "SfxLibraryContainer::getBasicManager:" );
    }
    return mpBasMgr;
}

// Methods XStorageBasedLibraryContainer
Reference< XStorage > SAL_CALL SfxLibraryContainer::getRootStorage()
{
    LibraryContainerMethodGuard aGuard( *this );
    return mxStorage;
}

void SAL_CALL SfxLibraryContainer::setRootStorage( const Reference< XStorage >& _rxRootStorage )
{
    LibraryContainerMethodGuard aGuard( *this );
    if ( !_rxRootStorage.is() )
    {
        throw IllegalArgumentException();
    }
    mxStorage = _rxRootStorage;
    onNewRootStorage();
}

void SAL_CALL SfxLibraryContainer::storeLibrariesToStorage( const Reference< XStorage >& _rxRootStorage )
{
    LibraryContainerMethodGuard aGuard( *this );
    if ( !_rxRootStorage.is() )
    {
        throw IllegalArgumentException();
    }
    try
    {
        storeLibraries_Impl( _rxRootStorage, true );
    }
    catch( const Exception& )
    {
        throw WrappedTargetException( OUString(),
                                      *this, ::cppu::getCaughtException() );
    }
}


// Methods XModifiable
sal_Bool SfxLibraryContainer::isModified()
{
    LibraryContainerMethodGuard aGuard( *this );
    if ( maModifiable.isModified() )
    {
        return true;
    }
    // the library container is not modified, go through the libraries and check whether they are modified
    Sequence< OUString > aNames = maNameContainer->getElementNames();
    const OUString* pNames = aNames.getConstArray();
    sal_Int32 nNameCount = aNames.getLength();

    for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
    {
        OUString aName = pNames[ i ];
        try
        {
            SfxLibrary* pImplLib = getImplLib( aName );
            if( pImplLib->isModified() )
            {
                if ( aName == "Standard" )
                {
                    // this is a workaround that has to be implemented because
                    // empty standard library should stay marked as modified
                    // but should not be treated as modified while it is empty
                    if ( pImplLib->hasElements() )
                        return true;
                }
                else
                {
                    return true;
                }
            }
        }
        catch(const css::container::NoSuchElementException&)
        {
        }
    }

    return false;
}

void SAL_CALL SfxLibraryContainer::setModified( sal_Bool _bModified )
{
    LibraryContainerMethodGuard aGuard( *this );
    maModifiable.setModified( _bModified );
}

void SAL_CALL SfxLibraryContainer::addModifyListener( const Reference< XModifyListener >& _rxListener )
{
    LibraryContainerMethodGuard aGuard( *this );
    maModifiable.addModifyListener( _rxListener );
}

void SAL_CALL SfxLibraryContainer::removeModifyListener( const Reference< XModifyListener >& _rxListener )
{
    LibraryContainerMethodGuard aGuard( *this );
    maModifiable.removeModifyListener( _rxListener );
}

// Methods XPersistentLibraryContainer
Any SAL_CALL SfxLibraryContainer::getRootLocation()
{
    LibraryContainerMethodGuard aGuard( *this );
    return Any( getRootStorage() );
}

OUString SAL_CALL SfxLibraryContainer::getContainerLocationName()
{
    LibraryContainerMethodGuard aGuard( *this );
    return maLibrariesDir;
}

void SAL_CALL SfxLibraryContainer::storeLibraries(  )
{
    LibraryContainerMethodGuard aGuard( *this );
    try
    {
        storeLibraries_Impl( mxStorage, mxStorage.is()  );
        // we need to store *all* libraries if and only if we are based on a storage:
        // in this case, storeLibraries_Impl will remove the source storage, after loading
        // all libraries, so we need to force them to be stored, again
    }
    catch( const Exception& )
    {
        throw WrappedTargetException( OUString(), *this, ::cppu::getCaughtException() );
    }
}

static void checkAndCopyFileImpl( const INetURLObject& rSourceFolderInetObj,
                                  const INetURLObject& rTargetFolderInetObj,
                                  const OUString& rCheckFileName,
                                  const OUString& rCheckExtension,
                                  const Reference< XSimpleFileAccess3 >& xSFI )
{
    INetURLObject aTargetFolderInetObj( rTargetFolderInetObj );
    aTargetFolderInetObj.insertName( rCheckFileName, true, INetURLObject::LAST_SEGMENT,
                                     INetURLObject::EncodeMechanism::All );
    aTargetFolderInetObj.setExtension( rCheckExtension );
    OUString aTargetFile = aTargetFolderInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
    if( !xSFI->exists( aTargetFile ) )
    {
        INetURLObject aSourceFolderInetObj( rSourceFolderInetObj );
        aSourceFolderInetObj.insertName( rCheckFileName, true, INetURLObject::LAST_SEGMENT,
                                         INetURLObject::EncodeMechanism::All );
        aSourceFolderInetObj.setExtension( rCheckExtension );
        OUString aSourceFile = aSourceFolderInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
        xSFI->copy( aSourceFile, aTargetFile );
    }
}

static void createVariableURL( OUString& rStr, const OUString& rLibName,
                               const OUString& rInfoFileName, bool bUser )
{
    if( bUser )
    {
        rStr = "$(USER)/basic/";
    }
    else
    {
        rStr = "$(INST)/" LIBO_SHARE_FOLDER "/basic/";
    }
    rStr += rLibName + "/" + rInfoFileName + ".xlb/";
}

void SfxLibraryContainer::init( const OUString& rInitialDocumentURL, const uno::Reference< embed::XStorage >& rxInitialStorage )
{
    // this might be called from within the ctor, and the impl_init might (indirectly) create
    // a UNO reference to ourself.
    // Ensure that we're not destroyed while we're in here
    osl_atomic_increment( &m_refCount );
    init_Impl( rInitialDocumentURL, rxInitialStorage );
    osl_atomic_decrement( &m_refCount );
}

void SfxLibraryContainer::init_Impl( const OUString& rInitialDocumentURL,
                                     const uno::Reference< embed::XStorage >& rxInitialStorage )
{
    uno::Reference< embed::XStorage > xStorage = rxInitialStorage;

    maInitialDocumentURL = rInitialDocumentURL;
    maInfoFileName = OUString::createFromAscii( getInfoFileName() );
    maOldInfoFileName = OUString::createFromAscii( getOldInfoFileName() );
    maLibElementFileExtension = OUString::createFromAscii( getLibElementFileExtension() );
    maLibrariesDir = OUString::createFromAscii( getLibrariesDir() );

    meInitMode = DEFAULT;
    INetURLObject aInitUrlInetObj( maInitialDocumentURL );
    OUString aInitFileName = aInitUrlInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
    if( !aInitFileName.isEmpty() )
    {
        // We need a BasicManager to avoid problems
        StarBASIC* pBas = new StarBASIC();
        mpBasMgr = new BasicManager( pBas );
        mbOwnBasMgr = true;

        OUString aExtension = aInitUrlInetObj.getExtension();
        if( aExtension == "xlc" )
        {
            meInitMode = CONTAINER_INIT_FILE;
            INetURLObject aLibPathInetObj( aInitUrlInetObj );
            aLibPathInetObj.removeSegment();
            maLibraryPath = aLibPathInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
        }
        else if( aExtension == "xlb" )
        {
            meInitMode = LIBRARY_INIT_FILE;
            uno::Reference< embed::XStorage > xDummyStor;
            ::xmlscript::LibDescriptor aLibDesc;
            implLoadLibraryIndexFile( nullptr, aLibDesc, xDummyStor, aInitFileName );
            return;
        }
        else
        {
            // Decide between old and new document
            bool bOldStorage = SotStorage::IsOLEStorage( aInitFileName );
            if ( bOldStorage )
            {
                meInitMode = OLD_BASIC_STORAGE;
                importFromOldStorage( aInitFileName );
                return;
            }
            else
            {
                meInitMode = OFFICE_DOCUMENT;
                try
                {
                    xStorage = ::comphelper::OStorageHelper::GetStorageFromURL( aInitFileName, embed::ElementModes::READ );
                }
                catch (const uno::Exception& )
                {
                    // TODO: error handling
                }
            }
        }
    }
    else
    {
        // Default paths
        maLibraryPath = SvtPathOptions().GetBasicPath();
    }

    Reference< XParser > xParser = xml::sax::Parser::create(mxContext);

    uno::Reference< io::XInputStream > xInput;

    mxStorage = xStorage;
    bool bStorage = mxStorage.is();


    // #110009: Scope to force the StorageRefs to be destructed and
    // so the streams to be closed before the preload operation
    {

    uno::Reference< embed::XStorage > xLibrariesStor;
    OUString aFileName;

    int nPassCount = 1;
    if( !bStorage && meInitMode == DEFAULT )
    {
        nPassCount = 2;
    }
    for( int nPass = 0 ; nPass < nPassCount ; nPass++ )
    {
        if( bStorage )
        {
            SAL_WARN_IF(
                meInitMode != DEFAULT && meInitMode != OFFICE_DOCUMENT, "basic",
                "Wrong InitMode for document");
            try
            {
                uno::Reference< io::XStream > xStream;
                xLibrariesStor = xStorage->openStorageElement( maLibrariesDir, embed::ElementModes::READ );

                if ( xLibrariesStor.is() )
                {
                    aFileName = maInfoFileName + "-lc.xml";
                    try
                    {
                        xStream = xLibrariesStor->openStreamElement( aFileName, embed::ElementModes::READ );
                    }
                    catch(const uno::Exception& )
                    {}

                    if( !xStream.is() )
                    {
                        mbOldInfoFormat = true;

                        // Check old version
                        aFileName = maOldInfoFileName + ".xml";
                        try
                        {
                            xStream = xLibrariesStor->openStreamElement( aFileName, embed::ElementModes::READ );
                        }
                        catch(const uno::Exception& )
                        {}

                        if( !xStream.is() )
                        {
                            // Check for EA2 document version with wrong extensions
                            aFileName = maOldInfoFileName + ".xli";
                            xStream = xLibrariesStor->openStreamElement( aFileName, embed::ElementModes::READ );
                        }
                    }
                }

                if ( xStream.is() )
                {
                    xInput = xStream->getInputStream();
                }
            }
            catch(const uno::Exception& )
            {
                // TODO: error handling?
            }
        }
        else
        {
            std::unique_ptr<INetURLObject> pLibInfoInetObj;
            if( meInitMode == CONTAINER_INIT_FILE )
            {
                aFileName = aInitFileName;
            }
            else
            {
                if( nPass == 1 )
                {
                    pLibInfoInetObj.reset(new INetURLObject( maLibraryPath.getToken(0, ';') ));
                }
                else
                {
                    pLibInfoInetObj.reset(new INetURLObject( maLibraryPath.getToken(1, ';') ));
                }
                pLibInfoInetObj->insertName( maInfoFileName, false, INetURLObject::LAST_SEGMENT, INetURLObject::EncodeMechanism::All );
                pLibInfoInetObj->setExtension( "xlc" );
                aFileName = pLibInfoInetObj->GetMainURL( INetURLObject::DecodeMechanism::NONE );
            }

            try
            {
                xInput = mxSFI->openFileRead( aFileName );
            }
            catch(const Exception& )
            {
                // Silently tolerate empty or missing files
                xInput.clear();
            }

            // Old variant?
            if( !xInput.is() && nPass == 0 )
            {
                INetURLObject aLibInfoInetObj( maLibraryPath.getToken(1, ';') );
                aLibInfoInetObj.insertName( maOldInfoFileName, false, INetURLObject::LAST_SEGMENT, INetURLObject::EncodeMechanism::All );
                aLibInfoInetObj.setExtension( "xli" );
                aFileName = aLibInfoInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );

                try
                {
                    xInput = mxSFI->openFileRead( aFileName );
                    mbOldInfoFormat = true;
                }
                catch(const Exception& )
                {
                    xInput.clear();
                }
            }
        }

        if( xInput.is() )
        {
            InputSource source;
            source.aInputStream = xInput;
            source.sSystemId    = aFileName;

            // start parsing
            std::unique_ptr< ::xmlscript::LibDescriptorArray> pLibArray(new ::xmlscript::LibDescriptorArray());

            try
            {
                xParser->setDocumentHandler( ::xmlscript::importLibraryContainer( pLibArray.get() ) );
                xParser->parseStream( source );
            }
            catch ( const xml::sax::SAXException& )
            {
                TOOLS_WARN_EXCEPTION( "basic", "" );
                return;
            }
            catch ( const io::IOException& )
            {
                TOOLS_WARN_EXCEPTION( "basic", "" );
                return;
            }

            sal_Int32 nLibCount = pLibArray->mnLibCount;
            for( sal_Int32 i = 0 ; i < nLibCount ; i++ )
            {
                ::xmlscript::LibDescriptor& rLib = pLibArray->mpLibs[i];

                // Check storage URL
                OUString aStorageURL = rLib.aStorageURL;
                if( !bStorage && aStorageURL.isEmpty() && nPass == 0 )
                {
                    OUString aLibraryPath;
                    if( meInitMode == CONTAINER_INIT_FILE )
                    {
                        aLibraryPath = maLibraryPath;
                    }
                    else
                    {
                        aLibraryPath = maLibraryPath.getToken(1, ';');
                    }
                    INetURLObject aInetObj( aLibraryPath );

                    aInetObj.insertName( rLib.aName, true, INetURLObject::LAST_SEGMENT,
                                         INetURLObject::EncodeMechanism::All );
                    OUString aLibDirPath = aInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
                    if( mxSFI->isFolder( aLibDirPath ) )
                    {
                        createVariableURL( rLib.aStorageURL, rLib.aName, maInfoFileName, true );
                        maModifiable.setModified( true );
                    }
                    else if( rLib.bLink )
                    {
                        // Check "share" path
                        INetURLObject aShareInetObj( maLibraryPath.getToken(0, ';') );
                        aShareInetObj.insertName( rLib.aName, true, INetURLObject::LAST_SEGMENT,
                                                  INetURLObject::EncodeMechanism::All );
                        OUString aShareLibDirPath = aShareInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
                        if( mxSFI->isFolder( aShareLibDirPath ) )
                        {
                            createVariableURL( rLib.aStorageURL, rLib.aName, maInfoFileName, false );
                            maModifiable.setModified( true );
                        }
                        else
                        {
                            // #i25537: Ignore lib if library folder does not really exist
                            continue;
                        }
                    }
                }

                OUString aLibName = rLib.aName;

                // If the same library name is used by the shared and the
                // user lib container index files the user file wins
                if( nPass == 1 && hasByName( aLibName ) )
                {
                    continue;
                }
                SfxLibrary* pImplLib;
                if( rLib.bLink )
                {
                    Reference< XNameAccess > xLib =
                        createLibraryLink( aLibName, rLib.aStorageURL, rLib.bReadOnly );
                    pImplLib = static_cast< SfxLibrary* >( xLib.get() );
                }
                else
                {
                    Reference< XNameContainer > xLib = createLibrary( aLibName );
                    pImplLib = static_cast< SfxLibrary* >( xLib.get() );
                    pImplLib->mbLoaded = false;
                    pImplLib->mbReadOnly = rLib.bReadOnly;
                    if( !bStorage )
                    {
                        checkStorageURL( rLib.aStorageURL, pImplLib->maLibInfoFileURL,
                                         pImplLib->maStorageURL, pImplLib->maUnexpandedStorageURL );
                    }
                }
                maModifiable.setModified( false );

                // Read library info files
                if( !mbOldInfoFormat )
                {
                    uno::Reference< embed::XStorage > xLibraryStor;
                    if( !pImplLib->mbInitialised && bStorage )
                    {
                        try
                        {
                            xLibraryStor = xLibrariesStor->openStorageElement( rLib.aName,
                                                                                embed::ElementModes::READ );
                        }
                        catch(const uno::Exception& )
                        {
                            #if OSL_DEBUG_LEVEL > 0
                            TOOLS_WARN_EXCEPTION(
                                "basic",
                                "couldn't open sub storage for library \"" << rLib.aName << "\"");
                            #endif
                        }
                    }

                    // Link is already initialised in createLibraryLink()
                    if( !pImplLib->mbInitialised && (!bStorage || xLibraryStor.is()) )
                    {
                        bool bLoaded = implLoadLibraryIndexFile( pImplLib, rLib, xLibraryStor, OUString() );
                        SAL_WARN_IF(
                            bLoaded && aLibName != rLib.aName, "basic",
                            ("Different library names in library container and"
                             " library info files!"));
                        if( GbMigrationSuppressErrors && !bLoaded )
                        {
                            removeLibrary( aLibName );
                        }
                    }
                }
                else if( !bStorage )
                {
                    // Write new index file immediately because otherwise
                    // the library elements will be lost when storing into
                    // the new info format
                    uno::Reference< embed::XStorage > xTmpStorage;
                    implStoreLibraryIndexFile( pImplLib, rLib, xTmpStorage );
                }

                implImportLibDescriptor( pImplLib, rLib );

                if( nPass == 1 )
                {
                    pImplLib->mbSharedIndexFile = true;
                    pImplLib->mbReadOnly = true;
                }
            }

            // Keep flag for documents to force writing the new index files
            if( !bStorage )
            {
                mbOldInfoFormat = false;
            }
        }
    }

    // #110009: END Scope to force the StorageRefs to be destructed
    }

    if( !bStorage && meInitMode == DEFAULT )
    {
        try
        {
            implScanExtensions();
        }
        catch(const uno::Exception& )
        {
            // TODO: error handling?
            SAL_WARN("basic", "Cannot access extensions!");
        }
    }

    // Preload?
    {
        Sequence< OUString > aNames = maNameContainer->getElementNames();
        const OUString* pNames = aNames.getConstArray();
        sal_Int32 nNameCount = aNames.getLength();
        for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
        {
            OUString aName = pNames[ i ];
            SfxLibrary* pImplLib = getImplLib( aName );
            if( pImplLib->mbPreload )
            {
                loadLibrary( aName );
            }
        }
    }

    if( meInitMode != DEFAULT )
        return;

    INetURLObject aUserBasicInetObj( maLibraryPath.getToken(1, ';') );
    OUString aStandardStr("Standard");

    INetURLObject aPrevUserBasicInetObj_1( aUserBasicInetObj );
    aPrevUserBasicInetObj_1.removeSegment();
    INetURLObject aPrevUserBasicInetObj_2 = aPrevUserBasicInetObj_1;
    aPrevUserBasicInetObj_1.Append( "__basic_80" );
    aPrevUserBasicInetObj_2.Append( "__basic_80_2" );

    // #i93163
    bool bCleanUp = false;
    try
    {
        INetURLObject aPrevUserBasicInetObj = aPrevUserBasicInetObj_1;
        OUString aPrevFolder = aPrevUserBasicInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
        if( mxSFI->isFolder( aPrevFolder ) )
        {
            // Check if Standard folder exists and is complete
            INetURLObject aUserBasicStandardInetObj( aUserBasicInetObj );
            aUserBasicStandardInetObj.insertName( aStandardStr, true, INetURLObject::LAST_SEGMENT,
                                                  INetURLObject::EncodeMechanism::All );
            INetURLObject aPrevUserBasicStandardInetObj( aPrevUserBasicInetObj );
            aPrevUserBasicStandardInetObj.insertName( aStandardStr, true, INetURLObject::LAST_SEGMENT,
                                                    INetURLObject::EncodeMechanism::All );
            OUString aPrevStandardFolder = aPrevUserBasicStandardInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
            if( mxSFI->isFolder( aPrevStandardFolder ) )
            {
                OUString aXlbExtension( "xlb" );
                OUString aCheckFileName;

                // Check if script.xlb exists
                aCheckFileName = "script";
                checkAndCopyFileImpl( aUserBasicStandardInetObj,
                                      aPrevUserBasicStandardInetObj,
                                      aCheckFileName, aXlbExtension, mxSFI );

                // Check if dialog.xlb exists
                aCheckFileName = "dialog";
                checkAndCopyFileImpl( aUserBasicStandardInetObj,
                                      aPrevUserBasicStandardInetObj,
                                      aCheckFileName, aXlbExtension, mxSFI );

                // Check if module1.xba exists
                aCheckFileName = "Module1";
                checkAndCopyFileImpl( aUserBasicStandardInetObj,
                                      aPrevUserBasicStandardInetObj,
                                      aCheckFileName, "xba", mxSFI );
            }
            else
            {
                OUString aStandardFolder = aUserBasicStandardInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
                mxSFI->copy( aStandardFolder, aPrevStandardFolder );
            }

            OUString aPrevCopyToFolder = aPrevUserBasicInetObj_2.GetMainURL( INetURLObject::DecodeMechanism::NONE );
            mxSFI->copy( aPrevFolder, aPrevCopyToFolder );
        }
        else
        {
            aPrevUserBasicInetObj = aPrevUserBasicInetObj_2;
            aPrevFolder = aPrevUserBasicInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
        }
        if( mxSFI->isFolder( aPrevFolder ) )
        {
            rtl::Reference<SfxLibraryContainer> pPrevCont = createInstanceImpl();

            // Rename previous basic folder to make storage URLs correct during initialisation
            OUString aFolderUserBasic = aUserBasicInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
            INetURLObject aUserBasicTmpInetObj( aUserBasicInetObj );
            aUserBasicTmpInetObj.removeSegment();
            aUserBasicTmpInetObj.Append( "__basic_tmp" );
            OUString aFolderTmp = aUserBasicTmpInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );

            mxSFI->move( aFolderUserBasic, aFolderTmp );
            try
            {
                mxSFI->move( aPrevFolder, aFolderUserBasic );
            }
            catch(const Exception& )
            {
                // Move back user/basic folder
                try
                {
                       mxSFI->kill( aFolderUserBasic );
                }
                catch(const Exception& )
                {}
                mxSFI->move( aFolderTmp, aFolderUserBasic );
                throw;
            }

            INetURLObject aPrevUserBasicLibInfoInetObj( aUserBasicInetObj );
            aPrevUserBasicLibInfoInetObj.insertName( maInfoFileName, false, INetURLObject::LAST_SEGMENT,
                                                INetURLObject::EncodeMechanism::All );
            aPrevUserBasicLibInfoInetObj.setExtension( "xlc");
            OUString aLibInfoFileName = aPrevUserBasicLibInfoInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
            Sequence<Any> aInitSeq( 1 );
            aInitSeq.getArray()[0] <<= aLibInfoFileName;
            GbMigrationSuppressErrors = true;
            pPrevCont->initialize( aInitSeq );
            GbMigrationSuppressErrors = false;

            // Rename folders back
            mxSFI->move( aFolderUserBasic, aPrevFolder );
            mxSFI->move( aFolderTmp, aFolderUserBasic );

            Sequence< OUString > aNames = pPrevCont->getElementNames();
            const OUString* pNames = aNames.getConstArray();
            sal_Int32 nNameCount = aNames.getLength();

            for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
            {
                OUString aLibName = pNames[ i ];
                if( hasByName( aLibName ) )
                {
                    if( aLibName == aStandardStr )
                    {
                        SfxLibrary* pImplLib = getImplLib( aStandardStr );
                        OUString aStandardFolder = pImplLib->maStorageURL;
                        mxSFI->kill( aStandardFolder );
                    }
                    else
                    {
                        continue;
                    }
                }

                SfxLibrary* pImplLib = pPrevCont->getImplLib( aLibName );
                if( pImplLib->mbLink )
                {
                    OUString aStorageURL = pImplLib->maUnexpandedStorageURL;
                    bool bCreateLink = true;
                    if( aStorageURL.indexOf( "vnd.sun.star.expand:$UNO_USER_PACKAGES_CACHE"   ) != -1 ||
                        aStorageURL.indexOf( "vnd.sun.star.expand:$UNO_SHARED_PACKAGES_CACHE" ) != -1 ||
                        aStorageURL.indexOf( "vnd.sun.star.expand:$BUNDLED_EXTENSIONS" ) != -1 ||
                        aStorageURL.indexOf( "$(INST)"   ) != -1 )
                    {
                        bCreateLink = false;
                    }
                    if( bCreateLink )
                    {
                        createLibraryLink( aLibName, pImplLib->maStorageURL, pImplLib->mbReadOnly );
                    }
                }
                else
                {
                    // Move folder if not already done
                    INetURLObject aUserBasicLibFolderInetObj( aUserBasicInetObj );
                    aUserBasicLibFolderInetObj.Append( aLibName );
                    OUString aLibFolder = aUserBasicLibFolderInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );

                    INetURLObject aPrevUserBasicLibFolderInetObj( aPrevUserBasicInetObj );
                    aPrevUserBasicLibFolderInetObj.Append( aLibName );
                    OUString aPrevLibFolder = aPrevUserBasicLibFolderInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );

                    if( mxSFI->isFolder( aPrevLibFolder ) && !mxSFI->isFolder( aLibFolder ) )
                    {
                        mxSFI->move( aPrevLibFolder, aLibFolder );
                    }

                    if( aLibName == aStandardStr )
                    {
                        maNameContainer->removeByName( aLibName );
                    }

                    // Create library
                    Reference< XNameContainer > xLib = createLibrary( aLibName );
                    SfxLibrary* pNewLib = static_cast< SfxLibrary* >( xLib.get() );
                    pNewLib->mbLoaded = false;
                    pNewLib->implSetModified( false );
                    checkStorageURL( aLibFolder, pNewLib->maLibInfoFileURL,
                                     pNewLib->maStorageURL, pNewLib->maUnexpandedStorageURL );

                    uno::Reference< embed::XStorage > xDummyStor;
                    ::xmlscript::LibDescriptor aLibDesc;
                    implLoadLibraryIndexFile( pNewLib, aLibDesc, xDummyStor, pNewLib->maLibInfoFileURL );
                    implImportLibDescriptor( pNewLib, aLibDesc );
                }
            }
            mxSFI->kill( aPrevFolder );
        }
    }
    catch(const Exception&)
    {
        TOOLS_WARN_EXCEPTION("basic", "Upgrade of Basic installation failed somehow" );
        bCleanUp = true;
    }

    // #i93163
    if( !bCleanUp )
        return;

    INetURLObject aPrevUserBasicInetObj_Err( aUserBasicInetObj );
    aPrevUserBasicInetObj_Err.removeSegment();
    aPrevUserBasicInetObj_Err.Append( "__basic_80_err" );
    OUString aPrevFolder_Err = aPrevUserBasicInetObj_Err.GetMainURL( INetURLObject::DecodeMechanism::NONE );

    bool bSaved = false;
    try
    {
        OUString aPrevFolder_1 = aPrevUserBasicInetObj_1.GetMainURL( INetURLObject::DecodeMechanism::NONE );
        if( mxSFI->isFolder( aPrevFolder_1 ) )
        {
            mxSFI->move( aPrevFolder_1, aPrevFolder_Err );
            bSaved = true;
        }
    }
    catch(const Exception& )
    {}
    try
    {
        OUString aPrevFolder_2 = aPrevUserBasicInetObj_2.GetMainURL( INetURLObject::DecodeMechanism::NONE );
        if( !bSaved && mxSFI->isFolder( aPrevFolder_2 ) )
        {
            mxSFI->move( aPrevFolder_2, aPrevFolder_Err );
        }
        else
        {
            mxSFI->kill( aPrevFolder_2 );
        }
    }
    catch(const Exception& )
    {}
}

void SfxLibraryContainer::implScanExtensions()
{
#if HAVE_FEATURE_EXTENSIONS
    ScriptExtensionIterator aScriptIt;

    bool bPureDialogLib = false;
    for (;;)
    {
        OUString aLibURL = aScriptIt.nextBasicOrDialogLibrary( bPureDialogLib );
        if (aLibURL.isEmpty())
            break;
        if( bPureDialogLib && maInfoFileName == "script" )
        {
            continue;
        }
        // Extract lib name
        sal_Int32 nLen = aLibURL.getLength();
        sal_Int32 indexLastSlash = aLibURL.lastIndexOf( '/' );
        sal_Int32 nReduceCopy = 0;
        if( indexLastSlash == nLen - 1 )
        {
            nReduceCopy = 1;
            indexLastSlash = aLibURL.lastIndexOf( '/', nLen - 1 );
        }

        OUString aLibName = aLibURL.copy( indexLastSlash + 1, nLen - indexLastSlash - nReduceCopy - 1 );

        // If a library of the same exists the existing library wins
        if( hasByName( aLibName ) )
        {
            continue;
        }
        // Add index file to URL
        OUString aIndexFileURL = aLibURL;
        if( nReduceCopy == 0 )
        {
            aIndexFileURL += "/";
        }
        aIndexFileURL += maInfoFileName + ".xlb";

        // Create link
        const bool bReadOnly = false;
        createLibraryLink( aLibName, aIndexFileURL, bReadOnly );
    }
#else
    (void) this;
#endif
}

// Handle maLibInfoFileURL and maStorageURL correctly
void SfxLibraryContainer::checkStorageURL( const OUString& aSourceURL,
                                           OUString& aLibInfoFileURL, OUString& aStorageURL,
                                           OUString& aUnexpandedStorageURL )
{
    OUString aExpandedSourceURL = expand_url( aSourceURL );
    if( aExpandedSourceURL != aSourceURL )
    {
        aUnexpandedStorageURL = aSourceURL;
    }
    INetURLObject aInetObj( aExpandedSourceURL );
    OUString aExtension = aInetObj.getExtension();
    if( aExtension == "xlb" )
    {
        // URL to xlb file
        aLibInfoFileURL = aExpandedSourceURL;
        aInetObj.removeSegment();
        aStorageURL = aInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
    }
    else
    {
        // URL to library folder
        aStorageURL = aExpandedSourceURL;
        aInetObj.insertName( maInfoFileName, false, INetURLObject::LAST_SEGMENT, INetURLObject::EncodeMechanism::All );
        aInetObj.setExtension( "xlb" );
        aLibInfoFileURL = aInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
    }
}

SfxLibrary* SfxLibraryContainer::getImplLib( const OUString& rLibraryName )
{
    Any aLibAny = maNameContainer->getByName( rLibraryName ) ;<--- Variable 'aLibAny' is assigned a value that is never used.
    Reference< XNameAccess > xNameAccess;
    aLibAny >>= xNameAccess;<--- Variable 'aLibAny' is assigned a value that is never used.
    SfxLibrary* pImplLib = static_cast< SfxLibrary* >( xNameAccess.get() );
    return pImplLib;
}


// Storing with password encryption

// Empty implementation, avoids unnecessary implementation in dlgcont.cxx
bool SfxLibraryContainer::implStorePasswordLibrary( SfxLibrary*,
                                                    const OUString&,
                                                    const uno::Reference< embed::XStorage >&,
                                                    const uno::Reference< task::XInteractionHandler >&  )
{
    return false;
}

bool SfxLibraryContainer::implStorePasswordLibrary(
    SfxLibrary* /*pLib*/,
    const OUString& /*aName*/,
    const css::uno::Reference< css::embed::XStorage >& /*xStorage*/,
    const OUString& /*aTargetURL*/,
    const Reference< XSimpleFileAccess3 >& /*xToUseSFI*/,
    const uno::Reference< task::XInteractionHandler >&  )
{
    return false;
}

bool SfxLibraryContainer::implLoadPasswordLibrary(
    SfxLibrary* /*pLib*/,
    const OUString& /*Name*/,
    bool /*bVerifyPasswordOnly*/ )
{
    return true;
}

OUString SfxLibraryContainer::createAppLibraryFolder( SfxLibrary* pLib, const OUString& aName )
{
    OUString aLibDirPath = pLib->maStorageURL;
    if( aLibDirPath.isEmpty() )
    {
        INetURLObject aInetObj( maLibraryPath.getToken(1, ';') );
        aInetObj.insertName( aName, true, INetURLObject::LAST_SEGMENT, INetURLObject::EncodeMechanism::All );
        checkStorageURL( aInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ), pLib->maLibInfoFileURL,
                         pLib->maStorageURL, pLib->maUnexpandedStorageURL );
        aLibDirPath = pLib->maStorageURL;
    }

    if( !mxSFI->isFolder( aLibDirPath ) )
    {
        try
        {
            mxSFI->createFolder( aLibDirPath );
        }
        catch(const Exception& )
        {}
    }

    return aLibDirPath;
}

// Storing
void SfxLibraryContainer::implStoreLibrary( SfxLibrary* pLib,
                                            const OUString& aName,
                                            const uno::Reference< embed::XStorage >& xStorage )
{
    Reference< XSimpleFileAccess3 > xDummySFA;
    Reference< XInteractionHandler > xDummyHandler;
    implStoreLibrary( pLib, aName, xStorage, OUString(), xDummySFA, xDummyHandler );
}

// New variant for library export
void SfxLibraryContainer::implStoreLibrary( SfxLibrary* pLib,
                                            const OUString& aName,
                                            const uno::Reference< embed::XStorage >& xStorage,
                                            const OUString& aTargetURL,
                                            const Reference< XSimpleFileAccess3 >& rToUseSFI,
                                            const Reference< XInteractionHandler >& xHandler )
{
    bool bLink = pLib->mbLink;
    bool bStorage = xStorage.is() && !bLink;

    Sequence< OUString > aElementNames = pLib->getElementNames();
    sal_Int32 nNameCount = aElementNames.getLength();
    const OUString* pNames = aElementNames.getConstArray();

    if( bStorage )
    {
        for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
        {
            OUString aElementName = pNames[ i ];
            OUString aStreamName = aElementName + ".xml";

            if( !isLibraryElementValid( pLib->getByName( aElementName ) ) )
            {
                SAL_WARN(
                    "basic",
                    "invalid library element \"" << aElementName << '"');
                continue;
            }
            try
            {
                uno::Reference< io::XStream > xElementStream = xStorage->openStreamElement(
                                                                    aStreamName,
                                                                    embed::ElementModes::READWRITE );
                //    throw uno::RuntimeException(); // TODO: method must either return the stream or throw an exception

                uno::Reference< beans::XPropertySet > xProps( xElementStream, uno::UNO_QUERY );
                SAL_WARN_IF(
                    !xProps.is(), "basic",
                    "The StorageStream must implement XPropertySet interface!");
                //if ( !xProps.is() ) //TODO

                if ( xProps.is() )
                {
                    xProps->setPropertyValue("MediaType", uno::Any( OUString( "text/xml" ) ) );

                    // #87671 Allow encryption
                    xProps->setPropertyValue("UseCommonStoragePasswordEncryption", uno::Any( true ) );

                    Reference< XOutputStream > xOutput = xElementStream->getOutputStream();
                    Reference< XNameContainer > xLib( pLib );
                    writeLibraryElement( xLib, aElementName, xOutput );
                }
            }
            catch(const uno::Exception& )
            {
                SAL_WARN("basic", "Problem during storing of library!");
                // TODO: error handling?
            }
        }
        pLib->storeResourcesToStorage( xStorage );
    }
    else
    {
        // Export?
        bool bExport = !aTargetURL.isEmpty();
        try
        {
            Reference< XSimpleFileAccess3 > xSFI = mxSFI;
            if( rToUseSFI.is() )
            {
                xSFI = rToUseSFI;
            }
            OUString aLibDirPath;
            if( bExport )
            {
                INetURLObject aInetObj( aTargetURL );
                aInetObj.insertName( aName, true, INetURLObject::LAST_SEGMENT, INetURLObject::EncodeMechanism::All );
                aLibDirPath = aInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );

                if( !xSFI->isFolder( aLibDirPath ) )
                {
                    xSFI->createFolder( aLibDirPath );
                }
                pLib->storeResourcesToURL( aLibDirPath, xHandler );
            }
            else
            {
                aLibDirPath = createAppLibraryFolder( pLib, aName );
                pLib->storeResources();
            }

            for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
            {
                OUString aElementName = pNames[ i ];

                INetURLObject aElementInetObj( aLibDirPath );
                aElementInetObj.insertName( aElementName, false,
                                            INetURLObject::LAST_SEGMENT,
                                            INetURLObject::EncodeMechanism::All );
                aElementInetObj.setExtension( maLibElementFileExtension );
                OUString aElementPath( aElementInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ) );

                if( !isLibraryElementValid( pLib->getByName( aElementName ) ) )
                {
                    SAL_WARN(
                        "basic",
                        "invalid library element \"" << aElementName << '"');
                    continue;
                }

                // TODO: Check modified
                try
                {
                    if( xSFI->exists( aElementPath ) )
                    {
                        xSFI->kill( aElementPath );
                    }
                    Reference< XOutputStream > xOutput = xSFI->openFileWrite( aElementPath );
                    Reference< XNameContainer > xLib( pLib );
                    writeLibraryElement( xLib, aElementName, xOutput );
                    xOutput->closeOutput();
                }
                catch(const Exception& )
                {
                    if( bExport )
                    {
                        throw;
                    }
                    SfxErrorContext aEc( ERRCTX_SFX_SAVEDOC, aElementPath );
                    ErrorHandler::HandleError( ERRCODE_IO_GENERAL );
                }
            }
        }
        catch(const Exception& )
        {
            if( bExport )
            {
                throw;
            }
        }
    }
}

void SfxLibraryContainer::implStoreLibraryIndexFile( SfxLibrary* pLib,
                                                     const ::xmlscript::LibDescriptor& rLib,
                                                     const uno::Reference< embed::XStorage >& xStorage )
{
    Reference< XSimpleFileAccess3 > xDummySFA;
    implStoreLibraryIndexFile( pLib, rLib, xStorage, OUString(), xDummySFA );
}

// New variant for library export
void SfxLibraryContainer::implStoreLibraryIndexFile( SfxLibrary* pLib,
                                                     const ::xmlscript::LibDescriptor& rLib,
                                                     const uno::Reference< embed::XStorage >& xStorage,
                                                     const OUString& aTargetURL,
                                                     const Reference< XSimpleFileAccess3 >& rToUseSFI )
{
    // Create sax writer
    Reference< XWriter > xWriter = xml::sax::Writer::create(mxContext);

    bool bLink = pLib->mbLink;
    bool bStorage = xStorage.is() && !bLink;

    // Write info file
    uno::Reference< io::XOutputStream > xOut;
    uno::Reference< io::XStream > xInfoStream;
    if( bStorage )
    {
        OUString aStreamName = maInfoFileName + "-lb.xml";

        try
        {
            xInfoStream = xStorage->openStreamElement( aStreamName, embed::ElementModes::READWRITE );
            SAL_WARN_IF(!xInfoStream.is(), "basic", "No stream!");
            uno::Reference< beans::XPropertySet > xProps( xInfoStream, uno::UNO_QUERY );
            //    throw uno::RuntimeException(); // TODO

            if ( xProps.is() )
            {
                xProps->setPropertyValue("MediaType", uno::Any( OUString("text/xml") ) );

                // #87671 Allow encryption
                xProps->setPropertyValue("UseCommonStoragePasswordEncryption", uno::Any( true ) );

                xOut = xInfoStream->getOutputStream();
            }
        }
        catch(const uno::Exception& )
        {
            SAL_WARN("basic", "Problem during storing of library index file!");
            // TODO: error handling?
        }
    }
    else
    {
        // Export?
        bool bExport = !aTargetURL.isEmpty();
        Reference< XSimpleFileAccess3 > xSFI = mxSFI;
        if( rToUseSFI.is() )
        {
            xSFI = rToUseSFI;
        }
        OUString aLibInfoPath;
        if( bExport )
        {
            INetURLObject aInetObj( aTargetURL );
            aInetObj.insertName( rLib.aName, true, INetURLObject::LAST_SEGMENT, INetURLObject::EncodeMechanism::All );
            OUString aLibDirPath = aInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
            if( !xSFI->isFolder( aLibDirPath ) )
            {
                xSFI->createFolder( aLibDirPath );
            }
            aInetObj.insertName( maInfoFileName, false, INetURLObject::LAST_SEGMENT, INetURLObject::EncodeMechanism::All );
            aInetObj.setExtension( "xlb" );
            aLibInfoPath = aInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
        }
        else
        {
            createAppLibraryFolder( pLib, rLib.aName );
            aLibInfoPath = pLib->maLibInfoFileURL;
        }

        try
        {
            if( xSFI->exists( aLibInfoPath ) )
            {
                xSFI->kill( aLibInfoPath );
            }
            xOut = xSFI->openFileWrite( aLibInfoPath );
        }
        catch(const Exception& )
        {
            if( bExport )
            {
                throw;
            }
            SfxErrorContext aEc( ERRCTX_SFX_SAVEDOC, aLibInfoPath );
            ErrorHandler::HandleError(  ERRCODE_IO_GENERAL );
        }
    }
    if( !xOut.is() )
    {
        SAL_WARN("basic", "couldn't open output stream");
        return;
    }
    xWriter->setOutputStream( xOut );
    xmlscript::exportLibrary( xWriter, rLib );
}


bool SfxLibraryContainer::implLoadLibraryIndexFile(  SfxLibrary* pLib,
                                                     ::xmlscript::LibDescriptor& rLib,
                                                     const uno::Reference< embed::XStorage >& xStorage,
                                                     const OUString& aIndexFileName )
{
    Reference< XParser > xParser = xml::sax::Parser::create(mxContext);

    bool bStorage = false;
    if( pLib )
    {
        bool bLink = pLib->mbLink;
        bStorage = xStorage.is() && !bLink;
    }

    // Read info file
    uno::Reference< io::XInputStream > xInput;
    OUString aLibInfoPath;
    if( bStorage )
    {
        aLibInfoPath = maInfoFileName + "-lb.xml";

        try
        {
            uno::Reference< io::XStream > xInfoStream =
                xStorage->openStreamElement( aLibInfoPath, embed::ElementModes::READ );
            xInput = xInfoStream->getInputStream();
        }
        catch(const uno::Exception& )
        {}
    }
    else
    {
        // Create Input stream
        //String aLibInfoPath; // attention: THIS PROBLEM MUST BE REVIEWED BY SCRIPTING OWNER!!!

        if( pLib )
        {
            createAppLibraryFolder( pLib, rLib.aName );
            aLibInfoPath = pLib->maLibInfoFileURL;
        }
        else
        {
            aLibInfoPath = aIndexFileName;
        }
        try
        {
            xInput = mxSFI->openFileRead( aLibInfoPath );
        }
        catch(const Exception& )
        {
            xInput.clear();
            if( !GbMigrationSuppressErrors )
            {
                SfxErrorContext aEc( ERRCTX_SFX_LOADBASIC, aLibInfoPath );
                ErrorHandler::HandleError(  ERRCODE_IO_GENERAL );
            }
        }
    }
    if( !xInput.is() )
    {
        return false;
    }

    InputSource source;
    source.aInputStream = xInput;
    source.sSystemId    = aLibInfoPath;

    // start parsing
    try
    {
        xParser->setDocumentHandler( ::xmlscript::importLibrary( rLib ) );
        xParser->parseStream( source );
    }
    catch(const Exception& )
    {
        SAL_WARN("basic", "Parsing error");
        SfxErrorContext aEc( ERRCTX_SFX_LOADBASIC, aLibInfoPath );
        ErrorHandler::HandleError(  ERRCODE_IO_GENERAL );
        return false;
    }

    if( !pLib )
    {
        Reference< XNameContainer > xLib = createLibrary( rLib.aName );
        pLib = static_cast< SfxLibrary* >( xLib.get() );
        pLib->mbLoaded = false;
        rLib.aStorageURL = aIndexFileName;
        checkStorageURL( rLib.aStorageURL, pLib->maLibInfoFileURL, pLib->maStorageURL,
                         pLib->maUnexpandedStorageURL );

        implImportLibDescriptor( pLib, rLib );
    }

    return true;
}

void SfxLibraryContainer::implImportLibDescriptor( SfxLibrary* pLib,
                                                   ::xmlscript::LibDescriptor const & rLib )
{
    if( pLib->mbInitialised )
        return;

    sal_Int32 nElementCount = rLib.aElementNames.getLength();
    const OUString* pElementNames = rLib.aElementNames.getConstArray();
    Any aDummyElement = createEmptyLibraryElement();
    for( sal_Int32 i = 0 ; i < nElementCount ; i++ )
    {
        pLib->maNameContainer->insertByName( pElementNames[i], aDummyElement );
    }
    pLib->mbPasswordProtected = rLib.bPasswordProtected;
    pLib->mbReadOnly = rLib.bReadOnly;
    pLib->mbPreload  = rLib.bPreload;
    pLib->implSetModified( false );
    pLib->mbInitialised = true;
}


// Methods of new XLibraryStorage interface?
void SfxLibraryContainer::storeLibraries_Impl( const uno::Reference< embed::XStorage >& i_rStorage,
                                               bool bComplete )
{
    const Sequence< OUString > aNames = maNameContainer->getElementNames();
    const sal_Int32 nNameCount = aNames.getLength();
    const OUString* pName = aNames.getConstArray();
    const OUString* pNamesEnd = aNames.getConstArray() + nNameCount;

    // Don't count libs from shared index file
    sal_Int32 nLibsToSave = nNameCount;
    for( ; pName != pNamesEnd; ++pName )
    {
        SfxLibrary* pImplLib = getImplLib( *pName );
        if( pImplLib->mbSharedIndexFile || pImplLib->mbExtension )
        {
            nLibsToSave--;
        }
    }
    // Write to storage?
    bool bStorage = i_rStorage.is();
    uno::Reference< embed::XStorage > xSourceLibrariesStor;
    uno::Reference< embed::XStorage > xTargetLibrariesStor;
    OUString sTempTargetStorName;
    const bool bInplaceStorage = bStorage && ( i_rStorage == mxStorage );

    if( nLibsToSave == 0 )
    {
        if ( bInplaceStorage && mxStorage->hasByName(maLibrariesDir) )
        {
            mxStorage->removeElement(maLibrariesDir);
        }
        return;
    }

    if ( bStorage )
    {
        // Don't write if only empty standard lib exists
        if ( ( nLibsToSave == 1 ) && ( aNames[0] == "Standard" ) )
        {
            Any aLibAny = maNameContainer->getByName( aNames[0] );
            Reference< XNameAccess > xNameAccess;
            aLibAny >>= xNameAccess;
            if ( ! xNameAccess->hasElements() )
            {
                if ( bInplaceStorage && mxStorage->hasByName(maLibrariesDir) )
                {
                    mxStorage->removeElement(maLibrariesDir);
                }
                return;
            }
        }

        // create the empty target storage
        try
        {
            OUString sTargetLibrariesStoreName;
            if ( bInplaceStorage )
            {
                // create a temporary target storage
                const OUStringBuffer aTempTargetNameBase = maLibrariesDir + "_temp_";
                sal_Int32 index = 0;
                do
                {
                    OUStringBuffer aTempTargetName( aTempTargetNameBase );
                    aTempTargetName.append( index++ );

                    sTargetLibrariesStoreName = aTempTargetName.makeStringAndClear();
                    if ( !i_rStorage->hasByName( sTargetLibrariesStoreName ) )
                    {
                        break;
                    }
                }
                while ( true );
                sTempTargetStorName = sTargetLibrariesStoreName;
            }
            else
            {
                sTargetLibrariesStoreName = maLibrariesDir;
                if ( i_rStorage->hasByName( sTargetLibrariesStoreName ) )
                {
                    i_rStorage->removeElement( sTargetLibrariesStoreName );
                }
            }

            xTargetLibrariesStor.set( i_rStorage->openStorageElement( sTargetLibrariesStoreName, embed::ElementModes::READWRITE ), UNO_SET_THROW );
        }
        catch( const uno::Exception& )
        {
            DBG_UNHANDLED_EXCEPTION("basic");
            return;
        }

        // open the source storage which might be used to copy yet-unmodified libraries
        try
        {
            if ( mxStorage->hasByName( maLibrariesDir ) || bInplaceStorage )
            {
                xSourceLibrariesStor = mxStorage->openStorageElement( maLibrariesDir,
                                                   bInplaceStorage ? embed::ElementModes::READWRITE : embed::ElementModes::READ );
            }
        }
        catch( const uno::Exception& )
        {
            DBG_UNHANDLED_EXCEPTION("basic");
            return;
        }
    }

    int iArray = 0;
    pName = aNames.getConstArray();
    ::xmlscript::LibDescriptor aLibDescriptorForExtensionLibs;
    std::unique_ptr< ::xmlscript::LibDescriptorArray > pLibArray(new ::xmlscript::LibDescriptorArray(nLibsToSave));
    for( ; pName != pNamesEnd; ++pName )
    {
        SfxLibrary* pImplLib = getImplLib( *pName );
        if( pImplLib->mbSharedIndexFile )
        {
            continue;
        }
        const bool bExtensionLib = pImplLib->mbExtension;
        ::xmlscript::LibDescriptor& rLib = bExtensionLib ?
              aLibDescriptorForExtensionLibs : pLibArray->mpLibs[iArray];
        if( !bExtensionLib )
        {
            iArray++;
        }
        rLib.aName = *pName;

        rLib.bLink = pImplLib->mbLink;
        if( !bStorage || pImplLib->mbLink )
        {
            rLib.aStorageURL = ( pImplLib->maUnexpandedStorageURL.getLength() ) ?
                pImplLib->maUnexpandedStorageURL : pImplLib->maLibInfoFileURL;
        }
        rLib.bReadOnly = pImplLib->mbReadOnly;
        rLib.bPreload = pImplLib->mbPreload;
        rLib.bPasswordProtected = pImplLib->mbPasswordProtected;
        rLib.aElementNames = pImplLib->getElementNames();

        if( pImplLib->implIsModified() || bComplete )
        {
// Testing pImplLib->implIsModified() is not reliable,
// IMHO the value of pImplLib->implIsModified() should
// reflect whether the library ( in-memory ) model
// is in sync with the library container's own storage. Currently
// whenever the library model is written to *any* storage
// pImplLib->implSetModified( sal_False ) is called
// The way the code works, especially the way that sfx uses
// temp storage when saving ( and later sets the root storage of the
// library container ) and similar madness in dbaccess means some surgery
// is required to make it possible to successfully use this optimisation
// It would be possible to do the implSetModified() call below only
// conditionally, but that would require an additional boolean to be
// passed in via the XStorageBasedDocument::storeLibrariesToStorage()...
// fdo#68983: If there's a password and the password is not known, only
// copying the storage works!
            // Can we simply copy the storage?
            bool isCopyStorage = !mbOldInfoFormat && !mbOasis2OOoFormat
                    && !pImplLib->isLoadedStorable()
                    && xSourceLibrariesStor.is() /* null for user profile */;
            if (isCopyStorage)
            {
                try
                {
                    (void)xSourceLibrariesStor->isStorageElement(rLib.aName);
                }
                catch (container::NoSuchElementException const&)
                {
                    isCopyStorage = false;
                }
            }
            if (isCopyStorage)
            {
                try
                {
                    xSourceLibrariesStor->copyElementTo( rLib.aName, xTargetLibrariesStor, rLib.aName );
                }
                catch( const uno::Exception& )
                {
                    DBG_UNHANDLED_EXCEPTION("basic");
                    // TODO: error handling?
                }
            }
            else
            {
                uno::Reference< embed::XStorage > xLibraryStor;
                if( bStorage )
                {
#if OSL_DEBUG_LEVEL > 0
                    try
                    {
#endif
                        xLibraryStor = xTargetLibrariesStor->openStorageElement(
                                                                        rLib.aName,
                                                                        embed::ElementModes::READWRITE );
#if OSL_DEBUG_LEVEL > 0
                    }
                    catch(const uno::Exception& )
                    {
                        TOOLS_WARN_EXCEPTION(
                            "basic",
                            "couldn't create sub storage for library \"" << rLib.aName << "\"");
                        throw;
                    }
#endif
                }

                // Maybe lib is not loaded?!
                if( bComplete )
                {
                    loadLibrary( rLib.aName );
                }
                if( pImplLib->mbPasswordProtected )
                {
                    implStorePasswordLibrary( pImplLib, rLib.aName, xLibraryStor, uno::Reference< task::XInteractionHandler >() );
                    // TODO: Check return value
                }
                else
                {
                    implStoreLibrary( pImplLib, rLib.aName, xLibraryStor );
                }
                implStoreLibraryIndexFile( pImplLib, rLib, xLibraryStor );
                if( bStorage )
                {
                    try
                    {
                        uno::Reference< embed::XTransactedObject > xTransact( xLibraryStor, uno::UNO_QUERY_THROW );
                        xTransact->commit();
                    }
                    catch(const uno::Exception& )
                    {
                        DBG_UNHANDLED_EXCEPTION("basic");
                        // TODO: error handling
                        throw;
                    }
                }
            }
            maModifiable.setModified( true );
            pImplLib->implSetModified( false );
        }

        // For container info ReadOnly refers to mbReadOnlyLink
        rLib.bReadOnly = pImplLib->mbReadOnlyLink;
    }

    // if we did an in-place save into a storage (i.e. a save into the storage we were already based on),
    // then we need to clean up the temporary storage we used for this
    if ( bInplaceStorage && !sTempTargetStorName.isEmpty() )
    {
        SAL_WARN_IF(
            !xSourceLibrariesStor.is(), "basic",
            ("SfxLibrariesContainer::storeLibraries_impl: unexpected: we should"
             " have a source storage here!"));
        try
        {
            // for this, we first remove everything from the source storage, then copy the complete content
            // from the temporary target storage. From then on, what used to be the "source storage" becomes
            // the "target storage" for all subsequent operations.

            // (We cannot simply remove the storage, denoted by maLibrariesDir, from i_rStorage - there might be
            // open references to it.)

            if ( xSourceLibrariesStor.is() )
            {
                // remove
                const Sequence< OUString > aRemoveNames( xSourceLibrariesStor->getElementNames() );
                for ( auto const & removeName : aRemoveNames )
                {
                    xSourceLibrariesStor->removeElement( removeName );
                }

                // copy
                const Sequence< OUString > aCopyNames( xTargetLibrariesStor->getElementNames() );
                for ( auto const & copyName : aCopyNames )
                {
                    xTargetLibrariesStor->copyElementTo( copyName, xSourceLibrariesStor, copyName );
                }
            }

            // close and remove temp target
            xTargetLibrariesStor->dispose();
            i_rStorage->removeElement( sTempTargetStorName );
            xTargetLibrariesStor.clear();
            sTempTargetStorName.clear();

            // adjust target
            xTargetLibrariesStor = xSourceLibrariesStor;
            xSourceLibrariesStor.clear();
        }
        catch( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION("basic");
            throw;
        }
    }

    if( !mbOldInfoFormat && !maModifiable.isModified() )
    {
        return;
    }
    maModifiable.setModified( false );
    mbOldInfoFormat = false;

    // Write library container info
    // Create sax writer
    Reference< XWriter > xWriter = xml::sax::Writer::create(mxContext);

    // Write info file
    uno::Reference< io::XOutputStream > xOut;
    uno::Reference< io::XStream > xInfoStream;
    if( bStorage )
    {
        OUString aStreamName = maInfoFileName + "-lc.xml";

        try
        {
            xInfoStream = xTargetLibrariesStor->openStreamElement( aStreamName, embed::ElementModes::READWRITE );
            uno::Reference< beans::XPropertySet > xProps( xInfoStream, uno::UNO_QUERY_THROW );
            xProps->setPropertyValue("MediaType", uno::Any( OUString( "text/xml" ) ) );

            // #87671 Allow encryption
            xProps->setPropertyValue("UseCommonStoragePasswordEncryption", uno::Any( true ) );

            xOut = xInfoStream->getOutputStream();
        }
        catch(const uno::Exception& )
        {
            ErrorHandler::HandleError(  ERRCODE_IO_GENERAL );
        }
    }
    else
    {
        // Create Output stream
        INetURLObject aLibInfoInetObj( maLibraryPath.getToken(1, ';') );
        aLibInfoInetObj.insertName( maInfoFileName, false, INetURLObject::LAST_SEGMENT, INetURLObject::EncodeMechanism::All );
        aLibInfoInetObj.setExtension( "xlc" );
        OUString aLibInfoPath( aLibInfoInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ) );

        try
        {
            if( mxSFI->exists( aLibInfoPath ) )
            {
                mxSFI->kill( aLibInfoPath );
            }
            xOut = mxSFI->openFileWrite( aLibInfoPath );
        }
        catch(const Exception& )
        {
            xOut.clear();
            SfxErrorContext aEc( ERRCTX_SFX_SAVEDOC, aLibInfoPath );
            ErrorHandler::HandleError(  ERRCODE_IO_GENERAL );
        }

    }
    if( !xOut.is() )
    {
        SAL_WARN("basic", "couldn't open output stream");
        return;
    }

    xWriter->setOutputStream( xOut );

    try
    {
        xmlscript::exportLibraryContainer( xWriter, pLibArray.get() );
        if ( bStorage )
        {
            uno::Reference< embed::XTransactedObject > xTransact( xTargetLibrariesStor, uno::UNO_QUERY_THROW );
            xTransact->commit();
        }
    }
    catch(const uno::Exception& )
    {
        SAL_WARN("basic", "Problem during storing of libraries!");
        ErrorHandler::HandleError(  ERRCODE_IO_GENERAL );
    }
}


// Methods XElementAccess
Type SAL_CALL SfxLibraryContainer::getElementType()
{
    LibraryContainerMethodGuard aGuard( *this );
    return maNameContainer->getElementType();
}

sal_Bool SfxLibraryContainer::hasElements()
{
    LibraryContainerMethodGuard aGuard( *this );
    bool bRet = maNameContainer->hasElements();
    return bRet;
}

// Methods XNameAccess
Any SfxLibraryContainer::getByName( const OUString& aName )
{
    LibraryContainerMethodGuard aGuard( *this );
    Any aRetAny = maNameContainer->getByName( aName ) ;
    return aRetAny;
}

Sequence< OUString > SfxLibraryContainer::getElementNames()
{
    LibraryContainerMethodGuard aGuard( *this );
    return maNameContainer->getElementNames();
}

sal_Bool SfxLibraryContainer::hasByName( const OUString& aName )
{
    LibraryContainerMethodGuard aGuard( *this );
    return maNameContainer->hasByName( aName ) ;
}

// Methods XLibraryContainer
Reference< XNameContainer > SAL_CALL SfxLibraryContainer::createLibrary( const OUString& Name )
{
    LibraryContainerMethodGuard aGuard( *this );
    SfxLibrary* pNewLib = implCreateLibrary( Name );
    pNewLib->maLibElementFileExtension = maLibElementFileExtension;

    createVariableURL( pNewLib->maUnexpandedStorageURL, Name, maInfoFileName, true );

    Reference< XNameAccess > xNameAccess = static_cast< XNameAccess* >( pNewLib );
    Any aElement;
    aElement <<= xNameAccess;
    maNameContainer->insertByName( Name, aElement );
    maModifiable.setModified( true );
    Reference< XNameContainer > xRet( xNameAccess, UNO_QUERY );
    return xRet;
}

Reference< XNameAccess > SAL_CALL SfxLibraryContainer::createLibraryLink
    ( const OUString& Name, const OUString& StorageURL, sal_Bool ReadOnly )
{
    LibraryContainerMethodGuard aGuard( *this );
    // TODO: Check other reasons to force ReadOnly status
    //if( !ReadOnly )
    //{
    //}

    OUString aLibInfoFileURL;
    OUString aLibDirURL;
    OUString aUnexpandedStorageURL;
    checkStorageURL( StorageURL, aLibInfoFileURL, aLibDirURL, aUnexpandedStorageURL );


    SfxLibrary* pNewLib = implCreateLibraryLink( Name, aLibInfoFileURL, aLibDirURL, ReadOnly );
    pNewLib->maLibElementFileExtension = maLibElementFileExtension;
    pNewLib->maUnexpandedStorageURL = aUnexpandedStorageURL;
    pNewLib->maOriginalStorageURL = StorageURL;

    uno::Reference< embed::XStorage > xDummyStor;
    ::xmlscript::LibDescriptor aLibDesc;
    implLoadLibraryIndexFile( pNewLib, aLibDesc, xDummyStor, OUString() );
    implImportLibDescriptor( pNewLib, aLibDesc );

    Reference< XNameAccess > xRet = static_cast< XNameAccess* >( pNewLib );
    Any aElement;
    aElement <<= xRet;
    maNameContainer->insertByName( Name, aElement );
    maModifiable.setModified( true );

    if( StorageURL.indexOf( "vnd.sun.star.expand:$UNO_USER_PACKAGES_CACHE" ) != -1 )
    {
        pNewLib->mbExtension = true;
    }
    else if( StorageURL.indexOf( "vnd.sun.star.expand:$UNO_SHARED_PACKAGES_CACHE" ) != -1
           || StorageURL.indexOf( "vnd.sun.star.expand:$BUNDLED_EXTENSIONS" ) != -1 )
    {
        pNewLib->mbExtension = true;
        pNewLib->mbReadOnly = true;
    }

    return xRet;
}

void SAL_CALL SfxLibraryContainer::removeLibrary( const OUString& Name )
{
    LibraryContainerMethodGuard aGuard( *this );
    // Get and hold library before removing
    Any aLibAny = maNameContainer->getByName( Name ) ;
    Reference< XNameAccess > xNameAccess;
    aLibAny >>= xNameAccess;
    SfxLibrary* pImplLib = static_cast< SfxLibrary* >( xNameAccess.get() );
    if( pImplLib->mbReadOnly && !pImplLib->mbLink )
    {
        throw IllegalArgumentException();
    }
    // Remove from container
    maNameContainer->removeByName( Name );
    maModifiable.setModified( true );

    // Delete library files, but not for linked libraries
    if( pImplLib->mbLink )
        return;

    if( mxStorage.is() )
    {
        return;
    }
    if( xNameAccess->hasElements() )
    {
        Sequence< OUString > aNames = pImplLib->getElementNames();
        sal_Int32 nNameCount = aNames.getLength();
        const OUString* pNames = aNames.getConstArray();
        for( sal_Int32 i = 0 ; i < nNameCount ; ++i, ++pNames )
        {
            pImplLib->removeElementWithoutChecks( *pNames, SfxLibrary::LibraryContainerAccess() );
        }
    }

    // Delete index file
    createAppLibraryFolder( pImplLib, Name );
    OUString aLibInfoPath = pImplLib->maLibInfoFileURL;
    try
    {
        if( mxSFI->exists( aLibInfoPath ) )
        {
            mxSFI->kill( aLibInfoPath );
        }
    }
    catch(const Exception& ) {}

    // Delete folder if empty
    INetURLObject aInetObj( maLibraryPath.getToken(1, ';') );
    aInetObj.insertName( Name, true, INetURLObject::LAST_SEGMENT,
                         INetURLObject::EncodeMechanism::All );
    OUString aLibDirPath = aInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );

    try
    {
        if( mxSFI->isFolder( aLibDirPath ) )
        {
            Sequence< OUString > aContentSeq = mxSFI->getFolderContents( aLibDirPath, true );
            sal_Int32 nCount = aContentSeq.getLength();
            if( !nCount )
            {
                mxSFI->kill( aLibDirPath );
            }
        }
    }
    catch(const Exception& )
    {
    }
}

sal_Bool SAL_CALL SfxLibraryContainer::isLibraryLoaded( const OUString& Name )
{
    LibraryContainerMethodGuard aGuard( *this );
    SfxLibrary* pImplLib = getImplLib( Name );
    bool bRet = pImplLib->mbLoaded;
    return bRet;
}


void SAL_CALL SfxLibraryContainer::loadLibrary( const OUString& Name )
{
    LibraryContainerMethodGuard aGuard( *this );
    Any aLibAny = maNameContainer->getByName( Name ) ;
    Reference< XNameAccess > xNameAccess;
    aLibAny >>= xNameAccess;
    SfxLibrary* pImplLib = static_cast< SfxLibrary* >( xNameAccess.get() );

    bool bLoaded = pImplLib->mbLoaded;
    pImplLib->mbLoaded = true;
    if( !(!bLoaded && xNameAccess->hasElements()) )
        return;

    if( pImplLib->mbPasswordProtected )
    {
        implLoadPasswordLibrary( pImplLib, Name );
        return;
    }

    bool bLink = pImplLib->mbLink;
    bool bStorage = mxStorage.is() && !bLink;

    uno::Reference< embed::XStorage > xLibrariesStor;
    uno::Reference< embed::XStorage > xLibraryStor;
    if( bStorage )
    {
#if OSL_DEBUG_LEVEL > 0
        try
        {
#endif
            xLibrariesStor = mxStorage->openStorageElement( maLibrariesDir, embed::ElementModes::READ );
            SAL_WARN_IF(
                !xLibrariesStor.is(), "basic",
                ("The method must either throw exception or return a"
                 " storage!"));
            if ( !xLibrariesStor.is() )
            {
                throw uno::RuntimeException("null returned from openStorageElement");
            }

            xLibraryStor = xLibrariesStor->openStorageElement( Name, embed::ElementModes::READ );
            SAL_WARN_IF(
                !xLibraryStor.is(), "basic",
                ("The method must either throw exception or return a"
                 " storage!"));
            if ( !xLibrariesStor.is() )
            {
                throw uno::RuntimeException("null returned from openStorageElement");
            }
#if OSL_DEBUG_LEVEL > 0
        }
        catch(const uno::Exception& )
        {
            TOOLS_WARN_EXCEPTION(
                "basic",
                "couldn't open sub storage for library \"" << Name << "\"");
            throw;
        }
#endif
    }

    Sequence< OUString > aNames = pImplLib->getElementNames();
    sal_Int32 nNameCount = aNames.getLength();
    const OUString* pNames = aNames.getConstArray();
    for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
    {
        OUString aElementName = pNames[ i ];

        OUString aFile;
        uno::Reference< io::XInputStream > xInStream;

        if( bStorage )
        {
            uno::Reference< io::XStream > xElementStream;

            aFile = aElementName + ".xml";

            try
            {
                xElementStream = xLibraryStor->openStreamElement( aFile, embed::ElementModes::READ );
            }
            catch(const uno::Exception& )
            {}

            if( !xElementStream.is() )
            {
                // Check for EA2 document version with wrong extensions
                aFile = aElementName + "." + maLibElementFileExtension;
                try
                {
                    xElementStream = xLibraryStor->openStreamElement( aFile, embed::ElementModes::READ );
                }
                catch(const uno::Exception& )
                {}
            }

            if ( xElementStream.is() )
            {
                xInStream = xElementStream->getInputStream();
            }
            if ( !xInStream.is() )
            {
                SAL_WARN(
                    "basic",
                    "couldn't open library element stream - attempted to"
                        " open library \"" << Name << '"');
                throw RuntimeException("couldn't open library element stream", *this);
            }
        }
        else
        {
            OUString aLibDirPath = pImplLib->maStorageURL;
            INetURLObject aElementInetObj( aLibDirPath );
            aElementInetObj.insertName( aElementName, false,
                                        INetURLObject::LAST_SEGMENT,
                                        INetURLObject::EncodeMechanism::All );
            aElementInetObj.setExtension( maLibElementFileExtension );
            aFile = aElementInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
        }

        Reference< XNameContainer > xLib( pImplLib );
        Any aAny = importLibraryElement( xLib, aElementName,
                                         aFile, xInStream );
        if( pImplLib->hasByName( aElementName ) )
        {
            if( aAny.hasValue() )
            {
                pImplLib->maNameContainer->replaceByName( aElementName, aAny );
            }
        }
        else
        {
            pImplLib->maNameContainer->insertNoCheck(aElementName, aAny);
        }
    }
    pImplLib->implSetModified( false );
}

// Methods XLibraryContainer2
sal_Bool SAL_CALL SfxLibraryContainer::isLibraryLink( const OUString& Name )
{
    LibraryContainerMethodGuard aGuard( *this );
    SfxLibrary* pImplLib = getImplLib( Name );
    bool bRet = pImplLib->mbLink;
    return bRet;
}

OUString SAL_CALL SfxLibraryContainer::getLibraryLinkURL( const OUString& Name )
{
    LibraryContainerMethodGuard aGuard( *this );
    SfxLibrary* pImplLib = getImplLib( Name );
    bool bLink = pImplLib->mbLink;
    if( !bLink )
    {
        throw IllegalArgumentException();
    }
    OUString aRetStr = pImplLib->maLibInfoFileURL;
    return aRetStr;
}

sal_Bool SAL_CALL SfxLibraryContainer::isLibraryReadOnly( const OUString& Name )
{
    LibraryContainerMethodGuard aGuard( *this );
    SfxLibrary* pImplLib = getImplLib( Name );
    bool bRet = pImplLib->mbReadOnly || (pImplLib->mbLink && pImplLib->mbReadOnlyLink);
    return bRet;
}

void SAL_CALL SfxLibraryContainer::setLibraryReadOnly( const OUString& Name, sal_Bool bReadOnly )
{
    LibraryContainerMethodGuard aGuard( *this );
    SfxLibrary* pImplLib = getImplLib( Name );
    if( pImplLib->mbLink )
    {
        if( pImplLib->mbReadOnlyLink != bool(bReadOnly) )
        {
            pImplLib->mbReadOnlyLink = bReadOnly;
            pImplLib->implSetModified( true );
            maModifiable.setModified( true );
        }
    }
    else
    {
        if( pImplLib->mbReadOnly != bool(bReadOnly) )
        {
            pImplLib->mbReadOnly = bReadOnly;
            pImplLib->implSetModified( true );
        }
    }
}

void SAL_CALL SfxLibraryContainer::renameLibrary( const OUString& Name, const OUString& NewName )
{
    LibraryContainerMethodGuard aGuard( *this );
    if( maNameContainer->hasByName( NewName ) )
    {
        throw ElementExistException();
    }
    // Get and hold library before removing
    Any aLibAny = maNameContainer->getByName( Name ) ;

    // #i24094 Maybe lib is not loaded!
    Reference< XNameAccess > xNameAccess;
    aLibAny >>= xNameAccess;
    SfxLibrary* pImplLib = static_cast< SfxLibrary* >( xNameAccess.get() );
    if( pImplLib->mbPasswordProtected && !pImplLib->mbPasswordVerified )
    {
        return;     // Lib with unverified password cannot be renamed
    }
    loadLibrary( Name );

    // Remove from container
    maNameContainer->removeByName( Name );
    maModifiable.setModified( true );

    // Rename library folder, but not for linked libraries
    bool bMovedSuccessful = true;

    // Rename files
    bool bStorage = mxStorage.is();
    if( !bStorage && !pImplLib->mbLink )
    {
        bMovedSuccessful = false;

        OUString aLibDirPath = pImplLib->maStorageURL;

        INetURLObject aDestInetObj( maLibraryPath.getToken(1, ';'));
        aDestInetObj.insertName( NewName, true, INetURLObject::LAST_SEGMENT,
                                 INetURLObject::EncodeMechanism::All );
        OUString aDestDirPath = aDestInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );

        // Store new URL
        OUString aLibInfoFileURL = pImplLib->maLibInfoFileURL;
        checkStorageURL( aDestDirPath, pImplLib->maLibInfoFileURL, pImplLib->maStorageURL,
                         pImplLib->maUnexpandedStorageURL );

        try
        {
            if( mxSFI->isFolder( aLibDirPath ) )
            {
                if( !mxSFI->isFolder( aDestDirPath ) )
                {
                    mxSFI->createFolder( aDestDirPath );
                }
                // Move index file
                try
                {
                    if( mxSFI->exists( pImplLib->maLibInfoFileURL ) )
                    {
                        mxSFI->kill( pImplLib->maLibInfoFileURL );
                    }
                    mxSFI->move( aLibInfoFileURL, pImplLib->maLibInfoFileURL );
                }
                catch(const Exception& )
                {
                }

                Sequence< OUString > aElementNames = xNameAccess->getElementNames();
                sal_Int32 nNameCount = aElementNames.getLength();
                const OUString* pNames = aElementNames.getConstArray();
                for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
                {
                    OUString aElementName = pNames[ i ];

                    INetURLObject aElementInetObj( aLibDirPath );
                    aElementInetObj.insertName( aElementName, false,
                        INetURLObject::LAST_SEGMENT, INetURLObject::EncodeMechanism::All );
                    aElementInetObj.setExtension( maLibElementFileExtension );
                    OUString aElementPath( aElementInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ) );

                    INetURLObject aElementDestInetObj( aDestDirPath );
                    aElementDestInetObj.insertName( aElementName, false,
                                                    INetURLObject::LAST_SEGMENT,
                                                    INetURLObject::EncodeMechanism::All );
                    aElementDestInetObj.setExtension( maLibElementFileExtension );
                    OUString aDestElementPath( aElementDestInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ) );

                    try
                    {
                        if( mxSFI->exists( aDestElementPath ) )
                        {
                            mxSFI->kill( aDestElementPath );
                        }
                        mxSFI->move( aElementPath, aDestElementPath );
                    }
                    catch(const Exception& )
                    {
                    }
                }
                pImplLib->storeResourcesAsURL( aDestDirPath, NewName );

                // Delete folder if empty
                Sequence< OUString > aContentSeq = mxSFI->getFolderContents( aLibDirPath, true );
                sal_Int32 nCount = aContentSeq.getLength();
                if( !nCount )
                {
                    mxSFI->kill( aLibDirPath );
                }

                bMovedSuccessful = true;
                pImplLib->implSetModified( true );
            }
        }
        catch(const Exception& )
        {
            // Restore old library
            maNameContainer->insertByName( Name, aLibAny ) ;
        }
    }

    if( bStorage && !pImplLib->mbLink )
    {
        pImplLib->implSetModified( true );
    }
    if( bMovedSuccessful )
    {
           maNameContainer->insertByName( NewName, aLibAny ) ;
    }
}


// Methods XInitialization
void SAL_CALL SfxLibraryContainer::initialize( const Sequence< Any >& _rArguments )
{
    LibraryContainerMethodGuard aGuard( *this );
    sal_Int32 nArgCount = _rArguments.getLength();
    if ( nArgCount == 1 )
    {
        OUString sInitialDocumentURL;
        Reference< XStorageBasedDocument > xDocument;
        if ( _rArguments[0] >>= sInitialDocumentURL )
        {
            init( sInitialDocumentURL, nullptr );
            return;
        }

        if ( _rArguments[0] >>= xDocument )
        {
            initializeFromDocument( xDocument );
            return;
        }
    }

    throw IllegalArgumentException();
}

void SfxLibraryContainer::initializeFromDocument( const Reference< XStorageBasedDocument >& _rxDocument )
{
    // check whether this is a valid OfficeDocument, and obtain the document's root storage
    Reference< XStorage > xDocStorage;
    try
    {
        Reference< XServiceInfo > xSI( _rxDocument, UNO_QUERY_THROW );
        if ( xSI->supportsService("com.sun.star.document.OfficeDocument"))
        {
            xDocStorage.set( _rxDocument->getDocumentStorage(), UNO_SET_THROW );
        }
        Reference< XModel > xDocument( _rxDocument, UNO_QUERY_THROW );
        Reference< XComponent > xDocComponent( _rxDocument, UNO_QUERY_THROW );

        mxOwnerDocument = xDocument;
        startComponentListening( xDocComponent );
    }
    catch( const Exception& ) { }

    if ( !xDocStorage.is() )
    {
        throw IllegalArgumentException();
    }
    init( OUString(), xDocStorage );
}

// OEventListenerAdapter
void SfxLibraryContainer::_disposing( const EventObject& _rSource )
{
#if OSL_DEBUG_LEVEL > 0
    Reference< XModel > xDocument( mxOwnerDocument.get(), UNO_QUERY );
    SAL_WARN_IF(
        xDocument != _rSource.Source || !xDocument.is(), "basic",
        "SfxLibraryContainer::_disposing: where does this come from?");
#else
    (void)_rSource;
#endif
    dispose();
}

// OComponentHelper
void SAL_CALL SfxLibraryContainer::disposing()
{
    Reference< XModel > xModel = mxOwnerDocument;
    EventObject aEvent( xModel.get() );
    maVBAScriptListeners.disposing( aEvent );
    stopAllComponentListening();
    mxOwnerDocument.clear();
}

// Methods XLibraryContainerPassword
sal_Bool SAL_CALL SfxLibraryContainer::isLibraryPasswordProtected( const OUString& )
{
    return false;
}

sal_Bool SAL_CALL SfxLibraryContainer::isLibraryPasswordVerified( const OUString& )
{
    throw IllegalArgumentException();
}

sal_Bool SAL_CALL SfxLibraryContainer::verifyLibraryPassword( const OUString&, const OUString& )
{
    throw IllegalArgumentException();
}

void SAL_CALL SfxLibraryContainer::changeLibraryPassword(const OUString&, const OUString&, const OUString& )
{
    throw IllegalArgumentException();
}

// Methods XContainer
void SAL_CALL SfxLibraryContainer::addContainerListener( const Reference< XContainerListener >& xListener )
{
    LibraryContainerMethodGuard aGuard( *this );
    maNameContainer->setEventSource( static_cast< XInterface* >( static_cast<OWeakObject*>(this) ) );
    maNameContainer->addContainerListener( xListener );
}

void SAL_CALL SfxLibraryContainer::removeContainerListener( const Reference< XContainerListener >& xListener )
{
    LibraryContainerMethodGuard aGuard( *this );
    maNameContainer->removeContainerListener( xListener );
}

// Methods XLibraryContainerExport
void SAL_CALL SfxLibraryContainer::exportLibrary( const OUString& Name, const OUString& URL,
    const Reference< XInteractionHandler >& Handler )
{
    LibraryContainerMethodGuard aGuard( *this );
    SfxLibrary* pImplLib = getImplLib( Name );

    Reference< XSimpleFileAccess3 > xToUseSFI;
    if( Handler.is() )
    {
        xToUseSFI = ucb::SimpleFileAccess::create( mxContext );
        xToUseSFI->setInteractionHandler( Handler );
    }

    // Maybe lib is not loaded?!
    loadLibrary( Name );

    uno::Reference< css::embed::XStorage > xDummyStor;
    if( pImplLib->mbPasswordProtected )
    {
        implStorePasswordLibrary( pImplLib, Name, xDummyStor, URL, xToUseSFI, Handler );
    }
    else
    {
        implStoreLibrary( pImplLib, Name, xDummyStor, URL, xToUseSFI, Handler );
    }
    ::xmlscript::LibDescriptor aLibDesc;
    aLibDesc.aName = Name;
    aLibDesc.bLink = false;             // Link status gets lost?
    aLibDesc.bReadOnly = pImplLib->mbReadOnly;
    aLibDesc.bPreload = false;          // Preload status gets lost?
    aLibDesc.bPasswordProtected = pImplLib->mbPasswordProtected;
    aLibDesc.aElementNames = pImplLib->getElementNames();

    implStoreLibraryIndexFile( pImplLib, aLibDesc, xDummyStor, URL, xToUseSFI );
}

OUString SfxLibraryContainer::expand_url( const OUString& url )
{
    if (url.startsWithIgnoreAsciiCase( "vnd.sun.star.expand:" ))
    {
        return comphelper::getExpandedUri(mxContext, url);
    }
    else if( mxStringSubstitution.is() )
    {
        OUString ret( mxStringSubstitution->substituteVariables( url, false ) );
        return ret;
    }
    else
    {
        return url;
    }
}

//XLibraryContainer3
OUString SAL_CALL SfxLibraryContainer::getOriginalLibraryLinkURL( const OUString& Name )
{
    LibraryContainerMethodGuard aGuard( *this );
    SfxLibrary* pImplLib = getImplLib( Name );
    bool bLink = pImplLib->mbLink;
    if( !bLink )
    {
        throw IllegalArgumentException();
    }
    OUString aRetStr = pImplLib->maOriginalStorageURL;
    return aRetStr;
}


// XVBACompatibility
sal_Bool SAL_CALL SfxLibraryContainer::getVBACompatibilityMode()
{
    return mbVBACompat;
}

void SAL_CALL SfxLibraryContainer::setVBACompatibilityMode( sal_Bool _vbacompatmodeon )
{
    /*  The member variable mbVBACompat must be set first, the following call
        to getBasicManager() may call getVBACompatibilityMode() which returns
        this value. */
    mbVBACompat = _vbacompatmodeon;
    BasicManager* pBasMgr = getBasicManager();
    if( !pBasMgr )
        return;

    // get the standard library
    OUString aLibName = pBasMgr->GetName();
    if ( aLibName.isEmpty())
    {
        aLibName = "Standard";
    }
    if( StarBASIC* pBasic = pBasMgr->GetLib( aLibName ) )
    {
        pBasic->SetVBAEnabled( _vbacompatmodeon );
    }
    /*  If in VBA compatibility mode, force creation of the VBA Globals
        object. Each application will create an instance of its own
        implementation and store it in its Basic manager. Implementations
        will do all necessary additional initialization, such as
        registering the global "This***Doc" UNO constant, starting the
        document events processor etc.
     */
    if( mbVBACompat ) try
    {
        Reference< XModel > xModel( mxOwnerDocument );   // weak-ref -> ref
        Reference< XMultiServiceFactory > xFactory( xModel, UNO_QUERY_THROW );
        xFactory->createInstance("ooo.vba.VBAGlobals");
    }
    catch(const Exception& )
    {
    }
}

void SAL_CALL SfxLibraryContainer::setProjectName( const OUString& _projectname )
{
    msProjectName = _projectname;
    BasicManager* pBasMgr = getBasicManager();
    // Temporary HACK
    // Some parts of the VBA handling ( e.g. in core basic )
    // code expect the name of the VBA project to be set as the name of
    // the basic manager. Provide fail back here.
    if( pBasMgr )
    {
        pBasMgr->SetName( msProjectName );
    }
}

sal_Int32 SAL_CALL SfxLibraryContainer::getRunningVBAScripts()
{
    LibraryContainerMethodGuard aGuard( *this );
    return mnRunningVBAScripts;
}

void SAL_CALL SfxLibraryContainer::addVBAScriptListener( const Reference< vba::XVBAScriptListener >& rxListener )
{
    maVBAScriptListeners.addTypedListener( rxListener );
}

void SAL_CALL SfxLibraryContainer::removeVBAScriptListener( const Reference< vba::XVBAScriptListener >& rxListener )
{
    maVBAScriptListeners.removeTypedListener( rxListener );
}

void SAL_CALL SfxLibraryContainer::broadcastVBAScriptEvent( sal_Int32 nIdentifier, const OUString& rModuleName )
{
    // own lock for accessing the number of running scripts
    enterMethod();
    switch( nIdentifier )
    {
    case vba::VBAScriptEventId::SCRIPT_STARTED:
        ++mnRunningVBAScripts;
        break;
    case vba::VBAScriptEventId::SCRIPT_STOPPED:
        --mnRunningVBAScripts;
        break;
    }
    leaveMethod();

    Reference< XModel > xModel = mxOwnerDocument;  // weak-ref -> ref
    vba::VBAScriptEvent aEvent( Reference<XInterface>(xModel, UNO_QUERY), nIdentifier, rModuleName );
    maVBAScriptListeners.notify( aEvent );
}

// Methods XServiceInfo
sal_Bool SAL_CALL SfxLibraryContainer::supportsService( const OUString& _rServiceName )
{
    return cppu::supportsService(this, _rServiceName);
}

// Implementation class SfxLibrary

// Ctor
SfxLibrary::SfxLibrary( ModifiableHelper& _rModifiable, const Type& aType,
    const Reference< XSimpleFileAccess3 >& xSFI )
        : OComponentHelper( m_aMutex )
        , mxSFI( xSFI )
        , mrModifiable( _rModifiable )
        , maNameContainer( new NameContainer(aType) )
        , mbLoaded( true )
        , mbIsModified( true )
        , mbInitialised( false )
        , mbLink( false )
        , mbReadOnly( false )
        , mbReadOnlyLink( false )
        , mbPreload( false )
        , mbPasswordProtected( false )
        , mbPasswordVerified( false )
        , mbDoc50Password( false )
        , mbSharedIndexFile( false )
        , mbExtension( false )
{
}

SfxLibrary::SfxLibrary( ModifiableHelper& _rModifiable, const Type& aType,
    const Reference< XSimpleFileAccess3 >& xSFI,
    const OUString& aLibInfoFileURL, const OUString& aStorageURL, bool ReadOnly )
        : OComponentHelper( m_aMutex )
        , mxSFI( xSFI )
        , mrModifiable( _rModifiable )
        , maNameContainer( new NameContainer(aType) )
        , mbLoaded( false )
        , mbIsModified( true )
        , mbInitialised( false )
        , maLibInfoFileURL( aLibInfoFileURL )
        , maStorageURL( aStorageURL )
        , mbLink( true )
        , mbReadOnly( false )
        , mbReadOnlyLink( ReadOnly )
        , mbPreload( false )
        , mbPasswordProtected( false )
        , mbPasswordVerified( false )
        , mbDoc50Password( false )
        , mbSharedIndexFile( false )
        , mbExtension( false )
{
}

bool SfxLibrary::isLoadedStorable()
{
    return mbLoaded && (!mbPasswordProtected || mbPasswordVerified);
}

void SfxLibrary::implSetModified( bool _bIsModified )
{
    if ( mbIsModified == _bIsModified )
    {
        return;
    }
    mbIsModified = _bIsModified;
    if ( mbIsModified )
    {
        mrModifiable.setModified( true );
    }
}

// Methods XInterface
Any SAL_CALL SfxLibrary::queryInterface( const Type& rType )
{
    Any aRet =
        ::cppu::queryInterface(
            rType,
            static_cast< XContainer * >( this ),
            static_cast< XNameContainer * >( this ),
            static_cast< XNameAccess * >( this ),
            static_cast< XElementAccess * >( this ),
            static_cast< XChangesNotifier * >( this ) );
    if( !aRet.hasValue() )
    {
        aRet = OComponentHelper::queryInterface( rType );
    }
    return aRet;
}

// Methods XElementAccess
Type SfxLibrary::getElementType()
{
    return maNameContainer->getElementType();
}

sal_Bool SfxLibrary::hasElements()
{
    bool bRet = maNameContainer->hasElements();
    return bRet;
}

// Methods XNameAccess
Any SfxLibrary::getByName( const OUString& aName )
{
    impl_checkLoaded();

    Any aRetAny = maNameContainer->getByName( aName ) ;
    return aRetAny;
}

Sequence< OUString > SfxLibrary::getElementNames()
{
    return maNameContainer->getElementNames();
}

sal_Bool SfxLibrary::hasByName( const OUString& aName )
{
    bool bRet = maNameContainer->hasByName( aName );
    return bRet;
}

void SfxLibrary::impl_checkReadOnly()
{
    if( mbReadOnly || (mbLink && mbReadOnlyLink) )
    {
        throw IllegalArgumentException(
            "Library is readonly.",
            // TODO: resource
            *this, 0
        );
    }
}

void SfxLibrary::impl_checkLoaded()
{
    if ( !mbLoaded )
    {
        throw WrappedTargetException(
            OUString(),
            *this,
            Any( LibraryNotLoadedException(
                OUString(),
                *this
            ) )
        );
    }
}

// Methods XNameReplace
void SfxLibrary::replaceByName( const OUString& aName, const Any& aElement )
{
    impl_checkReadOnly();
    impl_checkLoaded();

    SAL_WARN_IF(
        !isLibraryElementValid(aElement), "basic",
        "SfxLibrary::replaceByName: replacing element is invalid!");

    maNameContainer->replaceByName( aName, aElement );
    implSetModified( true );
}


// Methods XNameContainer
void SfxLibrary::insertByName( const OUString& aName, const Any& aElement )
{
    impl_checkReadOnly();
    impl_checkLoaded();

    SAL_WARN_IF(
        !isLibraryElementValid(aElement), "basic",
        "SfxLibrary::insertByName: to-be-inserted element is invalid!");

    maNameContainer->insertByName( aName, aElement );
    implSetModified( true );
}

void SfxLibrary::impl_removeWithoutChecks( const OUString& _rElementName )
{
    maNameContainer->removeByName( _rElementName );
    implSetModified( true );

    // Remove element file
    if( maStorageURL.isEmpty() )
        return;

    INetURLObject aElementInetObj( maStorageURL );
    aElementInetObj.insertName( _rElementName, false,
                                INetURLObject::LAST_SEGMENT,
                                INetURLObject::EncodeMechanism::All );
    aElementInetObj.setExtension( maLibElementFileExtension );
    OUString aFile = aElementInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );

    try
    {
        if( mxSFI->exists( aFile ) )
        {
            mxSFI->kill( aFile );
        }
    }
    catch(const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("basic");
    }
}

void SfxLibrary::removeByName( const OUString& Name )
{
    impl_checkReadOnly();
    impl_checkLoaded();
    impl_removeWithoutChecks( Name );
}

// XTypeProvider
Sequence< Type > SfxLibrary::getTypes()
{
    static OTypeCollection ourTypes_NameContainer(
                cppu::UnoType<XNameContainer>::get(),
                cppu::UnoType<XContainer>::get(),
                cppu::UnoType<XChangesNotifier>::get(),
                OComponentHelper::getTypes() );

    return ourTypes_NameContainer.getTypes();
}


Sequence< sal_Int8 > SfxLibrary::getImplementationId()
{
    return css::uno::Sequence<sal_Int8>();
}

// Methods XContainer
void SAL_CALL SfxLibrary::addContainerListener( const Reference< XContainerListener >& xListener )
{
    maNameContainer->setEventSource( static_cast< XInterface* >( static_cast<OWeakObject*>(this) ) );
    maNameContainer->addContainerListener( xListener );
}

void SAL_CALL SfxLibrary::removeContainerListener( const Reference< XContainerListener >& xListener )
{
    maNameContainer->removeContainerListener( xListener );
}

// Methods XChangesNotifier
void SAL_CALL SfxLibrary::addChangesListener( const Reference< XChangesListener >& xListener )
{
    maNameContainer->setEventSource( static_cast< XInterface* >( static_cast<OWeakObject*>(this) ) );
    maNameContainer->addChangesListener( xListener );
}

void SAL_CALL SfxLibrary::removeChangesListener( const Reference< XChangesListener >& xListener )
{
    maNameContainer->removeChangesListener( xListener );
}


// Implementation class ScriptExtensionIterator

#define sBasicLibMediaType "application/vnd.sun.star.basic-library"
#define sDialogLibMediaType "application/vnd.sun.star.dialog-library"

ScriptExtensionIterator::ScriptExtensionIterator()
    : m_xContext( comphelper::getProcessComponentContext() )
    , m_eState( USER_EXTENSIONS )
    , m_bUserPackagesLoaded( false )
    , m_bSharedPackagesLoaded( false )
    , m_bBundledPackagesLoaded( false )
    , m_iUserPackage( 0 )
    , m_iSharedPackage( 0 )
       , m_iBundledPackage( 0 )
    , m_pScriptSubPackageIterator( nullptr )
{}

OUString ScriptExtensionIterator::nextBasicOrDialogLibrary( bool& rbPureDialogLib )
{
    OUString aRetLib;

    while( aRetLib.isEmpty() && m_eState != END_REACHED )
    {
        switch( m_eState )
        {
            case USER_EXTENSIONS:
            {
                Reference< deployment::XPackage > xScriptPackage =
                    implGetNextUserScriptPackage( rbPureDialogLib );
                if( !xScriptPackage.is() )
                {
                    break;
                }
                aRetLib = xScriptPackage->getURL();
                break;
            }

            case SHARED_EXTENSIONS:
            {
                Reference< deployment::XPackage > xScriptPackage =
                    implGetNextSharedScriptPackage( rbPureDialogLib );
                if( !xScriptPackage.is() )
                {
                    break;
                }
                aRetLib = xScriptPackage->getURL();
                break;
            }
            case BUNDLED_EXTENSIONS:
            {
                Reference< deployment::XPackage > xScriptPackage =
                    implGetNextBundledScriptPackage( rbPureDialogLib );
                if( !xScriptPackage.is() )
                {
                    break;
                }
                aRetLib = xScriptPackage->getURL();
                break;
            }
            case END_REACHED:
                SAL_WARN(
                    "basic",
                    ("ScriptExtensionIterator::nextBasicOrDialogLibrary():"
                     " Invalid case END_REACHED"));
                break;
        }
    }

    return aRetLib;
}

ScriptSubPackageIterator::ScriptSubPackageIterator( Reference< deployment::XPackage > const & xMainPackage )
    : m_xMainPackage( xMainPackage )
    , m_bIsValid( false )
    , m_bIsBundle( false )
    , m_nSubPkgCount( 0 )
    , m_iNextSubPkg( 0 )
{
    if( !m_xMainPackage.is() )
    {
        return;
    }
    // Check if parent package is registered
    beans::Optional< beans::Ambiguous<sal_Bool> > option( m_xMainPackage->isRegistered
        ( Reference<task::XAbortChannel>(), Reference<ucb::XCommandEnvironment>() ) );
    bool bRegistered = false;
    if( option.IsPresent )
    {
        beans::Ambiguous<sal_Bool> const & reg = option.Value;
        if( !reg.IsAmbiguous && reg.Value )
        {
            bRegistered = true;
        }
    }
    if( bRegistered )
    {
        m_bIsValid = true;
        if( m_xMainPackage->isBundle() )
        {
            m_bIsBundle = true;
            m_aSubPkgSeq = m_xMainPackage->getBundle( Reference<task::XAbortChannel>(),
                                                      Reference<ucb::XCommandEnvironment>() );
            m_nSubPkgCount = m_aSubPkgSeq.getLength();
        }
    }
}

Reference< deployment::XPackage > ScriptSubPackageIterator::getNextScriptSubPackage( bool& rbPureDialogLib )
{
    rbPureDialogLib = false;

    Reference< deployment::XPackage > xScriptPackage;
    if( !m_bIsValid )
    {
        return xScriptPackage;
    }
    if( m_bIsBundle )
    {
        const Reference< deployment::XPackage >* pSeq = m_aSubPkgSeq.getConstArray();
        sal_Int32 iPkg;
        for( iPkg = m_iNextSubPkg ; iPkg < m_nSubPkgCount ; ++iPkg )
        {
            const Reference< deployment::XPackage > xSubPkg = pSeq[ iPkg ];
            xScriptPackage = implDetectScriptPackage( xSubPkg, rbPureDialogLib );
            if( xScriptPackage.is() )
            {
                break;
            }
        }
        m_iNextSubPkg = iPkg + 1;
    }
    else
    {
        xScriptPackage = implDetectScriptPackage( m_xMainPackage, rbPureDialogLib );
        m_bIsValid = false;     // No more script packages
    }

    return xScriptPackage;
}

Reference< deployment::XPackage > ScriptSubPackageIterator::implDetectScriptPackage ( const Reference< deployment::XPackage >& rPackage,
                                                                                      bool& rbPureDialogLib )
{
    Reference< deployment::XPackage > xScriptPackage;

    if( rPackage.is() )
    {
        const Reference< deployment::XPackageTypeInfo > xPackageTypeInfo = rPackage->getPackageType();
        OUString aMediaType = xPackageTypeInfo->getMediaType();
        if ( aMediaType == sBasicLibMediaType )
        {
            xScriptPackage = rPackage;
        }
        else if ( aMediaType == sDialogLibMediaType )
        {
            rbPureDialogLib = true;
            xScriptPackage = rPackage;
        }
    }

    return xScriptPackage;
}

Reference< deployment::XPackage > ScriptExtensionIterator::implGetNextUserScriptPackage( bool& rbPureDialogLib )
{
    Reference< deployment::XPackage > xScriptPackage;

    if( !m_bUserPackagesLoaded )
    {
        try
        {
            Reference< XExtensionManager > xManager = ExtensionManager::get( m_xContext );
            m_aUserPackagesSeq = xManager->getDeployedExtensions("user",
                                                                 Reference< task::XAbortChannel >(),
                                                                 Reference< ucb::XCommandEnvironment >() );
        }
        catch(const css::uno::DeploymentException& )
        {
            // Special Office installations may not contain deployment code
            m_eState = END_REACHED;
            return xScriptPackage;
        }

        m_bUserPackagesLoaded = true;
    }

    if( m_iUserPackage == m_aUserPackagesSeq.getLength() )
    {
        m_eState = SHARED_EXTENSIONS;       // Later: SHARED_MODULE
    }
    else
    {
        if( m_pScriptSubPackageIterator == nullptr )
        {
            const Reference< deployment::XPackage >* pUserPackages = m_aUserPackagesSeq.getConstArray();
            Reference< deployment::XPackage > xPackage = pUserPackages[ m_iUserPackage ];
            SAL_WARN_IF(
                !xPackage.is(), "basic",
                ("ScriptExtensionIterator::implGetNextUserScriptPackage():"
                 " Invalid package"));
            m_pScriptSubPackageIterator = new ScriptSubPackageIterator( xPackage );
        }

        xScriptPackage = m_pScriptSubPackageIterator->getNextScriptSubPackage( rbPureDialogLib );
        if( !xScriptPackage.is() )
        {
            delete m_pScriptSubPackageIterator;
            m_pScriptSubPackageIterator = nullptr;
            m_iUserPackage++;
        }
    }

    return xScriptPackage;
}

Reference< deployment::XPackage > ScriptExtensionIterator::implGetNextSharedScriptPackage( bool& rbPureDialogLib )
{
    Reference< deployment::XPackage > xScriptPackage;

    if( !m_bSharedPackagesLoaded )
    {
        try
        {
            Reference< XExtensionManager > xSharedManager = ExtensionManager::get( m_xContext );
            m_aSharedPackagesSeq = xSharedManager->getDeployedExtensions("shared",
                                                                         Reference< task::XAbortChannel >(),
                                                                         Reference< ucb::XCommandEnvironment >() );
        }
        catch(const css::uno::DeploymentException& )
        {
            // Special Office installations may not contain deployment code
            return xScriptPackage;
        }

        m_bSharedPackagesLoaded = true;
    }

    if( m_iSharedPackage == m_aSharedPackagesSeq.getLength() )
    {
        m_eState = BUNDLED_EXTENSIONS;
    }
    else
    {
        if( m_pScriptSubPackageIterator == nullptr )
        {
            const Reference< deployment::XPackage >* pSharedPackages = m_aSharedPackagesSeq.getConstArray();
            Reference< deployment::XPackage > xPackage = pSharedPackages[ m_iSharedPackage ];
            SAL_WARN_IF(
                !xPackage.is(), "basic",
                ("ScriptExtensionIterator::implGetNextSharedScriptPackage():"
                 " Invalid package"));
            m_pScriptSubPackageIterator = new ScriptSubPackageIterator( xPackage );
        }

        xScriptPackage = m_pScriptSubPackageIterator->getNextScriptSubPackage( rbPureDialogLib );
        if( !xScriptPackage.is() )
        {
            delete m_pScriptSubPackageIterator;
            m_pScriptSubPackageIterator = nullptr;
            m_iSharedPackage++;
        }
    }

    return xScriptPackage;
}

Reference< deployment::XPackage > ScriptExtensionIterator::implGetNextBundledScriptPackage( bool& rbPureDialogLib )
{
    Reference< deployment::XPackage > xScriptPackage;

    if( !m_bBundledPackagesLoaded )
    {
        try
        {
            Reference< XExtensionManager > xManager = ExtensionManager::get( m_xContext );
            m_aBundledPackagesSeq = xManager->getDeployedExtensions("bundled",
                                                                    Reference< task::XAbortChannel >(),
                                                                    Reference< ucb::XCommandEnvironment >() );
        }
        catch(const css::uno::DeploymentException& )
        {
            // Special Office installations may not contain deployment code
            return xScriptPackage;
        }

        m_bBundledPackagesLoaded = true;
    }

    if( m_iBundledPackage == m_aBundledPackagesSeq.getLength() )
    {
        m_eState = END_REACHED;
    }
    else
    {
        if( m_pScriptSubPackageIterator == nullptr )
        {
            const Reference< deployment::XPackage >* pBundledPackages = m_aBundledPackagesSeq.getConstArray();
            Reference< deployment::XPackage > xPackage = pBundledPackages[ m_iBundledPackage ];
            SAL_WARN_IF(
                !xPackage.is(), "basic",
                ("ScriptExtensionIterator::implGetNextBundledScriptPackage():"
                 " Invalid package"));
            m_pScriptSubPackageIterator = new ScriptSubPackageIterator( xPackage );
        }

        xScriptPackage = m_pScriptSubPackageIterator->getNextScriptSubPackage( rbPureDialogLib );
        if( !xScriptPackage.is() )
        {
            delete m_pScriptSubPackageIterator;
            m_pScriptSubPackageIterator = nullptr;
            m_iBundledPackage++;
        }
    }

    return xScriptPackage;
}

}   // namespace basic

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