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
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Error};
use std::path::{Path, PathBuf};
use std::{fs, io};

// for toml stuff
use serde::Deserialize;

#[derive(Deserialize, Debug)]
pub struct Config {
    indentation: Option<usize>,
    src: Option<PathBuf>,
    dest: Option<PathBuf>,
    html_void: Option<Vec<String>>,
    template: Option<Template>,
}
#[derive(Deserialize, Debug)]
struct Template {
    enable: Option<bool>,
    general: Option<PathBuf>,
    order: Option<Vec<String>>,
}

// for converiubng
#[derive(Debug, Clone)]
struct NodeData {
    // h1/p/pre/etc
    // plain text is none
    tag: String,

    // any misc data, depends on teh tag
    misc: Option<String>,
    // the raw data inside this node
    text: Option<String>,

    contents: Vec<NodeData>,
}

#[derive(Debug, Clone)]
struct ReferenceLink {
    reference: String,
    url: String,
    title: Option<String>,
}

#[derive(Debug)]
pub struct Converter {
    html_void: Vec<String>,
    references: HashMap<String, ReferenceLink>,
    indentation: usize,
    src: PathBuf,
    dest: PathBuf,
    template: ConverterTemplate,
}

#[derive(Debug, Clone)]
struct ConverterTemplate {
    enable: bool,
    general: Option<PathBuf>,
    order: Vec<String>,
}

#[derive(Debug)]
struct DefaultTemplateRow<'a> {
    data: &'a str,
    depth: usize,
}

impl Converter {
    // takes the external config if provided and returns an isntance of itself
    pub fn new(config_override: Option<Config>) -> Converter {
        // see if there is a config file

        // defaults set here
        let mut indentation: usize = 2;
        let mut html_void = vec![
            "area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen",
            "link", "meta", "param", "source", "track", "wbr",
        ]
        .iter()
        .map(|item| item.to_string())
        .collect::<Vec<String>>();

        let mut src: PathBuf = "./src".parse().unwrap();
        let mut dest: PathBuf = "./build".parse().unwrap();

        let mut template = ConverterTemplate {
            enable: false,
            general: None,
            order: vec![],
        };

        if let Some(config) = config_override {
            if let Some(value) = config.html_void {
                html_void = value;
            }
            if let Some(value) = config.indentation {
                indentation = value;
            }
            if let Some(value) = config.src {
                src = value;
            }
            if let Some(value) = config.dest {
                dest = value;
            }

            if let Some(template_file) = config.template {
                if let Some(value) = template_file.enable {
                    template.enable = value
                }
                // this is an option anyways
                template.general = template_file.general;

                if let Some(value) = template_file.order {
                    template.order = value
                }
            }
        }

        Converter {
            html_void,
            references: Default::default(),
            indentation,
            src,
            dest,
            template,
        }
    }

    // this manages the conversion
    pub fn convert(&mut self) -> Result<(), Error> {
        // wipe the existing dest folder
        fs::remove_dir_all(&self.dest)?;

        // get all teh files in teh specified folder
        let files = Converter::file_find_markdown(&self.src)?;

        self.copy_css(&self.src)?;

        // iterate through the files  replacing the extention, the src to dest
        for file in files {
            let src = file.clone();

            let mut dest = if let Ok(stripped) = file.clone().strip_prefix(&self.src) {
                Path::new(&self.dest).join(stripped)
            } else {
                // if the prefix cannot be stripped then put in the output files beside teh in
                // though considering that its based of of src this should never be called
                file.clone()
            };
            dest.set_extension("html");

            // we know the src folders exist, but check if the dest ones do
            if let Some(parent) = dest.parent() {
                fs::create_dir_all(parent)?
            }

            // send it to the converter function
            self.convert_file(&src, &dest)?;
        }

        Ok(())
    }

    pub fn convert_file(&mut self, input: &PathBuf, output: &PathBuf) -> Result<(), Error> {
        // read file into memory
        let lines = Converter::file_read(input)?;

        // grab the reference lines out of it
        let lines_processed_references = self.reference_link_get(lines);

        // get teh block elements
        let blocks = self.block_process(lines_processed_references, true)?;

        // get teh template, if applicable
        let (template, depth) = self.template_get(input);

        // merge it all together
        let processed = self.block_merge(blocks, depth);

        // merge template and processed
        let merged = self.template_merge(input, processed, template);

        // save
        Converter::file_write(merged, output)?;

        // clean up references
        self.references = Default::default();

        Ok(())
    }

    fn file_find_markdown(dir: &Path) -> io::Result<Vec<PathBuf>> {
        let mut markdown_files: Vec<PathBuf> = vec![];
        if dir.is_dir() {
            for entry in fs::read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_dir() {
                    let subfiles = Converter::file_find_markdown(&path)?;
                    markdown_files.extend(subfiles);
                } else {
                    // check if it ends with .md
                    if let Some(extension) = path.extension() {
                        if extension == "md" {
                            markdown_files.push(path)
                        }
                    }
                }
            }
        }
        Ok(markdown_files)
    }

    fn copy_css(&self, dir: &Path) -> io::Result<()> {
        if dir.is_dir() {
            for entry in fs::read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_dir() {
                    Converter::file_find_markdown(&path)?;
                } else {
                    // check if it ends with .css
                    if let Some(extension) = path.extension() {
                        if extension == "css" {
                            // grab the file

                            let dest = if let Ok(stripped) = path.clone().strip_prefix(&self.src) {
                                Path::new(&self.dest).join(stripped)
                            } else {
                                // if the prefix cannot be stripped then put in the output files beside teh in
                                // though considering that its based of of src this should never be called
                                path.clone()
                            };

                            // make sure it has a folder ot go into
                            if let Some(parent) = dest.parent() {
                                fs::create_dir_all(parent)?
                            }

                            fs::copy(&path, &dest)?;
                        }
                    }
                }
            }
        }
        Ok(())
    }

    // load the file into working memory
    fn file_read(path: &PathBuf) -> Result<Vec<String>, Error> {
        // read file into memory
        //println!("In file {}", path);
        // read the file into menory
        let input = File::open(path)?;
        let buffered = BufReader::new(input);

        let lines_all = buffered
            .lines()
            .map(|l| {
                let unwrapped = l.expect("Could not parse line");
                unwrapped.replace("\u{0000}", "\u{FFFD}")
            })
            .collect::<Vec<String>>();

        Ok(lines_all)
    }

    fn file_write(content: String, path: &PathBuf) -> Result<(), Error> {
        fs::write(path, content)?;
        Ok(())
    }

    fn template_get(&self, input: &PathBuf) -> (Option<String>, usize) {
        if !self.template.enable {
            (None, 0)
        } else {
            let mut use_default = false;

            for item in &self.template.order {
                match item.as_str() {
                    "adjacent" => {
                        // check for <path>/<name>.html
                        let mut input_test = input.clone();
                        input_test.set_extension("html");

                        if let Ok(template_file) = fs::read_to_string(input_test) {
                            return (Some(template_file), 1);
                        }
                    }
                    "general" => {
                        // see if genearal is set in teh config
                        if let Some(general_path) = &self.template.general {
                            // then see if that files actually exists
                            if let Ok(template_file) = fs::read_to_string(general_path) {
                                return (Some(template_file), 1);
                            }
                        }
                    }
                    "folder" => {
                        // in the folder that the md file is in check if there is a .html file with the same name as the parent
                        let path = input.clone();
                        // yes this looks cursed to me too

                        if let Some(parent) = path.parent() {
                            if let Some(parent_name) = parent.file_name() {
                                let mut to_be_tested = PathBuf::from(parent_name);
                                to_be_tested.set_extension("html");

                                if let Ok(template_file) = fs::read_to_string(to_be_tested) {
                                    return (Some(template_file), 1);
                                }
                            }
                        }
                    }
                    "default" => {
                        use_default = true;
                        break;
                    }
                    _ => {}
                }
            }

            if use_default {
                let default_data: Vec<DefaultTemplateRow> = vec![
                    DefaultTemplateRow {
                        data: "<!DOCTYPE html>",
                        depth: 0,
                    },
                    DefaultTemplateRow {
                        data: "<html lang='en'>",
                        depth: 0,
                    },
                    DefaultTemplateRow {
                        data: "<head>",
                        depth: 1,
                    },
                    DefaultTemplateRow {
                        data: "<title>{title}</title>",
                        depth: 2,
                    },
                    DefaultTemplateRow {
                        data: "</head>",
                        depth: 1,
                    },
                    DefaultTemplateRow {
                        data: "<body>",
                        depth: 1,
                    },
                    // handled by the processor itself
                    DefaultTemplateRow {
                        data: "{body}",
                        depth: 0,
                    },
                    DefaultTemplateRow {
                        data: "</body>",
                        depth: 1,
                    },
                    DefaultTemplateRow {
                        data: "</html>",
                        depth: 0,
                    },
                ];

                let mut tmp = vec![];

                // add in teh appropriate indentation
                for row in default_data {
                    let indented = format!(
                        "{:indent$}{}",
                        "",
                        row.data,
                        indent = (row.depth * self.indentation)
                    );
                    tmp.push(indented);
                }
                let template_default = tmp.join("\n");

                return (Some(template_default), 1);
            }

            // fallback to none
            (None, 0)
        }
    }

    fn template_merge(
        &self,
        input: &PathBuf,
        processed: String,
        template: Option<String>,
    ) -> String {
        if let Some(template_string) = template {
            // use the file name for the title
            let mut input_test = input.clone();
            input_test.set_extension("");

            let title = if let Some(file_name) = input_test.file_name() {
                if let Some(result) = file_name.to_str() {
                    result
                } else {
                    ""
                }
            } else {
                ""
            };

            // replace teh title and the body
            template_string
                .replace("{title}", title)
                .replace("{body}", &*processed)
        } else {
            // no template, just return teh processed right back
            processed
        }
    }

    fn reference_link_get(&mut self, lines: Vec<String>) -> Vec<String> {
        let mut result: Vec<String> = vec![];

        // iterate through the lines
        // if one matches the format it is not added to rteh reesult and added to teh link hash, if its not already there

        let mut references: HashMap<String, ReferenceLink> = HashMap::new();

        'outer: for line in lines {
            // only lines that start with [ are considered reference, number of spaces is irrelevent
            if !line.trim_start().starts_with('[') {
                result.push(line);
                continue;
            }

            // now check of the rest of the line matches

            // form manging position
            let characters: Vec<char> = line.trim_start().chars().collect();
            // starts at 1 to skip the first [
            let mut index_char = 1;

            // for getting teh identifiuer
            let mut reference_vec: Vec<char> = vec![];
            loop {
                if index_char >= characters.len() {
                    break;
                }

                let character = characters[index_char];

                match character {
                    ']' => {
                        // check if last character is a backslash
                        if characters[index_char - 1] == '\\' {
                            // remove teh slash
                            // add the bracket
                            reference_vec.pop();
                            reference_vec.push(character);
                        } else {
                            // incriment to account for this
                            index_char += 1;
                            break;
                        }
                    }
                    _ => reference_vec.push(character),
                }
                index_char += 1;
            }

            // need to havea n identifier
            if reference_vec.is_empty() {
                result.push(line);
                continue 'outer;
            }

            // check if next character is ':' (required)
            if index_char >= characters.len() {
                result.push(line);
                continue 'outer;
            }
            if characters[index_char] != ':' {
                // add to normal output
                result.push(line);
                continue 'outer;
            } else {
                // if ir is :
                index_char += 1;
            }

            // check if next character is whitespace, skip past tehse
            loop {
                if index_char >= characters.len() {
                    break;
                }
                let character = characters[index_char];

                if character == ' ' || character == '\t' {
                    index_char += 1;
                } else {
                    break;
                }
            }

            // now get teh url
            let mut url_vec: Vec<char> = vec![];
            // (start, end)
            let mut angle_brackets = (false, false);
            loop {
                if index_char >= characters.len() {
                    break;
                }
                let character = characters[index_char];

                match character {
                    '<' => {
                        // opening is only alloweed on teh first chr
                        if !angle_brackets.0 {
                            angle_brackets = (true, false);
                        } else {
                            url_vec.push(character)
                        }
                    }
                    '>' => {
                        // check if it was opened
                        if angle_brackets.0 {
                            // then this closes it out

                            // check if its presseded by backslash, its action is ignored
                            if characters[index_char - 1] == '\\' {
                                // remove teh slash
                                url_vec.pop();
                                url_vec.push(character);
                            } else {
                                // actually closes it out
                                angle_brackets = (true, true);

                                index_char += 1;
                                break;
                            }
                        } else {
                            url_vec.push(character);
                        }
                    }
                    ' ' | '\t' => {
                        // space breaks the url, unless its in an angled bracket

                        if angle_brackets.0 {
                            url_vec.push(character)
                        } else {
                            break;
                        }
                    }

                    _ => url_vec.push(character),
                }

                index_char += 1;
            }

            if url_vec.is_empty() {
                // check if its angle brackets
                if !angle_brackets.1 {
                    result.push(line);
                    continue 'outer;
                }
            }

            // if angle brackets were opened but never closed
            if angle_brackets.0 && !angle_brackets.1 {
                result.push(line);
                continue 'outer;
            }

            // check for whitespace again, but this time it must be at least 1 if its followed by an open quotation
            let mut whitespace = 0;
            loop {
                if index_char >= characters.len() {
                    break;
                }
                let character = characters[index_char];

                match character {
                    ' ' | '\t' => {
                        index_char += 1;
                        whitespace += 1;
                    }
                    '\'' | '"' => {
                        if whitespace == 0 {
                            result.push(line);
                            continue 'outer;
                        } else {
                            break;
                        }
                    }
                    _ => break,
                }
            }

            // find the optional title next

            // first char must be eitehr ' or "

            let mut title_quote: Option<char> = None;
            if index_char < characters.len() {
                let character = characters[index_char];
                match character {
                    '\'' | '"' => title_quote = Some(character),
                    _ => {}
                }
                index_char += 1;
            }

            let mut title_vec: Vec<char> = vec![];

            if let Some(delimiter) = title_quote {
                // starts off being opened
                let mut title_closed = false;

                loop {
                    if index_char >= characters.len() {
                        break;
                    }
                    let character = characters[index_char];

                    if character == delimiter {
                        // check if preceding was backslash

                        if characters[index_char - 1] == '\\' {
                            // remove teh slash
                            // add the bracket
                            title_vec.pop();
                            title_vec.push(character);
                        } else {
                            title_closed = true;

                            // increment to account for this
                            //index_char += 1;
                            break;
                        }
                    } else {
                        title_vec.push(character)
                    }

                    index_char += 1;
                }

                // check if it was closed properly
                if !title_closed {
                    // title is optional so just clear it instead of revoking teh line
                    title_vec = vec![];
                }
            }

            // tidy up
            let reference: String = reference_vec.iter().collect();
            let url: String = url_vec.iter().collect();

            let title: Option<String> = if title_vec.is_empty() {
                None
            } else {
                Some(title_vec.iter().collect())
            };

            let reference_data = ReferenceLink {
                reference: reference.clone(),
                url,
                title,
            };

            references.insert(reference, reference_data);
        }

        self.references = references;

        result
    }

    fn block_process(&self, lines: Vec<String>, _top_layer: bool) -> Result<Vec<NodeData>, Error> {
        // this gets most of the structure done

        // what gets returned
        let mut node_data: Vec<NodeData> = vec![];

        // these handle dealing with teh current lines
        let mut row: isize = 0;

        // These keep track of info about the current block
        let mut block_type: Option<String> = None;
        let mut block_start: usize = 0;
        let mut block_lines: Vec<String> = vec![];
        let mut block_excluded: Vec<String> = vec![];

        // specific for code blocks
        let mut pre_language: Option<String> = None;
        let mut pre_closer: String = Default::default();

        // soecificallyt for OL and ul lists
        let mut lists_lines: Vec<NodeData> = vec![];
        let mut lists_indent = 0;
        let mut lists_number: Option<String> = None;

        // for html tags, need to use this to find the closing tag
        let mut html_closing: Option<Vec<char>> = None;
        let mut html_tag = "".to_string();
        // sets the position a html tag ended on, if its nto teh whole line
        // (row, col)
        let mut html_end_col = (0, 0);
        let mut html_start = vec![];
        let mut html_depth = 0;

        let mut table_header_length = 0;
        let mut table_header: Vec<NodeData> = vec![];
        let mut table_rows: Vec<NodeData> = vec![];
        let mut table_alignment: HashMap<i32, String> = HashMap::new();

        'main: loop {
            // ensure that row is in bounds
            if row >= lines.len() as isize {
                break;
            }

            let line = if html_end_col.0 == row && html_end_col.1 != 0 {
                &lines[row as usize][html_end_col.1..]
            } else {
                lines[row as usize].as_str()
            };

            // check what type of line it is
            let line_current_type = Converter::block_process_line_type(line, &block_excluded);
            // check if the current line is teh last line
            let line_current_is_end = (row + 1) >= (lines.len() as isize);

            //println!("Start:  Top: {}. Row {} of {}. Block: {:?}, Current Line: {}. Line: {}. End?: {}", _top_layer, row, lines.len(), block_type, line_current_type.0, line, line_current_is_end);

            let mut block_finished = false;
            let mut block_reset = false;

            // block specific stuff

            let mut finished_p = false;
            let mut finished_pre = false;
            let mut finished_blockquote = false;

            let mut finished_xl = false;
            let mut finished_li = false;

            let mut finished_html = false;

            let mut finished_table = false;

            // now process based on what type of line it is
            match &block_type {
                // this handles first lines of everything
                None => {
                    // first line of the block, make sure the tmp array is cleared
                    block_lines = vec![];

                    // set the block start as well
                    block_start = row as usize;

                    // h and hr are inline and reset line_type after
                    match &line_current_type.0.as_str() {
                        &"h" => {
                            let mut count = 0;
                            let mut broken = false;
                            let mut content_array: Vec<char> = vec![];
                            for character in line.trim().chars() {
                                match character {
                                    // skip this one
                                    '#' => {
                                        if !broken && count < 6 {
                                            count += 1
                                        } else {
                                            content_array.push(character);
                                        }
                                    }
                                    // break on a space or closing tag <br/>
                                    _ => {
                                        broken = true;
                                        content_array.push(character);
                                    }
                                }
                            }

                            // for this the tag is depending on teh numebr of #'s at the beginning
                            let tag = format!("h{}", &count);

                            // clean si the raw with teh tag elements removed
                            let content_string = content_array.to_vec().iter().collect::<String>();
                            let text = Some(content_string.as_str().trim().to_string());

                            // add the data
                            node_data.push(NodeData {
                                tag,
                                text,
                                misc: None,
                                contents: vec![],
                            });

                            // reset it here
                            block_type = None;

                            // go straight to the next row
                            row += 1;
                            continue;
                        }
                        &"hr" => {
                            node_data.push(NodeData {
                                tag: "hr".to_string(),
                                text: None,
                                misc: None,
                                contents: vec![],
                            });
                            block_type = None;

                            // go straight to the next row
                            row += 1;
                            continue;
                        }

                        // blocks from here on out
                        // paragraph is the kinda catch all
                        &"p" => {
                            // paragraph is the catch all here
                            // anything that isnt caught in opther blocks ends up ehre

                            // first line of a paragraph

                            // check if tis whitespace, if it is then skip this line
                            // will still be None next time round
                            if line == "" {
                                row += 1;
                                continue;
                            }

                            let line_to_push = if block_excluded.contains(&"html".to_string())
                                || block_excluded.contains(&"html_comment".to_string())
                                || block_excluded.contains(&"html_cdata".to_string())
                            {
                                // strip first < from it, &gt;
                                line.replacen("<", "&gt;", 1).to_string()
                            } else {
                                line.to_string()
                            };

                            // add it to the tmp array
                            block_lines.push(line_to_push);

                            block_type = Some(line_current_type.0);

                            // no need for block_start as this is to catch teh dregs
                        }
                        &"pre" => {
                            // first line of pre
                            // only setting up the block,

                            // get the language
                            let mut pre_language_tmp: Vec<char> = vec![];
                            let mut closer: Vec<char> = vec![];
                            let mut space = false;
                            for character in line.trim().chars() {
                                match character {
                                    // skip this one
                                    '`' => {
                                        if !space {
                                            closer.push(character)
                                        }

                                        continue;
                                    }
                                    ' ' | '\t' => {
                                        // first one mark it as a space
                                        if !space {
                                            space = true;
                                        } else {
                                            pre_language_tmp.push(character);
                                        }
                                    }
                                    _ => {
                                        pre_language_tmp.push(character);
                                    }
                                }
                            }
                            pre_language = if pre_language_tmp.is_empty() {
                                None
                            } else {
                                let language = pre_language_tmp
                                    .iter()
                                    .collect::<String>()
                                    .trim()
                                    .to_string();

                                pre_closer = closer.iter().collect::<String>().trim().to_string();
                                if language == "" {
                                    None
                                } else {
                                    Some(language)
                                }
                            };

                            // set the block type
                            block_type = Some(line_current_type.0);
                        }

                        &"blockquote" => {
                            // like the p but every line is prefixed by >
                            // sort out the sub blocks when it is finished

                            // remove the first >
                            // add it to the tmp array
                            let cleaned = line.replacen(">", "", 1).replacen(" ", "", 1);
                            block_lines.push(cleaned);

                            // set the block type
                            block_type = Some(line_current_type.0);
                        }

                        &"ul*" | &"ul-" | &"ul+" => {
                            // * and -
                            // strip
                            let trimmed = line.trim_start();
                            let cleaned = if trimmed.starts_with("* ") {
                                trimmed.replacen("* ", "", 1)
                            } else {
                                trimmed.replacen("- ", "", 1)
                            };
                            block_lines.push(cleaned);

                            lists_indent = line_current_type.1.unwrap();

                            // set the block type
                            block_type = Some(line_current_type.0);
                        }

                        &"ol" => {
                            let vec_chars: Vec<char> = line.chars().collect();

                            // remove lists_indent's worth ofd characters
                            // let cleaned
                            let content_start = line_current_type.1.unwrap();
                            let trimmed = &vec_chars[content_start..];
                            let cleaned = trimmed.iter().collect::<String>();

                            block_lines.push(cleaned);

                            lists_indent = line_current_type.1.unwrap();

                            // only used for numbered lists
                            lists_number = Some(line_current_type.2.unwrap().to_string());

                            // set the block type
                            block_type = Some(line_current_type.0);
                        }

                        // html_php/html_comment/html_cdata
                        &"html" => {
                            /*

                            // commonmarks html stuff is basically a warcrime
                            // for example this breaks what you would expect https://spec.commonmark.org/0.30/#example-148
                            // best way I can figure doing this is to not have markdown in html, all html gets passed through.
                            // yes I know this is opinionated but it evades the issue in the example above
                            // Adding HTML to a markdown document should override the markdown, not teh other way round
                            // Some safety nets are removed like verifying urls are valid



                            // clean - tag starts on a new line and nothing after the closing tag
                            // one html block
                            // <tag>
                            // </tag>

                            // follwwed by html - a new html tag starts after this one,
                            // counts as two seperate html blocks
                            // <tag>
                            // </tag><tag2>
                            // </tag2>

                            // inline 1 - anything that would be classified as a paragraph after the tag
                            // all part of same paragraph block - html not touched by paragraph processing
                            // <tag></tag> same line

                            // inline 2 - anything that would be classified as a paragraph after the tag
                            // all part of same paragraph block - html not touched by paragraph processing
                            // <tag>
                            // </tag> same line as closing tag

                            // a line starting with < can be either be a html tag or an escaped url
                            // <tag></tag>
                            // <tag />
                            // not going to check if the url is valid, thats up to teh browser
                            // <protocol:url>
                            // <user@url>

                            */

                            // type of tag isnt known here

                            // this fuirst line is to find the tag name
                            let mut tag_vec: Vec<char> = vec![];

                            // 1 to skip the opening < in teh first run
                            let mut index = 1;
                            let line_chars: Vec<char> = line.chars().collect();
                            loop {
                                if index >= line_chars.len() {
                                    break;
                                }

                                let character = line_chars[index];

                                // set it to be used next round
                                index += 1;
                                match character {
                                    'a'..='z' | 'A'..='Z' | '0'..='9' => {
                                        tag_vec.push(character);
                                    }
                                    ':' => {
                                        // checkl to see if its a url
                                        if tag_vec.is_empty() {
                                            // if it is then go straight back to reprocessing it
                                            block_excluded.push(line_current_type.0);
                                            continue 'main;
                                        } else {
                                            break;
                                        }
                                    }
                                    _ => {
                                        // not a valid tag character
                                        break;
                                    }
                                }
                            }

                            // not a valid tag
                            if tag_vec.is_empty() {
                                // repeat teh current line, but not as a html tag
                                block_excluded.push(line_current_type.0);
                                continue;
                            }

                            // use html_void to see what type of closing it has
                            // if its in html_void then its />
                            // else its </tag>

                            let tag: String = tag_vec.iter().collect();

                            // check for nestled html
                            // <div>1<div>2</div></div>
                            //html_depth += 1;
                            html_start.push('<');
                            html_start.extend(&tag_vec);

                            // these are the self-closing tags
                            if self.html_void.contains(&tag) {
                                html_closing = Some(vec!['/', '>']);
                            } else {
                                let mut tmp = vec!['<', '/'];
                                tmp.extend(&tag_vec);
                                tmp.push('>');
                                html_closing = Some(tmp);
                            }

                            // set the type for the next round
                            // html_php/html_comment/html_cdata are handled by html in teh second round,
                            // only needed to be broken out in teh first round to deal with setting teh different end condition
                            block_type = Some(line_current_type.0);

                            // set the tag to be used lated for banned/permitted tags
                            html_tag = tag;
                        }

                        // these are much teh same as html, byt can skip directly to knowing teh closing tag
                        &"html_comment" => {
                            // -->
                            html_start = vec!['<', '!', '-', '-'];
                            html_closing = Some(vec!['-', '-', '>']);
                            block_type = Some(line_current_type.0);
                            html_tag = "custom_comment".to_string();
                        }

                        &"html_cdata" => {
                            // ]]>
                            html_start = vec!['<', '!', '[', 'C', 'D', 'A', 'T', 'A', '['];
                            html_closing = Some(vec![']', ']', '>']);
                            block_type = Some(line_current_type.0);
                            html_tag = "custom_cdata".to_string();
                        }

                        &"table" => {
                            /*
                            Mostly taken from https://github.github.com/gfm/#tables-extension- with a few changes:
                              First character on a line is always |, while a trailing | isnt explicity required it cna look better.
                              First like is always the header.
                                As a result no requirement for a delimiter line under it.
                                If you want multiple rows of headers, or spans please use a html table.
                              Delimiter lines are lines starting with |, with 1+ - 's, trailing | isnt required (like above) but does look better.
                                They are ignored in teh html, but make the table look better in markdown
                                All equal:
                                  |-
                                  |----------------|
                                  |--|---|----|----|
                              Table ends on teh first line not starting with |
                            */

                            // delimiter lines are ignored fo the table content
                            // but they do provide alignment
                            if line
                                .replace("|", "")
                                .replace("-", "")
                                .replace(":", "")
                                .trim()
                                == ""
                            {
                                // will use https://developer.mozilla.org/en-US/docs/Web/CSS/text-align as the way github does it is no longer valid

                                // alignment will impact subsequent lines, unless overwritten
                                table_alignment = Converter::block_process_table_alignment(line);

                                row += 1;
                                continue 'main;
                            }

                            let mut header_contents: Vec<NodeData> = vec![];

                            /*

                            from:
                            |th1|th2|..|thn

                            to:
                            NodeData {
                                tag: "th".to_string(),
                                misc: None,
                                text: Some("th1".to_string()),
                                contents: vec![
                                ]
                            },
                            */

                            // figure out how many headers there are

                            let mut content: Vec<char> = vec![];
                            let mut last_character: Option<char> = None;
                            for character in line.trim_end_matches('|').chars() {
                                match character {
                                    '|' => {
                                        if let Some(x) = last_character {
                                            if x == '\\' {
                                                // remove the backslash
                                                content.pop();
                                                content.push(character);
                                                last_character = Some(character);
                                                continue;
                                            }
                                        }

                                        if table_header_length > 0 {
                                            let text: String = content.iter().collect();
                                            let alignment = if let Some(x) =
                                                table_alignment.get(&(table_header_length as i32))
                                            {
                                                Some(x.clone())
                                            } else {
                                                None
                                            };

                                            // add current
                                            header_contents.push(NodeData {
                                                tag: "th".to_string(),
                                                misc: alignment,
                                                text: Some(text),
                                                contents: vec![],
                                            });
                                        }

                                        // add anotehr col
                                        table_header_length += 1;

                                        // clear teh existing data (since its previously used
                                        content = vec![];
                                    }
                                    _ => content.push(character),
                                }
                                last_character = Some(character);
                            }

                            // tidy up any trailing content
                            if !content.is_empty() {
                                let text: String = content.iter().collect();
                                let alignment = if let Some(x) =
                                    table_alignment.get(&(table_header_length as i32))
                                {
                                    Some(x.clone())
                                } else {
                                    None
                                };

                                // add current
                                header_contents.push(NodeData {
                                    tag: "th".to_string(),
                                    misc: alignment,
                                    text: Some(text),
                                    contents: vec![],
                                });
                            }

                            table_header.push(NodeData {
                                tag: "tr".to_string(),
                                misc: None,
                                text: None,
                                contents: header_contents,
                            });

                            block_type = Some(line_current_type.0);
                        }

                        _ => {
                            // just add it to teh array and deal with it when ti is finished
                            block_lines.push(line.to_string());

                            // mark it as a _ for teh next iteration
                            block_type = Some(line_current_type.0);
                        }
                    }
                }

                // this is second time+ round
                Some(line_type_previous) => {
                    let previous_line = line_type_previous.as_str();
                    match previous_line {
                        "p" => {
                            if &line_current_type.0 != "p" {
                                // if current line is not part of a paragraph
                                // dont add it to teh array
                                // go back one row to re-analyse it next run

                                // this is cancelled out later
                                row -= 1;

                                finished_p = true;
                            } else if line == "" {
                                // "" marks an empty line which is automatically the end of a paragraph
                                finished_p = true;
                            } else {
                                // normal action
                                block_lines.push(line.to_string());
                            };
                        }
                        "pre" => {
                            // trim line and check if it is the same as the opener
                            if line.trim() == pre_closer.as_str() {
                                // end of block, now tidy up
                                finished_pre = true;
                            } else {
                                // add the lines to teh block
                                block_lines.push(line.to_string());

                                // if its the last line then its caught alter down
                            }
                        }
                        "blockquote" => {
                            // like the paragraph there is no need to worry about reset as each line starts with >

                            if &line_current_type.0 != "blockquote" {
                                // dont add it to teh array
                                // go back one row to re-analyse it next run

                                // this is cancelled out later
                                row -= 1;

                                finished_blockquote = true;
                            } else {
                                let cleaned = line.replacen(">", "", 1).replacen(" ", "", 1);
                                block_lines.push(cleaned);
                            };
                        }
                        "ul*" | "ul-" | "ul+" | "ol" => {
                            // gotta do two things
                            // tody up teh current list entry block
                            // close out teh lsit

                            let indent_casted = lists_indent;
                            let leading_spaces =
                                String::from_utf8(vec![b' '; indent_casted]).unwrap();

                            if line.starts_with(&leading_spaces) {
                                // if it starts with lists_indent spaces its staying in teh same li
                                let trimmed = line.replacen(" ", "", indent_casted);
                                block_lines.push(trimmed);
                            } else if line == "" {
                                // if its "" its the same li
                                block_lines.push(line.to_string());
                            } else if line_current_type.0 == previous_line {
                                // if its ul then close up teh current li
                                // contents are not added to teh li
                                finished_li = true;

                                // repeat the current line next time
                                row -= 1;
                            } else {
                                // line is not part of the ul or li
                                // close out teh li and ul
                                finished_li = true;
                                finished_xl = true;

                                // reevaluate the line
                                row -= 1;
                            }
                        }

                        // html blocks
                        "html" | "html_comment" | "html_cdata" => {
                            // do nothing here, its handled below
                        }
                        "table" => {
                            if &line_current_type.0 != "table" {
                                // dont add it to teh array
                                // go back one row to re-analyse it next run

                                // this is cancelled out later
                                row -= 1;

                                finished_table = true;
                            } else {
                                // if its a delimiter then update the alignment, then skip to teh next row
                                if line
                                    .replace("|", "")
                                    .replace("-", "")
                                    .replace(":", "")
                                    .trim()
                                    == ""
                                {
                                    table_alignment =
                                        Converter::block_process_table_alignment(line);
                                    row += 1;
                                    continue 'main;
                                }

                                // process the current row
                                // can only have table_header_length cols, any less than that are filled in

                                let mut row_contents: Vec<NodeData> = vec![];

                                /*

                                from:
                                |cell1|cell2|..|celln

                                to:
                                NodeData {
                                    tag: "td".to_string(),
                                    misc: None,
                                    text: Some("th1".to_string()),
                                    contents: vec![
                                    ]
                                },
                                */

                                // figure out how many headers there are

                                let mut local_cols = 0;
                                let mut content: Vec<char> = vec![];
                                let mut last_character: Option<char> = None;
                                for character in line.chars() {
                                    match character {
                                        '|' => {
                                            // is this new col too many?
                                            if local_cols > table_header_length {
                                                content = vec![];
                                                break;
                                            }

                                            if let Some(x) = last_character {
                                                if x == '\\' {
                                                    // remove the backslash
                                                    content.pop();
                                                    content.push(character);
                                                    last_character = Some(character);
                                                    continue;
                                                }
                                            }

                                            // add previous data
                                            if local_cols > 0 {
                                                let text: String = content.iter().collect();
                                                let alignment = if let Some(x) =
                                                    table_alignment.get(&(local_cols as i32))
                                                {
                                                    Some(x.clone())
                                                } else {
                                                    None
                                                };

                                                // add current
                                                row_contents.push(NodeData {
                                                    tag: "td".to_string(),
                                                    misc: alignment,
                                                    text: Some(text),
                                                    contents: vec![],
                                                });
                                            }

                                            // add anotehr col
                                            local_cols += 1;

                                            // clear teh existing data (since its previously used
                                            content = vec![];
                                        }
                                        _ => content.push(character),
                                    }
                                }

                                // tidy up any trailing content
                                if !content.is_empty() {
                                    let text: String = content.iter().collect();
                                    let alignment = if let Some(x) =
                                        table_alignment.get(&(local_cols as i32))
                                    {
                                        Some(x.clone())
                                    } else {
                                        None
                                    };

                                    // add current
                                    row_contents.push(NodeData {
                                        tag: "td".to_string(),
                                        misc: alignment,
                                        text: Some(text),
                                        contents: vec![],
                                    });
                                }

                                // add in empty cells if its not up to teh header
                                while row_contents.len() < table_header_length {
                                    row_contents.push(NodeData {
                                        tag: "td".to_string(),
                                        misc: None,
                                        text: Some("".to_string()),
                                        contents: vec![],
                                    });
                                }

                                table_rows.push(NodeData {
                                    tag: "tr".to_string(),
                                    misc: None,
                                    text: None,
                                    contents: row_contents,
                                });
                            }
                        }

                        _ => {}
                    }
                }
            }

            // for specifically processing html blocks, fires off if there is a closing tag to match against
            if let Some(closing) = &html_closing {
                let mut index = 0;
                let line_chars: Vec<char> = line.chars().collect();

                let mut valid_chars_closing = 0;
                let mut valid_chars_opening = 0;
                loop {
                    if closing.is_empty() {
                        break;
                    }
                    if html_start.is_empty() {
                        break;
                    }
                    if index >= line_chars.len() {
                        break;
                    }

                    let character = line_chars[index];

                    // set it to be used next round
                    index += 1;

                    if html_start[valid_chars_opening] == character {
                        // character is valid,
                        valid_chars_opening += 1;

                        if valid_chars_opening == html_start.len() {
                            html_depth += 1;
                            valid_chars_opening = 0;
                        }
                    } else {
                        // reset
                        valid_chars_opening = 0;
                    }

                    if closing[valid_chars_closing] == character {
                        // character is valid,
                        valid_chars_closing += 1;

                        if valid_chars_closing == closing.len() {
                            html_depth -= 1;
                            if html_depth == 0 {
                                finished_html = true;
                                break;
                            }
                            // reset it
                            valid_chars_closing = 0;
                        }
                    } else {
                        // reset
                        valid_chars_closing = 0;
                    }
                }
                if finished_html {
                    let mut partial_line = false;
                    let mut permitted_in_p = false;
                    let forbidden_tag = false; // how handling forbidden tags would be

                    // check if there is anything left on teh line
                    if line[index..].trim() != "" {
                        partial_line = true;

                        // check if the tag is permitted in paragraphs
                        // https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#phrasing_content
                        // https://www.w3.org/TR/html52/dom.html#phrasing-content
                        let allowed_tags_p = vec![
                            // pure html stuff
                            "abbr",
                            "audio",
                            "b",
                            "button",
                            "canvas",
                            "cite",
                            "code",
                            "data",
                            "datalist",
                            "dfn",
                            "em",
                            "embed",
                            "i",
                            "iframe",
                            "img",
                            "input",
                            "label",
                            "mark",
                            "math",
                            "meter",
                            "noscript",
                            "object",
                            "output",
                            "picture",
                            "progress",
                            "q",
                            "ruby",
                            "samp",
                            "script",
                            "select",
                            "small",
                            "span",
                            "string",
                            "sub",
                            "sup",
                            "svg",
                            "textarea",
                            "time",
                            "u",
                            "var",
                            "video",
                            "wbr",
                            // according to dn these are not always applicable
                            "a",
                            "del",
                            "ins",
                            "map",
                            // these require an itemprop attribite, however not looking for these
                            // "link", "mata",

                            // these are the "custom" tags for misc heml stuff
                            "custom_comment",
                            "custom_cdata",
                        ];

                        if allowed_tags_p.contains(&html_tag.as_str()) {
                            permitted_in_p = true;
                        }
                    }

                    // add list of forbidden tags here

                    if forbidden_tag {
                        // if its forbidden then its not apssed through
                        // mark teh block as finished
                        block_finished = true;

                        // but dont do teh tidy up of the html tag
                        finished_html = false;
                    }

                    // tidy up the closing of html here
                    if partial_line {
                        if permitted_in_p {
                            // change the type to paragraph
                            block_type = Some("p".to_string());

                            // add whole line to teh array
                            block_lines.push(line.to_string());

                            // need to mark this as false as its going to be taken over as a paragraph enxxt round
                            finished_html = false;

                            // reset teh end col
                            html_end_col = (0, 0);
                        } else {
                            // teh first part is always added to teh tmp array
                            let tmp_line = &line[..index];
                            block_lines.push(tmp_line.to_string());

                            // decide what to do with teh rest

                            // get the type of the ramining line
                            // if its html or paragraph then its processed
                            // else it is completely skipped
                            let remaining = &line[index..];
                            let (line_next, _, _) =
                                Converter::block_process_line_type(remaining, &block_excluded);

                            match line_next.as_str() {
                                "p" | "html" | "html_comment" | "html_cdata" => {
                                    // other stuff after the html tag, mark the end here
                                    html_end_col = (row, index);

                                    // repeat this row to see the new stuff
                                    row -= 1;
                                }
                                _ => {
                                    // make sure the end col is reset back as its not html or a paragraph
                                    html_end_col = (0, 0);
                                }
                            }
                        }
                    } else {
                        // make sure teh end col is reset back
                        html_end_col = (0, 0);

                        // add whole line to teh array
                        block_lines.push(line.to_string());
                    }
                } else {
                    // add it like normal
                    block_lines.push(line.to_string());
                }
            }

            // to catch end of line stuff
            // specifically one liners
            if line_current_is_end {
                match &block_type {
                    None => {}
                    Some(line_type_previous) => match line_type_previous.as_str() {
                        "p" => {
                            finished_p = true;
                        }
                        "blockquote" => {
                            finished_blockquote = true;
                        }
                        "ul*" | "ul-" | "ul+" | "ol" => {
                            finished_li = true;
                            finished_xl = true;
                        }
                        "pre" => {
                            if !finished_pre {
                                block_reset = true;
                            }
                        }
                        "html" | "html_comment" | "html_cdata" => {
                            if !finished_html {
                                block_reset = true;
                            }
                        }
                        "table" => {
                            finished_table = true;
                        }
                        _ => {}
                    },
                }
            }

            // close out blocks

            if finished_p {
                node_data.push(NodeData {
                    tag: "p".to_string(),
                    text: Some(block_lines.join("\n")),
                    misc: None,
                    contents: vec![],
                });

                block_finished = true;
            }

            // not impacted by line_current_is_end, needs to have its closing tag
            if finished_pre {
                // replace every < with &lt;
                let text = block_lines.join("\n").replace("<", "&lt;").to_string();
                node_data.push(NodeData {
                    tag: "pre".to_string(),
                    text: Some(text),
                    misc: pre_language.to_owned(),
                    contents: vec![],
                });

                block_finished = true;
            }

            if finished_blockquote {
                let contents = self
                    .block_process(block_lines.clone(), false)
                    // if it errors then fail fairly gracefully
                    .unwrap_or_default();

                node_data.push(NodeData {
                    tag: "blockquote".to_string(),
                    text: None,
                    misc: None,
                    contents,
                });

                block_finished = true;
            }

            if finished_li {
                // block line is always >= 1
                if block_lines.len() == 1 {
                    // the li has text in it
                    lists_lines.push(NodeData {
                        tag: "li".to_string(),
                        text: Some(block_lines[0].to_owned()),
                        misc: lists_number.clone(),
                        contents: vec![],
                    });
                } else {
                    let contents = self
                        .block_process(block_lines.clone(), false)
                        // if it errors then fail fairly gracefully
                        .unwrap_or_default();

                    lists_lines.push(NodeData {
                        tag: "li".to_string(),
                        text: None,
                        misc: lists_number.clone(),
                        contents,
                    });
                }

                // only used temporary
                block_lines = vec![];
                block_type = None;
                //lists_number = None;
            }

            if finished_xl {
                // if a number is there then its a order list
                let list_type = match lists_number {
                    None => "ul".to_string(),
                    Some(_) => "ol".to_string(),
                };

                node_data.push(NodeData {
                    tag: list_type,
                    text: None,
                    misc: None,
                    contents: lists_lines.clone(),
                });

                // cleanup
                block_finished = true;
            }

            if finished_html {
                node_data.push(NodeData {
                    tag: "html".to_string(),
                    // gonna do no more processing on this, just going to pass it straight through
                    text: Some(block_lines.join("\n")),
                    misc: None,
                    contents: vec![],
                });
                // cleanup
                block_finished = true;
            }

            if finished_table {
                let table = NodeData {
                    tag: "table".to_string(),
                    misc: None,
                    text: None,
                    contents: vec![
                        NodeData {
                            tag: "thead".to_string(),
                            misc: None,
                            text: None,
                            contents: table_header.clone(),
                        },
                        NodeData {
                            tag: "tbody".to_string(),
                            misc: None,
                            text: None,
                            contents: table_rows.clone(),
                        },
                    ],
                };

                node_data.push(table);

                block_finished = true;
            }

            // handle resets first
            if block_reset {
                // reset row to teh start
                row = block_start as isize;

                // make sure it dosent come down this path again
                block_excluded.push(block_type.unwrap_or_default().to_owned());

                // reset blocktype
                block_type = None;

                pre_language = None;
                pre_closer = Default::default();

                // reset when not in use
                lists_lines = vec![];
                lists_indent = 0;
                lists_number = None;

                // html stuff
                html_closing = None;
                html_tag = "".to_string();
                html_start = vec![];
                html_depth = 0;

                // tables
                table_header = vec![];
                table_rows = vec![];
                table_header_length = 0;
                table_alignment = HashMap::new();

                // go back to start, do not pass go
                continue;
            }

            // do the cleanup for a finished block
            if block_finished {
                // if the block was anything but html then set the end col back to 0
                if let Some(x) = &block_type {
                    if !x.contains("html") {
                        html_end_col = (0, 0);
                    }
                }

                // reset the type
                block_type = None;
                block_lines = vec![];

                // clear teh exclusions
                block_excluded = vec![];

                // reset the language for pre blocks
                pre_language = None;
                pre_closer = Default::default();

                // reset when not in use
                lists_lines = vec![];
                lists_indent = 0;
                lists_number = None;

                // html stuff
                html_closing = None;
                html_tag = "".to_string();
                html_start = vec![];
                html_depth = 0;

                // tables
                table_header = vec![];
                table_rows = vec![];
                table_header_length = 0;
                table_alignment = HashMap::new();
            }

            // incriment
            // this may be returning to the same row
            row += 1;
        }
        Ok(node_data)
    }

    fn block_process_table_alignment(line: &str) -> HashMap<i32, String> {
        let mut alignment: HashMap<i32, String> = HashMap::new();

        let mut last_character: Option<char> = None;
        let mut start = false;
        let mut end = false;
        let mut counter = 0;
        for character in line.trim_end_matches('|').chars() {
            match character {
                '|' => {
                    // skip first character
                    if last_character.is_none() {
                        // dont forget to set it here
                        last_character = Some(character);
                        continue;
                    }

                    counter += 1;

                    if start && end {
                        alignment.insert(counter, "center".to_string());
                    } else if start {
                        alignment.insert(counter, "left".to_string());
                    } else if end {
                        alignment.insert(counter, "right".to_string());
                    } else {
                        // dont insert
                    }

                    // reset for next one
                    start = false;
                    end = false;
                }
                ':' => {
                    // if preceded by a space or bar then its a start

                    // if preceded by - then its a end

                    if let Some(last) = last_character {
                        if last == ' ' || last == '|' {
                            start = true;
                        }
                        if last == '-' {
                            end = true;
                        }
                    }
                }
                _ => {
                    // nothing should happen here
                }
            }

            last_character = Some(character);
        }

        counter += 1;
        // tidy up the trailing
        if start && end {
            alignment.insert(counter, "center".to_string());
        } else if start {
            alignment.insert(counter, "left".to_string());
        } else if end {
            alignment.insert(counter, "right".to_string());
        } else {
            // dont insert
        }

        alignment
    }

    // (type, indent, number)
    fn block_process_line_type(
        line: &str,
        excluded: &[String],
    ) -> (String, Option<usize>, Option<i32>) {
        let trimmed = line.trim();
        let paragraph = ("p".to_string(), None, None);

        if !excluded.contains(&"h".to_string()) && trimmed.starts_with('#') {
            ("h".to_string(), None, None)
        }
        // remove dashes and spaces
        // if the result is empty then its a hr
        // if not it will probally become a paragraph
        else if !excluded.contains(&"hr".to_string())
            && trimmed.starts_with("----")
            && line.replace("-", "").replace(" ", "").replace("\t", "") == ""
        {
            ("hr".to_string(), None, None)
        } else if line.starts_with('>') {
            // spoiler
            if line.starts_with(">!") {
                return paragraph;
            }

            if !excluded.contains(&"blockquote".to_string()) {
                ("blockquote".to_string(), None, None)
            } else {
                paragraph
            }
        } else if !excluded.contains(&"pre".to_string()) && line.starts_with("```") {
            ("pre".to_string(), None, None)
        } else if trimmed.starts_with('<') {
            // html sorting here

            // "html"| "html_comment"| "html_cdata"

            // <!--
            if trimmed.starts_with("<!--") && !excluded.contains(&"html_comment".to_string()) {
                return ("html_comment".to_string(), None, None);
            }

            // <![CDATA[
            if trimmed.starts_with("<![CDATA[") && !excluded.contains(&"html_cdata".to_string()) {
                return ("html_cdata".to_string(), None, None);
            }

            // autolinks now start with <<
            if trimmed.starts_with("<<") {
                return paragraph;
            }

            if !excluded.contains(&"html".to_string()) {
                ("html".to_string(), None, None)
            } else {
                // paragraph is the catch all if all teh above fail
                paragraph
            }
        } else if !excluded.contains(&"table".to_string()) && trimmed.starts_with('|') {
            ("table".to_string(), None, None)
        }
        // trim coupled with searching for a space will clear out any blank list start rows
        else if !excluded.contains(&"ul*".to_string()) && trimmed.starts_with("* ") {
            // figure out indent,
            // starts at 2 to account for teh */-
            let mut indent = 2;
            for character in line.chars() {
                match character {
                    ' ' => {
                        indent += 1;
                    }
                    _ => break,
                }
            }

            ("ul*".to_string(), Some(indent), None)
        } else if !excluded.contains(&"ul-".to_string()) && trimmed.starts_with("- ") {
            // figure out indent,
            // starts at 2 to account for teh */-
            let mut indent = 2;
            for character in line.chars() {
                match character {
                    ' ' => {
                        indent += 1;
                    }
                    _ => break,
                }
            }

            ("ul-".to_string(), Some(indent), None)
        } else if !excluded.contains(&"ul+".to_string()) && trimmed.starts_with("+ ") {
            // figure out indent,
            // starts at 2 to account for teh */-
            let mut indent = 2;
            for character in line.chars() {
                match character {
                    ' ' => {
                        indent += 1;
                    }
                    _ => break,
                }
            }

            ("ul+".to_string(), Some(indent), None)
        }
        // this covers everything that isnt as easy to find as the above
        else {
            // /((^ {0,8})([0-9]{1,9})(\.{1})( {1})(\w|\d))/gm

            // first check teh first 12 characters for an ordered List
            // diverging from commonmark in this regard to align up to the limit:
            //         1. First Line
            // 123456789. Last Line
            //
            // I can do it as I am not recognising four spaces as a code block

            // up to 8 initial spaces
            // number
            // dot
            // space
            // Non space character

            let characters: Vec<char> = line.chars().collect();
            let mut index = 0;

            // determine initial spaces
            loop {
                if index >= characters.len() {
                    break;
                }

                let character = characters[index];

                match character {
                    ' ' => {
                        // do nothing
                    }
                    _ => break,
                }
                index += 1;
            }

            /* unlimited indentation allowed
            if index > 8 {
                // not valid
                // too many spaces
                return paragraph;
            }
             */

            // get numbers next
            let mut numbers: Vec<char> = vec![];
            loop {
                if index >= characters.len() {
                    break;
                }

                let character = characters[index];
                match character {
                    '0'..='9' => {
                        numbers.push(character);
                    }
                    _ => break,
                }
                index += 1;
            }

            if numbers.is_empty() {
                // not valid
                // needs a number
                return paragraph;
            }
            if numbers.len() > 9 {
                // not valid
                // too many numbers
                return paragraph;
            }

            // need one dot
            let mut dot = false;
            if index < characters.len() {
                let character = characters[index];

                if character == '.' {
                    dot = true;
                }

                if character == ')' {
                    dot = true;
                }

                index += 1;
            }

            if !dot {
                // not valid
                // needs a dot
                return paragraph;
            }

            let mut space = false;
            if index < characters.len() {
                let character = characters[index];

                if character == '.' {
                    space = true;
                }

                index += 1;
            }

            if !space {
                // not valid
                // needs a space
                return paragraph;
            }

            // all the above are valid to make it here

            let number_str: String = numbers.into_iter().collect();
            let number: i32 = number_str.parse().unwrap_or(0);

            ("ol".to_string(), Some(index), Some(number))
        }
    }

    fn block_merge(&self, nodes: Vec<NodeData>, depth: usize) -> String {
        let mut result: Vec<String> = vec![];

        for node in nodes {
            let tag = node.tag.as_str();
            let (opening, content, closing) = match tag {
                // html just gets passed straight through
                "html" => {
                    if let Some(text) = node.text {
                        result.push(text);
                    }
                    (None, None, None)
                }
                // simple stuff first, no recursion

                "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
                    if let Some(text) = node.text {
                        let processed = self.inline_process(text, 0);

                        // no attributes or anything
                        let formatted = format!("<{}>{}</{}>", tag, processed, tag);

                        (Some(formatted), None, None)
                    }else{
                        (None, None, None)
                    }
                }

                "p" => {
                    if let Some(text) = node.text {
                        let processed = self.inline_process(text, depth+1);

                        // no attributes or anything
                        let open = format!("<{}>", tag);
                        let close = format!("</{}>", tag);

                        (Some(open), Some(processed), Some(close))
                    }else{
                        (None, None, None)
                    }
                }

                "hr" => {
                    // simplest of them all
                    (Some("<hr />".to_string()), None, None)
                }

                "pre" => {
                    if let Some(contents) = node.text {

                        // misc for fenced code blocks is used for the language
                        let formatted = if let Some(language) = node.misc {
                            // using class="language-{language}" is a psudo standard
                            format!("<pre><code class=\"language-{}\">\n{}\n</code></pre>", language, contents)
                        } else {
                            format!("<pre><code>\n{}\n</code></pre>", contents)
                        };

                        result.push(formatted);
                    }
                    (None, None, None)
                }

                ///////////////////////////
                // recursive beyond this //
                ///////////////////////////

                // table
                "table" | "thead" | "tbody"| "tr" |
                // blockquote always contains other stuff
                "blockquote" |
                // lists
                "ul" | "ol"
                => {
                    let processed = self.block_merge(node.contents, depth+1);
                    let open = format!("<{}>", tag);
                    let close = format!("</{}>", tag);
                    (Some(open), Some(processed), Some(close))
                }

                "th" | "td" => {
                    let processed = if let Some(text) = node.text {
                        self.inline_process(text, depth+1)
                    } else{
                        "".to_string()
                    };

                    let open = if let Some(alignment) = node.misc {
                        // text-align: alignment;
                        // https://developer.mozilla.org/en-US/docs/Web/CSS/text-align
                        format!("<{} style=\"text-align: {};\">", tag, alignment)
                    } else {
                        format!("<{}>", tag)
                    };

                    let close = format!("</{}>", tag);

                    (Some(open), Some(processed), Some(close))
                }

                "li" => {
                    // this handles the contents for both ordered and unordered lists

                    let processed = if let Some(text) = node.text {
                        self.inline_process(text, depth+1)
                    } else if !node.contents.is_empty() {
                        self.block_merge(node.contents, depth+1)
                    } else {
                        "".to_string()
                    };


                    let open = if let Some(value) = node.misc {
                        format!("<{} value=\"{}\">", tag, value)
                    } else {
                        format!("<{}>", tag)
                    };

                    let close = format!("</{}>", tag);

                    (Some(open), Some(processed), Some(close))
                }

                _ =>{
                    (None, None, None)
                }
            };

            if let Some(x_opening) = opening {
                let indented = format!(
                    "{:indent$}{}",
                    "",
                    x_opening,
                    indent = (depth * self.indentation)
                );
                result.push(indented)
            }
            if let Some(x_content) = content {
                let indented = format!("{:indent$}{}", "", x_content, indent = 0);
                // already indented in its section, specifically text content
                result.push(indented)
            }
            if let Some(x_closing) = closing {
                let indented = format!(
                    "{:indent$}{}",
                    "",
                    x_closing,
                    indent = (depth * self.indentation)
                );
                result.push(indented)
            }
        }

        result.join("\n")
    }

    fn inline_process(&self, input: String, depth: usize) -> String {
        // convert it into nodes
        let nodes = self.inline_spans(input);

        // merge them together according to the type of node
        let merged = self.inline_merge(nodes);

        // add line breaks if they are required
        // replace "  \n" with "\n<br />\n"
        let line_breaks_added = merged.replace("  \n", "\n<br />\n");

        // add the appropiate indentation to make it readable as raw html
        self.inline_indention(line_breaks_added, depth)
    }

    // this breaks down teh spans
    fn inline_spans(&self, input: String) -> Vec<NodeData> {
        /*

            //em//
            **strong**
            __underline__
            ~~strikethrough~~
            >!spoiler text!< class=md-spoiler-text , hiding it is handled in css, using teh format from Reddit
            ``code``
            <<autolink>>

            yes these are breaking changes with commonmark right abck to daringfireball's one.
            main reason is comformity.
            All of these have a specific opening and closing tag (em/strong from previous implemtations is tricky)
            identifiers dont do multiple jobs, _ was usied in place of * in previous versions


            contents of html are checked for markdown


            [link][]
            ![image]

            Valid:
                Normal:
                    []()
                    [](<>)
                    [text](url "title")
                    [text](<url with spaces>)

                Reference:
                    [identifier]: /url "title"
                    [text][identifier]

        text is subject to markdown
            ye some breaking changes here



            >! spoilered  **strong spoilered //emp strong spoilered// __not underlined** !< __
            >!![]!<

         */

        let mut node_data: Vec<NodeData> = vec![];

        let mut characters: Vec<char> = input.chars().collect();

        let mut index = 0;

        let mut span_closer: Vec<char> = vec![];
        let mut span_start = 0;

        /*
        normal = stuff created by the delimters
        html is any html blocks
        url is anything that matches a url [
        image is like the url but starts with ![
        */

        // marks the start of a span
        let mut span_active = false;
        let mut span_finished = false;
        let mut span_reset = false;

        // for allocating whereitems go
        let mut span_text = true; // defaults to this,
        let mut span_normal = false;
        let mut span_html = false;

        let mut span_normal_type: Option<String> = None;

        let mut html_tag_vec = vec![];
        let mut html_tag_complete = false;

        loop {
            if index >= characters.len() {
                break;
            }

            let character = characters[index];
            let character_next = if (index + 1) < characters.len() {
                Some(characters[index + 1])
            } else {
                None
            };
            let character_last_escape = if (index as isize - 1) > 0 {
                characters[index - 1] == '\\'
            } else {
                false
            };

            // this gets teh first section of a span
            if !span_active {
                match character {
                    // em
                    '/' => {
                        // /
                        if let Some(next) = character_next {
                            if next == '/' {
                                if character_last_escape {
                                    // remove the backslash
                                    characters.remove(index - 1);

                                    // since everything moved to the left so staying still is teh same as the normal +1 for the index
                                    // the -1 here will cancel otut eh +1 later
                                    index -= 1;
                                } else {
                                    span_normal_type = Some("em".to_string());
                                    span_closer = vec!['/', '/'];
                                    span_active = true;
                                    span_normal = true;
                                    span_text = false;
                                }
                            }
                        }
                    }
                    // strong
                    '*' => {
                        // *
                        if let Some(next) = character_next {
                            if next == '*' {
                                if character_last_escape {
                                    // remove the backslash
                                    characters.remove(index - 1);

                                    // since everything moved to the left so staying still is teh same as the normal +1 for the index
                                    // the -1 here will cancel otut eh +1 later
                                    index -= 1;
                                } else {
                                    span_normal_type = Some("strong".to_string());
                                    span_closer = vec!['*', '*'];
                                    span_active = true;
                                    span_normal = true;
                                    span_text = false;
                                }
                            }
                        }
                    }
                    // underline
                    '_' => {
                        // _
                        if let Some(next) = character_next {
                            if next == '_' {
                                if character_last_escape {
                                    // remove the backslash
                                    characters.remove(index - 1);

                                    // since everything moved to the left so staying still is teh same as the normal +1 for the index
                                    // the -1 here will cancel otut eh +1 later
                                    index -= 1;
                                } else {
                                    span_normal_type = Some("u".to_string());
                                    span_closer = vec!['_', '_'];
                                    span_active = true;
                                    span_normal = true;
                                    span_text = false;
                                }
                            }
                        }
                    }
                    // strikethrough
                    '~' => {
                        // ~
                        if let Some(next) = character_next {
                            if next == '~' {
                                if character_last_escape {
                                    // remove the backslash
                                    characters.remove(index - 1);

                                    // since everything moved to the left so staying still is teh same as the normal +1 for the index
                                    // the -1 here will cancel otut eh +1 later
                                    index -= 1;
                                } else {
                                    span_normal_type = Some("s".to_string());
                                    span_closer = vec!['~', '~'];
                                    span_active = true;
                                    span_normal = true;
                                    span_text = false;
                                }
                            }
                        }
                    }
                    // code
                    '`' => {
                        // `
                        if let Some(next) = character_next {
                            if next == '`' {
                                if character_last_escape {
                                    // remove the backslash
                                    characters.remove(index - 1);

                                    // since everything moved to the left so staying still is teh same as the normal +1 for the index
                                    // the -1 here will cancel otut eh +1 later
                                    index -= 1;
                                } else {
                                    span_normal_type = Some("code".to_string());
                                    span_closer = vec!['`', '`'];
                                    span_active = true;
                                    span_normal = true;
                                    span_text = false;
                                }
                            }
                        }
                    }
                    '>' => {
                        // >
                        // only one that breaks teh double mould
                        if let Some(next) = character_next {
                            if next == '!' {
                                if character_last_escape {
                                    // remove the backslash
                                    characters.remove(index - 1);

                                    // since everything moved to the left so staying still is teh same as the normal +1 for the index
                                    // the -1 here will cancel otut eh +1 later
                                    index -= 1;
                                } else {
                                    span_normal_type = Some("spoiler".to_string());
                                    span_closer = vec!['!', '<'];
                                    span_active = true;
                                    span_normal = true;
                                    span_text = false;
                                }
                            }
                        }
                    }
                    '<' => {
                        // set html first
                        span_active = true;
                        span_html = true;
                        span_text = false;

                        if let Some(next) = character_next {
                            // check if autolink
                            match next {
                                '<' => {
                                    // undo the html flag set above
                                    span_html = false;

                                    // set info for the closing
                                    span_normal_type = Some("autolink".to_string());
                                    span_closer = vec!['>', '>'];
                                    span_normal = true;
                                }
                                ' ' | '\t' | '/' | '>' => {
                                    // not a html tag
                                    span_active = false;
                                    span_html = false;
                                }
                                _ => {}
                            }
                        }

                        if span_active && character_last_escape {
                            // reset teh flags
                            span_active = false;
                            span_html = false;
                            span_text = true;
                            span_normal_type = None;
                            span_closer = vec![];
                            span_normal = false;

                            characters.remove(index - 1);

                            // since everything moved to the left so staying still is teh same as the normal +1 for the index
                            // the -1 here will cancel otut eh +1 later
                            index -= 1;
                        }
                    }
                    '[' => {
                        if character_last_escape {
                            // remove the backslash
                            characters.remove(index - 1);

                            // since everything moved to the left so staying still is teh same as the normal +1 for the index
                            // the -1 here will cancel otut eh +1 later
                            index -= 1;
                        } else if let Some((node, offset)) =
                            self.inline_spans_links(&characters[index..], "a".to_string())
                        {
                            // set teh stuff before to be a text
                            let text: String = characters[span_start..index].iter().collect();
                            node_data.push(NodeData {
                                tag: "text".to_string(),
                                misc: None,
                                text: Some(text),
                                contents: vec![],
                            });

                            // add the data to teh array
                            node_data.push(node);
                            index += offset;

                            // set the enw span start
                            span_start = index + 1;
                        }
                    }
                    '!' => {
                        if let Some(next) = character_next {
                            if next == '[' {
                                if character_last_escape {
                                    // remove the backslash
                                    characters.remove(index - 1);

                                    // since everything moved to the left so staying still is teh same as the normal +1 for the index
                                    // the -1 here will cancel otut eh +1 later
                                    index -= 1;
                                } else {
                                    // images require a +1 to the offsets to take into account teh !
                                    if let Some((node, offset)) = self.inline_spans_links(
                                        &characters[(index + 1)..],
                                        "img".to_string(),
                                    ) {
                                        // set teh stuff before to be a text
                                        let text: String =
                                            characters[span_start..index].iter().collect();
                                        node_data.push(NodeData {
                                            tag: "text".to_string(),
                                            misc: None,
                                            text: Some(text),
                                            contents: vec![],
                                        });

                                        // add the data to teh array
                                        node_data.push(node);
                                        index += offset + 1;

                                        // set the new span start
                                        span_start = index + 2;
                                    }
                                }
                            }
                        }
                    }

                    _ => {
                        // do nothing
                    }
                }

                if span_active {
                    // tidy up teh last text span here
                    // bnndle up everythign betweeen span_start and index into a string
                    let text: String = characters[span_start..index].iter().collect();
                    node_data.push(NodeData {
                        tag: "text".to_string(),
                        misc: None,
                        text: Some(text),
                        contents: vec![],
                    });

                    span_start = index;

                    // skip to the next character if html, two if its
                    if span_normal {
                        index += 2;
                    } else {
                        index += 1;
                    }

                    continue;
                }
            }

            // this captures the content of the spans
            if span_active {
                if span_normal {
                    // this aught to be pretty easy, just find the tail end of teh span, byundle it up into NodeData

                    if span_closer[0] == character {
                        if character_last_escape {
                            characters.remove(index - 1);

                            // since everything moved to the left so staying still is teh same as the normal +1 for the index
                            // the -1 here will cancel otut eh +1 later
                            index -= 1;
                        } else if let Some(next) = character_next {
                            if span_closer[1] == next {
                                // mark it as finished
                                span_finished = true;
                            }
                        }
                    }
                }

                if span_html {
                    // of the tag isnt complete then we need to find it
                    if !html_tag_complete {
                        match character {
                            ' ' | '\t' => {
                                html_tag_complete = true;
                            }
                            '/' | '>' => {
                                // check last character, if it was a backslash then remove the backsslash and add the current character
                                if characters[index - 1] == '\\' {
                                    // remove teh slash
                                    // add the bracket
                                    html_tag_vec.pop();
                                    html_tag_vec.push(character);
                                } else {
                                    html_tag_complete = true;
                                }
                            }
                            _ => {
                                // as long as there are no spaces
                                html_tag_vec.push(character);
                            }
                        }
                    }
                    if html_tag_complete {
                        if span_closer.is_empty() {
                            // sets teh
                            let tag: String = html_tag_vec.iter().collect();

                            if self.html_void.contains(&tag) {
                                span_closer = vec!['/', '>'];
                            } else {
                                span_closer = vec!['<', '/'];
                                span_closer.extend(&html_tag_vec);
                                span_closer.push('>');
                            }
                            // reverse it so it can be used easier down below
                            span_closer.reverse();
                        }
                        // using tag_closing find the end of the html span
                        // check if this is the

                        // starts off true
                        let mut matches = true;
                        for (position, closing_char) in span_closer.iter().enumerate() {
                            let index_new: isize = (index as isize) - (position as isize);
                            if index_new < 0 {
                                span_reset = true;
                                matches = false;
                                break;
                            }

                            if &characters[index_new as usize] != closing_char {
                                matches = false;
                                break;
                            }
                        }
                        if matches {
                            span_finished = true;
                        }
                    }
                }
            }

            if character_next.is_none() && !span_finished {
                if span_text {
                    span_finished = true;
                } else {
                    span_reset = true;
                }
            }

            if span_reset {
                // if the first character is < then replace it with &lt;
                if characters[span_start] == '<' {
                    let replacement_char = ['&', 'l', 't', ';'];
                    characters.splice(span_start..=span_start, replacement_char.iter().cloned());
                }

                span_closer = vec![];

                span_active = false;
                span_finished = false;
                span_reset = false; // reset this flag

                span_normal = false;
                span_html = false;
                span_text = true;

                span_normal_type = None;

                html_tag_vec = vec![];
                html_tag_complete = false;

                // reset back to the start of the span
                index = span_start;
                // skip to next character so it wont re-analyise the same set of characters
                index += 1;

                continue;
            }

            if span_finished {
                if span_text {
                    let text: String = characters[span_start..=index].iter().collect();
                    node_data.push(NodeData {
                        tag: "text".to_string(),
                        misc: None,
                        text: Some(text),
                        contents: vec![],
                    });

                    span_start = index;

                    // skip to the next character if html, two if its
                    if span_normal {
                        index += 1;
                    } else {
                        index += 0;
                    }
                }

                if span_normal {
                    // the offset of 2 is to exclude teh delimiter
                    let text_raw: String =
                        characters[(span_start + 2)..=(index - 1)].iter().collect();

                    let span_type = if let Some(span) = span_normal_type {
                        span
                    } else {
                        "text".to_string()
                    };

                    let (text, contents) = match span_type.as_str() {
                        "text" => (Some(text_raw), vec![]),
                        "code" => (Some(text_raw), vec![]),
                        "autolink" => (Some(text_raw), vec![]),
                        _ => (None, self.inline_spans(text_raw)),
                    };

                    node_data.push(NodeData {
                        tag: span_type,
                        misc: None,
                        text,
                        contents,
                    });

                    // skip to after the current delimter
                    span_start = index + 2;

                    // skip to the next character if html, two if its

                    index += 1;
                }

                if span_html {
                    let text: String = characters[span_start..=index].iter().collect();

                    node_data.push(NodeData {
                        tag: "html".to_string(),
                        misc: None,
                        text: Some(text),
                        contents: vec![],
                    });

                    span_start = index + 1;
                }

                span_closer = vec![];

                span_active = false;
                span_finished = false;

                span_normal = false;
                span_html = false;
                span_text = true;

                span_normal_type = None;

                html_tag_vec = vec![];
                html_tag_complete = false;
            }

            index += 1;
        }

        // catch anything at the end
        if span_start < (characters.len() - 1) {
            let text: String = characters[span_start..].iter().collect();
            node_data.push(NodeData {
                tag: "text".to_string(),
                misc: None,
                text: Some(text),
                contents: vec![],
            });
        }

        node_data
    }

    fn inline_spans_links(&self, characters: &[char], tag: String) -> Option<(NodeData, usize)> {
        let references = self.references.clone();

        // index starts a t 1 as first character is alwways the opener [
        let mut index = 1;

        let mut block_first = vec![];

        let mut link_type = None;
        loop {
            if index >= characters.len() {
                break;
            }

            let character = characters[index];
            let character_next = if (index + 1) < characters.len() {
                Some(characters[index + 1])
            } else {
                None
            };
            let character_last_escape = if (index as isize - 1) > 0 {
                characters[index - 1] == '\\'
            } else {
                false
            };

            match character {
                ']' => {
                    if character_last_escape {
                        block_first.pop();
                        block_first.push(character)
                    } else {
                        // find the type of link
                        if let Some(next) = character_next {
                            match next {
                                '(' => {
                                    link_type = Some("classic".to_string());
                                    // going to need to take a look at the contents
                                    index += 2;
                                }
                                '[' => {
                                    link_type = Some("reference_named".to_string());
                                    index += 2;
                                }
                                ' ' | '\t' | '\n' => {
                                    // check if the link_text is the same as the reference links in self.references
                                    link_type = Some("reference_anon".to_string());
                                }
                                _ => {
                                    // if it dosent match above its not a link
                                    return None;
                                }
                            }
                        } else {
                            // set up to test if its teh anon type
                            link_type = Some("reference_anon".to_string());
                        }

                        // regardless break it here
                        break;
                    }
                }

                _ => block_first.push(character),
            }

            index += 1;
        }

        // deal with teh anon references
        if let Some(type_) = &link_type {
            // only concerned with teh anon_test one this time
            if let "reference_anon" = type_.as_str() {
                let reference: String = block_first.iter().collect();

                return match references.get(&reference) {
                    Some(link_data) => {
                        let url = link_data.url.clone();
                        // reference us used as the contents if its an anon one
                        let contents = self.inline_spans(reference);

                        let node = NodeData {
                            tag,
                            misc: link_data.title.clone(),
                            // text here is used as the url
                            text: Some(url),
                            contents,
                        };

                        Some((node, index))
                    }
                    None => {
                        // not a link
                        None
                    }
                };
            }
        }

        let mut block_second = vec![];
        let mut angle_brackets = false;
        loop {
            if index >= characters.len() {
                break;
            }

            let character = characters[index];
            let character_last_escape = if (index as isize - 1) > 0 {
                characters[index - 1] == '\\'
            } else {
                false
            };

            // do stuff here

            if let Some(type_) = &link_type {
                match type_.as_str() {
                    "classic" => {
                        match character {
                            '<' => {
                                if block_second.is_empty() {
                                    angle_brackets = true;
                                }

                                // add it regardless, can be easially removed later
                                block_second.push(character)
                            }
                            ' ' | '\t' => {
                                if angle_brackets {
                                    block_second.push(character)
                                } else if block_second.is_empty() {
                                    // do nothing,
                                } else {
                                    // next loop wills tart on teh enxt character
                                    index += 1;
                                    // its teh end of the url
                                    break;
                                }
                            }
                            ')' => {
                                if angle_brackets {
                                    block_second.push(character)
                                } else if character_last_escape {
                                    block_second.pop();
                                    block_second.push(character);
                                } else {
                                    // this marks the classic link as finished
                                    // so make it and finish early

                                    let text_raw: String = block_first.iter().collect();
                                    let contents = self.inline_spans(text_raw);
                                    let url: String = block_second.iter().collect();
                                    let node = NodeData {
                                        tag,
                                        misc: None,
                                        text: Some(url),
                                        contents,
                                    };

                                    return Some((node, index));
                                }
                            }
                            '\n' => {
                                // all inline links must be on the one line, not split over multiple
                                // saves a lot of complexity
                                return None;
                            }
                            '>' => {
                                if angle_brackets {
                                    // marks teh end of the span
                                    // however if last char is a backslash its ignored
                                    if character_last_escape {
                                        block_second.pop();
                                        block_second.push(character);
                                    } else {
                                        // remove the first char which is a <
                                        block_second.remove(0);
                                        break;
                                    }
                                } else {
                                    block_second.push(character)
                                }
                            }
                            _ => block_second.push(character),
                        }
                    }
                    "reference_named" => match character {
                        ']' => {
                            if character_last_escape {
                                block_second.pop();
                                block_second.push(character);
                            } else {
                                break;
                            }
                        }
                        _ => block_second.push(character),
                    },
                    _ => {
                        // only classic and reference_named should show up
                    }
                }
            }

            index += 1;
        }

        // tidy up the references
        if let Some(type_) = &link_type {
            // not for classic
            if let "reference_named" = type_.as_str() {
                let reference: String = block_second.iter().collect();

                return match references.get(&reference) {
                    Some(link_data) => {
                        let text_raw: String = block_first.iter().collect();
                        let contents = self.inline_spans(text_raw);

                        let node = NodeData {
                            tag,
                            misc: link_data.title.clone(),
                            // text here is used as the url
                            text: Some(link_data.url.clone()),
                            contents,
                        };

                        Some((node, index))
                    }
                    None => {
                        // not a link
                        None
                    }
                };
            }
        }

        //
        /*
        now just left with classic

        // tehsea re the three general patterns to find
        [](<>)
        [](/url )
        [](/url "title")
         */

        // this handles the title
        let mut block_third = vec![];
        let mut delimiter = (' ', false, false);
        loop {
            if index >= characters.len() {
                break;
            }

            let character = characters[index];
            let character_last_escape = if (index as isize - 1) > 0 {
                characters[index - 1] == '\\'
            } else {
                false
            };

            match character {
                // manage delimiter
                '\'' | '"' => {
                    if !delimiter.1 {
                        // set the delimiter
                        delimiter = (character, true, false);
                    } else if delimiter.0 == character {
                        // check if last character was an escape
                        if character_last_escape {
                            block_third.pop();
                            block_third.push(character);
                        } else {
                            // mark it closed
                            delimiter = (character, true, true);
                        }
                    } else {
                        block_third.push(character);
                    }
                }

                //
                ')' => {
                    if delimiter.1 && !delimiter.2 {
                        // if delimiter is open then add it to teh array
                        block_third.push(character);
                    } else {
                        // else chack if its escaped
                        if character_last_escape {
                            block_third.pop();
                            block_third.push(character);
                        } else {
                            // this marks the classic link as finished
                            // so make it and finish early

                            let text_raw: String = block_first.iter().collect();
                            let contents = self.inline_spans(text_raw);

                            let url: String = block_second.iter().collect();

                            let title = if block_third.is_empty() {
                                None
                            } else {
                                let title_tmp: String = block_third.iter().collect();
                                Some(title_tmp)
                            };

                            let node = NodeData {
                                tag,
                                misc: title,
                                text: Some(url),
                                contents,
                            };

                            return Some((node, index));
                        }
                    }
                }

                ' ' | '\t' => {
                    if delimiter.1 && !delimiter.2 {
                        // if delimiter is open then add it to teh array
                        block_third.push(character);
                    } else {
                        // do nothing
                    }
                }
                _ => {
                    block_third.push(character);
                }
            }

            index += 1;
        }

        // if its gone to teh end without being closed out then its invalid

        None
    }

    fn inline_merge(&self, nodes: Vec<NodeData>) -> String {
        let mut result: Vec<String> = vec![];

        for node in nodes {
            let tag = node.tag.as_str();
            let (opening, content, closing) = match tag {
                // html  and text just gets passed straight through
                "html" | "text" => {
                    if let Some(text) = node.text {
                        result.push(text);
                    }
                    (None, None, None)
                }
                // treat this basically the same as html above
                "autolink" => {
                    if let Some(text) = node.text {
                        let (cleaned, mail, tel) = if text.starts_with("mailto:") {
                            (text.replacen("mailto:", "", 1), true, false)
                        } else if text.starts_with("MAILTO:") {
                            (text.replacen("MAILTO:", "", 1), true, false)
                        } else if text.starts_with("tel:") {
                            (text.replacen("tel:", "", 1), false, true)
                        } else if text.starts_with("TEL:") {
                            (text.replacen("TEL:", "", 1), false, true)
                        } else {
                            (text, false, false)
                        };

                        // check if it contains @
                        let formatted = if cleaned.contains('@') || mail {
                            format!("<a target='_blank' rel='noopener noreferrer' href='mailto:{}'>{}</a>", &cleaned, &cleaned)
                        } else if tel {
                            format!(
                                "<a target='_blank' rel='noopener noreferrer' href='tel:{}'>{}</a>",
                                &cleaned, &cleaned
                            )
                        } else {
                            format!(
                                "<a target='_blank' rel='noopener noreferrer' href='{}'>{}</a>",
                                &cleaned, &cleaned
                            )
                        };

                        result.push(formatted);
                    }
                    (None, None, None)
                }

                // set tags and no recursion
                "code" => {
                    if let Some(text) = node.text {
                        // no attributes or anything recursive
                        let open = format!("<{}>", tag);
                        let close = format!("</{}>", tag);

                        (Some(open), Some(text), Some(close))
                    } else {
                        (None, None, None)
                    }
                }

                // recursive
                "em" | "strong" | "u" | "s" => {
                    let processed = self.inline_merge(node.contents);
                    let open = format!("<{}>", tag);
                    let close = format!("</{}>", tag);
                    (Some(open), Some(processed), Some(close))
                }

                // spoiler is a span with a class of class="md-spoiler" on it as there is no html element for spoilers and must be done using css
                "spoiler" => {
                    let processed = self.inline_merge(node.contents);
                    let open = "<span class='md-spoiler'>".to_string();
                    let close = "</span>".to_string();
                    (Some(open), Some(processed), Some(close))
                }

                "a" => {
                    let url = node.text.unwrap_or_default();
                    let open = if let Some(title) = node.misc {
                        format!(
                            "<a target='_blank' rel='noopener noreferrer' href='{}' title='{}'>",
                            url, title
                        )
                    } else {
                        format!(
                            "<a target='_blank' rel='noopener noreferrer' href='{}'>",
                            url
                        )
                    };

                    let processed = self.inline_merge(node.contents);
                    let close = "</a>".to_string();

                    (Some(open), Some(processed), Some(close))
                }

                "img" => {
                    let url = node.text.unwrap_or_default();
                    let alt = self.inline_merge(node.contents);
                    let open = if let Some(title) = node.misc {
                        format!("<img src='{}' alt='{}' title='{}' />", url, alt, title)
                    } else {
                        format!("<img src='{}' alt='{}' />", url, alt)
                    };

                    (Some(open), None, None)
                }

                _ => (None, None, None),
            };

            if let Some(data) = opening {
                result.push(data)
            }
            if let Some(data) = content {
                result.push(data)
            }
            if let Some(data) = closing {
                result.push(data)
            }
        }

        result.join("")
    }

    fn inline_indention(&self, input: String, depth: usize) -> String {
        let mut result: Vec<String> = vec![];

        let lines = input.split('\n').collect::<Vec<_>>();
        for line in lines {
            let indented = format!(
                "{:indent$}{}",
                "",
                line,
                indent = (depth * self.indentation)
            );
            result.push(indented);
        }

        result.join("\n")
    }
}