aboutsummaryrefslogtreecommitdiff
path: root/Programs/Firewolf.bup/Contents/bits-UI/firewolf.lua
blob: d1ba857e1551fec7f641abb3233b5f14ee512e0b (plain) (blame)
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
--
--  Firewolf
--  Made by GravityScore and 1lann
--



--    Variables


local version = "3.5"
local build = 18

local w, h = term.getSize()

local isMenubarOpen = true
local menubarWindow = nil

local allowUnencryptedConnections = true
local enableTabBar = true

local currentWebsiteURL = ""
local builtInSites = {}

local currentProtocol = ""
local protocols = {}

local currentTab = 1
local maxTabs = 5
local maxTabNameWidth = 8
local tabs = {}

local languages = {}

local history = {}

local publicDNSChannel = 9999
local publicResponseChannel = 9998
local responseID = 41738

local httpTimeout = 10
local searchResultTimeout = 1
local initiationTimeout = 2
local animationInterval = 0.125
local fetchTimeout = 3
local serverLimitPerComputer = 1

local websiteErrorEvent = "firewolf_websiteErrorEvent"
local redirectEvent = "firewolf_redirectEvent"

local baseURL = "https://raw.githubusercontent.com/1lann/Firewolf/master/src"
local buildURL = baseURL .. "/build.txt"
local firewolfURL = baseURL .. "/client.lua"
local serverURL = baseURL .. "/server.lua"

local originalTerminal = term.current()

local firewolfLocation = "/" .. shell.getRunningProgram()
local downloadsLocation = "/downloads"


local theme = {}

local colorTheme = {
	background = colors.gray,
	accent = colors.red,
	subtle = colors.orange,

	lightText = colors.gray,
	text = colors.white,
	errorText = colors.red,
}

local grayscaleTheme = {
	background = colors.black,
	accent = colors.black,
	subtle = colors.black,

	lightText = colors.white,
	text = colors.white,
	errorText = colors.white,
}



--    Utilities


local modifiedRead = function(properties)
	local text = ""
	local startX, startY = term.getCursorPos()
	local pos = 0

	local previousText = ""
	local readHistory = nil
	local historyPos = 0

	if not properties then
		properties = {}
	end

	if properties.displayLength then
		properties.displayLength = math.min(properties.displayLength, w - 2)
	else
		properties.displayLength = w - startX - 1
	end

	if properties.startingText then
		text = properties.startingText
		pos = text:len()
	end

	if properties.history then
		readHistory = {}
		for k, v in pairs(properties.history) do
			readHistory[k] = v
		end
	end

	if readHistory[1] == text then
		table.remove(readHistory, 1)
	end

	local draw = function(replaceCharacter)
		local scroll = 0
		if properties.displayLength and pos > properties.displayLength then
			scroll = pos - properties.displayLength
		end

		local repl = replaceCharacter or properties.replaceCharacter
		term.setTextColor(theme.text)
		term.setCursorPos(startX, startY)
		if repl then
			term.write(string.rep(repl:sub(1, 1), text:len() - scroll))
		else
			term.write(text:sub(scroll + 1))
		end

		term.setCursorPos(startX + pos - scroll, startY)
	end

	term.setCursorBlink(true)
	draw()
	while true do
		local event, key, x, y, param4, param5 = os.pullEvent()

		if properties.onEvent then
			-- Actions:
			-- - exit (bool)
			-- - text
			-- - nullifyText

			term.setCursorBlink(false)
			local action = properties.onEvent(text, event, key, x, y, param4, param5)
			if action then
				if action.text then
					draw(" ")
					text = action.text
					pos = text:len()
				end if action.nullifyText then
					text = nil
					action.exit = true
				end if action.exit then
					break
				end
			end
			draw()
		end

		term.setCursorBlink(true)
		if event == "char" then
			local canType = true
			if properties.maxLength and text:len() >= properties.maxLength then
				canType = false
			end

			if canType then
				text = text:sub(1, pos) .. key .. text:sub(pos + 1, -1)
				pos = pos + 1
				draw()
			end
		elseif event == "key" then
			if key == keys.enter then
				break
			elseif key == keys.left and pos > 0 then
				pos = pos - 1
				draw()
			elseif key == keys.right and pos < text:len() then
				pos = pos + 1
				draw()
			elseif key == keys.backspace and pos > 0 then
				draw(" ")
				text = text:sub(1, pos - 1) .. text:sub(pos + 1, -1)
				pos = pos - 1
				draw()
			elseif key == keys.delete and pos < text:len() then
				draw(" ")
				text = text:sub(1, pos) .. text:sub(pos + 2, -1)
				draw()
			elseif key == keys.home then
				pos = 0
				draw()
			elseif key == keys["end"] then
				pos = text:len()
				draw()
			elseif (key == keys.up or key == keys.down) and readHistory then
				local shouldDraw = false
				if historyPos == 0 then
					previousText = text
				elseif historyPos > 0 then
					readHistory[historyPos] = text
				end

				if key == keys.up then
					if historyPos < #readHistory then
						historyPos = historyPos + 1
						shouldDraw = true
					end
				else
					if historyPos > 0 then
						historyPos = historyPos - 1
						shouldDraw = true
					end
				end

				if shouldDraw then
					draw(" ")
					if historyPos > 0 then
						text = readHistory[historyPos]
					else
						text = previousText
					end
					pos = text:len()
					draw()
				end
			end
		elseif event == "mouse_click" then
			local scroll = 0
			if properties.displayLength and pos > properties.displayLength then
				scroll = pos - properties.displayLength
			end

			if y == startY and x >= startX and x <= math.min(startX + text:len(), startX + (properties.displayLength or 10000)) then
				pos = x - startX + scroll
				draw()
			elseif y == startY then
				if x < startX then
					pos = scroll
					draw()
				elseif x > math.min(startX + text:len(), startX + (properties.displayLength or 10000)) then
					pos = text:len()
					draw()
				end
			end
		end
	end

	term.setCursorBlink(false)
	print("")
	return text
end


local prompt = function(items, x, y, w, h)
	local selected = 1
	local scroll = 0

	local draw = function()
		for i = scroll + 1, scroll + h do
			local item = items[i]
			if item then
				term.setCursorPos(x, y + i - 1)
				term.setBackgroundColor(theme.background)
				term.setTextColor(theme.lightText)

				if scroll + selected == i then
					term.setTextColor(theme.text)
					term.write(" > ")
				else
					term.write(" - ")
				end

				term.write(item)
			end
		end
	end

	draw()
	while true do
		local event, key, x, y = os.pullEvent()

		if event == "key" then
			if key == keys.up and selected > 1 then
				selected = selected - 1

				if selected - scroll == 0 then
					scroll = scroll - 1
				end
			elseif key == keys.down and selected < #items then
				selected = selected + 1
			end

			draw()
		elseif event == "mouse_click" then

		elseif event == "mouse_scroll" then
			if key > 0 then
				os.queueEvent("key", keys.down)
			else
				os.queueEvent("key", keys.up)
			end
		end
	end
end



--    GUI


local clear = function(bg, fg)
	term.setTextColor(fg)
	term.setBackgroundColor(bg)
	term.clear()
	term.setCursorPos(1, 1)
end


local fill = function(x, y, width, height, bg)
	term.setBackgroundColor(bg)
	for i = y, y + height - 1 do
		term.setCursorPos(x, i)
		term.write(string.rep(" ", width))
	end
end


local center = function(text)
	local x, y = term.getCursorPos()
	term.setCursorPos(math.floor(w / 2 - text:len() / 2) + (text:len() % 2 == 0 and 1 or 0), y)
	term.write(text)
	term.setCursorPos(1, y + 1)
end


local centerSplit = function(text, width)
	local words = {}
	for word in text:gmatch("[^ \t]+") do
		table.insert(words, word)
	end

	local lines = {""}
	while lines[#lines]:len() < width do
		lines[#lines] = lines[#lines] .. words[1] .. " "
		table.remove(words, 1)

		if #words == 0 then
			break
		end

		if lines[#lines]:len() + words[1]:len() >= width then
			table.insert(lines, "")
		end
	end

	for _, line in pairs(lines) do
		center(line)
	end
end



--    Updating


local download = function(url)
	http.request(url)
	local timeoutID = os.startTimer(httpTimeout)
	while true do
		local event, fetchedURL, response = os.pullEvent()
		if (event == "timer" and fetchedURL == timeoutID) or event == "http_failure" then
			return false
		elseif event == "http_success" and fetchedURL == url then
			local contents = response.readAll()
			response.close()
			return contents
		end
	end
end


local downloadAndSave = function(url, path)
	local contents = download(url)
	if contents and not fs.isReadOnly(path) and not fs.isDir(path) then
		local f = io.open(path, "w")
		f:write(contents)
		f:close()
		return false
	end
	return true
end


local updateAvailable = function()
	local number = download(buildURL)
	if not number then
		return false, true
	end

	if number and tonumber(number) and tonumber(number) > build then
		return true, false
	end

	return false, false
end


local redownloadBrowser = function()
	return downloadAndSave(firewolfURL, firewolfLocation)
end



--    Display Websites


builtInSites["display"] = {}


builtInSites["display"]["firewolf"] = function()
	local logo = {
		"______                         _  __ ",
		"|  ___|                       | |/ _|",
		"| |_  _ ____ _____      _____ | | |_ ",
		"|  _|| |  __/ _ \\ \\ /\\ / / _ \\| |  _|",
		"| |  | | | |  __/\\ V  V / <_> | | |  ",
		"\\_|  |_|_|  \\___| \\_/\\_/ \\___/|_|_|  ",
	}

	clear(theme.background, theme.text)
	fill(1, 3, w, 9, theme.subtle)

	term.setCursorPos(1, 3)
	for _, line in pairs(logo) do
		center(line)
	end

	term.setCursorPos(1, 10)
	center(version)

	term.setBackgroundColor(theme.background)
	term.setTextColor(theme.text)
	term.setCursorPos(1, 14)
	center("Search using the Query Box above")
	center("Visit rdnt://help for help using Firewolf.")

	term.setCursorPos(1, h - 2)
	center("Made by GravityScore and 1lann")
end


builtInSites["display"]["credits"] = function()
	clear(theme.background, theme.text)

	fill(1, 6, w, 3, theme.subtle)
	term.setCursorPos(1, 7)
	center("Credits")

	term.setBackgroundColor(theme.background)
	term.setCursorPos(1, 11)
	center("Written by GravityScore and 1lann")
	print("")
	center("RC4 Implementation by AgentE382")
end


builtInSites["display"]["help"] = function()
	clear(theme.background, theme.text)

	fill(1, 3, w, 3, theme.subtle)
	term.setCursorPos(1, 4)
	center("Help")

	term.setBackgroundColor(theme.background)
	term.setCursorPos(1, 7)
	center("Click on the URL bar or press control to")
	center("open the query box")
	print("")
	center("Type in a search query or website URL")
	center("into the query box.")
	print("")
	center("Search for nothing to see all available")
	center("websites.")
	print("")
	center("Visit rdnt://server to setup a server.")
	center("Visit rdnt://update to update Firewolf.")
end


builtInSites["display"]["server"] = function()
	clear(theme.background, theme.text)

	fill(1, 6, w, 3, theme.subtle)
	term.setCursorPos(1, 7)
	center("Server Software")

	term.setBackgroundColor(theme.background)
	term.setCursorPos(1, 11)
	if not http then
		center("HTTP is not enabled!")
		print("")
		center("Please enable it in your config file")
		center("to download Firewolf Server.")
	else
		center("Press space to download")
		center("Firewolf Server to:")
		print("")
		center("/fwserver")

		while true do
			local event, key = os.pullEvent()
			if event == "key" and key == 57 then
				fill(1, 11, w, 4, theme.background)
				term.setCursorPos(1, 11)
				center("Downloading...")

				local err = downloadAndSave(serverURL, "/fwserver")

				fill(1, 11, w, 4, theme.background)
				term.setCursorPos(1, 11)
				center(err and "Download failed!" or "Download successful!")
			end
		end
	end
end


builtInSites["display"]["update"] = function()
	clear(theme.background, theme.text)

	fill(1, 3, w, 3, theme.subtle)
	term.setCursorPos(1, 4)
	center("Update")

	term.setBackgroundColor(theme.background)
	if not http then
		term.setCursorPos(1, 9)
		center("HTTP is not enabled!")
		print("")
		center("Please enable it in your config")
		center("file to download Firewolf updates.")
	else
		term.setCursorPos(1, 10)
		center("Checking for updates...")

		local available, err = updateAvailable()

		term.setCursorPos(1, 10)
		if available then
			term.clearLine()
			center("Update found!")
			center("Press enter to download.")

			while true do
				local event, key = os.pullEvent()
				if event == "key" and key == keys.enter then
					break
				end
			end

			fill(1, 10, w, 2, theme.background)
			term.setCursorPos(1, 10)
			center("Downloading...")

			local err = redownloadBrowser()

			term.setCursorPos(1, 10)
			term.clearLine()
			if err then
				center("Download failed!")
			else
				center("Download succeeded!")
				center("Please restart Firewolf...")
			end
		elseif err then
			term.clearLine()
			center("Checking failed!")
		else
			term.clearLine()
			center("No updates found.")
		end
	end
end



--    Built In Websites


builtInSites["error"] = function(err)
	fill(1, 3, w, 3, theme.subtle)
	term.setCursorPos(1, 4)
	center("Failed to load page!")

	term.setBackgroundColor(theme.background)
	term.setCursorPos(1, 9)
	center(err)
	print("")
	center("Please try again.")
end


builtInSites["noresults"] = function()
	fill(1, 3, w, 3, theme.subtle)
	term.setCursorPos(1, 4)
	center("No results!")

	term.setBackgroundColor(theme.background)
	term.setCursorPos(1, 9)
	center("Your search didn't return")
	center("any results!")

	os.pullEvent("key")
	os.queueEvent("")
	os.pullEvent()
end


builtInSites["search advanced"] = function(results)
	local startY = 6
	local height = h - startY - 1
	local scroll = 0

	local draw = function()
		fill(1, startY, w, height + 1, theme.background)

		for i = scroll + 1, scroll + height do
			if results[i] then
				term.setCursorPos(5, (i - scroll) + startY)
				term.write(currentProtocol .. "://" .. results[i])
			end
		end
	end

	draw()
	while true do
		local event, but, x, y = os.pullEvent()

		if event == "mouse_click" and y >= startY and y <= startY + height then
			local item = results[y - startY + scroll]
			if item then
				os.queueEvent(redirectEvent, item)
				coroutine.yield()
			end
		elseif event == "key" then
			if but == keys.up then
				scroll = math.max(0, scroll - 1)
			elseif but == keys.down and #results > height then
				scroll = math.min(scroll + 1, #results - height)
			end

			draw()
		elseif event == "mouse_scroll" then
			if but > 0 then
				os.queueEvent("key", keys.down)
			else
				os.queueEvent("key", keys.up)
			end
		end
	end
end


builtInSites["search basic"] = function(results)
	local startY = 6
	local height = h - startY - 1
	local scroll = 0
	local selected = 1

	local draw = function()
		fill(1, startY, w, height + 1, theme.background)

		for i = scroll + 1, scroll + height do
			if results[i] then
				if i == selected + scroll then
					term.setCursorPos(3, (i - scroll) + startY)
					term.write("> " .. currentProtocol .. "://" .. results[i])
				else
					term.setCursorPos(5, (i - scroll) + startY)
					term.write(currentProtocol .. "://" .. results[i])
				end
			end
		end
	end

	draw()
	while true do
		local event, but, x, y = os.pullEvent()

		if event == "key" then
			if but == keys.up and selected + scroll > 1 then
				if selected > 1 then
					selected = selected - 1
				else
					scroll = math.max(0, scroll - 1)
				end
			elseif but == keys.down and selected + scroll < #results then
				if selected < height then
					selected = selected + 1
				else
					scroll = math.min(scroll + 1, #results - height)
				end
			elseif but == keys.enter then
				local item = results[scroll + selected]
				if item then
					os.queueEvent(redirectEvent, item)
					coroutine.yield()
				end
			end

			draw()
		elseif event == "mouse_scroll" then
			if but > 0 then
				os.queueEvent("key", keys.down)
			else
				os.queueEvent("key", keys.up)
			end
		end
	end
end


builtInSites["search"] = function(results)
	clear(theme.background, theme.text)

	fill(1, 3, w, 3, theme.subtle)
	term.setCursorPos(1, 4)
	center(#results .. " Search " .. (#results == 1 and "Result" or "Results"))

	term.setBackgroundColor(theme.background)

	if term.isColor() then
		builtInSites["search advanced"](results)
	else
		builtInSites["search basic"](results)
	end
end


builtInSites["crash"] = function(err)
	fill(1, 3, w, 3, theme.subtle)
	term.setCursorPos(1, 4)
	center("The website crashed!")

	term.setBackgroundColor(theme.background)
	term.setCursorPos(1, 8)
	centerSplit(err, w - 4)
	print("\n")
	center("Please report this error to")
	center("the website creator.")
end



--    Menubar


local getTabName = function(url)
	local name = url:match("^[^/]+")

	if not name then
		name = "Search"
	end

	if name:sub(1, 3) == "www" then
		name = name:sub(5):gsub("^%s*(.-)%s*$", "%1")
	end

	if name:len() > maxTabNameWidth then
		name = name:sub(1, maxTabNameWidth):gsub("^%s*(.-)%s*$", "%1")
	end

	if name:sub(-1, -1) == "." then
		name = name:sub(1, -2):gsub("^%s*(.-)%s*$", "%1")
	end

	return name:gsub("^%s*(.-)%s*$", "%1")
end


local determineClickedTab = function(x, y)
	if y == 2 then
		local minx = 2
		for i, tab in pairs(tabs) do
			local name = getTabName(tab.url)

			if x >= minx and x <= minx + name:len() - 1 then
				return i
			elseif x == minx + name:len() and i == currentTab and #tabs > 1 then
				return "close"
			else
				minx = minx + name:len() + 2
			end
		end

		if x == minx and #tabs < maxTabs then
			return "new"
		end
	end

	return nil
end


local setupMenubar = function()
	if enableTabBar then
		menubarWindow = window.create(originalTerminal, 1, 1, w, 2, false)
	else
		menubarWindow = window.create(originalTerminal, 1, 1, w, 1, false)
	end
end


local drawMenubar = function()
	if isMenubarOpen then
		term.redirect(menubarWindow)
		menubarWindow.setVisible(true)

		fill(1, 1, w, 1, theme.accent)
		term.setTextColor(theme.text)

		term.setBackgroundColor(theme.accent)
		term.setCursorPos(2, 1)
		if currentWebsiteURL:match("^[^%?]+") then
			term.write(currentProtocol .. "://" .. currentWebsiteURL:match("^[^%?]+"))
		else
			term.write(currentProtocol .. "://" ..currentWebsiteURL)
		end

		term.setCursorPos(w - 5, 1)
		term.write("[===]")

		if enableTabBar then
			fill(1, 2, w, 1, theme.subtle)

			term.setCursorPos(1, 2)
			for i, tab in pairs(tabs) do
				term.setBackgroundColor(theme.subtle)
				term.setTextColor(theme.lightText)
				if i == currentTab then
					term.setTextColor(theme.text)
				end

				local tabName = getTabName(tab.url)
				term.write(" " .. tabName)

				if i == currentTab and #tabs > 1 then
					term.setTextColor(theme.errorText)
					term.write("x")
				else
					term.write(" ")
				end
			end

			if #tabs < maxTabs then
				term.setTextColor(theme.lightText)
				term.setBackgroundColor(theme.subtle)
				term.write(" + ")
			end
		end
	else
		menubarWindow.setVisible(false)
	end
end



--  RC4
--  Implementation by AgentE382


local cryptWrapper = function(plaintext, salt)
	local key = type(salt) == "table" and {unpack(salt)} or {string.byte(salt, 1, #salt)}
	local S = {}
	for i = 0, 255 do
		S[i] = i
	end

	local j, keylength = 0, #key
	for i = 0, 255 do
		j = (j + S[i] + key[i % keylength + 1]) % 256
		S[i], S[j] = S[j], S[i]
	end

	local i = 0
	j = 0
	local chars, astable = type(plaintext) == "table" and {unpack(plaintext)} or {string.byte(plaintext, 1, #plaintext)}, false

	for n = 1, #chars do
		i = (i + 1) % 256
		j = (j + S[i]) % 256
		S[i], S[j] = S[j], S[i]
		chars[n] = bit.bxor(S[(S[i] + S[j]) % 256], chars[n])
		if chars[n] > 127 or chars[n] == 13 then
			astable = true
		end
	end

	return astable and chars or string.char(unpack(chars))
end


local crypt = function(text, key)
	local resp, msg = pcall(cryptWrapper, text, key)
	if resp then
		return msg
	else
		return nil
	end
end



--  Base64
--
--  Base64 Encryption/Decryption
--  By KillaVanilla
--  http://www.computercraft.info/forums2/index.php?/topic/12450-killavanillas-various-apis/
--  http://pastebin.com/rCYDnCxn
--


local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"


local function sixBitToBase64(input)
	return string.sub(alphabet, input+1, input+1)
end


local function base64ToSixBit(input)
	for i=1, 64 do
		if input == string.sub(alphabet, i, i) then
			return i-1
		end
	end
end


local function octetToBase64(o1, o2, o3)
	local shifted = bit.brshift(bit.band(o1, 0xFC), 2)
	local i1 = sixBitToBase64(shifted)
	local i2 = "A"
	local i3 = "="
	local i4 = "="
	if o2 then
		i2 = sixBitToBase64(bit.bor( bit.blshift(bit.band(o1, 3), 4), bit.brshift(bit.band(o2, 0xF0), 4) ))
		if not o3 then
			i3 = sixBitToBase64(bit.blshift(bit.band(o2, 0x0F), 2))
		else
			i3 = sixBitToBase64(bit.bor( bit.blshift(bit.band(o2, 0x0F), 2), bit.brshift(bit.band(o3, 0xC0), 6) ))
		end
	else
		i2 = sixBitToBase64(bit.blshift(bit.band(o1, 3), 4))
	end
	if o3 then
		i4 = sixBitToBase64(bit.band(o3, 0x3F))
	end

	return i1..i2..i3..i4
end


local function base64ToThreeOctet(s1)
	local c1 = base64ToSixBit(string.sub(s1, 1, 1))
	local c2 = base64ToSixBit(string.sub(s1, 2, 2))
	local c3 = 0
	local c4 = 0
	local o1 = 0
	local o2 = 0
	local o3 = 0
	if string.sub(s1, 3, 3) == "=" then
		c3 = nil
		c4 = nil
	elseif string.sub(s1, 4, 4) == "=" then
		c3 = base64ToSixBit(string.sub(s1, 3, 3))
		c4 = nil
	else
		c3 = base64ToSixBit(string.sub(s1, 3, 3))
		c4 = base64ToSixBit(string.sub(s1, 4, 4))
	end
	o1 = bit.bor( bit.blshift(c1, 2), bit.brshift(bit.band( c2, 0x30 ), 4) )
	if c3 then
		o2 = bit.bor( bit.blshift(bit.band(c2, 0x0F), 4), bit.brshift(bit.band( c3, 0x3C ), 2) )
	else
		o2 = nil
	end
	if c4 then
		o3 = bit.bor( bit.blshift(bit.band(c3, 3), 6), c4 )
	else
		o3 = nil
	end
	return o1, o2, o3
end


local function splitIntoBlocks(bytes)
	local blockNum = 1
	local blocks = {}
	for i=1, #bytes, 3 do
		blocks[blockNum] = {bytes[i], bytes[i+1], bytes[i+2]}
		blockNum = blockNum+1
	end
	return blocks
end


function base64Encode(bytes)
	local blocks = splitIntoBlocks(bytes)
	local output = ""
	for i=1, #blocks do
		output = output..octetToBase64( unpack(blocks[i]) )
	end
	return output
end


function base64Decode(str)
	local bytes = {}
	local blocks = {}
	local blockNum = 1

	for i=1, #str, 4 do
		blocks[blockNum] = string.sub(str, i, i+3)
		blockNum = blockNum+1
	end

	for i=1, #blocks do
		local o1, o2, o3 = base64ToThreeOctet(blocks[i])
		table.insert(bytes, o1)
		table.insert(bytes, o2)
		table.insert(bytes, o3)
	end

	return bytes
end



--  SHA-256
--
--  Adaptation of the Secure Hashing Algorithm (SHA-244/256)
--  Found Here: http://lua-users.org/wiki/SecureHashAlgorithm
--
--  Using an adapted version of the bit library
--  Found Here: https://bitbucket.org/Boolsheet/bslf/src/1ee664885805/bit.lua


local MOD = 2^32
local MODM = MOD-1


local function memoize(f)
	local mt = {}
	local t = setmetatable({}, mt)
	function mt:__index(k)
		local v = f(k)
		t[k] = v
		return v
	end
	return t
end


local function make_bitop_uncached(t, m)
	local function bitop(a, b)
		local res,p = 0,1
		while a ~= 0 and b ~= 0 do
			local am, bm = a % m, b % m
			res = res + t[am][bm] * p
			a = (a - am) / m
			b = (b - bm) / m
			p = p * m
		end
		res = res + (a + b) * p
		return res
	end

	return bitop
end


local function make_bitop(t)
	local op1 = make_bitop_uncached(t,2^1)
	local op2 = memoize(function(a)
		return memoize(function(b)
			return op1(a, b)
		end)
	end)
	return make_bitop_uncached(op2, 2 ^ (t.n or 1))
end


local customBxor1 = make_bitop({[0] = {[0] = 0,[1] = 1}, [1] = {[0] = 1, [1] = 0}, n = 4})

local function customBxor(a, b, c, ...)
	local z = nil
	if b then
		a = a % MOD
		b = b % MOD
		z = customBxor1(a, b)
		if c then
			z = customBxor(z, c, ...)
		end
		return z
	elseif a then
		return a % MOD
	else
		return 0
	end
end


local function customBand(a, b, c, ...)
	local z
	if b then
		a = a % MOD
		b = b % MOD
		z = ((a + b) - customBxor1(a,b)) / 2
		if c then
			z = customBand(z, c, ...)
		end
		return z
	elseif a then
		return a % MOD
	else
		return MODM
	end
end


local function bnot(x)
	return (-1 - x) % MOD
end


local function rshift1(a, disp)
	if disp < 0 then
		return lshift(a, -disp)
	end
	return math.floor(a % 2 ^ 32 / 2 ^ disp)
end


local function rshift(x, disp)
	if disp > 31 or disp < -31 then
		return 0
	end
	return rshift1(x % MOD, disp)
end


local function lshift(a, disp)
	if disp < 0 then
		return rshift(a, -disp)
	end
	return (a * 2 ^ disp) % 2 ^ 32
end


local function rrotate(x, disp)
    x = x % MOD
    disp = disp % 32
    local low = customBand(x, 2 ^ disp - 1)
    return rshift(x, disp) + lshift(low, 32 - disp)
end


local k = {
	0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
	0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
	0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
	0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
	0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
	0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
	0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
	0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
	0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
	0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
	0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
	0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
	0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
	0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
	0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
	0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
}


local function str2hexa(s)
	return (string.gsub(s, ".", function(c)
		return string.format("%02x", string.byte(c))
	end))
end


local function num2s(l, n)
	local s = ""
	for i = 1, n do
		local rem = l % 256
		s = string.char(rem) .. s
		l = (l - rem) / 256
	end
	return s
end


local function s232num(s, i)
	local n = 0
	for i = i, i + 3 do
		n = n*256 + string.byte(s, i)
	end
	return n
end


local function preproc(msg, len)
	local extra = 64 - ((len + 9) % 64)
	len = num2s(8 * len, 8)
	msg = msg .. "\128" .. string.rep("\0", extra) .. len
	assert(#msg % 64 == 0)
	return msg
end


local function initH256(H)
	H[1] = 0x6a09e667
	H[2] = 0xbb67ae85
	H[3] = 0x3c6ef372
	H[4] = 0xa54ff53a
	H[5] = 0x510e527f
	H[6] = 0x9b05688c
	H[7] = 0x1f83d9ab
	H[8] = 0x5be0cd19
	return H
end


local function digestblock(msg, i, H)
	local w = {}
	for j = 1, 16 do
		w[j] = s232num(msg, i + (j - 1)*4)
	end
	for j = 17, 64 do
		local v = w[j - 15]
		local s0 = customBxor(rrotate(v, 7), rrotate(v, 18), rshift(v, 3))
		v = w[j - 2]
		w[j] = w[j - 16] + s0 + w[j - 7] + customBxor(rrotate(v, 17), rrotate(v, 19), rshift(v, 10))
	end

	local a, b, c, d, e, f, g, h = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8]
	for i = 1, 64 do
		local s0 = customBxor(rrotate(a, 2), rrotate(a, 13), rrotate(a, 22))
		local maj = customBxor(customBand(a, b), customBand(a, c), customBand(b, c))
		local t2 = s0 + maj
		local s1 = customBxor(rrotate(e, 6), rrotate(e, 11), rrotate(e, 25))
		local ch = customBxor (customBand(e, f), customBand(bnot(e), g))
		local t1 = h + s1 + ch + k[i] + w[i]
		h, g, f, e, d, c, b, a = g, f, e, d + t1, c, b, a, t1 + t2
	end

	H[1] = customBand(H[1] + a)
	H[2] = customBand(H[2] + b)
	H[3] = customBand(H[3] + c)
	H[4] = customBand(H[4] + d)
	H[5] = customBand(H[5] + e)
	H[6] = customBand(H[6] + f)
	H[7] = customBand(H[7] + g)
	H[8] = customBand(H[8] + h)
end


local function sha256(msg)
	msg = preproc(msg, #msg)
	local H = initH256({})
	for i = 1, #msg, 64 do
		digestblock(msg, i, H)
	end
	return str2hexa(num2s(H[1], 4) .. num2s(H[2], 4) .. num2s(H[3], 4) .. num2s(H[4], 4) ..
		num2s(H[5], 4) .. num2s(H[6], 4) .. num2s(H[7], 4) .. num2s(H[8], 4))
end


local protocolName = "Firewolf"



--    Cryptography


local Cryptography = {}
Cryptography.sha = {}
Cryptography.base64 = {}
Cryptography.aes = {}


function Cryptography.bytesFromMessage(msg)
	local bytes = {}

	for i = 1, msg:len() do
		local letter = string.byte(msg:sub(i, i))
		table.insert(bytes, letter)
	end

	return bytes
end


function Cryptography.messageFromBytes(bytes)
	local msg = ""

	for i = 1, #bytes do
		local letter = string.char(bytes[i])
		msg = msg .. letter
	end

	return msg
end


function Cryptography.bytesFromKey(key)
	local bytes = {}

	for i = 1, key:len() / 2 do
		local group = key:sub((i - 1) * 2 + 1, (i - 1) * 2 + 1)
		local num = tonumber(group, 16)
		table.insert(bytes, num)
	end

	return bytes
end


function Cryptography.sha.sha256(msg)
	return sha256(msg)
end


function Cryptography.aes.encrypt(msg, key)
	return base64Encode(crypt(msg, key))
end


function Cryptography.aes.decrypt(msg, key)
	return crypt(base64Decode(msg), key)
end


function Cryptography.base64.encode(msg)
	return base64Encode(Cryptography.bytesFromMessage(msg))
end


function Cryptography.base64.decode(msg)
	return Cryptography.messageFromBytes(base64Decode(msg))
end


function Cryptography.channel(text)
	local hashed = Cryptography.sha.sha256(text)

	local total = 0

	for i = 1, hashed:len() do
		total = total + string.byte(hashed:sub(i, i))
	end

	return (total % 55530) + 10000
end


function Cryptography.sanatize(text)
	local sanatizeChars = {"%", "(", ")", "[", "]", ".", "+", "-", "*", "?", "^", "$"}

	for _, char in pairs(sanatizeChars) do
		text = text:gsub("%"..char, "%%%"..char)
	end
	return text
end



--  Modem


local Modem = {}
Modem.modems = {}


function Modem.exists()
	Modem.exists = false
	for _, side in pairs(rs.getSides()) do
		if peripheral.isPresent(side) and peripheral.getType(side) == "modem" then
			Modem.exists = true

			if not Modem.modems[side] then
				Modem.modems[side] = peripheral.wrap(side)
			end
		end
	end

	return Modem.exists
end


function Modem.open(channel)
	if not Modem.exists then
		return false
	end

	for side, modem in pairs(Modem.modems) do
		modem.open(channel)
		rednet.open(side)
	end

	return true
end


function Modem.close(channel)
	if not Modem.exists then
		return false
	end

	for side, modem in pairs(Modem.modems) do
		modem.close(channel)
	end

	return true
end


function Modem.closeAll()
	if not Modem.exists then
		return false
	end

	for side, modem in pairs(Modem.modems) do
		modem.closeAll()
	end

	return true
end


function Modem.isOpen(channel)
	if not Modem.exists then
		return false
	end

	local isOpen = false
	for side, modem in pairs(Modem.modems) do
		if modem.isOpen(channel) then
			isOpen = true
			break
		end
	end

	return isOpen
end


function Modem.transmit(channel, msg)
	if not Modem.exists then
		return false
	end

	if not Modem.isOpen(channel) then
		Modem.open(channel)
	end

	for side, modem in pairs(Modem.modems) do
		modem.transmit(channel, channel, msg)
	end

	return true
end



--    Handshake


local Handshake = {}

Handshake.prime = 625210769
Handshake.channel = 54569
Handshake.base = -1
Handshake.secret = -1
Handshake.sharedSecret = -1
Handshake.packetHeader = "["..protocolName.."-Handshake-Packet-Header]"
Handshake.packetMatch = "%["..protocolName.."%-Handshake%-Packet%-Header%](.+)"


function Handshake.exponentWithModulo(base, exponent, modulo)
	local remainder = base

	for i = 1, exponent-1 do
		remainder = remainder * remainder
		if remainder >= modulo then
			remainder = remainder % modulo
		end
	end

	return remainder
end


function Handshake.clear()
	Handshake.base = -1
	Handshake.secret = -1
	Handshake.sharedSecret = -1
end


function Handshake.generateInitiatorData()
	Handshake.base = math.random(10,99999)
	Handshake.secret = math.random(10,99999)
	return {
		type = "initiate",
		prime = Handshake.prime,
		base = Handshake.base,
		moddedSecret = Handshake.exponentWithModulo(Handshake.base, Handshake.secret, Handshake.prime)
	}
end


function Handshake.generateResponseData(initiatorData)
	local isPrimeANumber = type(initiatorData.prime) == "number"
	local isPrimeMatching = initiatorData.prime == Handshake.prime
	local isBaseANumber = type(initiatorData.base) == "number"
	local isInitiator = initiatorData.type == "initiate"
	local isModdedSecretANumber = type(initiatorData.moddedSecret) == "number"
	local areAllNumbersNumbers = isPrimeANumber and isBaseANumber and isModdedSecretANumber

	if areAllNumbersNumbers and isPrimeMatching then
		if isInitiator then
			Handshake.base = initiatorData.base
			Handshake.secret = math.random(10,99999)
			Handshake.sharedSecret = Handshake.exponentWithModulo(initiatorData.moddedSecret, Handshake.secret, Handshake.prime)
			return {
				type = "response",
				prime = Handshake.prime,
				base = Handshake.base,
				moddedSecret = Handshake.exponentWithModulo(Handshake.base, Handshake.secret, Handshake.prime)
			}, Handshake.sharedSecret
		elseif initiatorData.type == "response" and Handshake.base > 0 and Handshake.secret > 0 then
			Handshake.sharedSecret = Handshake.exponentWithModulo(initiatorData.moddedSecret, Handshake.secret, Handshake.prime)
			return Handshake.sharedSecret
		else
			return false
		end
	else
		return false
	end
end



--    Secure Connection


local SecureConnection = {}
SecureConnection.__index = SecureConnection


SecureConnection.packetHeaderA = "["..protocolName.."-"
SecureConnection.packetHeaderB = "-SecureConnection-Packet-Header]"
SecureConnection.packetMatchA = "%["..protocolName.."%-"
SecureConnection.packetMatchB = "%-SecureConnection%-Packet%-Header%](.+)"
SecureConnection.connectionTimeout = 0.1
SecureConnection.successPacketTimeout = 0.1


function SecureConnection.new(secret, key, identifier, distance, isRednet)
	local self = setmetatable({}, SecureConnection)
	self:setup(secret, key, identifier, distance, isRednet)
	return self
end


function SecureConnection:setup(secret, key, identifier, distance, isRednet)
	local rawSecret

	if isRednet then
		self.isRednet = true
		self.distance = -1
		self.rednet_id = distance
		rawSecret = protocolName .. "|" .. tostring(secret) .. "|" .. tostring(identifier) ..
		"|" .. tostring(key) .. "|rednet"
	else
		self.isRednet = false
		self.distance = distance
		rawSecret = protocolName .. "|" .. tostring(secret) .. "|" .. tostring(identifier) ..
		"|" .. tostring(key) .. "|" .. tostring(distance)
	end

	self.identifier = identifier
	self.packetMatch = SecureConnection.packetMatchA .. Cryptography.sanatize(identifier) .. SecureConnection.packetMatchB
	self.packetHeader = SecureConnection.packetHeaderA .. identifier .. SecureConnection.packetHeaderB
	self.secret = Cryptography.sha.sha256(rawSecret)
	self.channel = Cryptography.channel(self.secret)

	if not self.isRednet then
		Modem.open(self.channel)
	end
end


function SecureConnection:verifyHeader(msg)
	if msg:match(self.packetMatch) then
		return true
	else
		return false
	end
end


function SecureConnection:sendMessage(msg, rednetProtocol)
	local rawEncryptedMsg = Cryptography.aes.encrypt(self.packetHeader .. msg, self.secret)
	local encryptedMsg = self.packetHeader .. rawEncryptedMsg

	if self.isRednet then
		rednet.send(self.rednet_id, encryptedMsg, rednetProtocol)
		return true
	else
		return Modem.transmit(self.channel, encryptedMsg)
	end
end


function SecureConnection:decryptMessage(msg)
	if self:verifyHeader(msg) then
		local encrypted = msg:match(self.packetMatch)

		local unencryptedMsg = nil
		pcall(function() unencryptedMsg = Cryptography.aes.decrypt(encrypted, self.secret) end)
		if not unencryptedMsg then
			return false, "Could not decrypt"
		end

		if self:verifyHeader(unencryptedMsg) then
			return true, unencryptedMsg:match(self.packetMatch)
		else
			return false, "Could not verify"
		end
	else
		return false, "Could not stage 1 verify"
	end
end



--    RDNT Protocol


protocols["rdnt"] = {}

local header = {}
header.dnsPacket = "[Firewolf-DNS-Packet]"
header.dnsHeaderMatch = "^%[Firewolf%-DNS%-Response%](.+)$"
header.rednetHeader = "[Firewolf-Rednet-Channel-Simulation]"
header.rednetMatch = "^%[Firewolf%-Rednet%-Channel%-Simulation%](%d+)$"
header.responseMatchA = "^%[Firewolf%-"
header.responseMatchB = "%-"
header.responseMatchC = "%-Handshake%-Response%](.+)$"
header.requestHeaderA = "[Firewolf-"
header.requestHeaderB = "-Handshake-Request]"
header.pageRequestHeaderA = "[Firewolf-"
header.pageRequestHeaderB = "-Page-Request]"
header.pageResponseMatchA = "^%[Firewolf%-"
header.pageResponseMatchB = "%-Page%-Response%]%[HEADER%](.-)%[BODY%](.+)$"
header.closeHeaderA = "[Firewolf-"
header.closeHeaderB = "-Connection-Close]"


protocols["rdnt"]["setup"] = function()
	if not Modem.exists() then
		error("No modem found!")
	end
end


protocols["rdnt"]["fetchAllSearchResults"] = function()
	Modem.open(publicDNSChannel)
	Modem.open(publicResponseChannel)
	Modem.transmit(publicDNSChannel, header.dnsPacket)
	Modem.close(publicDNSChannel)

	rednet.broadcast(header.dnsPacket, header.rednetHeader .. publicDNSChannel)

	local uniqueServers = {}
	local uniqueDomains = {}

	local timer = os.startTimer(searchResultTimeout)

	while true do
		local event, id, channel, protocol, message, dist = os.pullEventRaw()
		if event == "modem_message" then
			if channel == publicResponseChannel and message:match(header.dnsHeaderMatch) then
				if not uniqueServers[tostring(dist)] then
					uniqueServers[tostring(dist)] = true
					local domain = message:match(header.dnsHeaderMatch)
					if not uniqueDomains[domain] then
						if not(domain:find("/") or domain:find(":") or domain:find("%?")) and #domain > 4 then
							timer = os.startTimer(searchResultTimeout)
							uniqueDomains[message:match(header.dnsHeaderMatch)] = tostring(dist)
						end
					end
				end
			end
		elseif event == "rednet_message" and allowUnencryptedConnections then
			if protocol and tonumber(protocol:match(header.rednetMatch)) == publicResponseChannel and channel:match(header.dnsHeaderMatch) then
				if not uniqueServers[tostring(id)] then
					uniqueServers[tostring(id)] = true
					local domain = channel:match(header.dnsHeaderMatch)
					if not uniqueDomains[domain] then
						if not(domain:find("/") or domain:find(":") or domain:find("%?")) and #domain > 4 then
							timer = os.startTimer(searchResultTimeout)
							uniqueDomains[domain] = tostring(id)
						end
					end
				end
			end
		elseif event == "timer" and id == timer then
			local results = {}
			for k, _ in pairs(uniqueDomains) do
				table.insert(results, k)
			end

			return results
		end
	end
end


protocols["rdnt"]["fetchConnectionObject"] = function(url)
	local serverChannel = Cryptography.channel(url)
	local requestHeader = header.requestHeaderA .. url .. header.requestHeaderB
	local responseMatch = header.responseMatchA .. Cryptography.sanatize(url) .. header.responseMatchB

	local serializedHandshake = textutils.serialize(Handshake.generateInitiatorData())

	local rednetResults = {}
	local directResults = {}

	local disconnectOthers = function(ignoreDirect)
		for k,v in pairs(rednetResults) do
			v.close()
		end
		for k,v in pairs(directResults) do
			if k ~= ignoreDirect then
				v.close()
			end
		end
	end

	local timer = os.startTimer(initiationTimeout)

	Modem.open(serverChannel)
	Modem.transmit(serverChannel, requestHeader .. serializedHandshake)

	rednet.broadcast(requestHeader .. serializedHandshake, header.rednetHeader .. serverChannel)

	-- Extendable to have server selection

	while true do
		local event, id, channel, protocol, message, dist = os.pullEventRaw()
		if event == "modem_message" then
			local fullMatch = responseMatch .. tostring(dist) .. header.responseMatchC
			if channel == serverChannel and message:match(fullMatch) and type(textutils.unserialize(message:match(fullMatch))) == "table" then
				local key = Handshake.generateResponseData(textutils.unserialize(message:match(fullMatch)))
				if key then
					local connection = SecureConnection.new(key, url, url, dist)
					table.insert(directResults, {
						connection = connection,
						fetchPage = function(page)
							if not connection then
								return nil
							end

							local fetchTimer = os.startTimer(fetchTimeout)

							local pageRequest = header.pageRequestHeaderA .. url .. header.pageRequestHeaderB .. page
							local pageResponseMatch = header.pageResponseMatchA .. Cryptography.sanatize(url) .. header.pageResponseMatchB

							connection:sendMessage(pageRequest, header.rednetHeader .. connection.channel)

							while true do
								local event, id, channel, protocol, message, dist = os.pullEventRaw()
								if event == "modem_message" and channel == connection.channel and connection:verifyHeader(message) then
									local resp, data = connection:decryptMessage(message)
									if not resp then
										-- Decryption error
									elseif data and data ~= page then
										if data:match(pageResponseMatch) then
											local head, body = data:match(pageResponseMatch)
											return body, textutils.unserialize(head)
										end
									end
								elseif event == "timer" and id == fetchTimer then
									return nil
								end
							end
						end,
						close = function()
							if connection ~= nil then
								connection:sendMessage(header.closeHeaderA .. url .. header.closeHeaderB, header.rednetHeader..connection.channel)
								Modem.close(connection.channel)
								connection = nil
							end
						end
					})

					disconnectOthers(1)
					return directResults[1]
				end
			end
		elseif event == "rednet_message" then
			local fullMatch = responseMatch .. os.getComputerID() .. header.responseMatchC
			if protocol and tonumber(protocol:match(header.rednetMatch)) == serverChannel and channel:match(fullMatch) and type(textutils.unserialize(channel:match(fullMatch))) == "table" then
				local key = Handshake.generateResponseData(textutils.unserialize(channel:match(fullMatch)))
				if key then
					local connection = SecureConnection.new(key, url, url, id, true)
					table.insert(rednetResults, {
						connection = connection,
						fetchPage = function(page)
							if not connection then
								return nil
							end

							local fetchTimer = os.startTimer(fetchTimeout)

							local pageRequest = header.pageRequestHeaderA .. url .. header.pageRequestHeaderB .. page
							local pageResponseMatch = header.pageResponseMatchA .. Cryptography.sanatize(url) .. header.pageResponseMatchB

							connection:sendMessage(pageRequest, header.rednetHeader .. connection.channel)

							while true do
								local event, id, channel, protocol, message, dist = os.pullEventRaw()
								if event == "rednet_message" and protocol and tonumber(protocol:match(header.rednetMatch)) == connection.channel and connection:verifyHeader(channel) then
									local resp, data = connection:decryptMessage(channel)
									if not resp then
										-- Decryption error
									elseif data and data ~= page then
										if data:match(pageResponseMatch) then
											local head, body = data:match(pageResponseMatch)
											return body, textutils.unserialize(head)
										end
									end
								elseif event == "timer" and id == fetchTimer then
									return nil
								end
							end
						end,
						close = function()
							connection:sendMessage(header.closeHeaderA .. url .. header.closeHeaderB, header.rednetHeader..connection.channel)
							Modem.close(connection.channel)
							connection = nil
						end
					})

					if #rednetResults == 1 then
						timer = os.startTimer(0.2)
					end
				end
			end
		elseif event == "timer" and id == timer then
			-- Return
			if #directResults > 0 then
				disconnectOthers(1)
				return directResults[1]
			elseif #rednetResults > 0 then
				local lowestID = math.huge
				local lowestResult = nil
				for k,v in pairs(rednetResults) do
					if v.connection.rednet_id < lowestID then
						lowestID = v.connection.rednet_id
						lowestResult = v
					end
				end

				for k,v in pairs(rednetResults) do
					if v.connection.rednet_id ~= lowestID then
						v.close()
					end
				end

				return lowestResult
			else
				return nil
			end
		end
	end
end



--    Fetching Raw Data


local fetchSearchResultsForQuery = function(query)
	local all = protocols[currentProtocol]["fetchAllSearchResults"]()
	local results = {}
	if query and query:len() > 0 then
		for _, v in pairs(all) do
			if v:find(query:lower()) then
				table.insert(results, v)
			end
		end
	else
		results = all
	end

	table.sort(results)
	return results
end


local getConnectionObjectFromURL = function(url)
	local domain = url:match("^([^/]+)")
	return protocols[currentProtocol]["fetchConnectionObject"](domain)
end


local determineLanguage = function(header)
	if type(header) == "table" then
		if header.language and header.language == "Firewolf Markup" then
			return "fwml"
		else
			return "lua"
		end
	else
		return "lua"
	end
end



--    History


local appendToHistory = function(url)
	if history[1] ~= url then
		table.insert(history, 1, url)
	end
end



--    Fetch Websites


local loadingAnimation = function()
	local state = -2

	term.setTextColor(theme.text)
	term.setBackgroundColor(theme.accent)

	term.setCursorPos(w - 5, 1)
	term.write("[=  ]")

	local timer = os.startTimer(animationInterval)

	while true do
		local event, timerID = os.pullEvent()
		if event == "timer" and timerID == timer then
			term.setTextColor(theme.text)
			term.setBackgroundColor(theme.accent)

			state = state + 1

			term.setCursorPos(w - 5, 1)
			term.write("[   ]")
			term.setCursorPos(w - 2 - math.abs(state), 1)
			term.write("=")

			if state == 2 then
				state = -2
			end

			timer = os.startTimer(animationInterval)
		end
	end
end


local normalizeURL = function(url)
	url = url:lower():gsub(" ", "")
	if url == "home" or url == "homepage" then
		url = "firewolf"
	end

	return url
end


local normalizePage = function(page)
	if not page then page = "" end
	page = page:lower()
	if page == "" then
		page = "/"
	end
	return page
end


local determineActionForURL = function(url)
	if url:len() > 0 and url:gsub("/", ""):len() == 0 then
		return "none"
	end

	if url == "exit" then
		return "exit"
	elseif builtInSites["display"][url] then
		return "internal website"
	elseif url == "" then
		local results = fetchSearchResultsForQuery()
		if #results > 0 then
			return "search", results
		else
			return "none"
		end
	else
		local connection = getConnectionObjectFromURL(url)
		if connection then
			return "external website", connection
		else
			local results = fetchSearchResultsForQuery(url)
			if #results > 0 then
				return "search", results
			else
				return "none"
			end
		end
	end
end


local fetchSearch = function(url, results)
	return languages["lua"]["runWithoutAntivirus"](builtInSites["search"], results)
end


local fetchInternal = function(url)
	return languages["lua"]["runWithoutAntivirus"](builtInSites["display"][url])
end


local fetchError = function(err)
	return languages["lua"]["runWithoutAntivirus"](builtInSites["error"], err)
end


local fetchExternal = function(url, connection)
	if connection.multipleServers then
		-- Please forgive me
		-- GravityScore forced me to do it like this
		-- I don't mean it, I really don't.
		connection = connection.servers[1]
	end

	local page = normalizePage(url:match("^[^/]+/(.+)"))
	local contents, head = connection.fetchPage(page)
	if contents then
		if type(contents) ~= "string" then
			return fetchNone()
		else
			local language = determineLanguage(head)
			return languages[language]["run"](contents, page, connection)
		end
	else
		if connection then
			connection.close()
			return "retry"
		end
		return fetchError("A connection error/timeout has occurred!")
	end
end


local fetchNone = function()
	return languages["lua"]["runWithoutAntivirus"](builtInSites["noresults"])
end


local fetchURL = function(url, inheritConnection)
	url = normalizeURL(url)
	currentWebsiteURL = url

	if inheritConnection then
		local resp = fetchExternal(url, inheritConnection)
		if resp ~= "retry" then
			return resp, false, inheritConnection
		end
	end

	local action, connection = determineActionForURL(url)

	if action == "search" then
		return fetchSearch(url, connection), true
	elseif action == "internal website" then
		return fetchInternal(url), true
	elseif action == "external website" then
		local resp = fetchExternal(url, connection)
		if resp == "retry" then
			return fetchError("A connection error/timeout has occurred!"), false, connection
		else
			return resp, false, connection
		end
	elseif action == "none" then
		return fetchNone(), true
	elseif action == "exit" then
		os.queueEvent("terminate")
	end

	return nil
end



--    Tabs


local switchTab = function(index, shouldntResume)
	if not tabs[index] then
		return
	end

	if tabs[currentTab].win then
		tabs[currentTab].win.setVisible(false)
	end

	currentTab = index
	isMenubarOpen = tabs[currentTab].isMenubarOpen
	currentWebsiteURL = tabs[currentTab].url

	term.redirect(originalTerminal)
	clear(theme.background, theme.text)
	drawMenubar()

	term.redirect(tabs[currentTab].win)
	term.setCursorPos(1, 1)
	tabs[currentTab].win.setVisible(true)
	tabs[currentTab].win.redraw()

	if not shouldntResume then
		coroutine.resume(tabs[currentTab].thread)
	end
end


local closeCurrentTab = function()
	if #tabs <= 0 then
		return
	end

	table.remove(tabs, currentTab)

	currentTab = math.max(currentTab - 1, 1)
	switchTab(currentTab, true)
end


local loadTab = function(index, url, givenFunc)
	url = normalizeURL(url)

	local func = nil
	local isOpen = true
	local currentConnection = false

	isMenubarOpen = true
	currentWebsiteURL = url
	drawMenubar()

	if tabs[index] and tabs[index].connection and tabs[index].url then
		if url:match("^([^/]+)") == tabs[index].url:match("^([^/]+)") then
			currentConnection = tabs[index].connection
		else
			tabs[index].connection.close()
			tabs[index].connection = nil
		end
	end

	if givenFunc then
		func = givenFunc
	else
		parallel.waitForAny(function()
			func, isOpen, connection = fetchURL(url, currentConnection)
		end, function()
			while true do
				local event, key = os.pullEvent()
				if event == "key" and (key == 29 or key == 157) then
					break
				end
			end
		end, loadingAnimation)
	end

	if func then
		appendToHistory(url)

		tabs[index] = {}
		tabs[index].url = url
		tabs[index].connection = connection
		tabs[index].win = window.create(originalTerminal, 1, 1, w, h, false)

		tabs[index].thread = coroutine.create(func)
		tabs[index].isMenubarOpen = isOpen
		tabs[index].isMenubarPermanent = isOpen

		tabs[index].ox = 1
		tabs[index].oy = 1

		term.redirect(tabs[index].win)
		clear(theme.background, theme.text)

		switchTab(index)
	end
end



--    Website Environments


local getWhitelistedEnvironment = function()
	local env = {}

	local function copy(source, destination, key)
		destination[key] = {}
		for k, v in pairs(source) do
			destination[key][k] = v
		end
	end

	copy(bit, env, "bit")
	copy(colors, env, "colors")
	copy(colours, env, "colours")
	copy(coroutine, env, "coroutine")

	copy(disk, env, "disk")
	env["disk"]["setLabel"] = nil
	env["disk"]["eject"] = nil

	copy(gps, env, "gps")
	copy(help, env, "help")
	copy(keys, env, "keys")
	copy(math, env, "math")

	copy(os, env, "os")
	env["os"]["run"] = nil
	env["os"]["shutdown"] = nil
	env["os"]["reboot"] = nil
	env["os"]["setComputerLabel"] = nil
	env["os"]["queueEvent"] = nil
	env["os"]["pullEvent"] = function(filter)
		while true do
			local event = {os.pullEvent(filter)}
			if not filter then
				return unpack(event)
			elseif filter and event[1] == filter then
				return unpack(event)
			end
		end
	end
	env["os"]["pullEventRaw"] = env["os"]["pullEvent"]

	copy(paintutils, env, "paintutils")
	copy(parallel, env, "parallel")
	copy(peripheral, env, "peripheral")
	copy(rednet, env, "rednet")
	copy(redstone, env, "redstone")
	copy(redstone, env, "rs")

	copy(shell, env, "shell")
	env["shell"]["run"] = nil
	env["shell"]["exit"] = nil
	env["shell"]["setDir"] = nil
	env["shell"]["setAlias"] = nil
	env["shell"]["clearAlias"] = nil
	env["shell"]["setPath"] = nil

	copy(string, env, "string")
	copy(table, env, "table")

	copy(term, env, "term")
	env["term"]["redirect"] = nil
	env["term"]["restore"] = nil

	copy(textutils, env, "textutils")
	copy(vector, env, "vector")

	if turtle then
		copy(turtle, env, "turtle")
	end

	if http then
		copy(http, env, "http")
	end

	env["assert"] = assert
	env["printError"] = printError
	env["tonumber"] = tonumber
	env["tostring"] = tostring
	env["type"] = type
	env["next"] = next
	env["unpack"] = unpack
	env["pcall"] = pcall
	env["xpcall"] = xpcall
	env["sleep"] = sleep
	env["pairs"] = pairs
	env["ipairs"] = ipairs
	env["read"] = read
	env["write"] = write
	env["select"] = select
	env["print"] = print
	env["setmetatable"] = setmetatable
	env["getmetatable"] = getmetatable

	env["_G"] = env

	return env
end


local overrideEnvironment = function(env)
	local localTerm = {}
	for k, v in pairs(term) do
		localTerm[k] = v
	end

	env["term"]["clear"] = function()
		localTerm.clear()
		drawMenubar()
	end

	env["term"]["scroll"] = function(n)
		localTerm.scroll(n)
		drawMenubar()
	end

	env["shell"]["getRunningProgram"] = function()
		return currentWebsiteURL
	end
end

local urlEncode = function(url)
	local result = url

	result = result:gsub("%%", "%%a")
	result = result:gsub(":", "%%c")
	result = result:gsub("/", "%%s")
	result = result:gsub("\n", "%%n")
	result = result:gsub(" ", "%%w")
	result = result:gsub("&", "%%m")
	result = result:gsub("%?", "%%q")
	result = result:gsub("=", "%%e")
	result = result:gsub("%.", "%%d")

	return result
end

local urlDecode = function(url)
	local result = url

	result = result:gsub("%%c", ":")
	result = result:gsub("%%s", "/")
	result = result:gsub("%%n", "\n")
	result = result:gsub("%%w", " ")
	result = result:gsub("%%&", "&")
	result = result:gsub("%%q", "%?")
	result = result:gsub("%%e", "=")
	result = result:gsub("%%d", "%.")
	result = result:gsub("%%m", "%%")

	return result
end

local applyAPIFunctions = function(env, connection)
	env["firewolf"] = {}
	env["firewolf"]["version"] = version
	env["firewolf"]["domain"] = currentWebsiteURL:match("^[^/]+")

	env["firewolf"]["redirect"] = function(url)
		if type(url) ~= "string" then
			return error("string (url) expected, got " .. type(url))
		end

		os.queueEvent(redirectEvent, url)
		coroutine.yield()
	end

	env["firewolf"]["download"] = function(page)
		if type(page) ~= "string" then
			return error("string (page) expected")
		end
		local bannedNames = {"ls", "dir", "delete", "copy", "move", "list", "rm", "cp", "mv", "clear", "cd", "lua"}

		local startSearch, endSearch = page:find(currentWebsiteURL:match("^[^/]+"))
		if startSearch == 1 then
			if page:sub(endSearch + 1, endSearch + 1) == "/" then
				page = page:sub(endSearch + 2, -1)
			else
				page = page:sub(endSearch + 1, -1)
			end
		end

		local filename = page:match("([^/]+)$")
		if not filename then
			return false, "Cannot download index"
		end

		for k, v in pairs(bannedNames) do
			if filename == v then
				return false, "Filename prohibited!"
			end
		end

		if not fs.exists(downloadsLocation) then
			fs.makeDir(downloadsLocation)
		elseif not fs.isDir(downloadsLocation) then
			return false, "Downloads disabled!"
		end

		contents = connection.fetchPage(normalizePage(page))
		if type(contents) ~= "string" then
			return false, "Download error!"
		else
			local f = io.open(downloadsLocation .. "/" .. filename, "w")
			f:write(contents)
			f:close()
			return true, downloadsLocation .. "/" .. filename
		end
	end

	env["firewolf"]["encode"] = function(vars)
		if type(vars) ~= "table" then
			return error("table (vars) expected, got " .. type(vars))
		end

		local startSearch, endSearch = page:find(currentWebsiteURL:match("^[^/]+"))
		if startSearch == 1 then
			if page:sub(endSearch + 1, endSearch + 1) == "/" then
				page = page:sub(endSearch + 2, -1)
			else
				page = page:sub(endSearch + 1, -1)
			end
		end

		local construct = "?"
		for k,v in pairs(vars) do
 			construct = construct .. urlEncode(tostring(k)) .. "=" .. urlEncode(tostring(v)) .. "&"
		end
		-- Get rid of that last ampersand
		construct = construct:sub(1, -2)

		return construct
	end

	env["firewolf"]["query"] = function(page, vars)
		if type(page) ~= "string" then
			return error("string (page) expected, got " .. type(page))
		end
		if vars and type(vars) ~= "table" then
			return error("table (vars) expected, got " .. type(vars))
		end

		local startSearch, endSearch = page:find(currentWebsiteURL:match("^[^/]+"))
		if startSearch == 1 then
			if page:sub(endSearch + 1, endSearch + 1) == "/" then
				page = page:sub(endSearch + 2, -1)
			else
				page = page:sub(endSearch + 1, -1)
			end
		end

		local construct = page .. "?"
		if vars then
			for k,v in pairs(vars) do
	 			construct = construct .. urlEncode(tostring(k)) .. "=" .. urlEncode(tostring(v)) .. "&"
			end
		end
		-- Get rid of that last ampersand
		construct = construct:sub(1, -2)

		contents = connection.fetchPage(normalizePage(construct))
		if type(contents) == "string" then
			return contents
		else
			return false
		end
	end

	env["firewolf"]["loadImage"] = function(page)
		if type(page) ~= "string" then
			return error("string (page) expected, got " .. type(page))
		end

		local startSearch, endSearch = page:find(currentWebsiteURL:match("^[^/]+"))
		if startSearch == 1 then
			if page:sub(endSearch + 1, endSearch + 1) == "/" then
				page = page:sub(endSearch + 2, -1)
			else
				page = page:sub(endSearch + 1, -1)
			end
		end

		local filename = page:match("([^/]+)$")
		if not filename then
			return false, "Cannot load index as an image!"
		end

		contents = connection.fetchPage(normalizePage(page))
		if type(contents) ~= "string" then
			return false, "Download error!"
		else
			local colorLookup = {}
			for n = 1, 16 do
				colorLookup[string.byte("0123456789abcdef", n, n)] = 2 ^ (n - 1)
			end

			local image = {}
			for line in contents:gmatch("[^\n]+") do
				local lines = {}
				for x = 1, line:len() do
					lines[x] = colorLookup[string.byte(line, x, x)] or 0
				end
				table.insert(image, lines)
			end

			return image
		end
	end

	env["center"] = center
	env["fill"] = fill
end


local getWebsiteEnvironment = function(antivirus, connection)
	local env = {}

	if antivirus then
		env = getWhitelistedEnvironment()
		overrideEnvironment(env)
	else
		setmetatable(env, {__index = _G})
	end

	applyAPIFunctions(env, connection)

	return env
end



--    FWML Execution


local render = {}

render["functions"] = {}
render["functions"]["public"] = {}
render["alignations"] = {}

render["variables"] = {
	scroll,
	maxScroll,
	align,
	linkData = {},
	blockLength,
	link,
	linkStart,
	markers,
	currentOffset,
}


local function getLine(loc, data)
	local _, changes = data:sub(1, loc):gsub("\n", "")
	if not changes then
		return 1
	else
		return changes + 1
	end
end


local function parseData(data)
	local commands = {}
	local searchPos = 1

	while #data > 0 do
		local sCmd, eCmd = data:find("%[[^%]]+%]", searchPos)
		if sCmd then
			sCmd = sCmd + 1
			eCmd = eCmd - 1

			if (sCmd > 2) then
				if data:sub(sCmd - 2, sCmd - 2) == "\\" then
					local t = data:sub(searchPos, sCmd - 1):gsub("\n", ""):gsub("\\%[", "%["):gsub("\\%]", "%]")
					if #t > 0 then
						if #commands > 0 and type(commands[#commands][1]) == "string" then
							commands[#commands][1] = commands[#commands][1] .. t
						else
							table.insert(commands, {t})
						end
					end
					searchPos = sCmd
				else
					local t = data:sub(searchPos, sCmd - 2):gsub("\n", ""):gsub("\\%[", "%["):gsub("\\%]", "%]")
					if #t > 0 then
						if #commands > 0 and type(commands[#commands][1]) == "string" then
							commands[#commands][1] = commands[#commands][1] .. t
						else
							table.insert(commands, {t})
						end
					end

					t = data:sub(sCmd, eCmd):gsub("\n", "")
					table.insert(commands, {getLine(sCmd, data), t})
					searchPos = eCmd + 2
				end
			else
				local t = data:sub(sCmd, eCmd):gsub("\n", "")
				table.insert(commands, {getLine(sCmd, data), t})
				searchPos = eCmd + 2
			end
		else
			local t = data:sub(searchPos, -1):gsub("\n", ""):gsub("\\%[", "%["):gsub("\\%]", "%]")
			if #t > 0 then
				if #commands > 0 and type(commands[#commands][1]) == "string" then
					commands[#commands][1] = commands[#commands][1] .. t
				else
					table.insert(commands, {t})
				end
			end

			break
		end
	end

	return commands
end


local function proccessData(commands)
	searchIndex = 0

	while searchIndex < #commands do
		searchIndex = searchIndex + 1

		local length = 0
		local origin = searchIndex

		if type(commands[searchIndex][1]) == "string" then
			length = length + #commands[searchIndex][1]
			local endIndex = origin
			for i = origin + 1, #commands do
				if commands[i][2] then
					local command = commands[i][2]:match("^(%w+)%s-")
					if not (command == "c" or command == "color" or command == "bg"
							or command == "background" or command == "newlink" or command == "endlink") then
						endIndex = i
						break
					end
				elseif commands[i][2] then

				else
					length = length + #commands[i][1]
				end
				if i == #commands then
					endIndex = i
				end
			end

			commands[origin][2] = length
			searchIndex = endIndex
			length = 0
		end
	end

	return commands
end


local function parse(original)
	return proccessData(parseData(original))
end


render["functions"]["display"] = function(text, length, offset, center)
	if not offset then
		offset = 0
	end

	return render.variables.align(text, length, w, offset, center);
end


render["functions"]["displayText"] = function(source)
	if source[2] then
		render.variables.blockLength = source[2]
		if render.variables.link and not render.variables.linkStart then
			render.variables.linkStart = render.functions.display(
				source[1], render.variables.blockLength, render.variables.currentOffset, w / 2)
		else
			render.functions.display(source[1], render.variables.blockLength, render.variables.currentOffset, w / 2)
		end
	else
		if render.variables.link and not render.variables.linkStart then
			render.variables.linkStart = render.functions.display(source[1], nil, render.variables.currentOffset, w / 2)
		else
			render.functions.display(source[1], nil, render.variables.currentOffset, w / 2)
		end
	end
end


render["functions"]["public"]["br"] = function(source)
	if render.variables.link then
		return "Cannot insert new line within a link on line " .. source[1]
	end

	render.variables.scroll = render.variables.scroll + 1
	render.variables.maxScroll = math.max(render.variables.scroll, render.variables.maxScroll)
end


render["functions"]["public"]["c "] = function(source)
	local sColor = source[2]:match("^%w+%s+(.+)$") or ""
	if colors[sColor] then
		term.setTextColor(colors[sColor])
	else
		return "Invalid color: \"" .. sColor .. "\" on line " .. source[1]
	end
end


render["functions"]["public"]["color "] = render["functions"]["public"]["c "]


render["functions"]["public"]["bg "] = function(source)
	local sColor = source[2]:match("^%w+%s+(.+)$") or ""
	if colors[sColor] then
		term.setBackgroundColor(colors[sColor])
	else
		return "Invalid color: \"" .. sColor .. "\" on line " .. source[1]
	end
end


render["functions"]["public"]["background "] = render["functions"]["public"]["bg "]


render["functions"]["public"]["newlink "] = function(source)
	if render.variables.link then
		return "Cannot nest links on line " .. source[1]
	end

	render.variables.link = source[2]:match("^%w+%s+(.+)$") or ""
	render.variables.linkStart = false
end


render["functions"]["public"]["endlink"] = function(source)
	if not render.variables.link then
		return "Cannot end a link without a link on line " .. source[1]
	end

	local linkEnd = term.getCursorPos()-1
	table.insert(render.variables.linkData, {render.variables.linkStart,
		linkEnd, render.variables.scroll, render.variables.link})
	render.variables.link = false
	render.variables.linkStart = false
end


render["functions"]["public"]["offset "] = function(source)
	local offset = tonumber((source[2]:match("^%w+%s+(.+)$") or ""))
	if offset then
		render.variables.currentOffset = offset
	else
		return "Invalid offset value: \"" .. (source[2]:match("^%w+%s+(.+)$") or "") .. "\" on line " .. source[1]
	end
end


render["functions"]["public"]["marker "] = function(source)
	render.variables.markers[(source[2]:match("^%w+%s+(.+)$") or "")] = render.variables.scroll
end


render["functions"]["public"]["goto "] = function(source)
	local location = source[2]:match("%w+%s+(.+)$")
	if render.variables.markers[location] then
		render.variables.scroll = render.variables.markers[location]
	else
		return "No such location: \"" .. (source[2]:match("%w+%s+(.+)$") or "") .. "\" on line " .. source[1]
	end
end


render["functions"]["public"]["box "] = function(source)
	local sColor, align, height, width, offset, url = source[2]:match("^box (%a+) (%a+) (%-?%d+) (%-?%d+) (%-?%d+) ?([^ ]*)")
	if not sColor then
		return "Invalid box syntax on line " .. source[1]
	end

	local x, y = term.getCursorPos()
	local startX

	if align == "center" or align == "centre" then
		startX = math.ceil((w / 2) - width / 2) + offset
	elseif align == "left" then
		startX = 1 + offset
	elseif align == "right" then
		startX = (w - width + 1) + offset
	else
		return "Invalid align option for box on line " .. source[1]
	end

	if not colors[sColor] then
		return "Invalid color: \"" .. sColor .. "\" for box on line " .. source[1]
	end

	term.setBackgroundColor(colors[sColor])
	for i = 0, height - 1 do
		term.setCursorPos(startX, render.variables.scroll + i)
		term.write(string.rep(" ", width))
		if url:len() > 3 then
			table.insert(render.variables.linkData, {startX, startX + width - 1, render.variables.scroll + i, url})
		end
	end

	render.variables.maxScroll = math.max(render.variables.scroll + height - 1, render.variables.maxScroll)
	term.setCursorPos(x, y)
end


render["alignations"]["left"] = function(text, length, _, offset)
	local x, y = term.getCursorPos()
	if length then
		term.setCursorPos(1 + offset, render.variables.scroll)
		term.write(text)
		return 1 + offset
	else
		term.setCursorPos(x, render.variables.scroll)
		term.write(text)
		return x
	end
end


render["alignations"]["right"] = function(text, length, width, offset)
	local x, y = term.getCursorPos()
	if length then
		term.setCursorPos((width - length + 1) + offset, render.variables.scroll)
		term.write(text)
		return (width - length + 1) + offset
	else
		term.setCursorPos(x, render.variables.scroll)
		term.write(text)
		return x
	end
end


render["alignations"]["center"] = function(text, length, _, offset, center)
	local x, y = term.getCursorPos()
	if length then
		term.setCursorPos(math.ceil(center - length / 2) + offset, render.variables.scroll)
		term.write(text)
		return math.ceil(center - length / 2) + offset
	else
		term.setCursorPos(x, render.variables.scroll)
		term.write(text)
		return x
	end
end


render["render"] = function(data, startScroll)
	if startScroll == nil then
		render.variables.startScroll = 0
	else
		render.variables.startScroll = startScroll
	end

	render.variables.scroll = startScroll + 1
	render.variables.maxScroll = render.variables.scroll

	render.variables.linkData = {}

	render.variables.align = render.alignations.left

	render.variables.blockLength = 0
	render.variables.link = false
	render.variables.linkStart = false
	render.variables.markers = {}
	render.variables.currentOffset = 0

	for k, v in pairs(data) do
		if type(v[2]) ~= "string" then
			render.functions.displayText(v)
		elseif v[2] == "<" or v[2] == "left" then
			render.variables.align = render.alignations.left
		elseif v[2] == ">" or v[2] == "right" then
			render.variables.align = render.alignations.right
		elseif v[2] == "=" or v[2] == "center" then
			render.variables.align = render.alignations.center
		else
			local existentFunction = false

			for name, func in pairs(render.functions.public) do
				if v[2]:find(name) == 1 then
					existentFunction = true
					local ret = func(v)
					if ret then
						return ret
					end
				end
			end

			if not existentFunction then
				return "Non-existent tag: \"" .. v[2] .. "\" on line " .. v[1]
			end
		end
	end

	return render.variables.linkData, render.variables.maxScroll - render.variables.startScroll
end



--    Lua Execution


languages["lua"] = {}
languages["fwml"] = {}


languages["lua"]["runWithErrorCatching"] = function(func, ...)
	local _, err = pcall(func, ...)
	if err then
		os.queueEvent(websiteErrorEvent, err)
	end
end


languages["lua"]["runWithoutAntivirus"] = function(func, ...)
	local args = {...}
	local env = getWebsiteEnvironment(false)
	setfenv(func, env)
	return function()
		languages["lua"]["runWithErrorCatching"](func, unpack(args))
	end
end


languages["lua"]["run"] = function(contents, page, connection, ...)
	local func, err = loadstring("sleep(0) " .. contents, page)
	if err then
		return languages["lua"]["runWithoutAntivirus"](builtInSites["crash"], err)
	else
		local args = {...}
		local env = getWebsiteEnvironment(true, connection)
		setfenv(func, env)
		return function()
			languages["lua"]["runWithErrorCatching"](func, unpack(args))
		end
	end
end


languages["fwml"]["run"] = function(contents, page, connection, ...)
	local err, data = pcall(parse, contents)
	if not err then
		return languages["lua"]["runWithoutAntivirus"](builtInSites["crash"], data)
	end

	return function()
		local currentScroll = 0
		local err, links, pageHeight = pcall(render.render, data, currentScroll)
		if type(links) == "string" or not err then
			term.clear()
			os.queueEvent(websiteErrorEvent, links)
		else
			while true do
				local e, scroll, x, y = os.pullEvent()
				if e == "mouse_click" then
					for k, v in pairs(links) do
						if x >= math.min(v[1], v[2]) and x <= math.max(v[1], v[2]) and y == v[3] then
							os.queueEvent(redirectEvent, v[4])
							coroutine.yield()
						end
					end
				elseif e == "mouse_scroll" then
					if currentScroll - scroll - h >= -pageHeight and currentScroll - scroll <= 0 then
						currentScroll = currentScroll - scroll
						clear(theme.background, theme.text)
						links = render.render(data, currentScroll)
					end
				elseif e == "key" and scroll == keys.up or scroll == keys.down then
					local scrollAmount

					if scroll == keys.up then
						scrollAmount = 1
					elseif scroll == keys.down then
						scrollAmount = -1
					end

					local scrollLessHeight = currentScroll + scrollAmount - h >= -pageHeight
					local scrollZero = currentScroll + scrollAmount <= 0
					if scrollLessHeight and scrollZero then
						currentScroll = currentScroll + scrollAmount
						clear(theme.background, theme.text)
						links = render.render(data, currentScroll)
					end
				end
			end
		end
	end
end



--    Query Bar


local readNewWebsiteURL = function()
	local onEvent = function(text, event, key, x, y)
		if event == "mouse_click" then
			if y == 2 then
				local index = determineClickedTab(x, y)
				if index == "new" and #tabs < maxTabs then
					loadTab(#tabs + 1, "firewolf")
				elseif index == "close" then
					closeCurrentTab()
				elseif index then
					switchTab(index)
				end

				return {["nullifyText"] = true, ["exit"] = true}
			elseif y > 2 then
				return {["nullifyText"] = true, ["exit"] = true}
			end
		elseif event == "key" then
			if key == 29 or key == 157 then
				return {["nullifyText"] = true, ["exit"] = true}
			end
		end
	end

	isMenubarOpen = true
	drawMenubar()
	term.setCursorPos(2, 1)
	term.setTextColor(theme.text)
	term.setBackgroundColor(theme.accent)
	term.clearLine()
	term.write(currentProtocol .. "://")

	local website = modifiedRead({
		["onEvent"] = onEvent,
		["displayLength"] = w - 9,
		["history"] = history,
	})

	if not website then
		if not tabs[currentTab].isMenubarPermanent then
			isMenubarOpen = false
			menubarWindow.setVisible(false)
		else
			isMenubarOpen = true
			menubarWindow.setVisible(true)
		end

		term.redirect(tabs[currentTab].win)
		tabs[currentTab].win.setVisible(true)
		tabs[currentTab].win.redraw()

		return
	elseif website == "exit" then
		error()
	end

	loadTab(currentTab, website)
end



--    Event Management


local handleKeyDown = function(event)
	if event[2] == 29 or event[2] == 157 then
		readNewWebsiteURL()
		return true
	end

	return false
end


local handleMouseDown = function(event)
	if isMenubarOpen then
		if event[4] == 1 then
			readNewWebsiteURL()
			return true
		elseif event[4] == 2 then
			local index = determineClickedTab(event[3], event[4])
			if index == "new" and #tabs < maxTabs then
				loadTab(#tabs + 1, "firewolf")
			elseif index == "close" then
				closeCurrentTab()
			elseif index then
				switchTab(index)
			end

			return true
		end
	end

	return false
end


local handleEvents = function()
	loadTab(1, "firewolf")
	currentTab = 1

	while true do
		drawMenubar()
		local event = {os.pullEventRaw()}
		drawMenubar()

		local cancelEvent = false
		if event[1] == "terminate" then
			break
		elseif event[1] == "key" then
			cancelEvent = handleKeyDown(event)
		elseif event[1] == "mouse_click" then
			cancelEvent = handleMouseDown(event)
		elseif event[1] == websiteErrorEvent then
			cancelEvent = true

			loadTab(currentTab, tabs[currentTab].url, function()
				builtInSites["crash"](event[2])
			end)
		elseif event[1] == redirectEvent then
			cancelEvent = true

			if (event[2]:match("^rdnt://(.+)$")) then
				event[2] = event[2]:match("^rdnt://(.+)$")
			end

			loadTab(currentTab, event[2])
		end

		if not cancelEvent then
			term.redirect(tabs[currentTab].win)
			term.setCursorPos(tabs[currentTab].ox, tabs[currentTab].oy)

			coroutine.resume(tabs[currentTab].thread, unpack(event))

			local ox, oy = term.getCursorPos()
			tabs[currentTab].ox = ox
			tabs[currentTab].oy = oy
		end
	end
end



--    Main


local main = function()
	currentProtocol = "rdnt"
	currentTab = 1

	if term.isColor() then
		theme = colorTheme
		enableTabBar = true
	else
		theme = grayscaleTheme
		enableTabBar = false
	end

	setupMenubar()
	protocols[currentProtocol]["setup"]()

	clear(theme.background, theme.text)
	handleEvents()
end


local handleError = function(err)
	clear(theme.background, theme.text)

	fill(1, 3, w, 3, theme.subtle)
	term.setCursorPos(1, 4)
	center("Firewolf has crashed!")

	term.setBackgroundColor(theme.background)
	term.setCursorPos(1, 8)
	centerSplit(err, w - 4)
	print("\n")
	center("Please report this error to")
	center("GravityScore or 1lann.")
	print("")
	center("Press any key to exit.")

	os.pullEvent("key")
	os.queueEvent("")
	os.pullEvent()
end

local _, err = pcall(main)
term.redirect(originalTerminal)

Modem.closeAll()

if err and not err:lower():find("terminate") then
	handleError(err)
end


clear(colors.black, colors.white)
center("Thanks for using Firewolf " .. version)
center("Made by GravityScore and 1lann")
print("")