jt
2021-06-10 5d0d028456874576560552f5a5c4e8b801786f11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using System.IO.Packaging;
using System.Security.Cryptography;
 
namespace Novacode
{
    /// <summary>
    /// Represents a document.
    /// </summary>
    public class DocX : Container, IDisposable
    {
        #region Namespaces
        static internal XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
        static internal XNamespace rel = "http://schemas.openxmlformats.org/package/2006/relationships";
 
        static internal XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
        static internal XNamespace m = "http://schemas.openxmlformats.org/officeDocument/2006/math";
        static internal XNamespace customPropertiesSchema = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties";
        static internal XNamespace customVTypesSchema = "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes";
 
        static internal XNamespace wp = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing";
        static internal XNamespace a = "http://schemas.openxmlformats.org/drawingml/2006/main";
        static internal XNamespace c = "http://schemas.openxmlformats.org/drawingml/2006/chart";
        #endregion
 
        internal float getMarginAttribute(XName name)
        {
            XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
            XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
            if (sectPr != null)
            {
                XElement pgMar = sectPr.Element(XName.Get("pgMar", DocX.w.NamespaceName));
                if (pgMar != null)
                {
                    XAttribute top = pgMar.Attribute(name);
                    if (top != null)
                    {
                        float f;
                        if (float.TryParse(top.Value, out f))
                            return (int)(f / 15.0f);
                    }
                }
            }
 
            return 0;
        }
 
        internal void setMarginAttribute(XName xName, float value)
        {
            XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
            XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
            if (sectPr != null)
            {
                XElement pgMar = sectPr.Element(XName.Get("pgMar", DocX.w.NamespaceName));
                if (pgMar != null)
                {
                    XAttribute top = pgMar.Attribute(xName);
                    if (top != null)
                    {
                        top.SetValue(value * 15);
                    }
                }
            }
        }
 
        public float MarginTop
        {
            get
            {
               return getMarginAttribute(XName.Get("top", DocX.w.NamespaceName));
            }
 
            set
            {
                setMarginAttribute(XName.Get("top", DocX.w.NamespaceName), value);
            }
        }
 
        public float MarginBottom
        {
            get
            {
                return getMarginAttribute(XName.Get("bottom", DocX.w.NamespaceName));
            }
 
            set
            {
                setMarginAttribute(XName.Get("bottom", DocX.w.NamespaceName), value);
            }
        }
 
        public float MarginLeft
        {
            get
            {
                return getMarginAttribute(XName.Get("left", DocX.w.NamespaceName));
            }
 
            set
            {
                setMarginAttribute(XName.Get("left", DocX.w.NamespaceName), value);
            }
        }
 
        public float MarginRight
        {
            get
            {
                return getMarginAttribute(XName.Get("right", DocX.w.NamespaceName));
            }
 
            set
            {
                setMarginAttribute(XName.Get("right", DocX.w.NamespaceName), value);
            }
        }
 
        public float PageWidth
        {
            get
            {
                XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
                XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
                if (sectPr != null)
                {
                    XElement pgSz = sectPr.Element(XName.Get("pgSz", DocX.w.NamespaceName));
 
                    if (pgSz != null)
                    {
                        XAttribute w = pgSz.Attribute(XName.Get("w", DocX.w.NamespaceName));
                        if (w != null)
                        {
                            float f;
                            if (float.TryParse(w.Value, out f))
                                return (int)(f / 15.0f);
                        }
                    }
                }
 
                return (int)(11906.0f / 15.0f);
            }
 
            set
            {
                XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
 
                if (body != null)
                {
                    XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
 
                    if (sectPr != null)
                    {
                        XElement pgSz = sectPr.Element(XName.Get("pgSz", DocX.w.NamespaceName));
 
                        if (pgSz != null)
                        {
                            pgSz.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), value * 15);
                        }
                    }
                }
            }
        }
 
        public float PageHeight
        {
            get
            {
                XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
                XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
                if (sectPr != null)
                {
                    XElement pgSz = sectPr.Element(XName.Get("pgSz", DocX.w.NamespaceName));
 
                    if (pgSz != null)
                    {
                        XAttribute w = pgSz.Attribute(XName.Get("h", DocX.w.NamespaceName));
                        if (w != null)
                        {
                            float f;
                            if (float.TryParse(w.Value, out f))
                                return (int)(f / 15.0f);
                        }
                    }
                }
 
                return (int)(16838.0f / 15.0f);
            }
 
            set
            {
                XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
 
                if (body != null)
                {
                    XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
 
                    if (sectPr != null)
                    {
                        XElement pgSz = sectPr.Element(XName.Get("pgSz", DocX.w.NamespaceName));
 
                        if (pgSz != null)
                        {
                            pgSz.SetAttributeValue(XName.Get("h", DocX.w.NamespaceName), value*15);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Returns true if any editing restrictions are imposed on this document.
        /// </summary>
        /// <example>
        /// <code>
        /// // Create a new document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///     if(document.isProtected)
        ///         Console.WriteLine("Protected");
        ///     else
        ///         Console.WriteLine("Not protected");
        ///         
        ///     // Save the document.
        ///     document.Save();
        /// }
        /// </code>
        /// </example>
        /// <seealso cref="AddProtection"/>
        /// <seealso cref="RemoveProtection"/>
        /// <seealso cref="GetProtectionType"/>
        public bool isProtected
        {
            get
            {
                return settings.Descendants(XName.Get("documentProtection", DocX.w.NamespaceName)).Count() > 0;
            }
        }
 
        /// <summary>
        /// Returns the type of editing protection imposed on this document.
        /// </summary>
        /// <returns>The type of editing protection imposed on this document.</returns>
        /// <example>
        /// <code>
        /// Create a new document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///     // Make sure the document is protected before checking the protection type.
        ///     if (document.isProtected)
        ///     {
        ///         EditRestrictions protection = document.GetProtectionType();
        ///         Console.WriteLine("Document is protected using " + protection.ToString());
        ///     }
        ///
        ///     else
        ///         Console.WriteLine("Document is not protected.");
        ///
        ///     // Save the document.
        ///     document.Save();
        /// }
        /// </code>
        /// </example>
        /// <seealso cref="AddProtection"/>
        /// <seealso cref="RemoveProtection"/>
        /// <seealso cref="isProtected"/>
        public EditRestrictions GetProtectionType()
        {
            if (isProtected)
            {
                XElement documentProtection = settings.Descendants(XName.Get("documentProtection", DocX.w.NamespaceName)).FirstOrDefault();
                string edit_type = documentProtection.Attribute(XName.Get("edit", DocX.w.NamespaceName)).Value;
                return (EditRestrictions)Enum.Parse(typeof(EditRestrictions), edit_type);
            }
 
            return EditRestrictions.none;
        }
 
        /// <summary>
        /// Add editing protection to this document. 
        /// </summary>
        /// <param name="er">The type of protection to add to this document.</param>
        /// <example>
        /// <code>
        /// // Create a new document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///     // Allow no editing, only the adding of comment.
        ///     document.AddProtection(EditRestrictions.comments);
        ///     
        ///     // Save the document.
        ///     document.Save();
        /// }
        /// </code>
        /// </example>
        /// <seealso cref="RemoveProtection"/>
        /// <seealso cref="GetProtectionType"/>
        /// <seealso cref="isProtected"/>
        public void AddProtection(EditRestrictions er)
        {
            // Call remove protection before adding a new protection element.
            RemoveProtection();
 
            if (er == EditRestrictions.none)
                return;
 
            XElement documentProtection = new XElement(XName.Get("documentProtection", DocX.w.NamespaceName));
            documentProtection.Add(new XAttribute(XName.Get("edit", DocX.w.NamespaceName), er.ToString()));
            documentProtection.Add(new XAttribute(XName.Get("enforcement", DocX.w.NamespaceName), "1"));
 
            settings.Root.AddFirst(documentProtection);
        }
 
        /// <summary>
        /// Remove editing protection from this document.
        /// </summary>
        /// <example>
        /// <code>
        /// // Create a new document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///     // Remove any editing restrictions that are imposed on this document.
        ///     document.RemoveProtection();
        ///
        ///     // Save the document.
        ///     document.Save();
        /// }
        /// </code>
        /// </example>
        /// <seealso cref="AddProtection"/>
        /// <seealso cref="GetProtectionType"/>
        /// <seealso cref="isProtected"/>
        public void RemoveProtection()
        {
            // Remove every node of type documentProtection.
            settings.Descendants(XName.Get("documentProtection", DocX.w.NamespaceName)).Remove();
        }
 
        public PageLayout PageLayout
        {
            get
            {
                XElement sectPr = Xml.Element(XName.Get("sectPr", DocX.w.NamespaceName));
                if (sectPr == null)
                {
                    Xml.SetElementValue(XName.Get("sectPr", DocX.w.NamespaceName), string.Empty);
                    sectPr = Xml.Element(XName.Get("sectPr", DocX.w.NamespaceName));
                }
 
                return new PageLayout(this, sectPr);
            }
        }
 
        /// <summary>
        /// Returns a collection of Headers in this Document.
        /// A document typically contains three Headers.
        /// A default one (odd), one for the first page and one for even pages.
        /// </summary>
        /// <example>
        /// <code>
        /// // Create a document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///    // Add header support to this document.
        ///    document.AddHeaders();
        ///
        ///    // Get a collection of all headers in this document.
        ///    Headers headers = document.Headers;
        ///
        ///    // The header used for the first page of this document.
        ///    Header first = headers.first;
        ///
        ///    // The header used for odd pages of this document.
        ///    Header odd = headers.odd;
        ///
        ///    // The header used for even pages of this document.
        ///    Header even = headers.even;
        /// }
        /// </code>
        /// </example>
        public Headers Headers
        {
            get
            {
                return headers;
            }
        }
        private Headers headers;
 
        /// <summary>
        /// Returns a collection of Footers in this Document.
        /// A document typically contains three Footers.
        /// A default one (odd), one for the first page and one for even pages.
        /// </summary>
        /// <example>
        /// <code>
        /// // Create a document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///    // Add footer support to this document.
        ///    document.AddFooters();
        ///
        ///    // Get a collection of all footers in this document.
        ///    Footers footers = document.Footers;
        ///
        ///    // The footer used for the first page of this document.
        ///    Footer first = footers.first;
        ///
        ///    // The footer used for odd pages of this document.
        ///    Footer odd = footers.odd;
        ///
        ///    // The footer used for even pages of this document.
        ///    Footer even = footers.even;
        /// }
        /// </code>
        /// </example>
        public Footers Footers
        {
            get
            {
                return footers;
            }
        }
 
        private Footers footers;
 
        /// <summary>
        /// Should the Document use different Headers and Footers for odd and even pages?
        /// </summary>
        /// // Create a document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///     // Add header support to this document.
        ///     document.AddHeaders();
        ///
        ///     // Get a collection of all headers in this document.
        ///     Headers headers = document.Headers;
        ///
        ///     // The header used for odd pages of this document.
        ///     Header odd = headers.odd;
        ///
        ///     // The header used for even pages of this document.
        ///     Header even = headers.even;
        ///
        ///     // Force the document to use a different header for odd and even pages.
        ///     document.DifferentOddAndEvenPages = true;
        ///
        ///     // Content can be added to the Headers in the same manor that it would be added to the main document.
        ///     Paragraph p1 = odd.InsertParagraph();
        ///     p1.Append("This is the odd pages header.");
        ///     
        ///     Paragraph p2 = even.InsertParagraph();
        ///     p2.Append("This is the even pages header.");
        ///
        ///     // Save all changes to this document.
        ///     document.Save();    
        /// }// Release this document from memory.
        /// </example>
        public bool DifferentOddAndEvenPages
        {
            get
            {
                XDocument settings;
                using (TextReader tr = new StreamReader(settingsPart.GetStream()))
                    settings = XDocument.Load(tr);
 
                XElement evenAndOddHeaders = settings.Root.Element(w + "evenAndOddHeaders");
 
                return evenAndOddHeaders != null;
            }
 
            set
            {
                XDocument settings;
                using (TextReader tr = new StreamReader(settingsPart.GetStream()))
                    settings = XDocument.Load(tr);
 
                XElement evenAndOddHeaders = settings.Root.Element(w + "evenAndOddHeaders");
                if (evenAndOddHeaders == null)
                {
                    if (value)
                        settings.Root.AddFirst(new XElement(w + "evenAndOddHeaders"));
                }
 
                else
                {
                    if (!value)
                        evenAndOddHeaders.Remove();
                }
 
                using (TextWriter tw = new StreamWriter(settingsPart.GetStream()))
                    settings.Save(tw);
            }
        }
 
        /// <summary>
        /// Should the Document use an independent Header and Footer for the first page?
        /// </summary>
        /// <example>
        /// // Create a document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///     // Add header support to this document.
        ///     document.AddHeaders();
        ///
        ///     // The header used for the first page of this document.
        ///     Header first = document.Headers.first;
        ///
        ///     // Force the document to use a different header for first page.
        ///     document.DifferentFirstPage = true;
        ///     
        ///     // Content can be added to the Headers in the same manor that it would be added to the main document.
        ///     Paragraph p = first.InsertParagraph();
        ///     p.Append("This is the first pages header.");
        ///
        ///     // Save all changes to this document.
        ///     document.Save();    
        /// }// Release this document from memory.
        /// </example>
        public bool DifferentFirstPage
        {
            get
            {
                XElement body = mainDoc.Root.Element(w + "body");
                XElement sectPr = body.Element(w + "sectPr");
 
                if (sectPr != null)
                {
                    XElement titlePg = sectPr.Element(w + "titlePg");
                    if (titlePg != null)
                        return true;
                }
 
                return false;
            }
 
            set
            {
                XElement body = mainDoc.Root.Element(w + "body");
                XElement sectPr = null;
                XElement titlePg = null;
 
                if (sectPr == null)
                    body.Add(new XElement(w + "sectPr", string.Empty));
 
                sectPr = body.Element(w + "sectPr");
 
                titlePg = sectPr.Element(w + "titlePg");
                if (titlePg == null)
                {
                    if (value)
                        sectPr.Add(new XElement(w + "titlePg", string.Empty));
                }
 
                else
                {
                    if (!value)
                        titlePg.Remove();
                }
            }
        }
 
        private Header GetHeaderByType(string type)
        {
            return (Header)GetHeaderOrFooterByType(type, true);
        }
 
        private Footer GetFooterByType(string type)
        {
            return (Footer)GetHeaderOrFooterByType(type, false);
        }
 
        private object GetHeaderOrFooterByType(string type, bool isHeader)
        {
            // Switch which handles either case Header\Footer, this just cuts down on code duplication.
            string reference = "footerReference";
            if (isHeader)
                reference = "headerReference";
 
            // Get the Id of the [default, even or first] [Header or Footer]
            string Id =
            (
                from e in mainDoc.Descendants(XName.Get("body", DocX.w.NamespaceName)).Descendants()
                where (e.Name.LocalName == reference) && (e.Attribute(w + "type").Value == type)
                select e.Attribute(r + "id").Value
            ).LastOrDefault();
 
            if (Id != null)
            {
                // Get the Xml file for this Header or Footer.
                Uri partUri = mainPart.GetRelationship(Id).TargetUri;
 
                // Weird problem with PackaePart API.
                if (!partUri.OriginalString.StartsWith("/word/"))
                    partUri = new Uri("/word/" + partUri.OriginalString, UriKind.Relative);
 
                // Get the Part and open a stream to get the Xml file.
                PackagePart part = package.GetPart(partUri);
 
                XDocument doc;
                using (TextReader tr = new StreamReader(part.GetStream()))
                {
                    doc = XDocument.Load(tr);
 
                    // Header and Footer extend Container.
                    Container c;
                    if (isHeader)
                        c = new Header(this, doc.Element(w + "hdr"), part);
                    else
                        c = new Footer(this, doc.Element(w + "ftr"), part);
 
                    return c;
                }
            }
 
            // If we got this far something went wrong.
            return null;
        }
 
        // Get the word\document.xml part
        internal PackagePart mainPart;
 
        // Get the word\settings.xml part
        internal PackagePart settingsPart;
        internal PackagePart endnotesPart;
        internal PackagePart footnotesPart;
        internal PackagePart stylesPart;
        internal PackagePart stylesWithEffectsPart;
        internal PackagePart numberingPart;
        internal PackagePart fontTablePart;
 
        #region Internal variables defined foreach DocX object
        // Object representation of the .docx
        internal Package package;
 
        // The mainDocument is loaded into a XDocument object for easy querying and editing
        internal XDocument mainDoc;
        internal XDocument settings;
        internal XDocument endnotes;
        internal XDocument footnotes;
        internal XDocument styles;
        internal XDocument stylesWithEffects;
        internal XDocument numbering;
        internal XDocument fontTable;
        internal XDocument header1;
        internal XDocument header2;
        internal XDocument header3;
 
        // A lookup for the Paragraphs in this document.
        internal Dictionary<int, Paragraph> paragraphLookup = new Dictionary<int, Paragraph>();
        // Every document is stored in a MemoryStream, all edits made to a document are done in memory.
        internal MemoryStream memoryStream;
        // The filename that this document was loaded from
        internal string filename;
        // The stream that this document was loaded from
        internal Stream stream;
        #endregion
 
        internal DocX(DocX document, XElement xml)
            : base(document, xml)
        {
 
        }
 
        /// <summary>
        /// Returns a list of Images in this document.
        /// </summary>
        /// <example>
        /// Get the unique Id of every Image in this document.
        /// <code>
        /// // Load a document.
        /// DocX document = DocX.Load(@"C:\Example\Test.docx");
        ///
        /// // Loop through each Image in this document.
        /// foreach (Novacode.Image i in document.Images)
        /// {
        ///     // Get the unique Id which identifies this Image.
        ///     string uniqueId = i.Id;
        /// }
        ///
        /// </code>
        /// </example>
        /// <seealso cref="AddImage(string)"/>
        /// <seealso cref="AddImage(Stream)"/>
        /// <seealso cref="Paragraph.Pictures"/>
        /// <seealso cref="Paragraph.InsertPicture"/>
        public List<Image> Images
        {
            get
            {
                PackageRelationshipCollection imageRelationships = mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
                if (imageRelationships.Count() > 0)
                {
                    return
                    (
                        from i in imageRelationships
                        select new Image(this, i)
                    ).ToList();
                }
 
                return new List<Image>();
            }
        }
 
        /// <summary>
        /// Returns a list of custom properties in this document.
        /// </summary>
        /// <example>
        /// Method 1: Get the name, type and value of each CustomProperty in this document.
        /// <code>
        /// // Load Example.docx
        /// DocX document = DocX.Load(@"C:\Example\Test.docx");
        ///
        /// /*
        ///  * No two custom properties can have the same name,
        ///  * so a Dictionary is the perfect data structure to store them in.
        ///  * Each custom property can be accessed using its name.
        ///  */
        /// foreach (string name in document.CustomProperties.Keys)
        /// {
        ///     // Grab a custom property using its name.
        ///     CustomProperty cp = document.CustomProperties[name];
        ///
        ///     // Write this custom properties details to Console.
        ///     Console.WriteLine(string.Format("Name: '{0}', Value: {1}", cp.Name, cp.Value));
        /// }
        ///
        /// Console.WriteLine("Press any key...");
        ///
        /// // Wait for the user to press a key before closing the Console.
        /// Console.ReadKey();
        /// </code>
        /// </example>
        /// <example>
        /// Method 2: Get the name, type and value of each CustomProperty in this document.
        /// <code>
        /// // Load Example.docx
        /// DocX document = DocX.Load(@"C:\Example\Test.docx");
        /// 
        /// /*
        ///  * No two custom properties can have the same name,
        ///  * so a Dictionary is the perfect data structure to store them in.
        ///  * The values of this Dictionary are CustomProperties.
        ///  */
        /// foreach (CustomProperty cp in document.CustomProperties.Values)
        /// {
        ///     // Write this custom properties details to Console.
        ///     Console.WriteLine(string.Format("Name: '{0}', Value: {1}", cp.Name, cp.Value));
        /// }
        ///
        /// Console.WriteLine("Press any key...");
        ///
        /// // Wait for the user to press a key before closing the Console.
        /// Console.ReadKey();
        /// </code>
        /// </example>
        /// <seealso cref="AddCustomProperty"/>
        public Dictionary<string, CustomProperty> CustomProperties
        {
            get
            {
                if (package.PartExists(new Uri("/docProps/custom.xml", UriKind.Relative)))
                {
                    PackagePart docProps_custom = package.GetPart(new Uri("/docProps/custom.xml", UriKind.Relative));
                    XDocument customPropDoc;
                    using (TextReader tr = new StreamReader(docProps_custom.GetStream(FileMode.Open, FileAccess.Read)))
                        customPropDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
 
                    // Get all of the custom properties in this document
                    return
                    (
                        from p in customPropDoc.Descendants(XName.Get("property", customPropertiesSchema.NamespaceName))
                        let Name = p.Attribute(XName.Get("name")).Value
                        let Type = p.Descendants().Single().Name.LocalName
                        let Value = p.Descendants().Single().Value
                        select new CustomProperty(Name, Type, Value)
                    ).ToDictionary(p => p.Name, StringComparer.CurrentCultureIgnoreCase);
                }
 
                return new Dictionary<string, CustomProperty>();
            }
        }
 
        ///<summary>
        /// Returns the list of document core properties with corresponding values.
        ///</summary>
        public Dictionary<string, string> CoreProperties
        {
            get
            {
                if (package.PartExists(new Uri("/docProps/core.xml", UriKind.Relative)))
                {
                    PackagePart docProps_Core = package.GetPart(new Uri("/docProps/core.xml", UriKind.Relative));
                    XDocument corePropDoc;
                    using (TextReader tr = new StreamReader(docProps_Core.GetStream(FileMode.Open, FileAccess.Read)))
                        corePropDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
 
                    // Get all of the core properties in this document
                    return (from docProperty in corePropDoc.Root.Elements()
                            select
                              new KeyValuePair<string, string>(
                              string.Format(
                                "{0}:{1}",
                                corePropDoc.Root.GetPrefixOfNamespace(docProperty.Name.Namespace),
                                docProperty.Name.LocalName),
                              docProperty.Value)).ToDictionary(p => p.Key, v => v.Value);
                }
 
                return new Dictionary<string, string>();
            }
        }
 
        /// <summary>
        /// Get the Text of this document.
        /// </summary>
        /// <example>
        /// Write to Console the Text from this document.
        /// <code>
        /// // Load a document
        /// DocX document = DocX.Load(@"C:\Example\Test.docx");
        ///
        /// // Get the text of this document.
        /// string text = document.Text;
        ///
        /// // Write the text of this document to Console.
        /// Console.Write(text);
        ///
        /// // Wait for the user to press a key before closing the console window.
        /// Console.ReadKey();
        /// </code>
        /// </example>
        public string Text
        {
            get
            {
                return HelperFunctions.GetText(Xml);
            }
        }
 
        internal string GetCollectiveText(List<PackagePart> list)
        {
            string text = string.Empty;
 
            foreach (var hp in list)
            {
                using (TextReader tr = new StreamReader(hp.GetStream()))
                {
                    XDocument d = XDocument.Load(tr);
 
                    StringBuilder sb = new StringBuilder();
 
                    // Loop through each text item in this run
                    foreach (XElement descendant in d.Descendants())
                    {
                        switch (descendant.Name.LocalName)
                        {
                            case "tab":
                                sb.Append("\t");
                                break;
                            case "br":
                                sb.Append("\n");
                                break;
                            case "t":
                                goto case "delText";
                            case "delText":
                                sb.Append(descendant.Value);
                                break;
                            default: break;
                        }
                    }
 
                    text += "\n" + sb.ToString();
                }
            }
 
            return text;
        }
 
        /// <summary>
        /// Insert the contents of another document at the end of this document. 
        /// </summary>
        /// <param name="document">The document to insert at the end of this document.</param>
        /// <example>
        /// Create a new document and insert an old document into it.
        /// <code>
        /// // Create a new document.
        /// using (DocX newDocument = DocX.Create(@"NewDocument.docx"))
        /// {
        ///     // Load an old document.
        ///     using (DocX oldDocument = DocX.Load(@"OldDocument.docx"))
        ///     {
        ///         // Insert the old document into the new document.
        ///         newDocument.InsertDocument(oldDocument);
        ///
        ///         // Save the new document.
        ///         newDocument.Save();
        ///     }// Release the old document from memory.
        /// }// Release the new document from memory.
        /// </code>
        /// <remarks>
        /// If the document being inserted contains Images, CustomProperties and or custom styles, these will be correctly inserted into the new document. In the case of Images, new ID's are generated for the Images being inserted to avoid ID conflicts. CustomProperties with the same name will be ignored not replaced.
        /// </remarks>
        /// </example>
        public void InsertDocument(DocX remote_document)
        {
            // We don't want to effect the origional XDocument, so create a new one from the old one.
            XDocument remote_mainDoc = new XDocument(remote_document.mainDoc);
 
            XDocument remote_footnotes = null ;
            if(remote_document.footnotes != null)
                remote_footnotes = new XDocument(remote_document.footnotes);
 
            XDocument remote_endnotes = null;
            if (remote_document.endnotes != null)
                remote_endnotes = new XDocument(remote_document.endnotes);
 
            // Remove all header and footer references.
            remote_mainDoc.Descendants(XName.Get("headerReference", DocX.w.NamespaceName)).Remove();
            remote_mainDoc.Descendants(XName.Get("footerReference", DocX.w.NamespaceName)).Remove();
 
            // Get the body of the remote document.
            XElement remote_body = remote_mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
 
            // Every file that is missing from the local document will have to be copied, every file that already exists will have to be merged.
            PackagePartCollection ppc = remote_document.package.GetParts();
 
            List<String> ignoreContentTypes = new List<string>
            {
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
                "application/vnd.openxmlformats-package.core-properties+xml",
                "application/vnd.openxmlformats-officedocument.extended-properties+xml",
                "application/vnd.openxmlformats-package.relationships+xml",
            };
            
            List<String> imageContentTypes = new List<string>
            {
                "image/jpeg",
                "image/png",
                "image/bmp",
                "image/gif",
                "image/tiff",
                "image/icon",
                "image/pcx",
                "image/emf",
                "image/wmf"
            };
            // Check if each PackagePart pp exists in this document.
            foreach (PackagePart remote_pp in ppc)
            {
                if (ignoreContentTypes.Contains(remote_pp.ContentType) || imageContentTypes.Contains(remote_pp.ContentType))
                    continue;
 
                // If this external PackagePart already exits then we must merge them.
                if (package.PartExists(remote_pp.Uri))
                {
                    PackagePart local_pp = package.GetPart(remote_pp.Uri);
                    switch (remote_pp.ContentType)
                    {
                        case "application/vnd.openxmlformats-officedocument.custom-properties+xml":
                            merge_customs(remote_pp, local_pp, remote_mainDoc);
                            break;
 
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":
                            merge_styles(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes, remote_endnotes);
                            break;
 
                        case "application/vnd.ms-word.stylesWithEffects+xml":
                            merge_styles(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes, remote_endnotes);
                            break;
 
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml":
                            merge_fonts(remote_pp, local_pp, remote_mainDoc, remote_document);
                            break;
 
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":
                            merge_numbering(remote_pp, local_pp, remote_mainDoc, remote_document);
                            break;
 
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":
                            merge_footnotes(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes);
                            break;
 
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":
                            merge_endnotes(remote_pp, local_pp, remote_mainDoc, remote_document, remote_endnotes);
                            break;
 
                        default:
                            break;
                    }
                }
 
                // If this external PackagePart does not exits in the internal document then we can simply copy it.
                else
                {
                    var packagePart = clonePackagePart(remote_pp);
                    switch (remote_pp.ContentType)
                    {
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":
                            endnotesPart = packagePart;
                            endnotes = remote_endnotes;
                            break;
 
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":
                            footnotesPart = packagePart;
                            footnotes = remote_footnotes;
                            break;
                        
                        case "application/vnd.openxmlformats-officedocument.custom-properties+xml":
                            break;
 
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":
                            stylesPart = packagePart;
                            using (TextReader tr = new StreamReader(stylesPart.GetStream()))
                                styles = XDocument.Load(tr);
                            break;
 
                        case "application/vnd.ms-word.stylesWithEffects+xml":
                            stylesWithEffectsPart = packagePart;
                            using (TextReader tr = new StreamReader(stylesWithEffectsPart.GetStream()))
                                stylesWithEffects = XDocument.Load(tr);
                            break;
 
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml":
                            fontTablePart = packagePart;
                            using (TextReader tr = new StreamReader(fontTablePart.GetStream()))
                                fontTable = XDocument.Load(tr);
                            break;
 
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":
                            numberingPart = packagePart;
                            using (TextReader tr = new StreamReader(numberingPart.GetStream()))
                                numbering = XDocument.Load(tr);
                            break;
 
                    }
 
                    clonePackageRelationship(remote_document, remote_pp, remote_mainDoc);
                }
            }
 
            foreach (var hyperlink_rel in remote_document.mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"))
            {
                var old_rel_Id = hyperlink_rel.Id;
                var new_rel_Id = mainPart.CreateRelationship(hyperlink_rel.TargetUri, hyperlink_rel.TargetMode, hyperlink_rel.RelationshipType).Id;
                var hyperlink_refs = remote_mainDoc.Descendants(XName.Get("hyperlink", DocX.w.NamespaceName));
                foreach (var hyperlink_ref in hyperlink_refs)
                {
                    XAttribute a0 = hyperlink_ref.Attribute(XName.Get("id", DocX.r.NamespaceName));
                    if (a0 != null && a0.Value == old_rel_Id)
                    {
                        a0.SetValue(new_rel_Id);
                    }
                }
            }
 
 
            foreach (PackagePart remote_pp in ppc)
            {
                if (imageContentTypes.Contains(remote_pp.ContentType))
                {
                    merge_images(remote_pp, remote_document, remote_mainDoc, remote_pp.ContentType);
                }
            }
 
            int id = 0;
            var local_docPrs = mainDoc.Root.Descendants(XName.Get("docPr", DocX.wp.NamespaceName));
            foreach (var local_docPr in local_docPrs)
            {
                XAttribute a_id = local_docPr.Attribute(XName.Get("id"));
                int a_id_value;
                if (a_id != null && int.TryParse(a_id.Value, out a_id_value))
                    if (a_id_value > id)
                        id = a_id_value;
            }
            id++;
 
            // docPr must be sequential
            var docPrs = remote_body.Descendants(XName.Get("docPr", DocX.wp.NamespaceName));
            foreach (var docPr in docPrs)
            {
                docPr.SetAttributeValue(XName.Get("id"), id);
                id++;
            }
 
            // Add the remote documents contents to this document.
            XElement local_body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
            local_body.Add(remote_body.Elements());
 
            // Copy any missing root attributes to the local document.
            foreach (XAttribute a in remote_mainDoc.Root.Attributes())
            {
                if (mainDoc.Root.Attribute(a.Name) == null)
                {
                    mainDoc.Root.SetAttributeValue(a.Name, a.Value);
                }
            }
 
        }
 
        private void merge_images(PackagePart remote_pp, DocX remote_document, XDocument remote_mainDoc, String contentType)
        {
            // Before doing any other work, check to see if this image is actually referenced in the document.
            // In my testing I have found cases of Images inside documents that are not refer
            var remote_rel = remote_document.mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(remote_pp.Uri.OriginalString.Replace("/word/", ""))).FirstOrDefault();
            if (remote_rel == null)
                return;
 
            String remote_Id = remote_rel.Id;
 
            String remote_hash = ComputeMD5HashString(remote_pp.GetStream());
            var image_parts = package.GetParts().Where(pp => pp.ContentType.Equals(contentType));
 
            bool found = false; 
            foreach (var part in image_parts)
            {
                String local_hash = ComputeMD5HashString(part.GetStream());
                if (local_hash.Equals(remote_hash))
                {
                    // This image already exists in this document.
                    found = true;
 
                    var local_rel = mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(part.Uri.OriginalString.Replace("/word/", ""))).FirstOrDefault();
                    if (local_rel != null)
                    {
                        String new_Id = local_rel.Id;
 
                        // Replace all instances of remote_Id in the local document with local_Id
                        var elems = remote_mainDoc.Descendants(XName.Get("blip", DocX.a.NamespaceName));
                        foreach (var elem in elems)
                        {
                            XAttribute embed = elem.Attribute(XName.Get("embed", DocX.r.NamespaceName));
                            if (embed != null && embed.Value == remote_Id)
                            {
                                embed.SetValue(new_Id);
                            }
                        }
                    }
 
                    break;
                }
            }
 
            // This image does not exist in this document.
            if (!found)
            {
                String new_uri = remote_pp.Uri.OriginalString;
                new_uri = new_uri.Remove(new_uri.LastIndexOf("/"));
                new_uri = new_uri.Replace("word/", "");
                new_uri += "/" + Guid.NewGuid().ToString() + contentType.Replace("image/", ".");
                if (!new_uri.StartsWith("/"))
                    new_uri = "/" + new_uri;
 
                PackagePart new_pp = package.CreatePart(new Uri(new_uri, UriKind.Relative), remote_pp.ContentType);
 
                using (Stream s_read = remote_pp.GetStream())
                {
                    using (Stream s_write = new_pp.GetStream(FileMode.Create))
                    {
                        byte[] buffer = new byte[32768];
                        int read;
                        while ((read = s_read.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            s_write.Write(buffer, 0, read);
                        }
                    }
                }
 
                PackageRelationship pr = mainPart.CreateRelationship(new Uri(new_uri, UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
 
                String new_Id = pr.Id;
 
                // Replace all instances of remote_Id in the local document with local_Id
                var elems = remote_mainDoc.Descendants(XName.Get("blip", DocX.a.NamespaceName));
                foreach (var elem in elems)
                {
                    XAttribute embed = elem.Attribute(XName.Get("embed", DocX.r.NamespaceName));
                    if (embed != null && embed.Value == remote_Id)
                    {
                        embed.SetValue(new_Id);
                    }
                }
            }
        }
 
        private string ComputeMD5HashString(Stream stream)
        {
            MD5 md5 = MD5.Create();
            byte[] hash = md5.ComputeHash(stream);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
                sb.Append(hash[i].ToString("X2"));
            return sb.ToString();
        }
 
        private void merge_endnotes(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote, XDocument remote_endnotes)
        {
            IEnumerable<int> ids =
            (
                from d in endnotes.Root.Descendants()
                where d.Name.LocalName == "endnote"
                select int.Parse(d.Attribute(XName.Get("id", DocX.w.NamespaceName)).Value)
            );
 
            int max_id = ids.Max() + 1;
            var endnoteReferences = remote_mainDoc.Descendants(XName.Get("endnoteReference", DocX.w.NamespaceName));
 
            foreach (var endnote in remote_endnotes.Root.Elements().OrderBy(fr => fr.Attribute(XName.Get("id", DocX.r.NamespaceName))).Reverse())
            {
                XAttribute id = endnote.Attribute(XName.Get("id", DocX.w.NamespaceName));
                int i;
                if (id != null && int.TryParse(id.Value, out i))
                {
                    if (i > 0)
                    {
                        foreach (var endnoteRef in endnoteReferences)
                        {
                            XAttribute a = endnoteRef.Attribute(XName.Get("id", DocX.w.NamespaceName));
                            if (a != null && int.Parse(a.Value).Equals(i))
                            {
                                a.SetValue(max_id);
                            }
                        }
 
                        // We care about copying this footnote.
                        endnote.SetAttributeValue(XName.Get("id", DocX.w.NamespaceName), max_id);
                        endnotes.Root.Add(endnote);
                        max_id++;
                    }
                }
            }
        }
 
        private void merge_footnotes(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote, XDocument remote_footnotes)
        {
            IEnumerable<int> ids =
            (
                from d in footnotes.Root.Descendants()
                where d.Name.LocalName == "footnote"
                select int.Parse(d.Attribute(XName.Get("id", DocX.w.NamespaceName)).Value)
            );
 
            int max_id = ids.Max() + 1;
            var footnoteReferences = remote_mainDoc.Descendants(XName.Get("footnoteReference", DocX.w.NamespaceName));
 
            foreach (var footnote in remote_footnotes.Root.Elements().OrderBy(fr => fr.Attribute(XName.Get("id", DocX.r.NamespaceName))).Reverse())
            {
                XAttribute id = footnote.Attribute(XName.Get("id", DocX.w.NamespaceName));
                int i;
                if (id != null && int.TryParse(id.Value, out i))
                {
                    if (i > 0)
                    {
                        foreach (var footnoteRef in footnoteReferences)
                        {
                            XAttribute a = footnoteRef.Attribute(XName.Get("id", DocX.w.NamespaceName));
                            if (a != null && int.Parse(a.Value).Equals(i))
                            {
                                a.SetValue(max_id);
                            }
                        }
 
                        // We care about copying this footnote.
                        footnote.SetAttributeValue(XName.Get("id", DocX.w.NamespaceName), max_id);
                        footnotes.Root.Add(footnote);
                        max_id++;
                    }
                }
            }
        }
 
        private void merge_customs(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc)
        {
            // Get the remote documents custom.xml file.
            XDocument remote_custom_document;
            using (TextReader tr = new StreamReader(remote_pp.GetStream()))
                remote_custom_document = XDocument.Load(tr);
 
            // Get the local documents custom.xml file.
            XDocument local_custom_document;
            using (TextReader tr = new StreamReader(local_pp.GetStream()))
                local_custom_document = XDocument.Load(tr);
 
            IEnumerable<int> pids =
            (
                from d in remote_custom_document.Root.Descendants()
                where d.Name.LocalName == "property"
                select int.Parse(d.Attribute(XName.Get("pid")).Value)
            );
 
            int pid = pids.Max() + 1;
 
            foreach (XElement remote_property in remote_custom_document.Root.Elements())
            {
                bool found = false;
                foreach (XElement local_property in local_custom_document.Root.Elements())
                {
                    XAttribute remote_property_name = remote_property.Attribute(XName.Get("name"));
                    XAttribute local_property_name = local_property.Attribute(XName.Get("name"));
 
                    if(remote_property != null && local_property_name != null && remote_property_name.Value.Equals(local_property_name.Value))
                        found = true;
                }
 
                if (!found)
                {
                    remote_property.SetAttributeValue(XName.Get("pid"), pid);
                    local_custom_document.Root.Add(remote_property);
 
                    pid++;
                }
            }
 
            // Save the modified local custom styles.xml file.
            using (TextWriter tw = new StreamWriter(local_pp.GetStream(FileMode.Create, FileAccess.Write)))
                local_custom_document.Save(tw, SaveOptions.None);
        }
 
        private void merge_numbering(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote)
        {
            // Add each remote numbering to this document.
            IEnumerable<XElement> remote_abstractNums = remote.numbering.Root.Elements(XName.Get("abstractNum", DocX.w.NamespaceName));
            int guidd = 0;
            foreach (var an in remote_abstractNums)
            {
                XAttribute a = an.Attribute(XName.Get("abstractNumId", DocX.w.NamespaceName));
                if(a != null)
                {
                    int i;
                    if (int.TryParse(a.Value, out i))
                    {
                        if (i > guidd)
                            guidd = i;
                    }
                }
            }
            guidd++;
 
            IEnumerable<XElement> remote_nums = remote.numbering.Root.Elements(XName.Get("num", DocX.w.NamespaceName));
            int guidd2 = 0;
            foreach (var an in remote_nums)
            {
                XAttribute a = an.Attribute(XName.Get("numId", DocX.w.NamespaceName));
                if (a != null)
                {
                    int i;
                    if (int.TryParse(a.Value, out i))
                    {
                        if (i > guidd2)
                            guidd2 = i;
                    }
                }
            }
            guidd2++;
 
            foreach (XElement remote_abstractNum in remote_abstractNums)
            {
                XAttribute abstractNumId = remote_abstractNum.Attribute(XName.Get("abstractNumId", DocX.w.NamespaceName));
                if (abstractNumId != null)
                {
                    String abstractNumIdValue = abstractNumId.Value;
                    abstractNumId.SetValue(guidd);
 
                    foreach (XElement remote_num in remote_nums)
                    {
                        var numIds = remote_mainDoc.Descendants(XName.Get("numId", DocX.w.NamespaceName));
                        foreach (var numId in numIds)
                        {
                            XAttribute attr = numId.Attribute(XName.Get("val", DocX.w.NamespaceName));
                            if (attr != null && attr.Value.Equals(remote_num.Attribute(XName.Get("numId", DocX.w.NamespaceName)).Value))
                            {
                                attr.SetValue(guidd2);
                            }
 
                        }
                        remote_num.SetAttributeValue(XName.Get("numId", DocX.w.NamespaceName), guidd2);
 
                        XElement e = remote_num.Element(XName.Get("abstractNumId", DocX.w.NamespaceName));
                        if (e != null)
                        {
                            XAttribute a2 = e.Attribute(XName.Get("val", DocX.w.NamespaceName));
                            if (a2 != null && a2.Value.Equals(abstractNumIdValue))
                                a2.SetValue(guidd);
                        }
 
                        guidd2++;
                    }
                }
 
                guidd++;
            }
 
            numbering.Root.Elements(XName.Get("abstractNum", DocX.w.NamespaceName)).Last().AddAfterSelf(remote_abstractNums);
            numbering.Root.Elements(XName.Get("num", DocX.w.NamespaceName)).Last().AddAfterSelf(remote_nums);
        }
 
        private void merge_fonts(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote)
        {
            // Add each remote font to this document.
            IEnumerable<XElement> remote_fonts = remote.fontTable.Root.Elements(XName.Get("font", DocX.w.NamespaceName));
            IEnumerable<XElement> local_fonts = fontTable.Root.Elements(XName.Get("font", DocX.w.NamespaceName));
 
            foreach (XElement remote_font in remote_fonts)
            {
                bool flag_addFont = true;
                foreach (XElement local_font in local_fonts)
                {
                    if (local_font.Attribute(XName.Get("name", DocX.w.NamespaceName)).Value == remote_font.Attribute(XName.Get("name", DocX.w.NamespaceName)).Value)
                    {
                        flag_addFont = false;
                        break;
                    }
                }
                
                if (flag_addFont)
                {
                    fontTable.Root.Add(remote_font);
                }
            }
        }
 
        private void merge_styles(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote, XDocument remote_footnotes, XDocument remote_endnotes)
        {
            Dictionary<String, String> local_styles = new Dictionary<string, string>();
            foreach (XElement local_style in styles.Root.Elements(XName.Get("style", DocX.w.NamespaceName)))
            {
                XElement temp = new XElement(local_style);
                XAttribute styleId = temp.Attribute(XName.Get("styleId", DocX.w.NamespaceName));
                String value = styleId.Value;
                styleId.Remove();
                String key = Regex.Replace(temp.ToString(), @"\s+", "");
                if (!local_styles.ContainsKey(key)) local_styles.Add(key, value); 
            }
 
            // Add each remote style to this document.
            IEnumerable<XElement> remote_styles = remote.styles.Root.Elements(XName.Get("style", DocX.w.NamespaceName));
            foreach (XElement remote_style in remote_styles)
            {
                XElement temp = new XElement(remote_style);
                XAttribute styleId = temp.Attribute(XName.Get("styleId", DocX.w.NamespaceName));
                String value = styleId.Value;
                styleId.Remove();
                String key = Regex.Replace(temp.ToString(), @"\s+", "");
                String guuid;
 
                // Check to see if the local document already contains the remote style.
                if (local_styles.ContainsKey(key))
                {
                    String local_value;
                    local_styles.TryGetValue(key, out local_value);
 
                    // If the styleIds are the same then nothing needs to be done.
                    if (local_value == value)
                        continue;
 
                    // All we need to do is update the styleId.
                    else
                    {
                        guuid = local_value;
                    }
                }
 
                else
                    guuid = Guid.NewGuid().ToString();
 
                foreach(XElement e in remote_mainDoc.Root.Descendants(XName.Get("pStyle", DocX.w.NamespaceName)))
                {
                    XAttribute e_styleId = e.Attribute(XName.Get("val", DocX.w.NamespaceName));
                    if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
                    {
                        e_styleId.SetValue(guuid);
                    }
                }
 
                foreach (XElement e in remote_mainDoc.Root.Descendants(XName.Get("rStyle", DocX.w.NamespaceName)))
                {
                    XAttribute e_styleId = e.Attribute(XName.Get("val", DocX.w.NamespaceName));
                    if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
                    {
                        e_styleId.SetValue(guuid);
                    }
                }
 
                foreach(XElement e in remote_mainDoc.Root.Descendants(XName.Get("tblStyle", DocX.w.NamespaceName)))
                {
                    XAttribute e_styleId = e.Attribute(XName.Get("val", DocX.w.NamespaceName));
                    if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
                    {
                        e_styleId.SetValue(guuid);
                    }
                }
 
                if (remote_endnotes != null)
                {
                    foreach (XElement e in remote_endnotes.Root.Descendants(XName.Get("rStyle", DocX.w.NamespaceName)))
                    {
                        XAttribute e_styleId = e.Attribute(XName.Get("val", DocX.w.NamespaceName));
                        if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
                        {
                            e_styleId.SetValue(guuid);
                        }
                    }
 
                    foreach (XElement e in remote_endnotes.Root.Descendants(XName.Get("pStyle", DocX.w.NamespaceName)))
                    {
                        XAttribute e_styleId = e.Attribute(XName.Get("val", DocX.w.NamespaceName));
                        if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
                        {
                            e_styleId.SetValue(guuid);
                        }
                    }
                }
 
                if (remote_footnotes != null)
                {
                    foreach (XElement e in remote_footnotes.Root.Descendants(XName.Get("rStyle", DocX.w.NamespaceName)))
                    {
                        XAttribute e_styleId = e.Attribute(XName.Get("val", DocX.w.NamespaceName));
                        if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
                        {
                            e_styleId.SetValue(guuid);
                        }
                    }
 
                    foreach (XElement e in remote_footnotes.Root.Descendants(XName.Get("pStyle", DocX.w.NamespaceName)))
                    {
                        XAttribute e_styleId = e.Attribute(XName.Get("val", DocX.w.NamespaceName));
                        if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
                        {
                            e_styleId.SetValue(guuid);
                        }
                    }
                }
 
                // Make sure they don't clash by using a uuid.
                styleId.SetValue(guuid);
                styles.Root.Add(remote_style);  
            }
        }
 
        protected void clonePackageRelationship(DocX remote_document, PackagePart pp, XDocument remote_mainDoc)
        {
            string url = pp.Uri.OriginalString.Replace("/", "");
            var remote_rels = remote_document.mainPart.GetRelationships();
            foreach (var remote_rel in remote_rels)
            {
                if (url.Equals("word" + remote_rel.TargetUri.OriginalString.Replace("/", "")))
                {
                    String remote_Id = remote_rel.Id;
                    String local_Id = mainPart.CreateRelationship(remote_rel.TargetUri, remote_rel.TargetMode, remote_rel.RelationshipType).Id;
 
                    // Replace all instances of remote_Id in the local document with local_Id
                    var elems = remote_mainDoc.Descendants(XName.Get("blip", DocX.a.NamespaceName));
                    foreach(var elem in elems)
                    {
                        XAttribute embed = elem.Attribute(XName.Get("embed", DocX.r.NamespaceName));
                        if (embed != null && embed.Value == remote_Id)
                        {
                            embed.SetValue(local_Id);
                        }
                    }
                    break;
                }
            }
        }
 
        protected PackagePart clonePackagePart(PackagePart pp)
        {
            PackagePart new_pp = package.CreatePart(pp.Uri, pp.ContentType);
 
            using (Stream s_read = pp.GetStream())
            {
                using (Stream s_write = new_pp.GetStream(FileMode.Create))
                {
                    byte[] buffer = new byte[32768];
                    int read;
                    while ((read = s_read.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        s_write.Write(buffer, 0, read);
                    }
                }
            }
 
            return new_pp;
        }
 
        protected string GetMD5HashFromStream(Stream stream)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(stream);
 
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
 
        /// <summary>
        /// Insert a new Table at the end of this document.
        /// </summary>
        /// <param name="columnCount">The number of columns to create.</param>
        /// <param name="rowCount">The number of rows to create.</param>
        /// <returns>A new Table.</returns>
        /// <example>
        /// Insert a new Table with 2 columns and 3 rows, at the end of a document.
        /// <code>
        /// // Create a document.
        /// using (DocX document = DocX.Create(@"C:\Example\Test.docx"))
        /// {
        ///     // Create a new Table with 2 columns and 3 rows.
        ///     Table newTable = document.InsertTable(2, 3);
        ///
        ///     // Set the design of this Table.
        ///     newTable.Design = TableDesign.LightShadingAccent2;
        ///
        ///     // Set the column names.
        ///     newTable.Rows[0].Cells[0].Paragraph.InsertText("Ice Cream", false);
        ///     newTable.Rows[0].Cells[1].Paragraph.InsertText("Price", false);
        ///
        ///     // Fill row 1
        ///     newTable.Rows[1].Cells[0].Paragraph.InsertText("Chocolate", false);
        ///     newTable.Rows[1].Cells[1].Paragraph.InsertText("€3:50", false);
        ///
        ///     // Fill row 2
        ///     newTable.Rows[2].Cells[0].Paragraph.InsertText("Vanilla", false);
        ///     newTable.Rows[2].Cells[1].Paragraph.InsertText("€3:00", false);
        ///
        ///     // Save all changes made to document b.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        public new Table InsertTable(int rowCount, int columnCount)
        {
            if (rowCount < 1 || columnCount < 1)
                throw new ArgumentOutOfRangeException("Row and Column count must be greater than zero.");
 
            Table t = base.InsertTable(rowCount, columnCount);
            t.mainPart = mainPart;
            return t;
        }
 
        public Table AddTable(int rowCount, int columnCount)
        {
            if (rowCount < 1 || columnCount < 1)
                throw new ArgumentOutOfRangeException("Row and Column count must be greater than zero.");
 
            Table t = new Table(this, HelperFunctions.CreateTable(rowCount, columnCount));
            t.mainPart = mainPart;
            return t;
        }
 
        /// <summary>
        /// Insert a Table into this document. The Table's source can be a completely different document.
        /// </summary>
        /// <param name="t">The Table to insert.</param>
        /// <param name="index">The index to insert this Table at.</param>
        /// <returns>The Table now associated with this document.</returns>
        /// <example>
        /// Extract a Table from document a and insert it into document b, at index 10.
        /// <code>
        /// // Place holder for a Table.
        /// Table t;
        ///
        /// // Load document a.
        /// using (DocX documentA = DocX.Load(@"C:\Example\a.docx"))
        /// {
        ///     // Get the first Table from this document.
        ///     t = documentA.Tables[0];
        /// }
        ///
        /// // Load document b.
        /// using (DocX documentB = DocX.Load(@"C:\Example\b.docx"))
        /// {
        ///     /* 
        ///      * Insert the Table that was extracted from document a, into document b. 
        ///      * This creates a new Table that is now associated with document b.
        ///      */
        ///     Table newTable = documentB.InsertTable(10, t);
        ///
        ///     // Save all changes made to document b.
        ///     documentB.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        public new Table InsertTable(int index, Table t)
        {
            Table t2 = base.InsertTable(index, t);
            t2.mainPart = mainPart;
            return t2;
        }
 
        /// <summary>
        /// Insert a Table into this document. The Table's source can be a completely different document.
        /// </summary>
        /// <param name="t">The Table to insert.</param>
        /// <returns>The Table now associated with this document.</returns>
        /// <example>
        /// Extract a Table from document a and insert it at the end of document b.
        /// <code>
        /// // Place holder for a Table.
        /// Table t;
        ///
        /// // Load document a.
        /// using (DocX documentA = DocX.Load(@"C:\Example\a.docx"))
        /// {
        ///     // Get the first Table from this document.
        ///     t = documentA.Tables[0];
        /// }
        ///
        /// // Load document b.
        /// using (DocX documentB = DocX.Load(@"C:\Example\b.docx"))
        /// {
        ///     /* 
        ///      * Insert the Table that was extracted from document a, into document b. 
        ///      * This creates a new Table that is now associated with document b.
        ///      */
        ///     Table newTable = documentB.InsertTable(t);
        ///
        ///     // Save all changes made to document b.
        ///     documentB.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        public new Table InsertTable(Table t)
        {
            t = base.InsertTable(t);
            t.mainPart = mainPart;
            return t;
        }
 
        /// <summary>
        /// Insert a new Table at the end of this document.
        /// </summary>
        /// <param name="columnCount">The number of columns to create.</param>
        /// <param name="rowCount">The number of rows to create.</param>
        /// <param name="index">The index to insert this Table at.</param>
        /// <returns>A new Table.</returns>
        /// <example>
        /// Insert a new Table with 2 columns and 3 rows, at index 37 in this document.
        /// <code>
        /// // Create a document.
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // Create a new Table with 3 rows and 2 columns. Insert this Table at index 37.
        ///     Table newTable = document.InsertTable(37, 3, 2);
        ///
        ///     // Set the design of this Table.
        ///     newTable.Design = TableDesign.LightShadingAccent3;
        ///
        ///     // Set the column names.
        ///     newTable.Rows[0].Cells[0].Paragraph.InsertText("Ice Cream", false);
        ///     newTable.Rows[0].Cells[1].Paragraph.InsertText("Price", false);
        ///
        ///     // Fill row 1
        ///     newTable.Rows[1].Cells[0].Paragraph.InsertText("Chocolate", false);
        ///     newTable.Rows[1].Cells[1].Paragraph.InsertText("€3:50", false);
        ///
        ///     // Fill row 2
        ///     newTable.Rows[2].Cells[0].Paragraph.InsertText("Vanilla", false);
        ///     newTable.Rows[2].Cells[1].Paragraph.InsertText("€3:00", false);
        ///
        ///     // Save all changes made to document b.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        public new Table InsertTable(int index, int rowCount, int columnCount)
        {
            if (rowCount < 1 || columnCount < 1)
                throw new ArgumentOutOfRangeException("Row and Column count must be greater than zero.");
 
            Table t = base.InsertTable(index, rowCount, columnCount);
            t.mainPart = mainPart;
            return t;
        }
 
        /// <summary>
        /// Creates a document using a Stream.
        /// </summary>
        /// <param name="stream">The Stream to create the document from.</param>
        /// <returns>Returns a DocX object which represents the document.</returns>
        /// <example>
        /// Creating a document from a FileStream.
        /// <code>
        /// // Use a FileStream fs to create a new document.
        /// using(FileStream fs = new FileStream(@"C:\Example\Test.docx", FileMode.Create))
        /// {
        ///     // Load the document using fs
        ///     using (DocX document = DocX.Create(fs))
        ///     {
        ///         // Do something with the document here.
        ///
        ///         // Save all changes made to this document.
        ///         document.Save();
        ///     }// Release this document from memory.
        /// }
        /// </code>
        /// </example>
        /// <example>
        /// Creating a document in a SharePoint site.
        /// <code>
        /// using(SPSite mySite = new SPSite("http://server/sites/site"))
        /// {
        ///     // Open a connection to the SharePoint site
        ///     using(SPWeb myWeb = mySite.OpenWeb())
        ///     {
        ///         // Create a MemoryStream ms.
        ///         using (MemoryStream ms = new MemoryStream())
        ///         {
        ///             // Create a document using ms.
        ///             using (DocX document = DocX.Create(ms))
        ///             {
        ///                 // Do something with the document here.
        ///
        ///                 // Save all changes made to this document.
        ///                 document.Save();
        ///             }// Release this document from memory
        ///
        ///             // Add the document to the SharePoint site
        ///             web.Files.Add("filename", ms.ToArray(), true);
        ///         }
        ///     }
        /// }
        /// </code>
        /// </example>
        /// <seealso cref="DocX.Create(string)"/>
        /// <seealso cref="DocX.Load(System.IO.Stream)"/>
        /// <seealso cref="DocX.Load(string)"/>
        /// <seealso cref="DocX.Save()"/>
        public static DocX Create(Stream stream)
        {
            // Store this document in memory
            MemoryStream ms = new MemoryStream();
 
            // Create the docx package
            Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
 
            PostCreation(ref package);
            DocX document = DocX.Load(ms);
            document.stream = stream;
            return document;
        }
 
        /// <summary>
        /// Creates a document using a fully qualified or relative filename.
        /// </summary>
        /// <param name="filename">The fully qualified or relative filename.</param>
        /// <returns>Returns a DocX object which represents the document.</returns>
        /// <example>
        /// <code>
        /// // Create a document using a relative filename.
        /// using (DocX document = DocX.Create(@"..\Test.docx"))
        /// {
        ///     // Do something with the document here.
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory
        /// </code>
        /// <code>
        /// // Create a document using a relative filename.
        /// using (DocX document = DocX.Create(@"..\Test.docx"))
        /// {
        ///     // Do something with the document here.
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory
        /// </code>
        /// <seealso cref="DocX.Create(System.IO.Stream)"/>
        /// <seealso cref="DocX.Load(System.IO.Stream)"/>
        /// <seealso cref="DocX.Load(string)"/>
        /// <seealso cref="DocX.Save()"/>
        /// </example>
        public static DocX Create(string filename)
        {
            // Store this document in memory
            MemoryStream ms = new MemoryStream();
 
            // Create the docx package
            //WordprocessingDocument wdDoc = WordprocessingDocument.Create(ms, DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
            Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
 
            PostCreation(ref package);
            DocX document = DocX.Load(ms);
            document.filename = filename;
            return document;
        }
 
        internal static void PostCreation(ref Package package)
        {
            XDocument mainDoc, stylesDoc;
 
            #region MainDocumentPart
            // Create the main document part for this package
            PackagePart mainDocumentPart = package.CreatePart(new Uri("/word/document.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
            package.CreateRelationship(mainDocumentPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");
 
            // Load the document part into a XDocument object
            using (TextReader tr = new StreamReader(mainDocumentPart.GetStream(FileMode.Create, FileAccess.ReadWrite)))
            {
                mainDoc = XDocument.Parse
                (@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
                   <w:document xmlns:ve=""http://schemas.openxmlformats.org/markup-compatibility/2006"" xmlns:o=""urn:schemas-microsoft-com:office:office"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:m=""http://schemas.openxmlformats.org/officeDocument/2006/math"" xmlns:v=""urn:schemas-microsoft-com:vml"" xmlns:wp=""http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"" xmlns:w10=""urn:schemas-microsoft-com:office:word"" xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"" xmlns:wne=""http://schemas.microsoft.com/office/word/2006/wordml"" xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"">
                   <w:body>
                    <w:sectPr w:rsidR=""003E25F4"" w:rsidSect=""00FC3028"">
                        <w:pgSz w:w=""11906"" w:h=""16838""/>
                        <w:pgMar w:top=""1440"" w:right=""1440"" w:bottom=""1440"" w:left=""1440"" w:header=""708"" w:footer=""708"" w:gutter=""0""/>
                        <w:cols w:space=""708""/>
                        <w:docGrid w:linePitch=""360""/>
                    </w:sectPr>
                   </w:body>
                   </w:document>"
                );
            }
 
            // Save the main document
            using (TextWriter tw = new StreamWriter(mainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)))
                mainDoc.Save(tw, SaveOptions.None);
            #endregion
 
            #region StylePart
            stylesDoc = HelperFunctions.AddDefaultStylesXml(package);
            #endregion
 
            package.Close();
        }
 
        internal static DocX PostLoad(ref Package package)
        {
            DocX document = new DocX(null, null);
            document.package = package;
            document.Document = document;
 
            #region MainDocumentPart
            document.mainPart = package.GetParts().Where
            (
                p => p.ContentType.Equals
                (
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
                    StringComparison.CurrentCultureIgnoreCase
                )
            ).Single();
 
            using (TextReader tr = new StreamReader(document.mainPart.GetStream(FileMode.Open, FileAccess.Read)))
                document.mainDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
            #endregion
 
            PopulateDocument(document, package);
 
            using (TextReader tr = new StreamReader(document.settingsPart.GetStream()))
                document.settings = XDocument.Load(tr);
 
            return document;
        }
 
        private static void PopulateDocument(DocX document, Package package)
        {
            Headers headers = new Headers();
            headers.odd = document.GetHeaderByType("default");
            headers.even = document.GetHeaderByType("even");
            headers.first = document.GetHeaderByType("first");
 
            Footers footers = new Footers();
            footers.odd = document.GetFooterByType("default");
            footers.even = document.GetFooterByType("even");
            footers.first = document.GetFooterByType("first");
 
            //// Get the sectPr for this document.
            //XElement sectPr = document.mainDoc.Descendants(XName.Get("sectPr", DocX.w.NamespaceName)).Single();
 
            //if (sectPr != null)
            //{
            //    // Extract the even header reference
            //    var header_even_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "headerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "even");
            //    string id = header_even_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res = document.mainPart.GetRelationship(id);
            //    string ans = res.SourceUri.OriginalString;
            //    headers.even.xml_filename = ans;
 
            //    // Extract the odd header reference
            //    var header_odd_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "headerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "default");
            //    string id2 = header_odd_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res2 = document.mainPart.GetRelationship(id2);
            //    string ans2 = res2.SourceUri.OriginalString;
            //    headers.odd.xml_filename = ans2;
 
            //    // Extract the first header reference
            //    var header_first_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "h
            //eaderReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "first");
            //    string id3 = header_first_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res3 = document.mainPart.GetRelationship(id3);
            //    string ans3 = res3.SourceUri.OriginalString;
            //    headers.first.xml_filename = ans3;
 
            //    // Extract the even footer reference
            //    var footer_even_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "even");
            //    string id4 = footer_even_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res4 = document.mainPart.GetRelationship(id4);
            //    string ans4 = res4.SourceUri.OriginalString;
            //    footers.even.xml_filename = ans4;
 
            //    // Extract the odd footer reference
            //    var footer_odd_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "default");
            //    string id5 = footer_odd_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res5 = document.mainPart.GetRelationship(id5);
            //    string ans5 = res5.SourceUri.OriginalString;
            //    footers.odd.xml_filename = ans5;
 
            //    // Extract the first footer reference
            //    var footer_first_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "first");
            //    string id6 = footer_first_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res6 = document.mainPart.GetRelationship(id6);
            //    string ans6 = res6.SourceUri.OriginalString;
            //    footers.first.xml_filename = ans6;
 
            //}
 
            document.Xml = document.mainDoc.Root.Element(w + "body");
            document.headers = headers;
            document.footers = footers;
            document.settingsPart = HelperFunctions.CreateOrGetSettingsPart(package);
 
            var ps = package.GetParts();
 
            //document.endnotesPart = HelperFunctions.GetPart();
            foreach (var rel in document.mainPart.GetRelationships())
            {
                switch (rel.RelationshipType)
                {
                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes":
                        document.endnotesPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.RelativeOrAbsolute));
                        using (TextReader tr = new StreamReader(document.endnotesPart.GetStream()))
                            document.endnotes= XDocument.Load(tr);
                        break;
 
                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes":
                        document.footnotesPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.RelativeOrAbsolute));
                        using (TextReader tr = new StreamReader(document.footnotesPart.GetStream()))
                            document.footnotes= XDocument.Load(tr);
                        break;
 
                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles":
                        document.stylesPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.RelativeOrAbsolute));
                        using (TextReader tr = new StreamReader(document.stylesPart.GetStream()))
                            document.styles = XDocument.Load(tr);
                        break;
 
                    case "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects":
                        document.stylesWithEffectsPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.RelativeOrAbsolute));
                        using (TextReader tr = new StreamReader(document.stylesWithEffectsPart.GetStream()))
                            document.stylesWithEffects = XDocument.Load(tr);
                        break;
 
                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable":
                        document.fontTablePart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.RelativeOrAbsolute));
                        using (TextReader tr = new StreamReader(document.fontTablePart.GetStream()))
                            document.fontTable = XDocument.Load(tr);
                        break;
 
                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering":
                        document.numberingPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.RelativeOrAbsolute));
                        using (TextReader tr = new StreamReader(document.numberingPart.GetStream()))
                            document.numbering = XDocument.Load(tr);
                        break;
 
                    default:
                        break;
                }
            }
        }
 
        /// <summary>
        /// Loads a document into a DocX object using a Stream.
        /// </summary>
        /// <param name="stream">The Stream to load the document from.</param>
        /// <returns>
        /// Returns a DocX object which represents the document.
        /// </returns>
        /// <example>
        /// Loading a document from a FileStream.
        /// <code>
        /// // Open a FileStream fs to a document.
        /// using (FileStream fs = new FileStream(@"C:\Example\Test.docx", FileMode.Open))
        /// {
        ///     // Load the document using fs.
        ///     using (DocX document = DocX.Load(fs))
        ///     {
        ///         // Do something with the document here.
        ///            
        ///         // Save all changes made to the document.
        ///         document.Save();
        ///     }// Release this document from memory.
        /// }
        /// </code>
        /// </example>
        /// <example>
        /// Loading a document from a SharePoint site.
        /// <code>
        /// // Get the SharePoint site that you want to access.
        /// using (SPSite mySite = new SPSite("http://server/sites/site"))
        /// {
        ///     // Open a connection to the SharePoint site
        ///     using (SPWeb myWeb = mySite.OpenWeb())
        ///     {
        ///         // Grab a document stored on this site.
        ///         SPFile file = web.GetFile("Source_Folder_Name/Source_File");
        ///
        ///         // DocX.Load requires a Stream, so open a Stream to this document.
        ///         Stream str = new MemoryStream(file.OpenBinary());
        ///
        ///         // Load the file using the Stream str.
        ///         using (DocX document = DocX.Load(str))
        ///         {
        ///             // Do something with the document here.
        ///
        ///             // Save all changes made to the document.
        ///             document.Save();
        ///         }// Release this document from memory.
        ///     }
        /// }
        /// </code>
        /// </example>
        /// <seealso cref="DocX.Load(string)"/>
        /// <seealso cref="DocX.Create(System.IO.Stream)"/>
        /// <seealso cref="DocX.Create(string)"/>
        /// <seealso cref="DocX.Save()"/>
        public static DocX Load(Stream stream)
        {
            MemoryStream ms = new MemoryStream();
 
            stream.Position = 0;
            byte[] data = new byte[stream.Length];
            stream.Read(data, 0, (int)stream.Length);
            ms.Write(data, 0, (int)stream.Length);
 
            // Open the docx package
            Package package = Package.Open(ms, FileMode.Open, FileAccess.ReadWrite);
 
            DocX document = PostLoad(ref package);
            document.package = package;
            document.memoryStream = ms;
            document.stream = stream;
            return document;
        }
 
        /// <summary>
        /// Loads a document into a DocX object using a fully qualified or relative filename.
        /// </summary>
        /// <param name="filename">The fully qualified or relative filename.</param>
        /// <returns>
        /// Returns a DocX object which represents the document.
        /// </returns>
        /// <example>
        /// <code>
        /// // Load a document using its fully qualified filename
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // Do something with the document here
        ///
        ///     // Save all changes made to document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// <code>
        /// // Load a document using its relative filename.
        /// using(DocX document = DocX.Load(@"..\..\Test.docx"))
        /// { 
        ///     // Do something with the document here.
        ///                
        ///     // Save all changes made to document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// <seealso cref="DocX.Load(System.IO.Stream)"/>
        /// <seealso cref="DocX.Create(System.IO.Stream)"/>
        /// <seealso cref="DocX.Create(string)"/>
        /// <seealso cref="DocX.Save()"/>
        /// </example>
        public static DocX Load(string filename)
        {
            if (!File.Exists(filename))
                throw new FileNotFoundException(string.Format("File could not be found {0}", filename));
 
            MemoryStream ms = new MemoryStream();
 
            using (FileStream fs = new FileStream(filename, FileMode.Open))
            {
                byte[] data = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
                ms.Write(data, 0, (int)fs.Length);
            }
 
            // Open the docx package
            Package package = Package.Open(ms, FileMode.Open, FileAccess.ReadWrite);
 
            DocX document = PostLoad(ref package);
            document.package = package;
            document.filename = filename;
            document.memoryStream = ms;
 
            return document;
        }
 
        ///<summary>
        /// Applies document template to the document. Document template may include styles, headers, footers, properties, etc. as well as text content.
        ///</summary>
        ///<param name="templateFilePath">The path to the document template file.</param>
        ///<exception cref="FileNotFoundException">The document template file not found.</exception>
        public void ApplyTemplate(string templateFilePath)
        {
            ApplyTemplate(templateFilePath, true);
        }
 
        ///<summary>
        /// Applies document template to the document. Document template may include styles, headers, footers, properties, etc. as well as text content.
        ///</summary>
        ///<param name="templateFilePath">The path to the document template file.</param>
        ///<param name="includeContent">Whether to copy the document template text content to document.</param>
        ///<exception cref="FileNotFoundException">The document template file not found.</exception>
        public void ApplyTemplate(string templateFilePath, bool includeContent)
        {
            if (!File.Exists(templateFilePath))
            {
                throw new FileNotFoundException(string.Format("File could not be found {0}", templateFilePath));
            }
            using (FileStream packageStream = new FileStream(templateFilePath, FileMode.Open, FileAccess.Read))
            {
                ApplyTemplate(packageStream, includeContent);
            }
        }
 
        ///<summary>
        /// Applies document template to the document. Document template may include styles, headers, footers, properties, etc. as well as text content.
        ///</summary>
        ///<param name="templateStream">The stream of the document template file.</param>
        public void ApplyTemplate(Stream templateStream)
        {
            ApplyTemplate(templateStream, true);
        }
 
        ///<summary>
        /// Applies document template to the document. Document template may include styles, headers, footers, properties, etc. as well as text content.
        ///</summary>
        ///<param name="templateStream">The stream of the document template file.</param>
        ///<param name="includeContent">Whether to copy the document template text content to document.</param>
        public void ApplyTemplate(Stream templateStream, bool includeContent)
        {
            Package templatePackage = Package.Open(templateStream);
            try
            {
                PackagePart documentPart = null;
                XDocument documentDoc = null;
                foreach (PackagePart packagePart in templatePackage.GetParts())
                {
                    switch (packagePart.Uri.ToString())
                    {
                        case "/word/document.xml":
                            documentPart = packagePart;
                            using (XmlReader xr = XmlReader.Create(packagePart.GetStream(FileMode.Open, FileAccess.Read)))
                            {
                                documentDoc = XDocument.Load(xr);
                            }
                            break;
                        case "/_rels/.rels":
                            if (!this.package.PartExists(packagePart.Uri))
                            {
                                this.package.CreatePart(packagePart.Uri, packagePart.ContentType, packagePart.CompressionOption);
                            }
                            PackagePart globalRelsPart = this.package.GetPart(packagePart.Uri);
                            using (
                              StreamReader tr = new StreamReader(
                                packagePart.GetStream(FileMode.Open, FileAccess.Read), Encoding.UTF8))
                            {
                                using (
                                  StreamWriter tw = new StreamWriter(
                                    globalRelsPart.GetStream(FileMode.Create, FileAccess.Write), Encoding.UTF8))
                                {
                                    tw.Write(tr.ReadToEnd());
                                }
                            }
                            break;
                        case "/word/_rels/document.xml.rels":
                            break;
                        default:
                            if (!this.package.PartExists(packagePart.Uri))
                            {
                                this.package.CreatePart(packagePart.Uri, packagePart.ContentType, packagePart.CompressionOption);
                            }
                            Encoding packagePartEncoding = Encoding.Default;
                            if (packagePart.Uri.ToString().EndsWith(".xml") || packagePart.Uri.ToString().EndsWith(".rels"))
                            {
                                packagePartEncoding = Encoding.UTF8;
                            }
                            PackagePart nativePart = this.package.GetPart(packagePart.Uri);
                            using (
                              StreamReader tr = new StreamReader(
                                packagePart.GetStream(FileMode.Open, FileAccess.Read), packagePartEncoding))
                            {
                                using (
                                  StreamWriter tw = new StreamWriter(
                                    nativePart.GetStream(FileMode.Create, FileAccess.Write), tr.CurrentEncoding))
                                {
                                    tw.Write(tr.ReadToEnd());
                                }
                            }
                            break;
                    }
                }
                if (documentPart != null)
                {
                    string mainContentType = documentPart.ContentType.Replace("template.main", "document.main");
                    if (this.package.PartExists(documentPart.Uri))
                    {
                        this.package.DeletePart(documentPart.Uri);
                    }
                    PackagePart documentNewPart = this.package.CreatePart(
                      documentPart.Uri, mainContentType, documentPart.CompressionOption);
                    using (XmlWriter xw = XmlWriter.Create(documentNewPart.GetStream(FileMode.Create, FileAccess.Write)))
                    {
                        documentDoc.WriteTo(xw);
                    }
                    foreach (PackageRelationship documentPartRel in documentPart.GetRelationships())
                    {
                        documentNewPart.CreateRelationship(
                          documentPartRel.TargetUri,
                          documentPartRel.TargetMode,
                          documentPartRel.RelationshipType,
                          documentPartRel.Id);
                    }
                    this.mainPart = documentNewPart;
                    this.mainDoc = documentDoc;
                    PopulateDocument(this, templatePackage);
 
                    // DragonFire: I added next line and recovered ApplyTemplate method. 
                    // I do it, becouse  PopulateDocument(...) writes into field "settingsPart" the part of Template's package 
                    //  and after line "templatePackage.Close();" in finally, field "settingsPart" becomes not available and method "Save" throw an exception...
                    // That's why I recreated settingsParts and unlinked it from Template's package =)
                    settingsPart = HelperFunctions.CreateOrGetSettingsPart(package);
                }
                if (!includeContent)
                {
                    foreach (Paragraph paragraph in this.Paragraphs)
                    {
                        paragraph.Remove(false);
                    }
                }
            }
            finally
            {
                this.package.Flush();
                var documentRelsPart = this.package.GetPart(new Uri("/word/_rels/document.xml.rels", UriKind.Relative));
                using (TextReader tr = new StreamReader(documentRelsPart.GetStream(FileMode.Open, FileAccess.Read)))
                {
                    tr.Read();
                }
                templatePackage.Close();
            }
        }
 
        /// <summary>
        /// Add an Image into this document from a fully qualified or relative filename.
        /// </summary>
        /// <param name="filename">The fully qualified or relative filename.</param>
        /// <returns>An Image file.</returns>
        /// <example>
        /// Add an Image into this document from a fully qualified filename.
        /// <code>
        /// // Load a document.
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // Add an Image from a file.
        ///     document.AddImage(@"C:\Example\Image.png");
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        /// <seealso cref="AddImage(System.IO.Stream)"/>
        /// <seealso cref="Paragraph.InsertPicture"/>
        public Image AddImage(string filename)
        {
            string contentType = "";
 
            // The extension this file has will be taken to be its format.
            switch (Path.GetExtension(filename))
            {
                case ".tiff": contentType = "image/tif"; break;
                case ".tif": contentType = "image/tif"; break;
                case ".png": contentType = "image/png"; break;
                case ".bmp": contentType = "image/png"; break;
                case ".gif": contentType = "image/gif"; break;
                case ".jpg": contentType = "image/jpg"; break;
                case ".jpeg": contentType = "image/jpeg"; break;
                default: contentType = "image/jpg"; break;
            }
 
            return AddImage(filename as object, contentType);
        }
 
        /// <summary>
        /// Add an Image into this document from a Stream.
        /// </summary>
        /// <param name="stream">A Stream stream.</param>
        /// <returns>An Image file.</returns>
        /// <example>
        /// Add an Image into a document using a Stream. 
        /// <code>
        /// // Open a FileStream fs to an Image.
        /// using (FileStream fs = new FileStream(@"C:\Example\Image.jpg", FileMode.Open))
        /// {
        ///     // Load a document.
        ///     using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        ///     {
        ///         // Add an Image from a filestream fs.
        ///         document.AddImage(fs);
        ///
        ///         // Save all changes made to this document.
        ///         document.Save();
        ///     }// Release this document from memory.
        /// }
        /// </code>
        /// </example>
        /// <seealso cref="AddImage(string)"/>
        /// <seealso cref="Paragraph.InsertPicture"/>
        public Image AddImage(Stream stream)
        {
            return AddImage(stream as object);
        }
 
        /// <summary>
        /// Adds a hyperlink to a document and creates a Paragraph which uses it.
        /// </summary>
        /// <param name="text">The text as displayed by the hyperlink.</param>
        /// <param name="uri">The hyperlink itself.</param>
        /// <returns>Returns a hyperlink that can be inserted into a Paragraph.</returns>
        /// <example>
        /// Adds a hyperlink to a document and creates a Paragraph which uses it.
        /// <code>
        /// // Create a document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///    // Add a hyperlink to this document.
        ///    Hyperlink h = document.AddHyperlink("Google", new Uri("http://www.google.com"));
        ///    
        ///    // Add a new Paragraph to this document.
        ///    Paragraph p = document.InsertParagraph();
        ///    p.Append("My favourite search engine is ");
        ///    p.AppendHyperlink(h);
        ///    p.Append(", I think it's great.");
        ///
        ///    // Save all changes made to this document.
        ///    document.Save();
        /// }
        /// </code>
        /// </example>
        public Hyperlink AddHyperlink(string text, Uri uri)
        {
            XElement i = new XElement
            (
                XName.Get("hyperlink", DocX.w.NamespaceName),
                new XAttribute(r + "id", string.Empty),
                new XAttribute(w + "history", "1"),
                new XElement(XName.Get("r", DocX.w.NamespaceName),
                new XElement(XName.Get("rPr", DocX.w.NamespaceName),
                new XElement(XName.Get("rStyle", DocX.w.NamespaceName),
                new XAttribute(w + "val", "Hyperlink"))),
                new XElement(XName.Get("t", DocX.w.NamespaceName), text))
            );
 
            Hyperlink h = new Hyperlink(this, mainPart, i);
 
            h.text = text;
            h.uri = uri;
 
            AddHyperlinkStyleIfNotPresent();
 
            return h;
        }
 
        internal void AddHyperlinkStyleIfNotPresent()
        {
            Uri word_styles_Uri = new Uri("/word/styles.xml", UriKind.Relative);
 
            // If the internal document contains no /word/styles.xml create one.
            if (!package.PartExists(word_styles_Uri))
                HelperFunctions.AddDefaultStylesXml(package);
 
            // Load the styles.xml into memory.
            XDocument word_styles;
            using (TextReader tr = new StreamReader(package.GetPart(word_styles_Uri).GetStream()))
                word_styles = XDocument.Load(tr);
 
            bool hyperlinkStyleExists =
            (
                from s in word_styles.Element(w + "styles").Elements()
                let styleId = s.Attribute(XName.Get("styleId", w.NamespaceName))
                where (styleId != null && styleId.Value == "Hyperlink")
                select s
            ).Count() > 0;
 
            if (!hyperlinkStyleExists)
            {
                XElement style = new XElement
                (
                    w + "style",
                    new XAttribute(w + "type", "character"),
                    new XAttribute(w + "styleId", "Hyperlink"),
                        new XElement(w + "name", new XAttribute(w + "val", "Hyperlink")),
                        new XElement(w + "basedOn", new XAttribute(w + "val", "DefaultParagraphFont")),
                        new XElement(w + "uiPriority", new XAttribute(w + "val", "99")),
                        new XElement(w + "unhideWhenUsed"),
                        new XElement(w + "rsid", new XAttribute(w + "val", "0005416C")),
                        new XElement
                        (
                            w + "rPr",
                            new XElement(w + "color", new XAttribute(w + "val", "0000FF"), new XAttribute(w + "themeColor", "hyperlink")),
                            new XElement
                            (
                                w + "u",
                                new XAttribute(w + "val", "single")
                            )
                        )
                );
                word_styles.Element(w + "styles").Add(style);
 
                // Save the styles document.
                using (TextWriter tw = new StreamWriter(package.GetPart(word_styles_Uri).GetStream()))
                    word_styles.Save(tw);
            }
        }
 
        private string GetNextFreeRelationshipID()
        {
            string id =
            (
                from r in mainPart.GetRelationships()
                select r.Id
            ).Max();
 
            // The convension for ids is rid01, rid02, etc
            string newId = id.Replace("rId", "");
            int result;
            if (int.TryParse(newId, out result))
                return ("rId" + (result + 1));
            else
            {
                String guid = String.Empty;
                do
                {
                    guid = Guid.NewGuid().ToString();
                } while (Char.IsDigit(guid[0]));
                return guid;
            }
        }
 
        /// <summary>
        /// Adds three new Headers to this document. One for the first page, one for odd pages and one for even pages.
        /// </summary>
        /// <example>
        /// // Create a document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///     // Add header support to this document.
        ///     document.AddHeaders();
        ///
        ///     // Get a collection of all headers in this document.
        ///     Headers headers = document.Headers;
        ///
        ///     // The header used for the first page of this document.
        ///     Header first = headers.first;
        ///
        ///     // The header used for odd pages of this document.
        ///     Header odd = headers.odd;
        ///
        ///     // The header used for even pages of this document.
        ///     Header even = headers.even;
        ///
        ///     // Force the document to use a different header for first, odd and even pages.
        ///     document.DifferentFirstPage = true;
        ///     document.DifferentOddAndEvenPages = true;
        ///
        ///     // Content can be added to the Headers in the same manor that it would be added to the main document.
        ///     Paragraph p = first.InsertParagraph();
        ///     p.Append("This is the first pages header.");
        ///
        ///     // Save all changes to this document.
        ///     document.Save();    
        /// }// Release this document from memory.
        /// </example>
        public void AddHeaders()
        {
            AddHeadersOrFooters(true);
 
            headers.odd = Document.GetHeaderByType("default");
            headers.even = Document.GetHeaderByType("even");
            headers.first = Document.GetHeaderByType("first");
        }
 
        /// <summary>
        /// Adds three new Footers to this document. One for the first page, one for odd pages and one for even pages.
        /// </summary>
        /// <example>
        /// // Create a document.
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///     // Add footer support to this document.
        ///     document.AddFooters();
        ///
        ///     // Get a collection of all footers in this document.
        ///     Footers footers = document.Footers;
        ///
        ///     // The footer used for the first page of this document.
        ///     Footer first = footers.first;
        ///
        ///     // The footer used for odd pages of this document.
        ///     Footer odd = footers.odd;
        ///
        ///     // The footer used for even pages of this document.
        ///     Footer even = footers.even;
        ///
        ///     // Force the document to use a different footer for first, odd and even pages.
        ///     document.DifferentFirstPage = true;
        ///     document.DifferentOddAndEvenPages = true;
        ///
        ///     // Content can be added to the Footers in the same manor that it would be added to the main document.
        ///     Paragraph p = first.InsertParagraph();
        ///     p.Append("This is the first pages footer.");
        ///
        ///     // Save all changes to this document.
        ///     document.Save();    
        /// }// Release this document from memory.
        /// </example>
        public void AddFooters()
        {
            AddHeadersOrFooters(false);
 
            footers.odd = Document.GetFooterByType("default");
            footers.even = Document.GetFooterByType("even");
            footers.first = Document.GetFooterByType("first");
        }
 
        /// <summary>
        /// Adds a Header to a document.
        /// If the document already contains a Header it will be replaced.
        /// </summary>
        /// <returns>The Header that was added to the document.</returns>
        internal void AddHeadersOrFooters(bool b)
        {
            string element = "ftr";
            string reference = "footer";
            if (b)
            {
                element = "hdr";
                reference = "header";
            }
 
            DeleteHeadersOrFooters(b);
 
            XElement sectPr = mainDoc.Root.Element(w + "body").Element(w + "sectPr");
 
            for (int i = 1; i < 4; i++)
            {
                string header_uri = string.Format("/word/{0}{1}.xml", reference, i);
 
                PackagePart headerPart = package.CreatePart(new Uri(header_uri, UriKind.Relative), string.Format("application/vnd.openxmlformats-officedocument.wordprocessingml.{0}+xml", reference));
                PackageRelationship headerRelationship = mainPart.CreateRelationship(headerPart.Uri, TargetMode.Internal, string.Format("http://schemas.openxmlformats.org/officeDocument/2006/relationships/{0}", reference));
 
                XDocument header;
 
                // Load the document part into a XDocument object
                using (TextReader tr = new StreamReader(headerPart.GetStream(FileMode.Create, FileAccess.ReadWrite)))
                {
                    header = XDocument.Parse
                    (string.Format(@"<?xml version=""1.0"" encoding=""utf-16"" standalone=""yes""?>
                       <w:{0} xmlns:ve=""http://schemas.openxmlformats.org/markup-compatibility/2006"" xmlns:o=""urn:schemas-microsoft-com:office:office"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:m=""http://schemas.openxmlformats.org/officeDocument/2006/math"" xmlns:v=""urn:schemas-microsoft-com:vml"" xmlns:wp=""http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"" xmlns:w10=""urn:schemas-microsoft-com:office:word"" xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"" xmlns:wne=""http://schemas.microsoft.com/office/word/2006/wordml"">
                         <w:p w:rsidR=""009D472B"" w:rsidRDefault=""009D472B"">
                           <w:pPr>
                             <w:pStyle w:val=""{1}"" />
                           </w:pPr>
                         </w:p>
                       </w:{0}>", element, reference)
                    );
                }
 
                // Save the main document
                using (TextWriter tw = new StreamWriter(headerPart.GetStream(FileMode.Create, FileAccess.Write)))
                    header.Save(tw, SaveOptions.None);
 
                string type;
                switch (i)
                {
                    case 1: type = "default"; break;
                    case 2: type = "even"; break;
                    case 3: type = "first"; break;
                    default: throw new ArgumentOutOfRangeException();
                }
 
                sectPr.Add
                (
                    new XElement
                    (
                        w + string.Format("{0}Reference", reference),
                        new XAttribute(w + "type", type),
                        new XAttribute(r + "id", headerRelationship.Id)
                    )
                );
            }
        }
 
        internal void DeleteHeadersOrFooters(bool b)
        {
            string reference = "footer";
            if (b)
                reference = "header";
 
            // Get all header Relationships in this document.
            var header_relationships = mainPart.GetRelationshipsByType(string.Format("http://schemas.openxmlformats.org/officeDocument/2006/relationships/{0}", reference));
 
            foreach (PackageRelationship header_relationship in header_relationships)
            {
                // Get the TargetUri for this Part.
                Uri header_uri = header_relationship.TargetUri;
 
                // Check to see if the document actually contains the Part.
                if (!header_uri.OriginalString.StartsWith("/word/"))
                    header_uri = new Uri("/word/" + header_uri.OriginalString, UriKind.Relative);
 
                if (package.PartExists(header_uri))
                {
                    // Delete the Part
                    package.DeletePart(header_uri);
 
                    // Get all references to this Relationship in the document.
                    var query =
                    (
                        from e in mainDoc.Descendants(XName.Get("body", DocX.w.NamespaceName)).Descendants()
                        where (e.Name.LocalName == string.Format("{0}Reference", reference)) && (e.Attribute(r + "id").Value == header_relationship.Id)
                        select e
                    );
 
                    // Remove all references to this Relationship in the document.
                    for (int i = 0; i < query.Count(); i++)
                        query.ElementAt(i).Remove();
 
                    // Delete the Relationship.
                    package.DeleteRelationship(header_relationship.Id);
                }
            }
        }
 
        internal Image AddImage(object o, string contentType = "image/jpeg")
        {
            // Open a Stream to the new image being added.
            Stream newImageStream;
            if (o is string)
                newImageStream = new FileStream(o as string, FileMode.Open, FileAccess.Read);
            else
                newImageStream = o as Stream;
 
            // Get all image parts in word\document.xml
            List<PackagePart> imageParts = mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image").Select(ir => package.GetParts().Where(p => p.Uri.ToString().EndsWith(ir.TargetUri.ToString())).First()).ToList();
            foreach (PackagePart relsPart in package.GetParts().Where(part => part.Uri.ToString().Contains("/word/")).Where(part => part.ContentType.Equals("application/vnd.openxmlformats-package.relationships+xml")))
            {
                XDocument relsPartContent;
                using (TextReader tr = new StreamReader(relsPart.GetStream(FileMode.Open, FileAccess.Read)))
                    relsPartContent = XDocument.Load(tr);
 
                IEnumerable<XElement> imageRelationships =
                relsPartContent.Root.Elements().Where
                (
                    imageRel =>
                    imageRel.Attribute(XName.Get("Type")).Value.Equals("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image")
                );
 
                foreach (XElement imageRelationship in imageRelationships)
                {
                    if (imageRelationship.Attribute(XName.Get("Target")) != null)
                    {
                        string imagePartUri = Path.Combine(Path.GetDirectoryName(relsPart.Uri.ToString()), imageRelationship.Attribute(XName.Get("Target")).Value);
                        imagePartUri = Path.GetFullPath(imagePartUri.Replace("\\_rels", string.Empty));
                        imagePartUri = imagePartUri.Replace(Path.GetFullPath("\\"), string.Empty).Replace("\\", "/");
 
                        if (!imagePartUri.StartsWith("/"))
                            imagePartUri = "/" + imagePartUri;
 
                        PackagePart imagePart = package.GetPart(new Uri(imagePartUri, UriKind.Relative));
                        imageParts.Add(imagePart);
                    }
                }
            }
 
            // Loop through each image part in this document.
            foreach (PackagePart pp in imageParts)
            {
                // Open a tempory Stream to this image part.
                using (Stream tempStream = pp.GetStream(FileMode.Open, FileAccess.Read))
                {
                    // Compare this image to the new image being added.
                    if (HelperFunctions.IsSameFile(tempStream, newImageStream))
                    {
                        // Get the image object for this image part
                        string id = mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image")
                        .Where(r => r.TargetUri == pp.Uri)
                        .Select(r => r.Id).First();
 
                        // Return the Image object
                        return Images.Where(i => i.Id == id).First();
                    }
                }
            }
 
            string imgPartUriPath = string.Empty;
            string extension = contentType.Substring(contentType.LastIndexOf("/") + 1);
            do
            {
                // Create a new image part.
                imgPartUriPath = string.Format
                (
                    "/word/media/{0}.{1}",
                    Guid.NewGuid().ToString(), // The unique part.
                    extension
                );
 
            } while (package.PartExists(new Uri(imgPartUriPath, UriKind.Relative)));
 
            // We are now guareenteed that imgPartUriPath is unique.
            PackagePart img = package.CreatePart(new Uri(imgPartUriPath, UriKind.Relative), contentType);
 
            // Create a new image relationship
            PackageRelationship rel = mainPart.CreateRelationship(img.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
 
            // Open a Stream to the newly created Image part.
            using (Stream stream = img.GetStream(FileMode.Create, FileAccess.Write))
            {
                // Using the Stream to the real image, copy this streams data into the newly create Image part.
                using (newImageStream)
                {
                    byte[] bytes = new byte[newImageStream.Length];
                    newImageStream.Read(bytes, 0, (int)newImageStream.Length);
                    stream.Write(bytes, 0, (int)newImageStream.Length);
                }// Close the Stream to the new image.
            }// Close the Stream to the new image part.
 
            return new Image(this, rel);
        }
 
        /// <summary>
        /// Save this document back to the location it was loaded from.
        /// </summary>
        /// <example>
        /// <code>
        /// // Load a document.
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // Add an Image from a file.
        ///     document.AddImage(@"C:\Example\Image.jpg");
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        /// <seealso cref="DocX.SaveAs(string)"/>
        /// <seealso cref="DocX.Create(System.IO.Stream)"/>
        /// <seealso cref="DocX.Create(string)"/>
        /// <seealso cref="DocX.Load(System.IO.Stream)"/>
        /// <seealso cref="DocX.Load(string)"/> 
        /// <!-- 
        /// Bug found and fixed by krugs525 on August 12 2009.
        /// Use TFS compare to see exact code change.
        /// -->
        public void Save()
        {
            Headers headers = Headers;
 
            // Save the main document
            using (TextWriter tw = new StreamWriter(mainPart.GetStream(FileMode.Create, FileAccess.Write)))
                mainDoc.Save(tw, SaveOptions.None);
 
            XElement body = mainDoc.Root.Element(w + "body");
            XElement sectPr = body.Descendants(w + "sectPr").FirstOrDefault();
 
            if (sectPr != null)
            {
                var evenHeaderRef =
                (
                    from e in mainDoc.Descendants(w + "headerReference")
                    let type = e.Attribute(w + "type")
                    where type != null && type.Value.Equals("even", StringComparison.CurrentCultureIgnoreCase)
                    select e.Attribute(r + "id").Value
                 ).LastOrDefault();
 
                if (evenHeaderRef != null)
                {
                    XElement even = headers.even.Xml;
 
                    Uri target = PackUriHelper.ResolvePartUri
                    (
                        mainPart.Uri,
                        mainPart.GetRelationship(evenHeaderRef).TargetUri
                    );
 
                    using (TextWriter tw = new StreamWriter(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write)))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            even
                        ).Save(tw, SaveOptions.None);
                    }
                }
 
                var oddHeaderRef =
                (
                    from e in mainDoc.Descendants(w + "headerReference")
                    let type = e.Attribute(w + "type")
                    where type != null && type.Value.Equals("default", StringComparison.CurrentCultureIgnoreCase)
                    select e.Attribute(r + "id").Value
                 ).LastOrDefault();
 
                if (oddHeaderRef != null)
                {
                    XElement odd = headers.odd.Xml;
 
                    Uri target = PackUriHelper.ResolvePartUri
                    (
                        mainPart.Uri,
                        mainPart.GetRelationship(oddHeaderRef).TargetUri
                    );
 
                    // Save header1
                    using (TextWriter tw = new StreamWriter(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write)))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            odd
                        ).Save(tw, SaveOptions.None);
                    }
                }
 
                var firstHeaderRef =
                (
                    from e in mainDoc.Descendants(w + "headerReference")
                    let type = e.Attribute(w + "type")
                    where type != null && type.Value.Equals("first", StringComparison.CurrentCultureIgnoreCase)
                    select e.Attribute(r + "id").Value
                 ).LastOrDefault();
 
                if (firstHeaderRef != null)
                {
                    XElement first = headers.first.Xml;
                    Uri target = PackUriHelper.ResolvePartUri
                    (
                        mainPart.Uri,
                        mainPart.GetRelationship(firstHeaderRef).TargetUri
                    );
 
                    // Save header3
                    using (TextWriter tw = new StreamWriter(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write)))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            first
                        ).Save(tw, SaveOptions.None);
                    }
                }
 
                var oddFooterRef =
                (
                    from e in mainDoc.Descendants(w + "footerReference")
                    let type = e.Attribute(w + "type")
                    where type != null && type.Value.Equals("default", StringComparison.CurrentCultureIgnoreCase)
                    select e.Attribute(r + "id").Value
                 ).LastOrDefault();
 
                if (oddFooterRef != null)
                {
                    XElement odd = footers.odd.Xml;
                    Uri target = PackUriHelper.ResolvePartUri
                    (
                        mainPart.Uri,
                        mainPart.GetRelationship(oddFooterRef).TargetUri
                    );
 
                    // Save header1
                    using (TextWriter tw = new StreamWriter(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write)))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            odd
                        ).Save(tw, SaveOptions.None);
                    }
                }
 
                var evenFooterRef =
                (
                    from e in mainDoc.Descendants(w + "footerReference")
                    let type = e.Attribute(w + "type")
                    where type != null && type.Value.Equals("even", StringComparison.CurrentCultureIgnoreCase)
                    select e.Attribute(r + "id").Value
                 ).LastOrDefault();
 
                if (evenFooterRef != null)
                {
                    XElement even = footers.even.Xml;
                    Uri target = PackUriHelper.ResolvePartUri
                    (
                        mainPart.Uri,
                        mainPart.GetRelationship(evenFooterRef).TargetUri
                    );
 
                    // Save header2
                    using (TextWriter tw = new StreamWriter(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write)))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            even
                        ).Save(tw, SaveOptions.None);
                    }
                }
 
                var firstFooterRef =
                (
                     from e in mainDoc.Descendants(w + "footerReference")
                     let type = e.Attribute(w + "type")
                     where type != null && type.Value.Equals("first", StringComparison.CurrentCultureIgnoreCase)
                     select e.Attribute(r + "id").Value
                ).LastOrDefault();
 
                if (firstFooterRef != null)
                {
                    XElement first = footers.first.Xml;
                    Uri target = PackUriHelper.ResolvePartUri
                    (
                        mainPart.Uri,
                        mainPart.GetRelationship(firstFooterRef).TargetUri
                    );
 
                    // Save header3
                    using (TextWriter tw = new StreamWriter(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write)))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            first
                        ).Save(tw, SaveOptions.None);
                    }
                }
 
                // Save the settings document.
                using (TextWriter tw = new StreamWriter(settingsPart.GetStream(FileMode.Create, FileAccess.Write)))
                    settings.Save(tw, SaveOptions.None);
 
                if (endnotesPart != null)
                {
                    using (TextWriter tw = new StreamWriter(endnotesPart.GetStream(FileMode.Create, FileAccess.Write)))
                        endnotes.Save(tw, SaveOptions.None);
                }
 
                if (footnotesPart != null)
                {
                    using (TextWriter tw = new StreamWriter(footnotesPart.GetStream(FileMode.Create, FileAccess.Write)))
                        footnotes.Save(tw, SaveOptions.None);
                }
 
                if (stylesPart != null)
                {
                    using (TextWriter tw = new StreamWriter(stylesPart.GetStream(FileMode.Create, FileAccess.Write)))
                        styles.Save(tw, SaveOptions.None);
                }
 
                if (stylesWithEffectsPart != null)
                {
                    using (TextWriter tw = new StreamWriter(stylesWithEffectsPart.GetStream(FileMode.Create, FileAccess.Write)))
                        stylesWithEffects.Save(tw, SaveOptions.None);
                }
 
                if (numberingPart != null)
                {
                    using (TextWriter tw = new StreamWriter(numberingPart.GetStream(FileMode.Create, FileAccess.Write)))
                        numbering.Save(tw, SaveOptions.None);
                }
 
                if (fontTablePart != null)
                {
                    using (TextWriter tw = new StreamWriter(fontTablePart.GetStream(FileMode.Create, FileAccess.Write)))
                        fontTable.Save(tw, SaveOptions.None);
                }
            }
 
            // Close the document so that it can be saved.
            package.Flush();
            
            #region Save this document back to a file or stream, that was specified by the user at save time.
            if (filename != null)
            {
                using (FileStream fs = new FileStream(filename, FileMode.Create))
                {
                    fs.Write(memoryStream.ToArray(), 0, (int)memoryStream.Length);
                }
            }
 
 
            else
            {
                // Set the length of this stream to 0
                stream.SetLength(0);
 
                // Write to the beginning of the stream
                stream.Position = 0;
 
                memoryStream.WriteTo(stream);
            }
            #endregion
        }
 
        /// <summary>
        /// Save this document to a file.
        /// </summary>
        /// <param name="filename">The filename to save this document as.</param>
        /// <example>
        /// Load a document from one file and save it to another.
        /// <code>
        /// // Load a document using its fully qualified filename.
        /// DocX document = DocX.Load(@"C:\Example\Test1.docx");
        ///
        /// // Insert a new Paragraph
        /// document.InsertParagraph("Hello world!", false);
        ///
        /// // Save the document to a new location.
        /// document.SaveAs(@"C:\Example\Test2.docx");
        /// </code>
        /// </example>
        /// <example>
        /// Load a document from a Stream and save it to a file.
        /// <code>
        /// DocX document;
        /// using (FileStream fs1 = new FileStream(@"C:\Example\Test1.docx", FileMode.Open))
        /// {
        ///     // Load a document using a stream.
        ///     document = DocX.Load(fs1);
        ///
        ///     // Insert a new Paragraph
        ///     document.InsertParagraph("Hello world again!", false);
        /// }
        ///    
        /// // Save the document to a new location.
        /// document.SaveAs(@"C:\Example\Test2.docx");
        /// </code>
        /// </example>
        /// <seealso cref="DocX.Save()"/>
        /// <seealso cref="DocX.Create(System.IO.Stream)"/>
        /// <seealso cref="DocX.Create(string)"/>
        /// <seealso cref="DocX.Load(System.IO.Stream)"/>
        /// <seealso cref="DocX.Load(string)"/>
        public void SaveAs(string filename)
        {
            this.filename = filename;
            this.stream = null;
            Save();
        }
 
        /// <summary>
        /// Save this document to a Stream.
        /// </summary>
        /// <param name="stream">The Stream to save this document to.</param>
        /// <example>
        /// Load a document from a file and save it to a Stream.
        /// <code>
        /// // Place holder for a document.
        /// DocX document;
        ///
        /// using (FileStream fs1 = new FileStream(@"C:\Example\Test1.docx", FileMode.Open))
        /// {
        ///     // Load a document using a stream.
        ///     document = DocX.Load(fs1);
        ///
        ///     // Insert a new Paragraph
        ///     document.InsertParagraph("Hello world again!", false);
        /// }
        ///
        /// using (FileStream fs2 = new FileStream(@"C:\Example\Test2.docx", FileMode.Create))
        /// {
        ///     // Save the document to a different stream.
        ///     document.SaveAs(fs2);
        /// }
        ///
        /// // Release this document from memory.
        /// document.Dispose();
        /// </code>
        /// </example>
        /// <example>
        /// Load a document from one Stream and save it to another.
        /// <code>
        /// DocX document;
        /// using (FileStream fs1 = new FileStream(@"C:\Example\Test1.docx", FileMode.Open))
        /// {
        ///     // Load a document using a stream.
        ///     document = DocX.Load(fs1);
        ///
        ///     // Insert a new Paragraph
        ///     document.InsertParagraph("Hello world again!", false);
        /// }
        /// 
        /// using (FileStream fs2 = new FileStream(@"C:\Example\Test2.docx", FileMode.Create))
        /// {
        ///     // Save the document to a different stream.
        ///     document.SaveAs(fs2);
        /// }
        /// </code>
        /// </example>
        /// <seealso cref="DocX.Save()"/>
        /// <seealso cref="DocX.Create(System.IO.Stream)"/>
        /// <seealso cref="DocX.Create(string)"/>
        /// <seealso cref="DocX.Load(System.IO.Stream)"/>
        /// <seealso cref="DocX.Load(string)"/>
        public void SaveAs(Stream stream)
        {
            this.filename = null;
            this.stream = stream;
            Save();
        }
 
        /// <summary>
        /// Add a core property to this document. If a core property already exists with the same name it will be replaced. Core property names are case insensitive.
        /// </summary>
        ///<param name="propertyName">The property name.</param>
        ///<param name="propertyValue">The property value.</param>
        ///<example>
        /// Add a core properties of each type to a document.
        /// <code>
        /// // Load Example.docx
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // If this document does not contain a core property called 'forename', create one.
        ///     if (!document.CoreProperties.ContainsKey("forename"))
        ///     {
        ///         // Create a new core property called 'forename' and set its value.
        ///         document.AddCoreProperty("forename", "Cathal");
        ///     }
        ///
        ///     // Get this documents core property called 'forename'.
        ///     string forenameValue = document.CoreProperties["forename"];
        ///
        ///     // Print all of the information about this core property to Console.
        ///     Console.WriteLine(string.Format("Name: '{0}', Value: '{1}'\nPress any key...", "forename", forenameValue));
        ///     
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// } // Release this document from memory.
        ///
        /// // Wait for the user to press a key before exiting.
        /// Console.ReadKey();
        /// </code>
        /// </example>
        /// <seealso cref="CoreProperties"/>
        /// <seealso cref="CustomProperty"/>
        /// <seealso cref="CustomProperties"/>
        public void AddCoreProperty(string propertyName, string propertyValue)
        {
            string propertyNamespacePrefix = propertyName.Contains(":") ? propertyName.Split(new[] { ':' })[0] : "cp";
            string propertyLocalName = propertyName.Contains(":") ? propertyName.Split(new[] { ':' })[1] : propertyName;
 
            // If this document does not contain a coreFilePropertyPart create one.)
            if (!package.PartExists(new Uri("/docProps/core.xml", UriKind.Relative)))
                throw new Exception("Core properties part doesn't exist.");
 
            XDocument corePropDoc;
            PackagePart corePropPart = package.GetPart(new Uri("/docProps/core.xml", UriKind.Relative));
            using (TextReader tr = new StreamReader(corePropPart.GetStream(FileMode.Open, FileAccess.Read)))
            {
                corePropDoc = XDocument.Load(tr);
            }
 
            XElement corePropElement =
              (from propElement in corePropDoc.Root.Elements()
               where (propElement.Name.LocalName.Equals(propertyLocalName))
               select propElement).SingleOrDefault();
            if (corePropElement != null)
            {
                corePropElement.SetValue(propertyValue);
            }
            else
            {
                var propertyNamespace = corePropDoc.Root.GetNamespaceOfPrefix(propertyNamespacePrefix);
                corePropDoc.Root.Add(new XElement(XName.Get(propertyLocalName, propertyNamespace.NamespaceName), propertyValue));
            }
 
            using (TextWriter tw = new StreamWriter(corePropPart.GetStream(FileMode.Create, FileAccess.Write)))
            {
                corePropDoc.Save(tw);
            }
            UpdateCorePropertyValue(this, propertyLocalName, propertyValue);
        }
 
        internal static void UpdateCorePropertyValue(DocX document, string corePropertyName, string corePropertyValue)
        {
            string matchPattern = string.Format(@"(DOCPROPERTY)?{0}\\\*MERGEFORMAT", corePropertyName).ToLower();
            foreach (XElement e in document.mainDoc.Descendants(XName.Get("fldSimple", w.NamespaceName)))
            {
                string attr_value = e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Replace(" ", string.Empty).Trim().ToLower();
 
                if (Regex.IsMatch(attr_value, matchPattern))
                {
                    XElement firstRun = e.Element(w + "r");
                    XElement firstText = firstRun.Element(w + "t");
                    XElement rPr = firstText.Element(w + "rPr");
 
                    // Delete everything and insert updated text value
                    e.RemoveNodes();
 
                    XElement t = new XElement(w + "t", rPr, corePropertyValue);
                    Novacode.Text.PreserveSpace(t);
                    e.Add(new XElement(firstRun.Name, firstRun.Attributes(), firstRun.Element(XName.Get("rPr", w.NamespaceName)), t));
                }
            }
 
            #region Headers
 
            IEnumerable<PackagePart> headerParts = from headerPart in document.package.GetParts()
                                                   where (Regex.IsMatch(headerPart.Uri.ToString(), @"/word/header\d?.xml"))
                                                   select headerPart;
            foreach (PackagePart pp in headerParts)
            {
                XDocument header = XDocument.Load(new StreamReader(pp.GetStream()));
 
                foreach (XElement e in header.Descendants(XName.Get("fldSimple", w.NamespaceName)))
                {
                    string attr_value = e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Replace(" ", string.Empty).Trim().ToLower();
                    if (Regex.IsMatch(attr_value, matchPattern))
                    {
                        XElement firstRun = e.Element(w + "r");
 
                        // Delete everything and insert updated text value
                        e.RemoveNodes();
 
                        XElement t = new XElement(w + "t", corePropertyValue);
                        Novacode.Text.PreserveSpace(t);
                        e.Add(new XElement(firstRun.Name, firstRun.Attributes(), firstRun.Element(XName.Get("rPr", w.NamespaceName)), t));
                    }
                }
 
                using (TextWriter tw = new StreamWriter(pp.GetStream(FileMode.Create, FileAccess.Write)))
                    header.Save(tw);
            }
            #endregion
 
            #region Footers
            IEnumerable<PackagePart> footerParts = from footerPart in document.package.GetParts()
                                                   where (Regex.IsMatch(footerPart.Uri.ToString(), @"/word/footer\d?.xml"))
                                                   select footerPart;
            foreach (PackagePart pp in footerParts)
            {
                XDocument footer = XDocument.Load(new StreamReader(pp.GetStream()));
 
                foreach (XElement e in footer.Descendants(XName.Get("fldSimple", w.NamespaceName)))
                {
                    string attr_value = e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Replace(" ", string.Empty).Trim().ToLower();
                    if (Regex.IsMatch(attr_value, matchPattern))
                    {
                        XElement firstRun = e.Element(w + "r");
 
                        // Delete everything and insert updated text value
                        e.RemoveNodes();
 
                        XElement t = new XElement(w + "t", corePropertyValue);
                        Novacode.Text.PreserveSpace(t);
                        e.Add(new XElement(firstRun.Name, firstRun.Attributes(), firstRun.Element(XName.Get("rPr", w.NamespaceName)), t));
                    }
                }
 
                using (TextWriter tw = new StreamWriter(pp.GetStream(FileMode.Create, FileAccess.Write)))
                    footer.Save(tw);
            }
            #endregion
            PopulateDocument(document, document.package);
        }
 
        /// <summary>
        /// Add a custom property to this document. If a custom property already exists with the same name it will be replace. CustomProperty names are case insensitive.
        /// </summary>
        /// <param name="cp">The CustomProperty to add to this document.</param>
        /// <example>
        /// Add a custom properties of each type to a document.
        /// <code>
        /// // Load Example.docx
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // A CustomProperty called forename which stores a string.
        ///     CustomProperty forename;
        ///
        ///     // If this document does not contain a custom property called 'forename', create one.
        ///     if (!document.CustomProperties.ContainsKey("forename"))
        ///     {
        ///         // Create a new custom property called 'forename' and set its value.
        ///         document.AddCustomProperty(new CustomProperty("forename", "Cathal"));
        ///     }
        ///
        ///     // Get this documents custom property called 'forename'.
        ///     forename = document.CustomProperties["forename"];
        ///
        ///     // Print all of the information about this CustomProperty to Console.
        ///     Console.WriteLine(string.Format("Name: '{0}', Value: '{1}'\nPress any key...", forename.Name, forename.Value));
        ///     
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// } // Release this document from memory.
        ///
        /// // Wait for the user to press a key before exiting.
        /// Console.ReadKey();
        /// </code>
        /// </example>
        /// <seealso cref="CustomProperty"/>
        /// <seealso cref="CustomProperties"/>
        public void AddCustomProperty(CustomProperty cp)
        {
            // If this document does not contain a customFilePropertyPart create one.
            if (!package.PartExists(new Uri("/docProps/custom.xml", UriKind.Relative)))
                HelperFunctions.CreateCustomPropertiesPart(this);
 
            XDocument customPropDoc;
            PackagePart customPropPart = package.GetPart(new Uri("/docProps/custom.xml", UriKind.Relative));
            using (TextReader tr = new StreamReader(customPropPart.GetStream(FileMode.Open, FileAccess.Read)))
                customPropDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
 
            // Each custom property has a PID, get the highest PID in this document.
            IEnumerable<int> pids =
            (
                from d in customPropDoc.Descendants()
                where d.Name.LocalName == "property"
                select int.Parse(d.Attribute(XName.Get("pid")).Value)
            );
 
            int pid = 1;
            if (pids.Count() > 0)
                pid = pids.Max();
 
            // Check if a custom property already exists with this name
            var customProperty =
            (
                from d in customPropDoc.Descendants()
                where (d.Name.LocalName == "property") && (d.Attribute(XName.Get("name")).Value == cp.Name)
                select d
            ).SingleOrDefault();
 
            // If a custom property with this name already exists remove it.
            if (customProperty != null)
                customProperty.Remove();
 
            XElement propertiesElement = customPropDoc.Element(XName.Get("Properties", customPropertiesSchema.NamespaceName));
            propertiesElement.Add
            (
                new XElement
                (
                    XName.Get("property", customPropertiesSchema.NamespaceName),
                    new XAttribute("fmtid", "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"),
                    new XAttribute("pid", pid + 1),
                    new XAttribute("name", cp.Name),
                        new XElement(customVTypesSchema + cp.Type, cp.Value)
                )
            );
 
            // Save the custom properties
            using (TextWriter tw = new StreamWriter(customPropPart.GetStream(FileMode.Create, FileAccess.Write)))
                customPropDoc.Save(tw, SaveOptions.None);
 
            // Refresh all fields in this document which display this custom property.
            UpdateCustomPropertyValue(this, cp.Name, cp.Value.ToString());
        }
 
        /// <summary>
        /// Update the custom properties inside the document
        /// </summary>
        /// <param name="document">The DocX document</param>
        /// <param name="customPropertyName">The property used inside the document</param>
        /// <param name="customPropertyValue">The new value for the property</param>
        /// <remarks>Different version of Word create different Document XML.</remarks>
        internal static void UpdateCustomPropertyValue(DocX document, string customPropertyName, string customPropertyValue)
        {
            // A list of documents, which will contain, The Main Document and if they exist: header1, header2, header3, footer1, footer2, footer3.
            List<XElement> documents = new List<XElement> { document.mainDoc.Root };
 
            // Check if each header exists and add if if so.
            #region Headers
            Headers headers = document.Headers;
            if (headers.first != null)
                documents.Add(headers.first.Xml);
            if (headers.odd != null)
                documents.Add(headers.odd.Xml);
            if (headers.even != null)
                documents.Add(headers.even.Xml);
            #endregion
 
            // Check if each footer exists and add if if so.
            #region Footers
            Footers footers = document.Footers;
            if (footers.first != null)
                documents.Add(footers.first.Xml);
            if (footers.odd != null)
                documents.Add(footers.odd.Xml);
            if (footers.even != null)
                documents.Add(footers.even.Xml);
            #endregion
 
            // Process each document in the list.
            foreach (XElement doc in documents)
            {
                #region Word 2010+
                foreach (XElement e in doc.Descendants(XName.Get("instrText", w.NamespaceName)))
                {
                    string attr_value = e.Value.Replace(" ", string.Empty).Trim();
                    string match_value = string.Format(@"DOCPROPERTY  {0}  \* MERGEFORMAT", customPropertyName).Replace(" ", string.Empty);
 
                    if (attr_value.Equals(match_value, StringComparison.CurrentCultureIgnoreCase))
                    {
                        XNode node = e.Parent.NextNode;
                        bool found = false;
                        while (true)
                        {
                            if (node.NodeType == XmlNodeType.Element)
                            {
                                var ele = node as XElement;
                                var match = ele.Descendants(XName.Get("t", w.NamespaceName));
                                if (match.Count() > 0)
                                {
                                    if (!found)
                                    {
                                        match.First().Value = customPropertyValue;
                                        found = true;
                                    }
                                    else
                                    {
                                        ele.RemoveNodes();
                                    }
                                }
                                else
                                {
                                    match = ele.Descendants(XName.Get("fldChar", w.NamespaceName));
                                    if (match.Count() > 0)
                                    {
                                        var endMatch = match.First().Attribute(XName.Get("fldCharType", w.NamespaceName));
                                        if (endMatch != null && endMatch.Value == "end")
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                            node = node.NextNode;
                        }
                    }
                }
            #endregion
 
                #region < Word 2010
                foreach (XElement e in doc.Descendants(XName.Get("fldSimple", w.NamespaceName)))
                {
                    string attr_value = e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Replace(" ", string.Empty).Trim();
                    string match_value = string.Format(@"DOCPROPERTY  {0}  \* MERGEFORMAT", customPropertyName).Replace(" ", string.Empty);
 
                    if (attr_value.Equals(match_value, StringComparison.CurrentCultureIgnoreCase))
                    {
                        XElement firstRun = e.Element(w + "r");
                        XElement firstText = firstRun.Element(w + "t");
                        XElement rPr = firstText.Element(w + "rPr");
 
                        // Delete everything and insert updated text value
                        e.RemoveNodes();
 
                        XElement t = new XElement(w + "t", rPr, customPropertyValue);
                        Novacode.Text.PreserveSpace(t);
                        e.Add(new XElement(firstRun.Name, firstRun.Attributes(), firstRun.Element(XName.Get("rPr", w.NamespaceName)), t));
                    }
                }
                #endregion
            }
        }
 
        public override Paragraph InsertParagraph()
        {
            Paragraph p = base.InsertParagraph();
            p.PackagePart = mainPart;
            return p;
        }
 
        public override Paragraph InsertParagraph(int index, string text, bool trackChanges)
        {
            Paragraph p = base.InsertParagraph(index, text, trackChanges);
            p.PackagePart = mainPart;
            return p;
        }
 
        public override Paragraph InsertParagraph(Paragraph p)
        {
            p.PackagePart = mainPart;
            return base.InsertParagraph(p);
        }
 
        public override Paragraph InsertParagraph(int index, Paragraph p)
        {
            p.PackagePart = mainPart;
            return base.InsertParagraph(index, p);
        }
 
        public override Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
        {
            Paragraph p = base.InsertParagraph(index, text, trackChanges, formatting);
            p.PackagePart = mainPart;
            return p;
        }
 
        public override Paragraph InsertParagraph(string text)
        {
            Paragraph p = base.InsertParagraph(text);
            p.PackagePart = mainPart;
            return p;
        }
 
        public override Paragraph InsertParagraph(string text, bool trackChanges)
        {
            Paragraph p = base.InsertParagraph(text, trackChanges);
            p.PackagePart = mainPart;
            return p;
        }
 
        public override Paragraph InsertParagraph(string text, bool trackChanges, Formatting formatting)
        {
            Paragraph p = base.InsertParagraph(text, trackChanges, formatting);
            p.PackagePart = mainPart;
 
            return p;
        }
 
        public Paragraph[] InsertParagraphs(string text)
        {
            String[] textArray = text.Split('\n');
            List<Paragraph> paragraphs = new List<Paragraph>();
            foreach (var textForParagraph in textArray)
            {
                Paragraph p = base.InsertParagraph(text);
                p.PackagePart = mainPart;
                paragraphs.Add(p);
            }
            return paragraphs.ToArray();
        }
 
        public override List<Paragraph> Paragraphs
        {
            get
            {
                List<Paragraph> l = base.Paragraphs;
                l.ForEach(x => x.PackagePart = mainPart);
                return l;
            }
        }
 
        public override List<Table> Tables
        {
            get
            {
                List<Table> l = base.Tables;
                l.ForEach(x => x.mainPart = mainPart);
                return l;
            }
        }
 
        /// <summary>
        /// Create an equation and insert it in the new paragraph
        /// </summary>        
        public override Paragraph InsertEquation(String equation)
        {
            Paragraph p = base.InsertEquation(equation);
            p.PackagePart = mainPart;
            return p;
        }
 
        /// <summary>
        /// Insert a chart in document
        /// </summary>
        public void InsertChart(Chart chart)
        {
            // Create a new chart part uri.
            String chartPartUriPath = String.Empty;
            Int32 chartIndex = 1;
            do
            {
                chartPartUriPath = String.Format
                (
                    "/word/charts/chart{0}.xml",
                    chartIndex
                );
                chartIndex++;
            } while (package.PartExists(new Uri(chartPartUriPath, UriKind.Relative)));
 
            // Create chart part.
            PackagePart chartPackagePart = package.CreatePart(new Uri(chartPartUriPath, UriKind.Relative), "application/vnd.openxmlformats-officedocument.drawingml.chart+xml");
 
            // Create a new chart relationship
            String relID = GetNextFreeRelationshipID();
            PackageRelationship rel = mainPart.CreateRelationship(chartPackagePart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart", relID);
 
            // Save a chart info the chartPackagePart
            using (TextWriter tw = new StreamWriter(chartPackagePart.GetStream(FileMode.Create, FileAccess.Write)))
                chart.Xml.Save(tw);
 
            // Insert a new chart into a paragraph.
            Paragraph p = InsertParagraph();
            XElement chartElement = new XElement(
                XName.Get("r", DocX.w.NamespaceName),
                new XElement(
                    XName.Get("drawing", DocX.w.NamespaceName),
                    new XElement(
                        XName.Get("inline", DocX.wp.NamespaceName),
                        new XElement(XName.Get("extent", DocX.wp.NamespaceName), new XAttribute("cx", "5486400"), new XAttribute("cy", "3200400")),
                        new XElement(XName.Get("effectExtent", DocX.wp.NamespaceName), new XAttribute("l", "0"), new XAttribute("t", "0"), new XAttribute("r", "19050"), new XAttribute("b", "19050")),
                        new XElement(XName.Get("docPr", DocX.wp.NamespaceName), new XAttribute("id", "1"), new XAttribute("name", "chart")),
                        new XElement(
                            XName.Get("graphic", DocX.a.NamespaceName),
                            new XElement(
                                XName.Get("graphicData", DocX.a.NamespaceName),
                                new XAttribute("uri", DocX.c.NamespaceName),
                                new XElement(
                                    XName.Get("chart", DocX.c.NamespaceName),
                                    new XAttribute(XName.Get("id", DocX.r.NamespaceName), relID)
                                )
                            )
                        )
                    )
               ));
            p.Xml.Add(chartElement);
        }
 
        #region IDisposable Members
 
        /// <summary>
        /// Releases all resources used by this document.
        /// </summary>
        /// <example>
        /// If you take advantage of the using keyword, Dispose() is automatically called for you.
        /// <code>
        /// // Load document.
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///      // The document is only in memory while in this scope.
        ///
        /// }// Dispose() is automatically called at this point.
        /// </code>
        /// </example>
        /// <example>
        /// This example is equilivant to the one above example.
        /// <code>
        /// // Load document.
        /// DocX document = DocX.Load(@"C:\Example\Test.docx");
        /// 
        /// // Do something with the document here.
        ///
        /// // Dispose of the document.
        /// document.Dispose();
        /// </code>
        /// </example>
        public void Dispose()
        {
            package.Close();
        }
 
        #endregion
    }
}