Source

srb2ztm1094 / engine / src / p_spec.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
// Emacs style mode select   -*- C++ -*-
//-----------------------------------------------------------------------------
//
// Copyright (C) 1993-1996 by id Software, Inc.
// Copyright (C) 1998-2000 by DooM Legacy Team.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//-----------------------------------------------------------------------------
/// \file
/// \brief Implements special effects:
///	 - Texture animation, height or lighting changes
///	 according to adjacent sectors, respective
///	 utility functions, etc.
///	 - Line Tag handling. Line and Sector triggers.

#include "doomdef.h"
#include "g_game.h"
#include "p_local.h"
#include "p_setup.h" // levelflats for flat animation
#include "r_data.h"
#include "m_random.h"
#include "p_mobj.h"
#include "i_system.h"
#include "s_sound.h"
#include "w_wad.h"
#include "z_zone.h"
#include "dstrings.h" //SoM: 3/10/2000
#include "r_main.h" //Two extra includes.
#include "r_sky.h"
#include "p_polyobj.h"

#include "hardware/hw3sound.h"

#include "TMNT/TMNTmisc.h" // TMNTCANCARY

#ifdef SONICR
#include "r_things.h" // for skins
#endif

static void P_SpawnScrollers(void);
static void P_SpawnFriction(void);
static void P_SpawnPushers(void);
static void Add_Pusher(pushertype_e type, fixed_t x_mag, fixed_t y_mag, mobj_t *source, long affectee, long referrer, int exclusive); //SoM: 3/9/2000
static void P_AddBlockThinker(sector_t *sec, line_t *sourceline);
static void P_AddFloatThinker(sector_t *sec, int tag);
#ifdef SRB2TODO
static void P_AddBridgeThinker(line_t *sourceline, sector_t *sec);
#endif
static void P_AddFakeFloorsByLine(size_t line, ffloortype_e ffloorflags);
static void P_ProcessLineSpecial(line_t *line, mobj_t *mo);
static void Add_Friction(long friction, long movefactor, long affectee, long referrer);
static void P_AddSpikeThinker(sector_t *sec, int referrer);

/** Animated texture descriptor
  * This keeps track of an animated texture or an animated flat.
  * \sa P_UpdateSpecials, P_InitPicAnims, animdef_t
  */
typedef struct
{
	boolean istexture; ///< ::true for a texture, ::false for a flat
	long picnum;       ///< The end flat number
	long basepic;      ///< The start flat number
	long numpics;      ///< Number of frames in the animation
	tic_t speed;       ///< Number of tics for which each frame is shown
} anim_t;

#if defined(_MSC_VER)
#pragma pack(1)
#endif

/** Animated texture definition.
  * Used for ::harddefs and for loading an ANIMATED lump from a wad.
  *
  * Animations are defined by the first and last frame (i.e., flat or texture).
  * The animation sequence uses all flats between the start and end entry, in
  * the order found in the wad.
  *
  * \sa anim_t
  */
typedef struct
{
	char istexture; ///< True for a texture, false for a flat.
	char endname[9]; ///< Name of the last frame, null-terminated.
	char startname[9]; ///< Name of the first frame, null-terminated.
	int speed ; ///< Number of tics for which each frame is shown.
} ATTRPACK animdef_t;

#if defined(_MSC_VER)
#pragma pack()
#endif

#define PUSH_MASK      0x200
#define MAXANIMS 64

//SoM: 3/7/2000: New sturcture without limits.
static anim_t *lastanim;
static anim_t *anims = NULL; /// \todo free leak
static size_t maxanims;

//
// P_InitPicAnims
//
/** Hardcoded animation sequences.
  * Used if no ANIMATED lump is found in a loaded wad.
  */
static animdef_t harddefs[] =
{
#ifdef TMNTANIMFLATS
	/*char istexture; ///< True for a texture, false for a flat.
	char endname[9]; ///< Name of the last frame, null-terminated.
	char startname[9]; ///< Name of the first frame, null-terminated.
	int speed ; ///< Number of tics for which each frame is shown.*/
	// TODO (Turtle Man#1#): change ANIMATED textures and flats.

#else
	{false,     "NUKAGE3",     "NUKAGE1",     4},
	{false,     "FWATER16",    "FWATER1",     4},
	{false,     "BWATER16",    "BWATER01",    4},
	{false,     "LWATER16",    "LWATER1",     4},
	{false,     "WATER7",      "WATER0",      4},
	{false,     "SWATER4",     "SWATER1",     8},
	{false,     "LAVA4",       "LAVA1",       8},
	{false,     "BLOOD3",      "BLOOD1",      8},

	{false,     "RROCK08",     "RROCK05",     8},
	{false,     "QUIKSN16",    "QUIKSN01",    4}, // Quicksand
	{false,     "CHEMG16",     "CHEMG01",     4}, // THZ Chemical gunk
	{false,     "GOOP16",      "GOOP01",      4}, // Green chemical gunk
	{false,     "SLIME08",     "SLIME05",     4},
	{false,     "THZBOXF4",    "THZBOXF1",    2}, // Moved up with the flats
	{false,     "ALTBOXF4",    "ALTBOXF1",    2},

	{false,     "BLUE3",       "BLUE1",       4},
	{false,     "GREY3",       "GREY1",       4},

	// animated textures
	{true,      "GFALL4",      "GFALL1",      2}, // Short waterfall
	{true,      "CFALL4",      "CFALL1",      2}, // Long waterfall
	{true,      "TFALL4",      "TFALL1",      2}, // THZ Chemical fall
	{true,      "AFALL4",      "AFALL1",      2}, // Green Chemical fall
	{true,      "THZBOX04",    "THZBOX01",    2},
	{true,      "ALTBOX04",    "ALTBOX01",    2},
	{true,      "SFALL4",      "SFALL1",      4}, // Lava fall
	{true,      "BFALL4",      "BFALL1",      2}, // HPZ waterfall
	{true,      "GREYW3",      "GREYW1",      4},
	{true,      "BLUEW3",      "BLUEW1",      4},
	{true,      "COMP6",       "COMP4",       4},
	{true,      "RED3",        "RED1",        4},
	{true,      "YEL3",        "YEL1",        4},
#endif

	// begin dummy slots
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},
	{false,     "DUMYSLOT",    "DUMYSLOT",    8},

	{   -1,             "",            "",    0},
};

// Animating line specials

// Init animated textures
// - now called at level loading P_SetupLevel()

static animdef_t *animdefs;

/** Sets up texture and flat animations.
  *
  * Converts an ::animdef_t array loaded from ::harddefs or a lump into
  * ::anim_t format.
  *
  * Issues an error if any animation cycles are invalid.
  *
  * \sa P_FindAnimatedFlat, P_SetupLevelFlatAnims
  * \author Steven McGranahan
  */
void P_InitPicAnims(void)
{
	// Init animation
	int i;

	if (W_CheckNumForName("ANIMATED") != LUMPERROR)
		animdefs = (animdef_t *)W_CacheLumpName("ANIMATED", PU_STATIC);
	else
		animdefs = harddefs;

	for (i = 0; animdefs[i].istexture != (char)-1; i++, maxanims++);

	if (anims)
		free(anims);

	anims = (anim_t *)malloc(sizeof (*anims)*(maxanims + 1));
	if (!anims)
		I_Error("No free memory for ANIMATED data");

	lastanim = anims;
	for (i = 0; animdefs[i].istexture != (char)-1; i++)
	{
		if (animdefs[i].istexture)
		{
			if (R_CheckTextureNumForName(animdefs[i].startname, 0xffff) == -1)
				continue;

			lastanim->picnum = R_TextureNumForName(animdefs[i].endname, 0xffff);
			lastanim->basepic = R_TextureNumForName(animdefs[i].startname, 0xffff);
		}
		else
		{
			if ((W_CheckNumForName(animdefs[i].startname)) == LUMPERROR)
				continue;

			lastanim->picnum = R_FlatNumForName(animdefs[i].endname);
			lastanim->basepic = R_FlatNumForName(animdefs[i].startname);
		}

		lastanim->istexture = (boolean)animdefs[i].istexture;
		lastanim->numpics = lastanim->picnum - lastanim->basepic + 1;

		if (lastanim->numpics < 2)
		{
			free(anims);
			I_Error("P_InitPicAnims: bad cycle from %s to %s",
				animdefs[i].startname, animdefs[i].endname);
		}

		lastanim->speed = LONG(animdefs[i].speed) * NEWTICRATERATIO;
		lastanim++;
	}
	lastanim->istexture = (boolean)-1;

	if (animdefs != harddefs)
		Z_ChangeTag(animdefs, PU_CACHE);
}

/** Checks for flats in levelflats that are part of a flat animation sequence
  * and sets them up for animation.
  *
  * \param animnum Index into ::anims to find flats for.
  * \sa P_SetupLevelFlatAnims
  */
static inline void P_FindAnimatedFlat(int animnum)
{
	size_t i;
	lumpnum_t startflatnum, endflatnum;
	levelflat_t *foundflats;

	foundflats = levelflats;
	startflatnum = anims[animnum].basepic;
	endflatnum = anims[animnum].picnum;

	// note: high word of lumpnum is the wad number
	if ((startflatnum>>16) != (endflatnum>>16))
		I_Error("AnimatedFlat start %s not in same wad as end %s\n",
			animdefs[animnum].startname, animdefs[animnum].endname);

	//
	// now search through the levelflats if this anim flat sequence is used
	//
	for (i = 0; i < numlevelflats; i++, foundflats++)
	{
		// is that levelflat from the flat anim sequence ?
		if (foundflats->lumpnum >= startflatnum && foundflats->lumpnum <= endflatnum)
		{
			foundflats->baselumpnum = startflatnum;
			foundflats->animseq = foundflats->lumpnum - startflatnum;
			foundflats->numpics = endflatnum - startflatnum + 1;
			foundflats->speed = anims[animnum].speed;

			if (devparm)
				I_OutputMsg("animflat: #%03u name:%.8s animseq:%d numpics:%d speed:%d\n",
					i, foundflats->name, foundflats->animseq,
					foundflats->numpics,foundflats->speed);
		}
	}
}

/** Sets up all flats used in a level.
  *
  * \sa P_InitPicAnims, P_FindAnimatedFlat
  */
void P_SetupLevelFlatAnims(void)
{
	int i;

	// the original game flat anim sequences
	for (i = 0; anims[i].istexture != (boolean)-1; i++)
	{
		if (!anims[i].istexture)
			P_FindAnimatedFlat(i);
	}
}

//
// UTILITIES
//

/** Gets a side from a sector line.
  *
  * \param currentSector Sector the line is in.
  * \param line          Index of the line within the sector.
  * \param side          0 for front, 1 for back.
  * \return Pointer to the side_t of the side you want.
  * \sa getSector, twoSided, getNextSector
  */
static inline side_t *getSide(int currentSector, int line, int side)
{
	return &sides[(sectors[currentSector].lines[line])->sidenum[side]];
}

/** Gets a sector from a sector line.
  *
  * \param currentSector Sector the line is in.
  * \param line          Index of the line within the sector.
  * \param side          0 for front, 1 for back.
  * \return Pointer to the ::sector_t of the sector on that side.
  * \sa getSide, twoSided, getNextSector
  */
static inline sector_t *getSector(int currentSector, int line, int side)
{
	return sides[(sectors[currentSector].lines[line])->sidenum[side]].sector;
}

/** Determines whether a sector line is two-sided.
  * Uses the Boom method, checking if the line's back side is set to -1, rather
  * than looking for ::ML_TWOSIDED.
  *
  * \param sector The sector.
  * \param line   Line index within the sector.
  * \return 1 if the sector is two-sided, 0 otherwise.
  * \sa getSide, getSector, getNextSector
  */
static inline boolean twoSided(int sector, int line)
{
	return (sectors[sector].lines[line])->sidenum[1] != 0xffff;
}

/** Finds sector next to current.
  *
  * \param line Pointer to the line to cross.
  * \param sec  Pointer to the current sector.
  * \return Pointer to a ::sector_t of the adjacent sector, or NULL if the line
  *         is one-sided.
  * \sa getSide, getSector, twoSided
  * \author Steven McGranahan
  */
#ifndef DOORS
static inline
#endif
sector_t *getNextSector(line_t *line, sector_t *sec)
{
	if (line->frontsector == sec)
	{
		if (line->backsector != sec)
			return line->backsector;
		else
			return NULL;
	}
	return line->frontsector;
}

/** Finds lowest floor in adjacent sectors.
  *
  * \param sec Sector to start in.
  * \return Lowest floor height in an adjacent sector.
  * \sa P_FindHighestFloorSurrounding, P_FindNextLowestFloor,
  *     P_FindLowestCeilingSurrounding
  */
fixed_t P_FindLowestFloorSurrounding(sector_t *sec)
{
	size_t i;
	line_t *check;
	sector_t *other;
	fixed_t floorh;

	floorh = sec->floorheight;

	for (i = 0; i < sec->linecount; i++)
	{
		check = sec->lines[i];
		other = getNextSector(check,sec);

		if (!other)
			continue;

		if (other->floorheight < floorh)
			floorh = other->floorheight;
	}
	return floorh;
}

/** Finds highest floor in adjacent sectors.
  *
  * \param sec Sector to start in.
  * \return Highest floor height in an adjacent sector.
  * \sa P_FindLowestFloorSurrounding, P_FindNextHighestFloor,
  *     P_FindHighestCeilingSurrounding
  */
fixed_t P_FindHighestFloorSurrounding(sector_t *sec)
{
	size_t i;
	line_t *check;
	sector_t *other;
	fixed_t floorh = -500*FRACUNIT;
	int foundsector = 0;

	for (i = 0; i < sec->linecount; i++)
	{
		check = sec->lines[i];
		other = getNextSector(check, sec);

		if (!other)
			continue;

		if (other->floorheight > floorh || !foundsector)
			floorh = other->floorheight;

		if (!foundsector)
			foundsector = 1;
	}
	return floorh;
}

/** Finds next highest floor in adjacent sectors.
  *
  * \param sec           Sector to start in.
  * \param currentheight Height to start at.
  * \return Next highest floor height in an adjacent sector, or currentheight
  *         if there are none higher.
  * \sa P_FindHighestFloorSurrounding, P_FindNextLowestFloor,
  *     P_FindNextHighestCeiling
  * \author Lee Killough
  */
fixed_t P_FindNextHighestFloor(sector_t *sec, fixed_t currentheight)
{
	sector_t *other;
	size_t i;
	fixed_t height;

	for (i = 0; i < sec->linecount; i++)
	{
		other = getNextSector(sec->lines[i],sec);
		if (other && other->floorheight > currentheight)
		{
			height = other->floorheight;
			while (++i < sec->linecount)
			{
				other = getNextSector(sec->lines[i], sec);
				if (other &&
					other->floorheight < height &&
					other->floorheight > currentheight)
					height = other->floorheight;
			}
			return height;
		}
	}
	return currentheight;
}

////////////////////////////////////////////////////
// SoM: Start new Boom functions
////////////////////////////////////////////////////

/** Finds next lowest floor in adjacent sectors.
  *
  * \param sec           Sector to start in.
  * \param currentheight Height to start at.
  * \return Next lowest floor height in an adjacent sector, or currentheight
  *         if there are none lower.
  * \sa P_FindLowestFloorSurrounding, P_FindNextHighestFloor,
  *     P_FindNextLowestCeiling
  * \author Lee Killough
  */
fixed_t P_FindNextLowestFloor(sector_t *sec, fixed_t currentheight)
{
	sector_t *other;
	size_t i;
	fixed_t height;

	for (i = 0; i < sec->linecount; i++)
	{
		other = getNextSector(sec->lines[i], sec);
		if (other && other->floorheight < currentheight)
		{
			height = other->floorheight;
			while (++i < sec->linecount)
			{
				other = getNextSector(sec->lines[i], sec);
				if (other &&	other->floorheight > height
					&& other->floorheight < currentheight)
					height = other->floorheight;
			}
			return height;
		}
	}
	return currentheight;
}

#if 0
/** Finds next lowest ceiling in adjacent sectors.
  *
  * \param sec           Sector to start in.
  * \param currentheight Height to start at.
  * \return Next lowest ceiling height in an adjacent sector, or currentheight
  *         if there are none lower.
  * \sa P_FindLowestCeilingSurrounding, P_FindNextHighestCeiling,
  *     P_FindNextLowestFloor
  * \author Lee Killough
  */
static fixed_t P_FindNextLowestCeiling(sector_t *sec, fixed_t currentheight)
{
	sector_t *other;
	size_t i;
	fixed_t height;

	for (i = 0; i < sec->linecount; i++)
	{
		other = getNextSector(sec->lines[i],sec);
		if (other &&	other->ceilingheight < currentheight)
		{
			height = other->ceilingheight;
			while (++i < sec->linecount)
			{
				other = getNextSector(sec->lines[i],sec);
				if (other &&	other->ceilingheight > height
					&& other->ceilingheight < currentheight)
					height = other->ceilingheight;
			}
			return height;
		}
	}
	return currentheight;
}

/** Finds next highest ceiling in adjacent sectors.
  *
  * \param sec           Sector to start in.
  * \param currentheight Height to start at.
  * \return Next highest ceiling height in an adjacent sector, or currentheight
  *         if there are none higher.
  * \sa P_FindHighestCeilingSurrounding, P_FindNextLowestCeiling,
  *     P_FindNextHighestFloor
  * \author Lee Killough
  */
static fixed_t P_FindNextHighestCeiling(sector_t *sec, fixed_t currentheight)
{
	sector_t *other;
	size_t i;
	fixed_t height;

	for (i = 0; i < sec->linecount; i++)
	{
		other = getNextSector(sec->lines[i], sec);
		if (other && other->ceilingheight > currentheight)
		{
			height = other->ceilingheight;
			while (++i < sec->linecount)
			{
				other = getNextSector(sec->lines[i],sec);
				if (other && other->ceilingheight < height
					&& other->ceilingheight > currentheight)
					height = other->ceilingheight;
			}
			return height;
		}
	}
	return currentheight;
}
#endif

////////////////////////////
// End New Boom functions
////////////////////////////

/** Finds lowest ceiling in adjacent sectors.
  *
  * \param sec Sector to start in.
  * \return Lowest ceiling height in an adjacent sector.
  * \sa P_FindHighestCeilingSurrounding, P_FindNextLowestCeiling,
  *     P_FindLowestFloorSurrounding
  */
fixed_t P_FindLowestCeilingSurrounding(sector_t *sec)
{
	size_t i;
	line_t *check;
	sector_t *other;
	fixed_t height = 32000*FRACUNIT; //SoM: 3/7/2000: Remove ovf
	int foundsector = 0;

	for (i = 0; i < sec->linecount; i++)
	{
		check = sec->lines[i];
		other = getNextSector(check, sec);

		if (!other)
			continue;

		if (other->ceilingheight < height || !foundsector)
			height = other->ceilingheight;

		if (!foundsector)
			foundsector = 1;
	}
	return height;
}

/** Finds Highest ceiling in adjacent sectors.
  *
  * \param sec Sector to start in.
  * \return Highest ceiling height in an adjacent sector.
  * \sa P_FindLowestCeilingSurrounding, P_FindNextHighestCeiling,
  *     P_FindHighestFloorSurrounding
  */
fixed_t P_FindHighestCeilingSurrounding(sector_t *sec)
{
	size_t i;
	line_t *check;
	sector_t *other;
	fixed_t height = 0;
	int foundsector = 0;

	for (i = 0; i < sec->linecount; i++)
	{
		check = sec->lines[i];
		other = getNextSector(check, sec);

		if (!other)
			continue;

		if (other->ceilingheight > height || !foundsector)
			height = other->ceilingheight;

		if (!foundsector)
			foundsector = 1;
	}
	return height;
}

#if 0
//SoM: 3/7/2000: UTILS.....
//
// P_FindShortestTextureAround()
//
// Passed a sector number, returns the shortest lower texture on a
// linedef bounding the sector.
//
//
static fixed_t P_FindShortestTextureAround(int secnum)
{
	fixed_t minsize = 32000<<FRACBITS;
	side_t *side;
	size_t i;
	sector_t *sec= &sectors[secnum];

	for (i = 0; i < sec->linecount; i++)
	{
		if (twoSided(secnum, i))
		{
			side = getSide(secnum,i,0);
			if (side->bottomtexture > 0)
				if (textureheight[side->bottomtexture] < minsize)
					minsize = textureheight[side->bottomtexture];
			side = getSide(secnum,i,1);
			if (side->bottomtexture > 0)
				if (textureheight[side->bottomtexture] < minsize)
					minsize = textureheight[side->bottomtexture];
		}
	}
	return minsize;
}

//SoM: 3/7/2000: Stuff.... (can you tell I'm getting tired? It's 12 : 30!)
//
// P_FindShortestUpperAround()
//
// Passed a sector number, returns the shortest upper texture on a
// linedef bounding the sector.
//
//
static fixed_t P_FindShortestUpperAround(int secnum)
{
	fixed_t minsize = 32000<<FRACBITS;
	side_t *side;
	size_t i;
	sector_t *sec = &sectors[secnum];

	for (i = 0; i < sec->linecount; i++)
	{
		if (twoSided(secnum, i))
		{
			side = getSide(secnum,i,0);
			if (side->toptexture > 0)
				if (textureheight[side->toptexture] < minsize)
					minsize = textureheight[side->toptexture];
			side = getSide(secnum,i,1);
			if (side->toptexture > 0)
				if (textureheight[side->toptexture] < minsize)
					minsize = textureheight[side->toptexture];
		}
	}
	return minsize;
}

//SoM: 3/7/2000
//
// P_FindModelFloorSector()
//
// Passed a floor height and a sector number, return a pointer to a
// a sector with that floor height across the lowest numbered two sided
// line surrounding the sector.
//
// Note: If no sector at that height bounds the sector passed, return NULL
//
//
static sector_t *P_FindModelFloorSector(fixed_t floordestheight, int secnum)
{
	size_t i;
	sector_t *sec = &sectors[secnum];

	for (i = 0; i < sec->linecount; i++)
	{
		if (twoSided(secnum, i))
		{
			if (getSide(secnum,i,0)->sector-sectors == secnum)
				sec = getSector(secnum,i,1);
			else
				sec = getSector(secnum,i,0);

			if (sec->floorheight == floordestheight)
				return sec;
		}
	}
	return NULL;
}

//
// P_FindModelCeilingSector()
//
// Passed a ceiling height and a sector number, return a pointer to a
// a sector with that ceiling height across the lowest numbered two sided
// line surrounding the sector.
//
// Note: If no sector at that height bounds the sector passed, return NULL
//
static sector_t *P_FindModelCeilingSector(fixed_t ceildestheight, int secnum)
{
	size_t i;
	sector_t *sec = &sectors[secnum];

	for (i = 0; i < sec->linecount; i++)
	{
		if (twoSided(secnum, i))
		{
			if (getSide(secnum, i, 0)->sector - sectors == secnum)
				sec = getSector(secnum, i, 1);
			else
				sec = getSector(secnum, i, 0);

			if (sec->ceilingheight == ceildestheight)
				return sec;
		}
	}
	return NULL;
}
#endif

/** Searches the tag lists for the next sector tagged to a line.
  *
  * \param line  Tagged line used as a reference.
  * \param start -1 to start at the beginning, or the result of a previous call
  *              to keep searching.
  * \return Number of the next tagged sector found.
  * \sa P_FindSectorFromTag, P_FindLineFromLineTag
  */
long P_FindSectorFromLineTag(line_t *line, long start)
{
	start = start >= 0 ? sectors[start].nexttag :
		sectors[(unsigned)line->tag % numsectors].firsttag;
	while (start >= 0 && sectors[start].tag != line->tag)
		start = sectors[start].nexttag;
	return start;
}

/** Searches the tag lists for the next sector with a given tag.
  *
  * \param tag   Tag number to look for.
  * \param start -1 to start anew, or the result of a previous call to keep
  *              searching.
  * \return Number of the next tagged sector found.
  * \sa P_FindSectorFromLineTag
  */
long P_FindSectorFromTag(short tag, long start)
{
	start = start >= 0 ? sectors[start].nexttag :
		sectors[(unsigned)tag % numsectors].firsttag;
	while (start >= 0 && sectors[start].tag != tag)
		start = sectors[start].nexttag;
	return start;
}

/** Searches the tag lists for the next line tagged to a line.
  *
  * \param line  Tagged line used as a reference.
  * \param start -1 to start anew, or the result of a previous call to keep
  *              searching.
  * \return Number of the next tagged line found.
  * \sa P_FindSectorFromLineTag
  */
static long P_FindLineFromLineTag(const line_t *line, long start)
{
	start = start >= 0 ? lines[start].nexttag :
		lines[(unsigned)line->tag % numlines].firsttag;
	while (start >= 0 && lines[start].tag != line->tag)
		start = lines[start].nexttag;
	return start;
}

#if 0
/** Searches the tag lists for the next line with a given tag and special.
  *
  * \param tag     Tag number.
  * \param start   -1 to start anew, or the result of a previous call to keep
  *                searching.
  * \return Number of next suitable line found.
  * \sa P_FindLineFromLineTag
  * \author Graue <graue@oceanbase.org>
  */
static long P_FindLineFromTag(long tag, long start)
{
	start = start >= 0 ? lines[start].nexttag :
		lines[(unsigned)tag % numlines].firsttag;
	while (start >= 0 && lines[start].tag != tag)
		start = lines[start].nexttag;
	return start;
}
#endif

//
// P_FindSpecialLineFromTag
//
long P_FindSpecialLineFromTag(short special, short tag, long start)
{
	start = start >= 0 ? lines[start].nexttag :
		lines[(unsigned)tag % numlines].firsttag;
	while (start >= 0 && (lines[start].tag != tag || lines[start].special != special))
		start = lines[start].nexttag;
	return start;
}

// haleyjd: temporary define
#ifdef POLYOBJECTS

//
// PolyDoor
//
// Parses arguments for parameterized polyobject door types
//
static boolean PolyDoor(line_t *line)
{
	polydoordata_t pdd;

	pdd.polyObjNum = line->tag; // polyobject id

	switch(line->special)
	{
		case 480: // Polyobj_DoorSlide
			pdd.doorType = POLY_DOOR_SLIDE;
			pdd.speed    = sides[line->sidenum[0]].textureoffset / 8;
			pdd.angle    = R_PointToAngle2(line->v1->x, line->v1->y, line->v2->x, line->v2->y); // angle of motion
			pdd.distance = sides[line->sidenum[0]].rowoffset;

			if (line->sidenum[1] != 0xffff)
				pdd.delay = sides[line->sidenum[1]].textureoffset >> FRACBITS; // delay in tics
			else
				pdd.delay = 0;
			break;
		case 481: // Polyobj_DoorSwing
			pdd.doorType = POLY_DOOR_SWING;
			pdd.speed    = sides[line->sidenum[0]].textureoffset >> FRACBITS; // angular speed
			pdd.distance = sides[line->sidenum[0]].rowoffset >> FRACBITS; // angular distance

			if (line->sidenum[1] != 0xffff)
				pdd.delay = sides[line->sidenum[1]].textureoffset >> FRACBITS; // delay in tics
			else
				pdd.delay = 0;
			break;
		default:
#ifdef POLYDEBUG
			CONS_Printf("PolyDoor: Linetype not found\n");
#endif
			return 0; // ???
	}

#ifdef POLYDEBUG
	CONS_Printf("PolyDoor: speed=%d, dist=\n", pdd.speed, pdd.distance);
#endif

	return EV_DoPolyDoor(&pdd);
}

//
// PolyMove
//
// Parses arguments for parameterized polyobject move specials
//
static boolean PolyMove(line_t *line)
{
	polymovedata_t pmd;

	pmd.polyObjNum = line->tag;
	pmd.speed      = sides[line->sidenum[0]].textureoffset / 8;
	pmd.angle      = R_PointToAngle2(line->v1->x, line->v1->y, line->v2->x, line->v2->y);
	pmd.distance   = sides[line->sidenum[0]].rowoffset;

	pmd.overRide = (line->special == 483); // Polyobj_OR_Move

	return EV_DoPolyObjMove(&pmd);
}

//
// PolyRotate
//
// Parses arguments for parameterized polyobject rotate specials
//
static boolean PolyRotate(line_t *line)
{
	polyrotdata_t prd;

	prd.polyObjNum = line->tag;
	prd.speed      = sides[line->sidenum[0]].textureoffset >> FRACBITS; // angular speed
	prd.distance   = sides[line->sidenum[0]].rowoffset >> FRACBITS; // angular distance

	// Polyobj_(OR_)RotateRight have dir == -1
	prd.direction = (line->special == 484 || line->special == 485) ? -1 : 1;

	// Polyobj_OR types have override set to true
	prd.overRide  = (line->special == 485 || line->special == 487);

	return EV_DoPolyObjRotate(&prd);
}

#endif // ifdef POLYOBJECTS

/** Changes a sector's tag.
  * Used by the linedef executor tag changer and by crumblers.
  *
  * \param sector Sector whose tag will be changed.
  * \param newtag New tag number for this sector.
  * \sa P_InitTagLists, P_FindSectorFromTag
  * \author Graue <graue@oceanbase.org>
  */
void P_ChangeSectorTag(ULONG sector, short newtag)
{
	short oldtag;
	long i;

	I_Assert(sector < numsectors);

	if ((oldtag = sectors[sector].tag) == newtag)
		return;

	// first you have to remove it from the old tag's taglist
	i = sectors[(unsigned)oldtag % numsectors].firsttag;

	if (i == -1) // shouldn't happen
		I_Error("Corrupt tag list for sector %lu\n", sector);
	else if ((ULONG)i == sector)
		sectors[(unsigned)oldtag % numsectors].firsttag = sectors[sector].nexttag;
	else
	{
		while (sectors[i].nexttag != -1 && (ULONG)sectors[i].nexttag < sector )
			i = sectors[i].nexttag;

		sectors[i].nexttag = sectors[sector].nexttag;
	}

	sectors[sector].tag = newtag;

	// now add it to the new tag's taglist
	if ((ULONG)sectors[(unsigned)newtag % numsectors].firsttag > sector)
	{
		sectors[sector].nexttag = sectors[(unsigned)newtag % numsectors].firsttag;
		sectors[(unsigned)newtag % numsectors].firsttag = sector;
	}
	else
	{
		i = sectors[(unsigned)newtag % numsectors].firsttag;

		if (i == -1)
		{
			sectors[(unsigned)newtag % numsectors].firsttag = sector;
			sectors[sector].nexttag = -1;
		}
		else
		{
			while (sectors[i].nexttag != -1 && (ULONG)sectors[i].nexttag < sector )
				i = sectors[i].nexttag;

			sectors[sector].nexttag = sectors[i].nexttag;
			sectors[i].nexttag = sector;
		}
	}
}

/** Hashes the sector tags across the sectors and linedefs.
  *
  * \sa P_FindSectorFromTag, P_ChangeSectorTag
  * \author Lee Killough
  */
static inline void P_InitTagLists(void)
{
	register size_t i;

	for (i = numsectors - 1; i != (size_t)-1; i--)
	{
		size_t j = (unsigned)sectors[i].tag % numsectors;
		sectors[i].nexttag = sectors[j].firsttag;
		sectors[j].firsttag = (long)i;
	}

	for (i = numlines - 1; i != (size_t)-1; i--)
	{
		size_t j = (unsigned)lines[i].tag % numlines;
		lines[i].nexttag = lines[j].firsttag;
		lines[j].firsttag = (long)i;
	}
}

/** Finds minimum light from an adjacent sector.
  *
  * \param sector Sector to start in.
  * \param max    Maximum value to return.
  * \return Minimum light value from an adjacent sector, or max if the minimum
  *         light value is greater than max.
  */
int P_FindMinSurroundingLight(sector_t *sector, int max)
{
	size_t i;
	int min = max;
	line_t *line;
	sector_t *check;

	for (i = 0; i < sector->linecount; i++)
	{
		line = sector->lines[i];
		check = getNextSector(line,sector);

		if (!check)
			continue;

		if (check->lightlevel < min)
			min = check->lightlevel;
	}
	return min;
}

void T_ExecutorDelay(executor_t *e)
{
	if (--e->timer <= 0)
	{
		P_ProcessLineSpecial(e->line, e->caller);
		P_RemoveThinker(&e->thinker);
	}
}

static void P_AddExecutorDelay(line_t *line, mobj_t *mobj)
{
	executor_t *e;

	if (!line->backsector)
		I_Error("P_AddExecutorDelay: Line has no backsector!\n");

	e = Z_Calloc(sizeof (*e), PU_LEVSPEC, NULL);

	e->thinker.function.acp1 = (actionf_p1)T_ExecutorDelay;
	e->line = line;
	e->timer = (line->backsector->ceilingheight>>FRACBITS)+(line->backsector->floorheight>>FRACBITS);
	e->caller = mobj;
	P_AddThinker(&e->thinker);
}

static sector_t *triplinecaller;

/** Runs a linedef executor.
  * Can be called by:
  *   - a player moving into a special sector or FOF.
  *   - a pushable object moving into a special sector or FOF.
  *   - a ceiling or floor movement from a previous linedef executor finishing.
  *   - any object in a state with the A_LinedefExecute() action.
  *
  * \param tag Tag of the linedef executor to run.
  * \param actor Object initiating the action; should not be NULL.
  * \param caller Sector in which the action was started. May be NULL.
  * \sa P_ProcessLineSpecial
  * \author Graue <graue@oceanbase.org>
  */
void P_LinedefExecute(long tag, mobj_t *actor, sector_t *caller)
{
	sector_t *ctlsector;
	fixed_t dist;
	size_t masterline, i, linecnt;
	short specialtype;

	for (masterline = 0; masterline < numlines; masterline++)
	{
		if (lines[masterline].tag != tag)
			continue;

		if (!(lines[masterline].special == 9
			|| lines[masterline].special == 10
			|| lines[masterline].special == 11
			|| lines[masterline].special == 12
			|| lines[masterline].special == 13
			|| lines[masterline].special == 19
			|| lines[masterline].special == 20
			|| lines[masterline].special == 21
			|| lines[masterline].special == 95
			|| lines[masterline].special == 96
			|| lines[masterline].special == 97
			|| lines[masterline].special == 98
			|| lines[masterline].special == 99))
			continue;

		specialtype = lines[masterline].special;

		// Special handling for some executors

#ifdef DOORS // Switches
		// Linetypes 95 and 99 require key cards
		// if ML_PASSUSE no floor touch is needed.
		// 95 (Repeatedly)
		// 99 (Once)
		if (specialtype == 95 || specialtype == 99)
		{
			byte locktype = 0;

			if (!actor || !actor->player)
				return;

			// Check for caller, this is needed to allow executing from a switch.
		 	// If caller (i.e. not a switch) and the line doesn't have the ML_PASSUSE flag and the player didn't just hit the floor. 
			if (caller && !(lines[masterline].flags & ML_PASSUSE) && !(actor->eflags & (MF_JUSTHITFLOOR | MF_JUSTSTEPPEDDOWN)))
				return;

			// Need Blue key to use.
			if (lines[masterline].flags & ML_NOCLIMB)
				locktype |= it_bluecard;
			// Need Red key to use.
			if (lines[masterline].flags & ML_PASSUSE)
				locktype |= it_redcard;
			// Need Yellow key to use.
			if (lines[masterline].flags & ML_ALLTRIGGER)
				locktype |= it_yellowcard;

			// Check if the player has the needed cards.
			if (!(actor->player->cards & locktype))
			{
				// Missing a key card.
				return;
			}
		}
#else
		// Linetypes 95 and 99 require a specific
		// number, or minimum or maximum, of rings.
		if (actor && actor->player && (specialtype == 95
			|| specialtype == 99))
		{
			fixed_t rings = 0;

			// With the passuse flag, count all player's
			// rings.
			if (lines[masterline].flags & ML_PASSUSE)
			{
				for (i = 0; i < MAXPLAYERS; i++)
				{
					if (!playeringame[i])
						continue;

					if (!players[i].mo)
						continue;

#ifdef TMNTHEALTH
					rings += players[i].mo->health;
#else
					rings += players[i].mo->health-1;
#endif
				}
			}
			else
#ifdef TMNTHEALTH
				rings = actor->health;
#else
				rings = actor->health-1;
#endif

			dist = P_AproxDistance(lines[masterline].dx, lines[masterline].dy)>>FRACBITS;

			if (lines[masterline].flags & ML_NOCLIMB)
			{
				if (rings > dist)
					return;
			}
			else if (lines[masterline].flags & ML_BLOCKMONSTERS)
			{
				if (rings < dist)
					return;
			}
			else
			{
				if (rings != dist)
					return;
			}
		}
#endif
		else if (caller)
		{
#ifndef NOEMERALDS
			if (caller->special == 967)
			{
				if (lines[masterline].flags & ML_NOCLIMB)
				{
					if (!((ALL7EMERALDS) && (emeralds & EMERALD8)))
						return;
				}
				else if (!(ALL7EMERALDS))
					return;
			}
			else
#endif
			if (caller->special == 968)
			{
				byte mare;

				if (!(maptol & TOL_NIGHTS))
					return;

				dist = P_AproxDistance(lines[masterline].dx, lines[masterline].dy)>>FRACBITS;
				mare = P_FindLowestMare();

				if (lines[masterline].flags & ML_NOCLIMB)
				{
					if (!(mare <= dist))
						return;
				}
				else if (lines[masterline].flags & ML_BLOCKMONSTERS)
				{
					if (!(mare >= dist))
						return;
				}
				else
				{
					if (!(mare == dist))
						return;
				}
			}
		}

		if (specialtype >= 19 && specialtype <= 21)
		{
			if (!actor)
				return;

			if (!actor->player)
				return;

			if (actor->player->charability != (P_AproxDistance(lines[masterline].dx, lines[masterline].dy)>>FRACBITS)/10)
				return;
		}

		// Only red team members can activate this.
		if ((specialtype == 10 || specialtype == 11)
			&& !(actor && actor->player && actor->player->ctfteam == 1))
			return;

		// Only blue team members can activate this.
		if ((specialtype == 12 || specialtype == 13)
			&& !(actor && actor->player && actor->player->ctfteam == 2))
			return;

		// Special type 97 only works once when you hit floor
		if ((specialtype == 97 || specialtype == 11 || specialtype == 13 || specialtype == 20) && actor && !(actor->eflags & (MF_JUSTHITFLOOR | MF_JUSTSTEPPEDDOWN))
#ifdef DOORS /// This is needed for executing the 'Each time Tinedef Executers' from a switch.
			&& caller
#endif
		)
			return;

		triplinecaller = caller;
		ctlsector = lines[masterline].frontsector;
		linecnt = ctlsector->linecount;

		if (lines[masterline].flags & ML_ALLTRIGGER) // disregard order for efficiency
		{
			for (i = 0; i < linecnt; i++)
				if (ctlsector->lines[i]->special > 99)
				{
					if (ctlsector->lines[i]->flags & ML_DONTPEGTOP)
						P_AddExecutorDelay(ctlsector->lines[i], actor);
					else
						P_ProcessLineSpecial(ctlsector->lines[i], actor);
				}
		}
		else // walk around the sector in a defined order
		{
			boolean backwards = false;
			size_t j, masterlineindex = (size_t)-1;

			for (i = 0; i < linecnt; i++)
				if (ctlsector->lines[i] == &lines[masterline])
				{
					masterlineindex = i;
					break;
				}

#ifdef PARANOIA
			if (masterlineindex == (size_t)-1)
				I_Error("Line %d isn't linked into its front sector", ctlsector->lines[i] - lines);
#endif

			// i == masterlineindex
			for (;;)
			{
				if (backwards) // v2 to v1
				{
					for (j = 0; j < linecnt; j++)
					{
						if (i == j)
							continue;
						if (ctlsector->lines[i]->v1 == ctlsector->lines[j]->v2)
						{
							i = j;
							break;
						}
						if (ctlsector->lines[i]->v1 == ctlsector->lines[j]->v1)
						{
							i = j;
							backwards = false;
							break;
						}
					}
					if (j == linecnt)
					{
						CONS_Printf("Warning: Sector %i is not closed at vertex %d (%d, %d)\n",
							ctlsector - sectors, ctlsector->lines[i]->v1 - vertexes,
							ctlsector->lines[i]->v1->x, ctlsector->lines[i]->v1->y);
						return; // abort
					}
				}
				else // v1 to v2
				{
					for (j = 0; j < linecnt; j++)
					{
						if (i == j)
							continue;
						if (ctlsector->lines[i]->v2 == ctlsector->lines[j]->v1)
						{
							i = j;
							break;
						}
						if (ctlsector->lines[i]->v2 == ctlsector->lines[j]->v2)
						{
							i = j;
							backwards = true;
							break;
						}
					}
					if (j == linecnt)
					{
						CONS_Printf("Warning: Sector %i is not closed at vertex %d (%d, %d)\n",
							ctlsector - sectors, ctlsector->lines[i]->v2 - vertexes,
							ctlsector->lines[i]->v2->x, ctlsector->lines[i]->v2->y);
						return; // abort
					}
				}

				if (i == masterlineindex)
					break;

				if (ctlsector->lines[i]->special > 99)
				{
					if (ctlsector->lines[i]->flags & ML_DONTPEGTOP)
						P_AddExecutorDelay(ctlsector->lines[i], actor);
					else
						P_ProcessLineSpecial(ctlsector->lines[i], actor);
				}
			}
		}

		// Special type 9, 21, 98 & 99 only work once
		if (specialtype == 9 || specialtype == 21 || specialtype == 98 || specialtype == 99)
		{
			lines[masterline].special = 0; // Clear it out
			if (caller && ((caller->special >= 971 && caller->special <= 975) || caller->special == 967 || caller->special == 968))
				caller->special = 0; // Clear that out, too, so this function doesn't get run forever
		}
	}
}

//
// P_SwitchWeather
//
// Switches the weather!
//
void P_SwitchWeather(int weathernum)
{
	boolean purge = false;
	int swap = 0;

	switch (weathernum)
	{
		case PRECIP_NONE: // None
			if (curWeather == PRECIP_NONE)
				return; // Nothing to do.
			purge = true;
			break;
		case PRECIP_STORM: // Storm
		case PRECIP_RAIN: // Rain
			if (curWeather == PRECIP_SNOW || curWeather == PRECIP_BLANK || curWeather == PRECIP_STORM_NORAIN)
				swap = PRECIP_RAIN;
			break;
		case PRECIP_SNOW: // Snow
			if (curWeather == PRECIP_SNOW)
				return; // Nothing to do.
			if (curWeather == PRECIP_RAIN || curWeather == PRECIP_STORM || curWeather == PRECIP_BLANK || curWeather == PRECIP_STORM_NORAIN)
				swap = PRECIP_SNOW; // Need to delete the other precips.
			break;
		case PRECIP_STORM_NORAIN: // Storm w/o rain
			if (curWeather == PRECIP_SNOW
				|| curWeather == PRECIP_STORM
				|| curWeather == PRECIP_RAIN
				|| curWeather == PRECIP_BLANK)
				swap = PRECIP_STORM_NORAIN;
			else if (curWeather == PRECIP_STORM_NORAIN)
				return;
			break;
		case PRECIP_BLANK:
			if (curWeather == PRECIP_SNOW
				|| curWeather == PRECIP_STORM
				|| curWeather == PRECIP_RAIN)
				swap = PRECIP_BLANK;
			else if (curWeather == PRECIP_STORM_NORAIN)
				swap = PRECIP_BLANK;
			else if (curWeather == PRECIP_BLANK)
				return;
			break;
		default:
			CONS_Printf("Unknown weather type %d.\n", weathernum);
			break;
	}

	if (purge)
	{
		thinker_t *think;
		precipmobj_t *precipmobj;

		for (think = thinkercap.next; think != &thinkercap; think = think->next)
		{
			if ((think->function.acp1 != (actionf_p1)P_SnowThinker)
				&& (think->function.acp1 != (actionf_p1)P_RainThinker))
				continue; // not a precipmobj thinker

			precipmobj = (precipmobj_t *)think;

			P_RemovePrecipMobj(precipmobj);
		}
	}
	else if (swap && !((swap == PRECIP_BLANK && curWeather == PRECIP_STORM_NORAIN) || (swap == PRECIP_STORM_NORAIN && curWeather == PRECIP_BLANK))) // Rather than respawn all that crap, reuse it!
	{
		thinker_t *think;
		precipmobj_t *precipmobj;
		state_t *st;

		for (think = thinkercap.next; think != &thinkercap; think = think->next)
		{
			if (swap == PRECIP_RAIN) // Snow To Rain
			{
				if (!(think->function.acp1 == (actionf_p1)P_SnowThinker
					|| think->function.acp1 == (actionf_p1)P_NullPrecipThinker))
					continue; // not a precipmobj thinker

				precipmobj = (precipmobj_t *)think;

				precipmobj->flags = mobjinfo[MT_RAIN].flags;
				st = &states[mobjinfo[MT_RAIN].spawnstate];
				precipmobj->state = st;
				precipmobj->tics = st->tics;
				precipmobj->sprite = st->sprite;
				precipmobj->frame = st->frame;
				precipmobj->momz = mobjinfo[MT_RAIN].speed;

				precipmobj->invisible = 0;

				think->function.acp1 = (actionf_p1)P_RainThinker;
			}
			else if (swap == PRECIP_SNOW) // Rain To Snow
			{
				int z;

				if (!(think->function.acp1 == (actionf_p1)P_RainThinker
					|| think->function.acp1 == (actionf_p1)P_NullPrecipThinker))
					continue; // not a precipmobj thinker

				precipmobj = (precipmobj_t *)think;

				precipmobj->flags = mobjinfo[MT_SNOWFLAKE].flags;
				z = M_Random();

				if (z < 64)
					z = 2;
				else if (z < 144)
					z = 1;
				else
					z = 0;

				st = &states[mobjinfo[MT_SNOWFLAKE].spawnstate+z];
				precipmobj->state = st;
				precipmobj->tics = st->tics;
				precipmobj->sprite = st->sprite;
				precipmobj->frame = st->frame;
				precipmobj->momz = mobjinfo[MT_SNOWFLAKE].speed;

				precipmobj->invisible = 0;

				think->function.acp1 = (actionf_p1)P_SnowThinker;
			}
			else if (swap == PRECIP_BLANK || swap == PRECIP_STORM_NORAIN) // Remove precip, but keep it around for reuse.
			{
				if (!(think->function.acp1 == (actionf_p1)P_RainThinker
					|| think->function.acp1 == (actionf_p1)P_SnowThinker))
					continue;

				precipmobj = (precipmobj_t *)think;

				think->function.acp1 = (actionf_p1)P_NullPrecipThinker;

				precipmobj->invisible = 1;
			}
		}
	}

	if (weathernum == PRECIP_SNOW) // snow
	{
		curWeather = PRECIP_SNOW;

		if (!swap)
			P_SpawnPrecipitation();
	}
	else if (weathernum == PRECIP_RAIN) // rain
	{
		boolean dontspawn = false;

		if (curWeather == PRECIP_RAIN || curWeather == PRECIP_STORM)
			dontspawn = true;

		curWeather = PRECIP_RAIN;

		if (!dontspawn && !swap)
			P_SpawnPrecipitation();
	}
	else if (weathernum == PRECIP_STORM) // storm
	{
		boolean dontspawn = false;

		if (curWeather == PRECIP_RAIN || curWeather == PRECIP_STORM)
			dontspawn = true;

		curWeather = PRECIP_STORM;

		if (!dontspawn && !swap)
			P_SpawnPrecipitation();
	}
	else if (weathernum == PRECIP_STORM_NORAIN) // storm w/o rain
	{
		curWeather = PRECIP_STORM_NORAIN;

		if (!swap)
			P_SpawnPrecipitation();
	}
	else if (weathernum == PRECIP_BLANK)
	{
		curWeather = PRECIP_BLANK;

		if (!swap)
			P_SpawnPrecipitation();
	}
	else
		curWeather = PRECIP_NONE;
}

/** Gets an object.
  *
  * \param type Object type to look for.
  * \param s Sector number to look in.
  * \return Pointer to the first ::type found in the sector.
  * \sa P_GetPushThing
  */
static mobj_t *P_GetObjectTypeInSectorNum(mobjtype_t type, size_t s)
{
	sector_t *sec = sectors + s;
	mobj_t *thing = sec->thinglist;

	while (thing)
	{
		if (thing->type == type)
			return thing;
		thing = thing->snext;
	}
	return NULL;
}

/** Processes the line special triggered by an object.
  * The external variable ::triplinecaller points to the sector in which the
  * action was initiated; it can be NULL. Because of the A_LinedefExecute()
  * action, even if non-NULL, this sector might not have the same tag as the
  * linedef executor, and it might not have the linedef executor sector type.
  *
  * \param line Line with the special command on it.
  * \param mo   mobj that triggered the line. Must be valid and non-NULL.
  * \todo Get rid of the secret parameter and make ::triplinecaller actually get
  *       passed to the function.
  * \todo Handle mo being NULL gracefully. T_MoveFloor() and T_MoveCeiling()
  *       don't have an object to pass.
  * \todo Split up into multiple functions.
  * \sa P_LinedefExecute
  * \author Graue <graue@oceanbase.org>
  */
static void P_ProcessLineSpecial(line_t *line, mobj_t *mo)
{
	long secnum = -1;

#ifdef DOORS // Switch
	// Only if something happens set linedefExecuted to true.
	// Turtle Man March 11, 2008
#endif

	// note: no commands with linedef types <= 98 can be used
	switch (line->special)
	{
		case 101: // Set tagged sector's floor height/pic
#ifdef DOORS // Switch
			if (EV_DoFloor(line, instantMoveFloorByFrontSector))
			{
				linedefExecuted = true;
			}
#else
			EV_DoFloor(line, instantMoveFloorByFrontSector);
#endif
			break;

		case 102: // Set tagged sector's ceiling height/pic
#ifdef DOORS // Switch
			if (EV_DoCeiling(line, instantMoveCeilingByFrontSector))
			{
				linedefExecuted = true;
			}
#else
			EV_DoCeiling(line, instantMoveCeilingByFrontSector);
#endif
			break;

		case 103: // Set tagged sector's light level
			{
				short newlightlevel;
				long newfloorlightsec, newceilinglightsec;

				newlightlevel = line->frontsector->lightlevel;
				newfloorlightsec = line->frontsector->floorlightsec;
				newceilinglightsec = line->frontsector->ceilinglightsec;

				// act on all sectors with the same tag as the triggering linedef
				while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0)
				{
#ifdef DOORS // Switch
					linedefExecuted = true;
#endif
					if (sectors[secnum].lightingdata)
					{
						// Stop the lighting madness going on in this sector!
						P_RemoveThinker(&((elevator_t *)sectors[secnum].lightingdata)->thinker);
						sectors[secnum].lightingdata = NULL;

						// No, it's not an elevator_t, but any struct with a thinker_t named
						// 'thinker' at the beginning will do here. (We don't know what it
						// actually is: could be lightlevel_t, fireflicker_t, glow_t, etc.)
					}

					sectors[secnum].lightlevel = newlightlevel;
					sectors[secnum].floorlightsec = newfloorlightsec;
					sectors[secnum].ceilinglightsec = newceilinglightsec;
				}
			}
			break;

		case 106: // Move floor, linelen = speed, frontsector floor = dest height
#ifdef DOORS // Switch
			if (EV_DoFloor(line, moveFloorByFrontSector))
			{
				linedefExecuted = true;
			}
#else
			EV_DoFloor(line, moveFloorByFrontSector);
#endif
			break;

		case 107: // Move ceiling, linelen = speed, frontsector ceiling = dest height
#ifdef DOORS // Switch
			if (EV_DoCeiling(line, moveCeilingByFrontSector))
			{
				linedefExecuted = true;
			}
#else
			EV_DoCeiling(line, moveCeilingByFrontSector);
#endif
			break;

		case 108: // Lower floor by line, dx = speed, dy = amount to lower
#ifdef DOORS // Switch
			if (EV_DoFloor(line, lowerFloorByLine))
			{
				linedefExecuted = true;
			}
#else
			EV_DoFloor(line, lowerFloorByLine);
#endif
			break;

		case 109: // Raise floor by line, dx = speed, dy = amount to raise
#ifdef DOORS // Switch
			if (EV_DoFloor(line, raiseFloorByLine))
			{
				linedefExecuted = true;
			}
#else
			EV_DoFloor(line, raiseFloorByLine);
#endif
			break;

		case 110: // Lower ceiling by line, dx = speed, dy = amount to lower
#ifdef DOORS // Switch
			if (EV_DoCeiling(line, lowerCeilingByLine))
			{
				linedefExecuted = true;
			}
#else
			EV_DoCeiling(line, lowerCeilingByLine);
#endif
			break;

		case 111: // Raise ceiling by line, dx = speed, dy = amount to raise
#ifdef DOORS // Switch
			if (EV_DoCeiling(line, raiseCeilingByLine))
			{
				linedefExecuted = true;
			}
#else
			EV_DoCeiling(line, raiseCeilingByLine);
#endif
			break;

		case 112: // Change tagged sectors' tag
		// (formerly "Change calling sectors' tag", but behavior
		//  was changed)
		{
			while ((secnum = P_FindSectorFromLineTag(line,
				secnum)) != -1)
			{
#ifdef DOORS // Switch
				linedefExecuted = true;
#endif
				P_ChangeSectorTag(secnum,
					(short)(P_AproxDistance(line->dx, line->dy)
					>>FRACBITS));
			}
			break;
		}

		case 114: // Change front sector's tag
#ifdef DOORS // Switch
			linedefExecuted = true;
#endif
			P_ChangeSectorTag((ULONG)(line->frontsector - sectors), (short)(P_AproxDistance(line->dx, line->dy)>>FRACBITS));
			break;

		case 116: // Stop floor/ceiling movement in tagged sector(s)
			while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0)
			{
#ifdef DOORS // Switch
				linedefExecuted = true;
#endif
				if (sectors[secnum].floordata)
				{
					if (sectors[secnum].floordata == sectors[secnum].ceilingdata) // elevator
					{
						P_RemoveThinker(&((elevator_t *)sectors[secnum].floordata)->thinker);
						sectors[secnum].floordata = sectors[secnum].ceilingdata = NULL;
						sectors[secnum].floorspeed = sectors[secnum].ceilspeed = 0;
					}
					else // floormove
					{
						P_RemoveThinker(&((floormove_t *)sectors[secnum].floordata)->thinker);
						sectors[secnum].floordata = NULL;
						sectors[secnum].floorspeed = 0;
					}
				}

				if (sectors[secnum].ceilingdata) // ceiling
				{
					P_RemoveThinker(&((ceiling_t *)sectors[secnum].ceilingdata)->thinker);
					sectors[secnum].ceilingdata = NULL;
					sectors[secnum].ceilspeed = 0;
				}
			}
			break;

		case 104: // Teleport the player or thing
			{
				mobj_t *dest;

				if (!mo) // nothing to teleport
					return;

				if ((secnum = P_FindSectorFromLineTag(line, -1)) < 0)
					return;

				dest = P_GetObjectTypeInSectorNum(MT_TELEPORTMAN, secnum);
				if (!dest)
					return;

#ifdef DOORS // Switch
				linedefExecuted = true;
#endif

				if (line->flags & ML_BLOCKMONSTERS)
					P_Teleport(mo, dest->x, dest->y, dest->z, (line->flags & ML_NOCLIMB) ?  mo->angle : dest->angle, false, (line->flags & ML_PASSUSE));
				else
				{
					P_Teleport(mo, dest->x, dest->y, dest->z, (line->flags & ML_NOCLIMB) ?  mo->angle : dest->angle, true, (line->flags & ML_PASSUSE));
					// Play the 'bowrwoosh!' sound
					S_StartSound(dest, sfx_mixup);
				}
			}
			break;

		case 105: // Change music
#ifdef DOORS // Switch
			// Don't do only for console player.
			linedefExecuted = true;
#endif
			if (mo && mo->player && P_IsLocalPlayer(mo->player)) // console player only
			{
				fixed_t musicnum;

				musicnum = P_AproxDistance(line->dx, line->dy)>>FRACBITS;

				if (line->flags & ML_BLOCKMONSTERS)
					musicnum += 2048;

				if ((musicnum & ~2048) < NUMMUSIC && (musicnum & ~2048) > mus_None)
					S_ChangeMusic(musicnum & 2047, !(line->flags & ML_NOCLIMB));
				else
					S_StopMusic();

				mapmusic = (short)musicnum; // but it gets reset if you die

				// Except, you can use the ML_BLOCKMONSTERS flag to change this behavior.
				// if (mapmusic & 2048) then it won't reset the music in G_PlayerReborn as usual.
				// This is why I do the crazy anding with musicnum above.
			}
			break;

		case 115: // Play SFX
			{
				fixed_t sfxnum;

				sfxnum = P_AproxDistance(line->dx, line->dy)>>FRACBITS;

				if (sfxnum < NUMSFX && sfxnum > sfx_None)
				{
#ifdef DOORS // Switch
					// This could be better...
					linedefExecuted = true;
#endif
					if (line->flags & ML_NOCLIMB)
					{
						// play the sound from nowhere, but only if display player triggered it
						if (mo && mo->player && (mo->player == &players[displayplayer] || mo->player == &players[secondarydisplayplayer]))
							S_StartSound(NULL, sfxnum);
					}
					else if (line->flags & ML_PASSUSE)
					{
						// play the sound from nowhere
						S_StartSound(NULL, sfxnum);
					}
					else if (line->flags & ML_BLOCKMONSTERS)
					{
						// play the sound from calling sector's soundorg
						if (triplinecaller)
							S_StartSound(&triplinecaller->soundorg, sfxnum);
						else if (mo)
							S_StartSound(&mo->subsector->sector->soundorg, sfxnum);
					}
					else if (mo)
					{
						// play the sound from mobj that triggered it
						S_StartSound(mo, sfxnum);
					}
				}
			}
			break;

		case 113: // Run a script
			if (cv_runscripts.value)
			{
				int scrnum;
				lumpnum_t lumpnum;
				char newname[9];

#ifdef DOORS // Switch
				linedefExecuted = true;
#endif

				strcpy(newname, G_BuildMapName(gamemap));
				newname[0] = 'S';
				newname[1] = 'C';
				newname[2] = 'R';

				scrnum = line->frontsector->floorheight>>FRACBITS;
				if (scrnum > 999)
				{
					scrnum = 0;
					newname[5] = newname[6] = newname[7] = '0';
				}
				else
				{
					newname[5] = (char)('0' + (char)((scrnum/100)));
					newname[6] = (char)('0' + (char)((scrnum%100)/10));
					newname[7] = (char)('0' + (char)(scrnum%10));
				}
				newname[8] = '\0';

				lumpnum = W_CheckNumForName(newname);

				if (lumpnum == LUMPERROR || W_LumpLength(lumpnum) == 0)
					CONS_Printf("SOC Error: script lump %s not found/not valid.\n", newname);
				else
					COM_BufInsertText(W_CacheLumpNum(lumpnum, PU_CACHE));
			}
			break;

		case 119: // Spawn adjustable fire flicker
			while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0)
			{
#ifdef DOORS // Switch
				linedefExecuted = true;
#endif
				if (line->flags & ML_NOCLIMB && line->backsector)
				{
					// Use front sector for min light level, back sector for max.
					// This is tricky because P_SpawnAdjustableFireFlicker expects
					// the maxsector (second argument) to also be the target
					// sector, so we have to do some light level twiddling.
					fireflicker_t *flick;
					short reallightlevel = sectors[secnum].lightlevel;
					sectors[secnum].lightlevel = line->backsector->lightlevel;

					flick = P_SpawnAdjustableFireFlicker(line->frontsector, &sectors[secnum],
						P_AproxDistance(line->dx, line->dy)>>FRACBITS);

					// Make sure the starting light level is in range.
					if (reallightlevel < flick->minlight)
						reallightlevel = (short)flick->minlight;
					else if (reallightlevel > flick->maxlight)
						reallightlevel = (short)flick->maxlight;

					sectors[secnum].lightlevel = reallightlevel;
				}
				else
				{
					// Use front sector for min, target sector for max,
					// the same way linetype 61 does it.
					P_SpawnAdjustableFireFlicker(line->frontsector, &sectors[secnum],
						P_AproxDistance(line->dx, line->dy)>>FRACBITS);
				}
			}
			break;

		case 120: // Spawn adjustable glowing light
			while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0)
			{
#ifdef DOORS // Switch
				linedefExecuted = true;
#endif
				if (line->flags & ML_NOCLIMB && line->backsector)
				{
					// Use front sector for min light level, back sector for max.
					// This is tricky because P_SpawnAdjustableGlowingLight expects
					// the maxsector (second argument) to also be the target
					// sector, so we have to do some light level twiddling.
					glow_t *glow;
					short reallightlevel = sectors[secnum].lightlevel;
					sectors[secnum].lightlevel = line->backsector->lightlevel;

					glow = P_SpawnAdjustableGlowingLight(line->frontsector, &sectors[secnum],
						P_AproxDistance(line->dx, line->dy)>>FRACBITS);

					// Make sure the starting light level is in range.
					if (reallightlevel < glow->minlight)
						reallightlevel = (short)glow->minlight;
					else if (reallightlevel > glow->maxlight)
						reallightlevel = (short)glow->maxlight;

					sectors[secnum].lightlevel = reallightlevel;
				}
				else
				{
					// Use front sector for min, target sector for max,
					// the same way linetype 60 does it.
					P_SpawnAdjustableGlowingLight(line->frontsector, &sectors[secnum],
						P_AproxDistance(line->dx, line->dy)>>FRACBITS);
				}
			}
			break;

		case 117: // Fade light levels in tagged sectors to new value
			P_FadeLight(line->tag, sectors[secnum].lightlevel, P_AproxDistance(line->dx, line->dy));
#ifdef DOORS // Switch
			linedefExecuted = true;
#endif
			break;

		case 118: // Stop lighting effect in tagged sectors
			while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0)
				if (sectors[secnum].lightingdata)
				{
#ifdef DOORS // Switch
					linedefExecuted = true;
#endif
					P_RemoveThinker(&((elevator_t *)sectors[secnum].lightingdata)->thinker);
					sectors[secnum].lightingdata = NULL;
				}
			break;

		case 121: // Cut away to another view
			{
				mobj_t *altview;

				if (!mo || !mo->player) // only players have views
					return;

				if ((secnum = P_FindSectorFromLineTag(line, -1)) < 0)
					return;

				altview = P_GetObjectTypeInSectorNum(MT_ALTVIEWMAN, secnum);
				if (!altview)
					return;

#ifdef DOORS // Switch
				linedefExecuted = true;
#endif

				P_SetTarget(&mo->player->awayviewmobj, altview);
				mo->player->awayviewtics = P_AproxDistance(line->dx, line->dy)>>FRACBITS;

				if (line->flags & ML_NOCLIMB) // lets you specify a vertical angle
				{
					int aim;

					aim = sides[line->sidenum[0]].textureoffset>>FRACBITS;
					while (aim < 0)
						aim += 360;
					while (aim >= 360)
						aim -= 360;
					aim *= (ANG90>>8);
					aim /= 90;
					aim <<= 8;
					mo->player->awayviewaiming = (angle_t)aim;
				}
				else
					mo->player->awayviewaiming = 0; // straight ahead
			}
			break;

		case 123: // Change Sky
			if ((mo && P_IsLocalPlayer(mo->player)) || (line->flags & ML_NOCLIMB))
			{
#ifdef DOORS // Switch
				linedefExecuted = true;
#endif
				if (line->flags & ML_NOCLIMB)
					globallevelskynum = line->frontsector->floorheight>>FRACBITS;

				levelskynum = line->frontsector->floorheight>>FRACBITS;
				P_SetupLevelSky(levelskynum);
			}
			break;

		case 124: // Change Weather - Extremely CPU-Intense.
			if ((mo && P_IsLocalPlayer(mo->player)) || (line->flags & ML_NOCLIMB))
			{
#ifdef DOORS // Switch
				linedefExecuted = true;
#endif
				if (line->flags & ML_NOCLIMB)
					globalweather = (line->frontsector->floorheight>>FRACBITS)/10;

				P_SwitchWeather((line->frontsector->floorheight>>FRACBITS)/10);
			}
			break;

		case 125: // Calls P_SetMobjState on calling mobj
			if (mo)
#ifdef DOORS // Switch
			{
				linedefExecuted = true;
#endif
				P_SetMobjState(mo, P_AproxDistance(line->dx, line->dy)>>FRACBITS);
#ifdef DOORS // Switch
			}
#endif
			break;

		case 122: // Moves the mobj to its sector's soundorg and on the floor, and stops it
			if (!mo)
				return;

#ifdef DOORS // Switch
			linedefExecuted = true;
#endif

			if (line->flags & ML_NOCLIMB)
			{
				P_UnsetThingPosition(mo);
				mo->x = mo->subsector->sector->soundorg.x;
				mo->y = mo->subsector->sector->soundorg.y;
				mo->z = mo->floorz;
				P_SetThingPosition(mo);
			}

			mo->momx = mo->momy = mo->momz = 1;
			mo->pmomz = 0;

			if (mo->player)
			{
/*				if (splitscreen && cv_chasecam2.value && mo->player == &players[secondarydisplayplayer])
					P_ResetCamera(mo->player, &camera2);
				else if (cv_chasecam.value && mo->player == &players[displayplayer])
					P_ResetCamera(mo->player, &camera);*/

				mo->player->rmomx = mo->player->rmomy = 1;
				mo->player->cmomx = mo->player->cmomy = 0;
				P_ResetPlayer(mo->player);
				P_SetPlayerMobjState(mo, S_PLAY_STND);
			}
			break;

		case 126: // Awards points if the mobj is a player
			if (mo && mo->player)
#ifdef DOORS // Switch
			{
				linedefExecuted = true;
#endif
				P_AddPlayerScore(mo->player, line->frontsector->floorheight>>FRACBITS);
#ifdef DOORS // Switch
			}
#endif
			break;

		case 127: // Start floating platform movement
#ifdef DOORS // Switch
			if (EV_DoElevator(line, elevateContinuous, true))
			{
				linedefExecuted = true;
			}
#else
			EV_DoElevator(line, elevateContinuous, true);
#endif
			break;

#ifdef DOORS // Door line types
		// The lines MUST be in the same order as vldoor_e.
		case 130: // doorraise
		case 131: // doorlower
		case 132: // doorclose
		case 133: // dooropen
		case 134: // dooropenclose
		case 135: // doorwaitopen
		case 136: // doorwaitclose
		{
			// Normal Speed is VDOORSPEED(2*FRACUNIT)
			// Div by ten so the line's length is 20 not 2...
			fixed_t speed = P_AproxDistance(line->dx, line->dy)/10;
			long xofs = sides[line->sidenum[0]].rowoffset >> FRACBITS;
			byte locktype = 0;

			// Need Blue key to use.
			if (line->flags & ML_NOCLIMB)
				locktype |= it_bluecard;
			// Need Red key to use.
			if (line->flags & ML_PASSUSE)
				locktype |= it_redcard;
			// Need Yellow key to use.
			if (line->flags & ML_ALLTRIGGER)
				locktype |= it_yellowcard;

#ifdef DOORDEBUG
			CONS_Printf("Begin door, speed/FRACUNIT = %d\n", speed/FRACUNIT);
#endif

			// Check if the door is locked.
			if (locktype)
			{
				if (mo && mo->player)
				{
					if (EV_DoLockedDoor(line, line->special-130, mo->player,
						speed, xofs, locktype))
					{
						linedefExecuted = true;
					}
				}
			}
			else
			{
				if (EV_DoDoor(line, line->special-130, speed, xofs))
				{
					linedefExecuted = true;
				}
			}
			break;
		}

		// leave room for more doors...

		case 140: // Exit level, visa switches.
			if (mo && mo->player && !mo->player->exiting)
			{
				P_DoPlayerExit(mo->player);
				linedefExecuted = true;
			}
			break;
		case 141: // Change Light Level
			// How-to:
			// Set up the normal Linedef Ex sector with a line of type 141
			// Set the light levels in the frontside 
			//     texture offsets of the line with type 141.
			// Set the front sectors lightlevel to what you want it to
			//     "current lighting" meaning that the other one will be
			//     used for the new light level when the line is ran.
			//
			// Note: If you only want one lightlevel have both the
			//     offset be the same number...
			{
				sector_t *sec = sides[line->sidenum[0]].sector;
				int xofs = sides[line->sidenum[0]].rowoffset >> FRACBITS;
				int yofs = sides[line->sidenum[0]].textureoffset >> FRACBITS;
				int lightlevel = 0;

				// Start with X offset.
				lightlevel = xofs;

				// Check if X offset is in use.
				if (lightlevel == sec->lightlevel)
				{
					// Currently using X offset.
					// Use Y offset.
					lightlevel = yofs;
				}

				// Update the light level in use.
				sec->lightlevel = lightlevel;

				if (EV_LightTurnOn(line, lightlevel))
				{
					linedefExecuted = true;
				}
				break;
			}
#endif

#ifdef SRB2TODO
		case 432: // Enable 2D Mode
			if (mo->player)
#ifdef DOORS // Switch
			{
#endif
				mo->flags2 |= MF2_TWOD;
#ifdef DOORS // Switch
				linedefExecuted = true;
			}
#endif
			break;

		case 433: // Disable 2D Mode
			if (mo->player)
#ifdef DOORS // Switch
			{
#endif
				mo->flags2 &= ~MF2_TWOD;
#ifdef DOORS // Switch
				linedefExecuted = true;
			}
#endif
			break;

		case 434: // Custom Power
			if (mo->player)
			{
				mobj_t *dummy = P_SpawnMobj(mo->x, mo->y, mo->z, MT_DISS);
				var1 = (line->dx>>FRACBITS)-1;
				var2 = line->dy>>FRACBITS;
				P_SetTarget(&dummy->target, mo);
				A_CustomPower(dummy);
#ifdef DOORS // Switch
				linedefExecuted = true;
#endif
			}
			break;
#endif

#ifdef POLYOBJECTS
		case 480: // Polyobj_DoorSlide
		case 481: // Polyobj_DoorSwing
#ifdef POLYDEBUG
			CONS_Printf("EV_DoPolyDoor: Found linetype.\n");
#endif
#ifdef DOORS // Switch
			if (PolyDoor(line))
			{
				linedefExecuted = true;
			}
#else
			PolyDoor(line);
#endif
			break;
		case 482: // Polyobj_Move
		case 483: // Polyobj_OR_Move
#ifdef DOORS // Switch
			if (PolyMove(line))
			{
				linedefExecuted = true;
			}
#else
			PolyMove(line);
#endif
			break;
		case 484: // Polyobj_RotateRight
		case 485: // Polyobj_OR_RotateRight
		case 486: // Polyobj_RotateLeft
		case 487: // Polyobj_OR_RotateLeft
#ifdef DOORS // Switch
			if (PolyRotate(line))
			{
				linedefExecuted = true;
			}
#else
			PolyRotate(line);
#endif
			break;
#endif

		default:
			break;
	}
}

//
// P_SetupSignExit
//
// Finds the exit sign in the current sector and
// sets its target to the player who passed the map.
//
void P_SetupSignExit(player_t *player)
{
	mobj_t *thing;
	msecnode_t *node = player->mo->subsector->sector->touching_thinglist; // things touching this sector

	for (; node; node = node->m_snext)
	{
		thing = node->m_thing;
		if (thing->type != MT_SIGN)
			continue;

		if (thing->state != &states[thing->info->spawnstate])
			continue;

		P_SetTarget(&thing->target, player->mo);
		P_SetMobjState(thing, S_SIGN1);
		if (thing->info->seesound)
			S_StartSound(thing, thing->info->seesound);
	}
}

//
// P_IsFlagAtBase
//
// Checks to see if a flag is at its base.
//
static boolean P_IsFlagAtBase(mobjtype_t flag)
{
	thinker_t *think;
	mobj_t *mo;
	int specialnum = 0;

	for (think = thinkercap.next; think != &thinkercap; think = think->next)
	{
		if (think->function.acp1 != (actionf_p1)P_MobjThinker)
			continue; // not a mobj thinker

		mo = (mobj_t *)think;

		if (mo->type != flag)
			continue;

		if (mo->type == MT_REDFLAG)
			specialnum = 988;
		else if (mo->type == MT_BLUEFLAG)
			specialnum = 989;

		if (mo->subsector->sector->special == specialnum)
			return true;
		else if (mo->subsector->sector->ffloors) // Check the 3D floors
		{
			ffloor_t *rover;

			for (rover = mo->subsector->sector->ffloors; rover; rover = rover->next)
			{
				if (!(rover->flags & FF_EXISTS))
					continue;

				if (rover->master->frontsector->special != specialnum)
					continue;

				if (mo->z <= *rover->topheight
					&& mo->z >= *rover->bottomheight)
					return true;
			}
		}
	}
	return false;
}

/** Applies a sector special to a player.
  *
  * \param player       Player in the sector.
  * \param sector       Sector with the special.
  * \param roverspecial If true, sector is actually an FOF; otherwise, sector
  *                     is being physically contacted by the player.
  * \todo Split up into multiple functions.
  * \sa P_PlayerInSpecialSector, P_PlayerOnSpecial3DFloor
  */
static void P_ProcessSpecialSector(player_t *player, sector_t *sector, boolean roverspecial)
{
	int i = 0;
	int special;

	// Conveyor stuff
	if (sector->special == 512 || sector->special == 984
	 || sector->special == 985 || sector->special == 519)
		player->onconveyor = sector->special;

	special = sector->special;

	// Process Section 1
	switch (special)
	{
		case 11: // Damage (Generic)
			P_DamageMobj(player->mo, NULL, NULL, 1);
			break;
		case 983: // Damage (Water)
		case 984: // Damage (Water) + Currect
#ifdef POWERS2
			if (player->powers[pw_underwater])
#else
			if (player->powers[pw_underwater] && !player->powers[pw_watershield])
#endif
			{
				player->specialsector = sector->special;
				P_DamageMobj(player->mo, NULL, NULL, 1);
			}
			break;
		case 7: // Damage (Fire)
		case 519: // Lava & Current
#ifndef POWERS2 // When player gets hurt set to burned frame?
			if (!player->powers[pw_fireshield])
#endif
			{
				player->specialsector = sector->special;
				P_DamageMobj(player->mo, NULL, NULL, 1);
			}
			break;
		case 18: // Damage (Electrical)
#ifndef POWERS2 // When player gets hurt set to zaped frame?
			if (!player->powers[pw_ringshield])
#endif
			{
				player->specialsector = sector->special;
				P_DamageMobj(player->mo, NULL, NULL, 1);
			}
			break;
		case 4: // Spikes
			// Don't do anything. In Soviet Russia, spikes find you.
			break;
		case 16: // Death Pit (Camera Mod)
			player->specialsector = sector->special;
			P_DamageMobj(player->mo, NULL, NULL, 10000);
			break;
		case 5: // Death Pit (No Camera Mod)
			player->specialsector = sector->special;
			P_DamageMobj(player->mo, NULL, NULL, 10000);
			break;
		case 10: // Instant kill
			P_DamageMobj(player->mo, NULL, NULL, 10000);
			break;
		case 978: // Ring Drainer (Floor Touch)
		case 980: // Ring Drainer (No Floor Touch)
			if (leveltime % (TICRATE/2) == 0 && player->mo->health > 1)
			{
				player->mo->health--;
				player->health--;
				S_StartSound(player->mo, sfx_itemup);
			}
			break;
		case 9: // Special Stage Damage - Kind of like a mini-P_DamageMobj()
			if (player->powers[pw_invulnerability]
#ifndef POWERS3
				|| player->powers[pw_super]
#endif
				|| player->exiting)
				break;

#ifndef POWERS2 // add TMNT powers?
			if (player->powers[pw_fireshield] || player->powers[pw_ringshield] || player->powers[pw_jumpshield] || player->powers[pw_watershield] || player->powers[pw_bombshield])
			{
				player->powers[pw_fireshield] = false;
				player->powers[pw_jumpshield] = false;
				player->powers[pw_watershield] = false;
				player->powers[pw_ringshield] = false;

				if (player->powers[pw_bombshield]) // Give them what's coming to them!
				{
					player->blackow = 1; // BAM!
					player->powers[pw_bombshield] = false;
					player->pflags |= PF_JUMPDOWN;
				}
				player->mo->z++;

				if (player->mo->eflags & MF_UNDERWATER)
					player->mo->momz = FixedDiv(10511*FRACUNIT,2600*FRACUNIT);
				else
					player->mo->momz = FixedDiv(69*FRACUNIT,10*FRACUNIT);

				P_InstaThrust(player->mo, player->mo->angle-ANG180, 4*FRACUNIT);

				P_SetPlayerMobjState(player->mo, player->mo->info->painstate);
				player->powers[pw_flashing] = flashingtics;

				player->powers[pw_fireflower] = false;
				player->mo->flags = (player->mo->flags & ~MF_TRANSLATION)
					| ((player->skincolor)<<MF_TRANSSHIFT);

				P_ResetPlayer(player);

				S_StartSound(player->mo, sfx_shldls); // Ba-Dum! Shield loss.

				if (gametype == GT_CTF && (player->gotflag & MF_REDFLAG || player->gotflag & MF_BLUEFLAG))
					P_PlayerFlagBurst(player, false);
			}
#endif
			if (player->mo->health > 1)
			{
				if (player->powers[pw_flashing])
					return;
				player->powers[pw_flashing] = flashingtics;
				P_PlayRinglossSound(player->mo);
				if (player->mo->health > 10)
					player->mo->health -= 10;
				else
					player->mo->health = 1;
				player->health = player->mo->health;
				player->mo->z++;
				if (player->mo->eflags & MF_UNDERWATER)
					player->mo->momz = FixedDiv(10511*FRACUNIT,2600*FRACUNIT);
				else
					player->mo->momz = FixedDiv(69*FRACUNIT,10*FRACUNIT);
				P_InstaThrust (player->mo, player->mo->angle - ANG180, 4*FRACUNIT);
				P_ResetPlayer(player);
				P_SetPlayerMobjState(player->mo, player->mo->info->painstate);
			}
			break;
		case 6: // Space countdown
#ifdef POWERS2
			if (!player->powers[pw_spacetime])
#else
			if (!player->powers[pw_watershield] && !player->powers[pw_spacetime])
#endif
			{
				player->powers[pw_spacetime] = spacetimetics + 1;

				if (P_IsLocalPlayer(player))
					S_ChangeMusic(mus_drown, false);
			}
			break;
		case 992: // Ramp Sector (Increase step-up)
		case 996: // Non-Ramp Sector (Don't step-down)
		case 14: // Bouncy Sector (FOF Control Only)
			break;

	// Process Section 2
		case 971: // Trigger Linedef Exec (Pushable Objects)
			break;
		case 972: // Linedef executor requires all players present+doesn't require touching floor
		case 973: // Linedef executor requires all players present
			/// \todo take FOFs into account (+continues for proper splitscreen support?)
			for (i = 0; i < MAXPLAYERS; i++)
				if (playeringame[i] && players[i].mo && (gametype != GT_COOP || players[i].lives > 0) && players[i].mo->subsector->sector != sector)
			return;
		case 974: // Linedef executor that doesn't require touching floor
		case 975: // Linedef executor
		case 967: // Linedef executor (7 Emeralds)
		case 968: // Linedef executor (NiGHTS Mare)
			P_LinedefExecute(sector->tag, player->mo, sector);
			return;
		case 970: // Tells pushable things to check FOFs
			break;
		case 666: // Egg trap capsule
		{
			thinker_t *th;
			mobj_t *mo2;
			line_t junk;

			if (sector->ceilingdata || sector->floordata)
				return;
			junk.tag = 680;
			EV_DoElevator(&junk, elevateDown, false);
			junk.tag = 681;
			EV_DoFloor(&junk, raiseFloorToNearestFast);
			junk.tag = 682;
			EV_DoCeiling(&junk, lowerToLowestFast);
			sector->special = 0;

			// Find the center of the Eggtrap and release all the pretty animals!
			// The chimps are my friends.. heeheeheheehehee..... - LouisJM
			for (th = thinkercap.next; th != &thinkercap; th = th->next)
			{
				if (th->function.acp1 != (actionf_p1)P_MobjThinker)
					continue;

				mo2 = (mobj_t *)th;
				if (mo2->type == MT_EGGTRAP)
				{
					mo2->fuse = TICRATE/7;
					break;
				}
			}
			break;
		}
#ifndef NOEMERALDS
		case 990: // Special Stage Time/Rings
#endif
		case 991: // Custom Gravity
			break;

	// Process Section 3
		case 256: // Ice/Sludge
		case 512: // Wind/Current
		case 758: // Ice/Sludge and Wind/Current
		case 985: // Conveyor belt
			break;
		case 976: // Speed pad w/o spin
#ifndef TMNTMOVES
		case 977: // Speed pad w/ spin
#endif
			if (player->powers[pw_flashing] != 0 && player->powers[pw_flashing] < TICRATE/2)
				return;

			i = P_FindSpecialLineFromTag(65, sector->tag, -1);

			if (i != -1)
			{
				angle_t lineangle;
				fixed_t linespeed;

#if 0 ///#ifdef SRB2TODO
				lineangle = R_PointToAngle2(lines[i].v1->x, lines[i].v1->y, lines[i].v2->x, lines[i].v2->y);
#else // Alam: let not fix the Speed pad bug, ok?
				lineangle = R_PointToAngle2(lines[i].v2->x, lines[i].v2->y, lines[i].v1->x, lines[i].v1->y);
#endif
				linespeed = P_AproxDistance(lines[i].v2->x-lines[i].v1->x, lines[i].v2->y-lines[i].v1->y);

				if (linespeed > MAXMOVE)
					linespeed = MAXMOVE;

				player->mo->angle = lineangle;

				if (player == &players[consoleplayer])
#ifdef LOCALPLAYERS
					localangle[0] = player->mo->angle;
#else
					localangle = player->mo->angle;
#endif
				else if (player == &players[secondarydisplayplayer])
#ifdef LOCALPLAYERS
					localangle[1] = player->mo->angle;
#else
					localangle2 = player->mo->angle;
#endif
#ifdef TMNT4PLAYERS
				else if (player == &players[thirddisplayplayer])
					localangle[2] = player->mo->angle;
				else if (player == &players[fourthdisplayplayer])
					localangle[3] = player->mo->angle;
#endif

				if (!(lines[i].flags & ML_PASSUSE))
				{
					P_UnsetThingPosition(player->mo);
					if (roverspecial) // make FOF speed pads work
					{
						player->mo->x = player->mo->subsector->sector->soundorg.x;
						player->mo->y = player->mo->subsector->sector->soundorg.y;
					}
					else
					{
						player->mo->x = sector->soundorg.x;
						player->mo->y = sector->soundorg.y;
					}
					P_SetThingPosition(player->mo);
				}

				P_InstaThrust(player->mo, player->mo->angle, linespeed);

#ifndef TMNTMOVES
				if (special == 977 && (player->charflags & SF_SPINALLOWED))
				{
					if (!(player->pflags & PF_SPINNING))
					{
#ifndef TMNTRESETSCORE
						P_ResetScore(player);
#endif
						player->pflags |= PF_SPINNING;
					}

					P_SetPlayerMobjState(player->mo, S_PLAY_ATK1);
				}
#endif

				player->powers[pw_flashing] = TICRATE/3;
				S_StartSound(player->mo, sfx_spdpad);
			}
			break;
	// Process Section 4
		case 993: // Starpost Activator
		{
			mobj_t *post = P_GetObjectTypeInSectorNum(MT_STARPOST, sector - sectors);

			if (!post)
				return;

			P_TouchSpecialThing(post, player->mo, false);
			break;
		}

#ifndef NOEMERALDS
		case 33: // Special stage GOAL sector
			if (sstimer > 6 && gamemap >= sstage_start && gamemap <= sstage_end)
				sstimer = 6; // Just let P_Ticker take care of the rest.
			break;
#endif
		case 982: // Exit (for FOF exits; others are handled in P_PlayerThink in p_user.c)
			{
				// this is mostly a copy/paste from P_PlayerThink handling of exits
				int lineindex;

				P_DoPlayerExit(player);

				P_SetupSignExit(player);
				// important: use sector->tag on next line instead of player->mo->subsector->tag
				// this part is different from in P_PlayerThink, this is what was causing
				// FOF custom exits not to work.
				lineindex = P_FindSpecialLineFromTag(71, sector->tag, -1);

				if (gametype != GT_RACE && lineindex != -1) // Custom exit!
				{
#ifndef NOEMERALDS
					// Special goodies with the block monsters flag depending on emeralds collected
					if ((lines[lineindex].flags & ML_BLOCKMONSTERS) && ALL7EMERALDS)
					{
							if (emeralds & EMERALD8) // The secret eighth emerald. Use linedef length.
								nextmapoverride = P_AproxDistance(lines[lineindex].dx, lines[lineindex].dy);
							else // The first seven, not bad. Use front sector's ceiling.
								nextmapoverride = lines[lineindex].frontsector->ceilingheight;
					}
					else
#endif
						nextmapoverride = lines[lineindex].frontsector->floorheight;

					nextmapoverride >>= FRACBITS;

					if (lines[lineindex].flags & ML_NOCLIMB)
						skipstats = true;

					// change the gametype using front x offset if passuse flag is given
					// ...but not in single player!
					if (multiplayer && lines[lineindex].flags & ML_PASSUSE)
					{
						int xofs = sides[lines[lineindex].sidenum[0]].textureoffset;
						if (xofs >= 0 && xofs < NUMGAMETYPES)
							nextmapgametype = xofs;
					}
				}
			}
			break;

		case 988: // Red Team's Base
			if (gametype == GT_CTF && P_IsObjectOnGround(player->mo))
			{
				if (!player->ctfteam)
				{
					if (player == &players[consoleplayer])
					{
						COM_BufAddText("changeteam red");
						COM_BufExecute();
					}
#ifdef TMNT4PLAYERS
					else if (cv_players.value >= 2 && player == &players[secondarydisplayplayer])
					{
						COM_BufAddText("changeteam2 red");
						COM_BufExecute();
					}
					else if (cv_players.value >= 3 && player == &players[thirddisplayplayer])
					{
						COM_BufAddText("changeteam3 red");
						COM_BufExecute();
					}
					else if (cv_players.value >= 4 && player == &players[fourthdisplayplayer])
					{
						COM_BufAddText("changeteam4 red");
						COM_BufExecute();
					}
#else
					else if (splitscreen && player == &players[secondarydisplayplayer])
					{
						COM_BufAddText("changeteam2 red");
						COM_BufExecute();
					}
#endif
					return;
				}

				if (player->ctfteam == 1)
				{
					if (player->gotflag & MF_BLUEFLAG)
					{
						mobj_t *mo;

						// Make sure the red team still has their own
						// flag at their base so they can score.
						for (i = 0; i < MAXPLAYERS; i++)
						{
							if (!playeringame[i])
								continue;

							if (players[i].gotflag & MF_REDFLAG)
								return;
						}

						if (!P_IsFlagAtBase(MT_REDFLAG))
							return;

						redscore += 1;
						P_AddPlayerScore(player, 250);
						COM_BufAddText("cechoflags 0\n");
						COM_BufAddText("cechoduration 5\n");
						COM_BufAddText(va("cecho %s\\captured the blue flag.\\\\\\\\\n", player_names[player-players]));
						I_OutputMsg("%s captured the blue flag.\n", player_names[player-players]);

						if (players[consoleplayer].ctfteam == 1)
							S_StartSound(NULL, sfx_cgot);
						else if (players[consoleplayer].ctfteam == 2)
							S_StartSound(NULL, sfx_lose);

						P_CheckPointLimit(player);

#ifdef CARRYCTF
						T_DropMobj(player, false, false);
#endif
						mo = P_SpawnMobj(player->mo->x,
										player->mo->y,
										player->mo->z,
										MT_BLUEFLAG);
						player->gotflag &= ~MF_BLUEFLAG;
						mo->flags &= ~MF_SPECIAL;
						mo->fuse = TICRATE;
						mo->spawnpoint = bflagpoint;
						mo->flags2 |= MF2_JUSTATTACKED;
					}
					if (player->gotflag & MF_REDFLAG) // Returning a flag to your base
					{
						mobj_t *mo;

#ifdef CARRYCTF
						T_DropMobj(player, false, false);
#endif
						mo = P_SpawnMobj(player->mo->x,
										player->mo->y,
										player->mo->z,
										MT_REDFLAG);
						mo->flags &= ~MF_SPECIAL;
						player->gotflag &= ~MF_REDFLAG;
						mo->fuse = TICRATE;
						mo->spawnpoint = rflagpoint;
						COM_BufAddText("cechoflags 0\n");
						COM_BufAddText("cechoduration 5\n");

						if (players[consoleplayer].ctfteam == 2)
							COM_BufAddText("cecho the enemy has returned\\their flag.\\\\\\\\\n");
						else if (players[consoleplayer].ctfteam == 1)
						{
							COM_BufAddText("cecho your flag was returned\\to base.\\\\\\\\\n");
							S_StartSound(NULL, sfx_chchng);
						}
					}
				}
			}
			break;

		case 989: // Blue Team's Base
			if (gametype == GT_CTF && P_IsObjectOnGround(player->mo))
			{
				if (!player->ctfteam)
				{
					if (player == &players[consoleplayer])
					{
						COM_BufAddText("changeteam blue");
						COM_BufExecute();
					}
#ifdef TMNT4PLAYERS
					else if (cv_players.value >= 2 && player == &players[secondarydisplayplayer])
					{
						COM_BufAddText("changeteam2 blue");
						COM_BufExecute();
					}
					else if (cv_players.value >= 3 && player == &players[thirddisplayplayer])
					{
						COM_BufAddText("changeteam3 blue");
						COM_BufExecute();
					}
					else if (cv_players.value >= 4 && player == &players[fourthdisplayplayer])
					{
						COM_BufAddText("changeteam4 blue");
						COM_BufExecute();
					}
#else
					else if (splitscreen && player == &players[secondarydisplayplayer])
					{
						COM_BufAddText("changeteam2 blue");
						COM_BufExecute();
					}
#endif
					return;
				}

				if (player->ctfteam == 2)
				{
					if (player->gotflag & MF_REDFLAG)
					{
						mobj_t *mo;

						for (i = 0; i < MAXPLAYERS; i++)
						{
							if (!playeringame[i])
								continue;

							if (players[i].gotflag & MF_BLUEFLAG)
								return;
						}

						if (!P_IsFlagAtBase(MT_BLUEFLAG))
							return;

						bluescore += 1;
						P_AddPlayerScore(player, 250);
						COM_BufAddText("cechoflags 0\n");
						COM_BufAddText("cechoduration 5\n");
						COM_BufAddText(va("cecho %s\\captured the red flag.\\\\\\\\\n", player_names[player-players]));
						I_OutputMsg("%s captured the red flag.\n", player_names[player-players]);

						if (players[consoleplayer].ctfteam == 2)
							S_StartSound(NULL, sfx_cgot);
						else if (players[consoleplayer].ctfteam == 1)
							S_StartSound(NULL, sfx_lose);

						P_CheckPointLimit(player);

#ifdef CARRYCTF
						T_DropMobj(player, false, false);
#endif
						mo = P_SpawnMobj(player->mo->x,
										player->mo->y,
										player->mo->z,
										MT_REDFLAG);
						player->gotflag &= ~MF_REDFLAG;
						mo->flags &= ~MF_SPECIAL;
						mo->fuse = TICRATE;
						mo->spawnpoint = rflagpoint;
						mo->flags2 |= MF2_JUSTATTACKED;
					}
					if (player->gotflag & MF_BLUEFLAG) // Returning a flag to your base
					{
						mobj_t *mo;

#ifdef CARRYCTF
						T_DropMobj(player, false, false);
#endif
						mo = P_SpawnMobj(player->mo->x,
										player->mo->y,
										player->mo->z,
										MT_BLUEFLAG);
						mo->flags &= ~MF_SPECIAL;
						player->gotflag &= ~MF_BLUEFLAG;
						mo->fuse = TICRATE;
						mo->spawnpoint = bflagpoint;
						if (players[consoleplayer].ctfteam == 1)
							COM_BufAddText("cecho the enemy has returned\\their flag.\\\\\\\\\n");
						else if (players[consoleplayer].ctfteam == 2)
						{
							COM_BufAddText("cecho your flag was returned\\to base.\\\\\\\\\n");
							S_StartSound(NULL, sfx_chchng);
						}
					}
				}
			}
			break;

		case 997: // Fan sector
			player->mo->momz = mobjinfo[MT_FAN].speed;
#ifndef TMNTRESETSCORE
			P_ResetPlayer(player);
#endif
			if (player->mo->state != &states[S_PLAY_FALL1]
				&& player->mo->state != &states[S_PLAY_FALL2])
			{
				P_SetPlayerMobjState(player->mo, S_PLAY_FALL1);
			}
			break;

#ifndef POWERS3
		case 969: // Super Sonic transformer
			if (player->mo->health > 0 && (player->charflags & SF_ALLOWSUPER) && !player->powers[pw_super] && ALL7EMERALDS)
				P_DoSuperTransformation(player, true);
			break;
#endif

#ifndef TMNTMOVES
		case 979: // Make player spin
			/// Question: Do we really need to check z with floorz here?
			// Answer: YES.
			if (!(player->pflags & PF_SPINNING) && P_IsObjectOnGround(player->mo) && (player->charflags & SF_SPINALLOWED))
			{
				P_ResetScore(player);
				player->pflags |= PF_SPINNING;
				P_SetPlayerMobjState(player->mo, S_PLAY_ATK1);
				S_StartAttackSound(player->mo, sfx_spin);

				if ((player->rmomx < 5*FRACUNIT/NEWTICRATERATIO
				&& player->rmomx > -5*FRACUNIT/NEWTICRATERATIO)
				&& (player->rmomy < 5*FRACUNIT/NEWTICRATERATIO
				&& player->rmomy > -5*FRACUNIT/NEWTICRATERATIO))
					P_InstaThrust(player->mo, player->mo->angle, 10*FRACUNIT);
			}
			break;
#endif

		case 998: // Zoom Tube Start
			{
				int sequence;
				fixed_t speed;
				int lineindex;
				thinker_t *th;
				mobj_t *waypoint = NULL;
				mobj_t *mo2;
				angle_t an;

				if (player->mo->tracer && player->mo->tracer->type == MT_TUBEWAYPOINT)
					return;

				// Find line #18 tagged to this sector
				lineindex = P_FindSpecialLineFromTag(18, sector->tag, -1);

				if (lineindex == -1)
				{
					CONS_Printf("ERROR: Sector special %d missing line special #18.\n", sector->special);
					return;
				}

				// Grab speed and sequence values
				speed = abs(lines[lineindex].dx)/8;
				sequence = abs(lines[lineindex].dy)>>FRACBITS;

				// scan the thinkers
				// to find the first waypoint
				for (th = thinkercap.next; th != &thinkercap; th = th->next)
				{
					if (th->function.acp1 != (actionf_p1)P_MobjThinker)
						continue;

					mo2 = (mobj_t *)th;

					if (mo2->type == MT_TUBEWAYPOINT && mo2->threshold == sequence
						&& mo2->health == 0)
					{
						waypoint = mo2;
						break;
					}
				}

				if (!waypoint)
				{
					CONS_Printf("ERROR: FIRST WAYPOINT IN SEQUENCE %d NOT FOUND.\n", sequence);
					return;
				}
				else if (cv_debug)
					CONS_Printf("Waypoint %ld found in sequence %d - speed = %d\n",
																waypoint->health,
																sequence,
																speed);

				an = R_PointToAngle2(player->mo->x, player->mo->y, waypoint->x, waypoint->y) - player->mo->angle;

				if (an > ANG90 && an < ANG270)
					return; // behind back

				P_SetTarget(&player->mo->tracer, waypoint);
				player->speed = speed;
#ifdef TMNTATTACK
				P_StopAttacking(player);
#elif !defined TMNTMOVES
				player->pflags |= PF_SPINNING;
#endif
				player->pflags &= ~PF_JUMPED;
#ifndef TMNTMOVES
				player->pflags &= ~PF_GLIDING;
#endif
				player->climbing = 0;
#ifdef TMNTRESETSCORE
				player->chaintime = 0;
#endif
				player->scoreadd = 0;

#ifdef TMNTMOVES
				if (speed >= player->runspeed)
				{
					if (!(player->mo->state >= &states[S_PLAY_SPD1] && player->mo->state <= &states[S_PLAY_SPD4]))
						P_SetPlayerMobjState(player->mo, S_PLAY_SPD1);
				}
				else if (!(player->mo->state >= &states[S_PLAY_RUN1] && player->mo->state <= &states[S_PLAY_RUN4]))
				{
					P_SetPlayerMobjState(player->mo, S_PLAY_RUN1);
				}
#else
				if (!(player->mo->state >= &states[S_PLAY_ATK1] && player->mo->state <= &states[S_PLAY_ATK4]))
				{
					P_SetPlayerMobjState(player->mo, S_PLAY_ATK1);
					S_StartSound(player->mo, sfx_spin);
				}
#endif
			}
			break;

		case 999: // Zoom Tube End
			{
				int sequence;
				fixed_t speed;
				int lineindex;
				thinker_t *th;
				mobj_t *waypoint = NULL;
				mobj_t *mo2;
				angle_t an;

				if (player->mo->tracer && player->mo->tracer->type == MT_TUBEWAYPOINT)
					return;

				// Find line #18 tagged to this sector
				lineindex = P_FindSpecialLineFromTag(18, sector->tag, -1);

				if (lineindex == -1)
				{
					CONS_Printf("ERROR: Sector special %d missing line special #18.\n", sector->special);
					return;
				}

				// Grab speed and sequence values
				speed = -(abs(lines[lineindex].dx)/8); // Negative means reverse
				sequence = abs(lines[lineindex].dy)>>FRACBITS;

				// scan the thinkers
				// to find the last waypoint
				for (th = thinkercap.next; th != &thinkercap; th = th->next)
				{
					if (th->function.acp1 != (actionf_p1)P_MobjThinker)
						continue;

					mo2 = (mobj_t *)th;

					if (mo2->type == MT_TUBEWAYPOINT && mo2->threshold == sequence)
					{
						if (!waypoint)
							waypoint = mo2;
						else if (mo2->health > waypoint->health)
							waypoint = mo2;
					}
				}

				if (!waypoint)
				{
					CONS_Printf("ERROR: LAST WAYPOINT IN SEQUENCE %d NOT FOUND.\n", sequence);
					return;
				}
				else if (cv_debug)
					CONS_Printf("Waypoint %ld found in sequence %d - speed = %d\n",
																waypoint->health,
																sequence,
																speed);

				an = R_PointToAngle2(player->mo->x, player->mo->y, waypoint->x, waypoint->y) - player->mo->angle;

				if (an > ANG90 && an < ANG270)
					return; // behind back

				P_SetTarget(&player->mo->tracer, waypoint);
				player->speed = speed;
#ifdef TMNTATTACK
				P_StopAttacking(player);
#elif !defined TMNTMOVES
				player->pflags |= PF_SPINNING;
#endif
				player->pflags &= ~PF_JUMPED;
				player->scoreadd = 0;

#ifdef TMNTMOVES
				if (speed >= player->runspeed)
				{
					if (!(player->mo->state >= &states[S_PLAY_SPD1] && player->mo->state <= &states[S_PLAY_SPD4]))
						P_SetPlayerMobjState(player->mo, S_PLAY_SPD1);
				}
				else if (!(player->mo->state >= &states[S_PLAY_RUN1] && player->mo->state <= &states[S_PLAY_RUN4]))
				{
					P_SetPlayerMobjState(player->mo, S_PLAY_RUN1);
				}
#else
				if (!(player->mo->state >= &states[S_PLAY_ATK1] && player->mo->state <= &states[S_PLAY_ATK4]))
				{
					P_SetPlayerMobjState(player->mo, S_PLAY_ATK1);
					S_StartSound(player->mo, sfx_spin);
				}
#endif
			}
			break;

		case 994:  // Finish Line
			if (gametype == GT_RACE && !player->exiting)
			{
				if (player->starpostnum == numstarposts) // Must have touched all the starposts
				{
					thinker_t *th;
					mobj_t *post;

					player->laps++;

					if (player->pflags & PF_NIGHTSMODE)
						player->drillmeter += 48*20;

					if (player->laps >= (unsigned)cv_numlaps.value)
						CONS_Printf(FINISHEDFINALLAP, player_names[player-players]);
					else
						CONS_Printf(STARTEDLAP, player_names[player-players],player->laps+1);

					// Reset starposts (checkpoints) info
					player->starpostangle = player->starposttime = player->starpostnum = player->starpostbit = 0;
					player->starpostx = player->starposty = player->starpostz = 0;
					for (th = thinkercap.next; th != &thinkercap; th = th->next)
					{
						if (th->function.acp1 != (actionf_p1)P_MobjThinker)
							continue;

						post = (mobj_t *)th;

						if (post->type == MT_STARPOST)
							P_SetMobjState(post, post->info->spawnstate);
					}
				}

				if (player->laps >= (unsigned)cv_numlaps.value)
				{
					if (P_IsLocalPlayer(player))
					{
						COM_BufAddText("cechoflags 0\n");
						COM_BufAddText("cechoduration 5\n");
						COM_BufAddText("cecho FINISHED!");
					}

					P_DoPlayerExit(player);
				}
			}
			break;

	// Special Other
		case 981: // Water rise stuff
		{
			line_t junk;
			junk.tag = 744;
			EV_DoCeiling(&junk, raiseToHighest);
				break;
		}
#ifdef HOCKEY // Sector types
		case 960: // Red Team's Goal
			if (gametype == GT_CTF && player->mo->z == player->mo->floorz)
			{
				if (!player->ctfteam)
				{
					if (player == &players[consoleplayer])
					{
						COM_BufAddText("changeteam red");
						COM_BufExecute();
					}
					else if (splitscreen && player == &players[secondarydisplayplayer])
					{
						COM_BufAddText("changeteam2 red");
						COM_BufExecute();
					}
					return;
				}
				return;
			}
			return;
		case 961: // Blue Team's Goal
			if (gametype == GT_CTF && player->mo->z == player->mo->floorz)
			{
				if (!player->ctfteam)
				{
					if (player == &players[consoleplayer])
					{
						COM_BufAddText("changeteam blue");
						COM_BufExecute();
					}
					else if (splitscreen && player == &players[secondarydisplayplayer])
					{
						COM_BufAddText("changeteam2 blue");
						COM_BufExecute();
					}
				}
			}
			return;
#endif
	}
}

/** Checks if an object is standing on or is inside a special 3D floor.
  * If so, the sector is returned.
  *
  * \param mo Object to check.
  * \return Pointer to the sector with a special type, or NULL if no special 3D
  *         floors are being contacted.
  * \sa P_PlayerOnSpecial3DFloor
  */
sector_t *P_ThingOnSpecial3DFloor(mobj_t *mo)
{
	sector_t *sector;
	ffloor_t *rover;

	sector = mo->subsector->sector;
	if (!sector->ffloors)
		return NULL;

	for (rover = sector->ffloors; rover; rover = rover->next)
	{
		if (!rover->master->frontsector->special)
			continue;

		if (!(rover->flags & FF_EXISTS))
			continue;

		// Check the 3D floor's type...
		if (rover->flags & FF_SOLID)
		{
			// Thing must be on top of the floor to be affected...
			if (rover->master->frontsector->flipspecial == FLIPSPECIAL_FLOORONLY)
			{
				if ((mo->eflags & MF_VERTICALFLIP) || mo->z != *rover->topheight)
					continue;
			}
			else if (rover->master->frontsector->flipspecial == FLIPSPECIAL_CEILONLY)
			{
				if (!(mo->eflags & MF_VERTICALFLIP)
					|| mo->z + mo->height != *rover->bottomheight)
					continue;
			}
			else if (rover->master->frontsector->flipspecial == FLIPSPECIAL_BOTH)
			{
				if (!((mo->eflags & MF_VERTICALFLIP && mo->z + mo->height == *rover->bottomheight)
					|| (!(mo->eflags & MF_VERTICALFLIP) && mo->z == *rover->topheight)))
					continue;
			}
		}
		else
		{
			// Water and intangible FOFs
			if (mo->z > *rover->topheight || (mo->z + mo->height) < *rover->bottomheight)
				continue;
		}

		return rover->master->frontsector;
	}

	return NULL;
}

/** Checks if a player is standing on or is inside a 3D floor (e.g. water) and
  * applies any specials.
  *
  * \param player Player to check.
  * \sa P_ThingOnSpecial3DFloor, P_PlayerInSpecialSector
  */
static void P_PlayerOnSpecial3DFloor(player_t *player)
{
	sector_t *sector;
	ffloor_t *rover;

	sector = player->mo->subsector->sector;
	if (!sector->ffloors)
		return;

	for (rover = sector->ffloors; rover; rover = rover->next)
	{
		if (!rover->master->frontsector->special)
			continue;

		if (!(rover->flags & FF_EXISTS))
			continue;

		// Check the 3D floor's type...
		if (rover->flags & FF_SOLID)
		{
			// Thing must be on top of the floor to be affected...
			if (rover->master->frontsector->flipspecial == FLIPSPECIAL_FLOORONLY)
			{
				if ((player->mo->eflags & MF_VERTICALFLIP) || player->mo->z != *rover->topheight)
					continue;
			}
			else if (rover->master->frontsector->flipspecial == FLIPSPECIAL_CEILONLY)
			{
				if (!(player->mo->eflags & MF_VERTICALFLIP)
					|| player->mo->z + player->mo->height != *rover->bottomheight)
					continue;
			}
			else if (rover->master->frontsector->flipspecial == FLIPSPECIAL_BOTH)
			{
				if (!((player->mo->eflags & MF_VERTICALFLIP && player->mo->z + player->mo->height == *rover->bottomheight)
					|| (!(player->mo->eflags & MF_VERTICALFLIP) && player->mo->z == *rover->topheight)))
					continue;
			}
		}
		else
		{
			//Water and DEATH FOG!!! heh
			if (player->mo->z > *rover->topheight || (player->mo->z + player->mo->height) < *rover->bottomheight)
				continue;
		}

		P_ProcessSpecialSector(player, rover->master->frontsector, true);
	}
}

#ifndef DOORS // define moved to p_spec.h
#define VDOORSPEED (FRACUNIT*2/NEWTICRATERATIO)
#endif

/** Checks if the player is in a special sector or FOF and apply any specials.
  *
  * \param player Player to check.
  * \sa P_PlayerOnSpecial3DFloor, P_ProcessSpecialSector
  */
void P_PlayerInSpecialSector(player_t *player)
{
	sector_t *sector;
	boolean nofloorneeded = false;
	line_t junk; // buttons and more

	// Check 3D floors...
	P_PlayerOnSpecial3DFloor(player);

	sector = player->mo->subsector->sector;

	if (sector->special == 666) // Egg trap capsule -- should only be for 3dFloors!
		return;

	// keep track of what sector type the player's currently in
	player->specialsector = sector->special;

	if (!player->specialsector) // nothing special, exit
		return;

	switch (player->specialsector)
	{
		case 983: // Damage (water)
		case 984: // Damage (water) + current
		case 10: // Instant kill
		case 980: // Ring Drainer (No Floor Touch)
		case 6: // Ring drainer that doesn't require floor touch
		case 972: // Linedef executor (All players needed)
		case 974: // Linedef executor
		case 967: // Linedef executor (7 Emeralds)
		case 968: // Linedef executor (NiGHTS Mare)
		case 981: // Water rise stuff
		case 993: // Starpost activator
		case 33: // Special stage GOAL sector
		case 982: // Exit?
		case 997: // Fan sector
		case 969: // Super Sonic Transform
		case 998: // Zoom Tube Start
		case 999: // Zoom Tube End
		case 994: // Finish line
			nofloorneeded = true;
			break;
	}

	if (nofloorneeded)
	{
		P_ProcessSpecialSector(player, sector, false);
		return;
	}

	// Falling, not all the way down yet?
	// Damage if in slimey water!
	if (sector->heightsec != -1 && !(player->specialsector == 712 || player->specialsector == 713))
	{
		if (player->mo->z > sectors[sector->heightsec].floorheight)
			return;
	}

	// Only go further if on the ground
	if (sector->flipspecial == FLIPSPECIAL_FLOORONLY && player->mo->z != sector->floorheight)
		return;

	if (sector->flipspecial == FLIPSPECIAL_CEILONLY && player->mo->z + player->mo->height != sector->ceilingheight)
		return;

	if (sector->flipspecial == FLIPSPECIAL_BOTH
		&& player->mo->z != sector->floorheight
		&& player->mo->z + player->mo->height != sector->ceilingheight)
		return;

	if (player->specialsector >= 690 && player->specialsector <= 709)
	{
		junk.tag = (short)(player->specialsector * 2 - 680);
		junk.dx = VDOORSPEED;
		EV_DoCeiling(&junk, raiseToLowest);
		junk.tag++;
		EV_DoFloor(&junk, lowerFloorToLowest);
		return;
	}

	switch (player->specialsector)
	{
		// start button 21 (special used for THZ2)
		case 710:
			junk.tag = 740;
			EV_DoFloor(&junk, instantLower);
			junk.tag = 741;
			EV_DoFloor(&junk, lowerFloorToLowest);
			junk.tag = 742;
			junk.dx = VDOORSPEED;
			EV_DoCeiling(&junk, raiseToLowest);
			junk.tag = 745;
			{
				long secnum = -1;
				sector_t *sec;
				fixed_t temp;
				// act on all sectors with the same tag as the triggering linedef
				while ((secnum = P_FindSectorFromLineTag(&junk,secnum)) >= 0)
				{
					sec = &sectors[secnum];

					temp = P_FindNextLowestFloor(sec, sec->floorheight);
					sec->ceilingheight = temp + sec->ceilingheight - sec->floorheight;
					sec->floorheight = temp;
				}
			}
			return;
		// end button 21 (special used for THZ2)
		// start door closer
		case 711:
			junk.tag = 743;
			junk.dx = VDOORSPEED*4;
			EV_DoCeiling(&junk, lowerAndCrush);
			return;
		// end door closer

		// Start THZ2-specific Slime Lower button
		case 986:
			// Button
			junk.tag = 712;
			EV_DoFloor(&junk, lowerFloorToLowest);

			// Water
			junk.tag = 713;
			EV_DoCeiling(&junk, lowerToLowestFast);

			// The door
			junk.tag = 715;
			junk.dx = VDOORSPEED/2; // Open slowly now...
			EV_DoCeiling(&junk, raiseToLowest);

			// I saw the sign!
			junk.tag = 716;
			EV_DoFloor(&junk, instantLower);
			return;
		// End THZ2-specific Slime Lower button
	}

	P_ProcessSpecialSector(player, sector, false);
}

/** Animate planes, scroll walls, etc. and keeps track of level timelimit and exits if time is up.
  *
  * \sa cv_timelimit, P_CheckPointLimit
  */
void P_UpdateSpecials(void)
{
	anim_t *anim;
	int i;
	long pic;
	size_t j;

	levelflat_t *foundflats; // for flat animation

	// LEVEL TIMER
	// Only exit if the time is exactly equal to the timelimit.
	// Why? Suppose after playing for three and a half minutes you decide you want a timelimit
	//   of 10 minutes. You go to the menu item for timelimit, press right, and the round is
	//   suddenly over, because more than one minute has passed. Oops.
	if (cv_timelimit.value && timelimitintics <= leveltime && !menuactive)
		G_ExitLevel();

	// ANIMATE TEXTURES
	for (anim = anims; anim < lastanim; anim++)
	{
		for (i = anim->basepic; i < anim->basepic + anim->numpics; i++)
		{
			pic = anim->basepic + ((leveltime/anim->speed + i) % anim->numpics);
			if (anim->istexture)
				texturetranslation[i] = pic;
		}
	}

	// ANIMATE FLATS
	/// \todo do not check the non-animate flat.. link the animated ones?
	/// \note its faster than the original anywaysince it animates only
	///    flats used in the level, and there's usually very few of them
	foundflats = levelflats;
	for (j = 0; j < numlevelflats; j++, foundflats++)
	{
		if (foundflats->speed) // it is an animated flat
		{
			// update the levelflat lump number
			foundflats->lumpnum = foundflats->baselumpnum +
				((leveltime/foundflats->speed + foundflats->animseq) % foundflats->numpics);
		}
	}
}

/** Adds a newly formed 3Dfloor structure to a sector's ffloors list.
  *
  * \param sec    Target sector.
  * \param ffloor Newly formed 3Dfloor structure.
  * \todo Give this function a less confusing name.
  * \sa P_AddFakeFloor
  */
static inline void P_AddFFloor(sector_t *sec, ffloor_t *ffloor)
{
	ffloor_t *rover;

	if (!sec->ffloors)
	{
		sec->ffloors = ffloor;
		ffloor->next = 0;
		ffloor->prev = 0;
		return;
	}

	for (rover = sec->ffloors; rover->next; rover = rover->next);

	rover->next = ffloor;
	ffloor->prev = rover;
	ffloor->next = 0;
}

/** Adds a 3Dfloor.
  *
  * \param sec    Target sector.
  * \param sec2   Control sector.
  * \param master Control linedef.
  * \param flags  Options affecting this 3Dfloor.
  * \return Pointer to the new 3Dfloor.
  * \sa P_AddFFloor, P_AddFakeFloorsByLine, P_SpawnSpecials
  */
static ffloor_t *P_AddFakeFloor(sector_t *sec, sector_t *sec2, line_t *master, ffloortype_e flags)
{
	ffloor_t *ffloor;
	thinker_t *th;
	friction_t *f;
	pusher_t *p;
	levelspecthink_t *lst;

#ifdef SONICRWEATHER
	if (/* xmasmode */curWeather == PRECIP_SNOW && (flags & FF_SWIMMABLE))
	{
		flags &= ~FF_SWIMMABLE;
		flags |= FF_SOLID;
	}
#endif

	if (sec2->ceilingheight < sec2->floorheight)
		I_Error("One of your FOFs with a tag of %d has a top height less than that of the bottom.\n", master->tag);

	if (sec2->numattached == 0)
	{
		sec2->attached = malloc(sizeof (*sec2->attached) * sec2->maxattached);
		if (!sec2->attached)
			I_Error("No more free memory to AddFakeFloor");
		sec2->attached[0] = sec - sectors;
		sec2->numattached = 1;
	}
	else
	{
		size_t i;

		for (i = 0; i < sec2->numattached; i++)
			if (sec2->attached[i] == (size_t)(sec - sectors))
				return NULL;

		if (sec2->numattached >= sec2->maxattached)
		{
			sec2->maxattached *= 2;
			sec2->attached = realloc(sec2->attached, sizeof (*sec2->attached) * sec2->maxattached);
			if (!sec2->attached)
				I_Error("Out of Memory in P_AddFakeFloor");
		}
		sec2->attached[sec2->numattached] = sec - sectors;
		sec2->numattached++;
	}

	// Add the floor
	ffloor = Z_Calloc(sizeof (*ffloor), PU_LEVEL, NULL);
	ffloor->secnum = sec2 - sectors;
	ffloor->target = sec;
	ffloor->bottomheight = &sec2->floorheight;
	ffloor->bottompic = &sec2->floorpic;
	ffloor->bottomxoffs = &sec2->floor_xoffs;
	ffloor->bottomyoffs = &sec2->floor_yoffs;
	ffloor->bottomangle = &sec2->floorpic_angle;

	// Add the ceiling
	ffloor->topheight = &sec2->ceilingheight;
	ffloor->toppic = &sec2->ceilingpic;
	ffloor->toplightlevel = &sec2->lightlevel;
	ffloor->topxoffs = &sec2->ceiling_xoffs;
	ffloor->topyoffs = &sec2->ceiling_yoffs;
	ffloor->topangle = &sec2->ceilingpic_angle;

	ffloor->flags = flags;
	ffloor->master = master;
#ifdef DOORS
	ffloor->doordata = NULL;
#endif

	// scan the thinkers
	// to see if this FOF should have spikeness
	for (th = thinkercap.next; th != &thinkercap; th = th->next)
	{
		if (th->function.acp1 != (actionf_p1)T_SpikeSector)
			continue;

		lst = (levelspecthink_t *)th;

		if (lst->sector == sec2)
			P_AddSpikeThinker(sec, sec2-sectors);
	}

	// scan the thinkers
	// to see if this FOF should have friction
	for (th = thinkercap.next; th != &thinkercap; th = th->next)
	{
		if (th->function.acp1 != (actionf_p1)T_Friction)
			continue;

		f = (friction_t *)th;

		if (&sectors[f->affectee] == sec2)
			Add_Friction(f->friction, f->movefactor, (long)(sec-sectors), f->affectee);
	}

	// scan the thinkers
	// to see if this FOF should have wind/current/pusher
	for (th = thinkercap.next; th != &thinkercap; th = th->next)
	{
		if (th->function.acp1 != (actionf_p1)T_Pusher)
			continue;

		p = (pusher_t *)th;

		if (&sectors[p->affectee] == sec2)
			Add_Pusher(p->type, p->x_mag<<FRACBITS, p->y_mag<<FRACBITS, p->source, (long)(sec-sectors), p->affectee, p->exclusive);
	}

	if (flags & FF_TRANSLUCENT)
	{
		if (sides[master->sidenum[0]].toptexture > 0)
			ffloor->alpha = sides[master->sidenum[0]].toptexture;
		else
			ffloor->alpha = 0x80;
	}
	else
		ffloor->alpha = 0xff;

	if (flags & FF_QUICKSAND)
		CheckForQuicksand = true;

	if ((flags & FF_BUSTUP) || (flags & FF_SHATTER) || (flags & FF_SPINBUST))
		CheckForBustableBlocks = true;

	if ((flags & FF_MARIO))
	{
		P_AddBlockThinker(sec2, master);
		CheckForMarioBlocks = true;
	}

	if ((flags & FF_CRUMBLE))
		sec2->crumblestate = 1;

	if ((flags & FF_FLOATBOB))
	{
		P_AddFloatThinker(sec2, sec->tag);
		CheckForFloatBob = true;
	}

	P_AddFFloor(sec, ffloor);

	return ffloor;
}

//
// SPECIAL SPAWNING
//

/** Adds a spike thinker.
  * Sector type 4 will result in this effect.
  *
  * \param sec Sector in which to add the thinker.
  * \param referrer If != sec, then we're dealing with a FOF
  * \sa P_SpawnSpecials, T_SpikeSector
  * \author SSNTails <http://www.ssntails.org>
  */
static void P_AddSpikeThinker(sector_t *sec, int referrer)
{
	levelspecthink_t *spikes;

	// create and initialize new thinker
	spikes = Z_Calloc(sizeof (*spikes), PU_LEVSPEC, NULL);
	P_AddThinker(&spikes->thinker);

	spikes->thinker.function.acp1 = (actionf_p1)T_SpikeSector;

	spikes->sector = sec;
	spikes->vars[0] = referrer;
}

/** Adds a float thinker.
  * Float thinkers cause solid 3Dfloors to float on water.
  *
  * \param sec          Control sector.
  * \param actionsector Target sector.
  * \sa P_SpawnSpecials, T_FloatSector
  * \author SSNTails <http://www.ssntails.org>
  */
static void P_AddFloatThinker(sector_t *sec, int tag)
{
	levelspecthink_t *floater;

	// create and initialize new thinker
	floater = Z_Calloc(sizeof (*floater), PU_LEVSPEC, NULL);
	P_AddThinker(&floater->thinker);

	floater->thinker.function.acp1 = (actionf_p1)T_FloatSector;

	floater->sector = sec;
	floater->vars[0] = tag;
}

#ifdef SRB2TODO
/** Adds a bridge thinker.
  * Bridge thinkers cause a group of FOFs to behave like
  * a bridge made up of pieces, that bows under weight.
  *
  * \param sec          Control sector.
  * \sa P_SpawnSpecials, T_BridgeThinker
  * \author SSNTails <http://www.ssntails.org>
  */
static void P_AddBridgeThinker(line_t *sourceline, sector_t *sec)
{
	levelspecthink_t *bridge;

	// create an initialize new thinker
	bridge = Z_Calloc(sizeof (*bridge), PU_LEVSPEC, NULL);
	P_AddThinker(&bridge->thinker);

	bridge->thinker.function.acp1 = (actionf_p1)T_BridgeThinker;

	bridge->sector = sec;
	bridge->vars[0] = sourceline->frontsector->floorheight;
	bridge->vars[1] = sourceline->frontsector->ceilingheight;
	bridge->vars[2] = P_AproxDistance(sourceline->dx, sourceline->dy)>>2; // Speed
	bridge->vars[3] = bridge->vars[2];

	// Start tag and end tag are TARGET SECTORS, not CONTROL SECTORS
	// Control sector tags should be End_Tag + (End_Tag - Start_Tag)
	bridge->vars[4] = sourceline->tag; // Start tag
	bridge->vars[5] = (sides[sourceline->sidenum[0]].textureoffset>>FRACBITS); // End tag
}
#endif

/** Adds a Mario block thinker, which changes the block's texture between blank
  * and ? depending on whether it has contents.
  * Needed in case objects respawn inside.
  *
  * \param sec          Control sector.
  * \param actionsector Target sector.
  * \param sourceline   Control linedef.
  * \sa P_SpawnSpecials, T_MarioBlockChecker
  * \author SSNTails <http://www.ssntails.org>
  */
static void P_AddBlockThinker(sector_t *sec, line_t *sourceline)
{
	levelspecthink_t *block;

	// create and initialize new elevator thinker
	block = Z_Calloc(sizeof (*block), PU_LEVSPEC, NULL);
	P_AddThinker(&block->thinker);

	block->thinker.function.acp1 = (actionf_p1)T_MarioBlockChecker;
	block->sourceline = sourceline;

	block->sector = sec;
}

/** Adds a raise thinker.
  * A raise thinker checks to see if the
  * player is standing on its 3D Floor,
  * and if so, raises the platform towards
  * it's destination. Otherwise, it lowers
  * to the lowest nearby height if not
  * there already.
  *
  * Replaces the old "AirBob".
  *
  * \param sec          Control sector.
  * \param actionsector Target sector.
  * \param sourceline   Control linedef.
  * \sa P_SpawnSpecials, T_RaiseSector
  * \author SSNTails <http://www.ssntails.org>
  */
static void P_AddRaiseThinker(sector_t *sec, line_t *sourceline)
{
	levelspecthink_t *raise;

	raise = Z_Calloc(sizeof (*raise), PU_LEVSPEC, NULL);
	P_AddThinker(&raise->thinker);

	raise->thinker.function.acp1 = (actionf_p1)T_RaiseSector;

	if (sourceline->flags & ML_BLOCKMONSTERS)
		raise->vars[0] = 1;
	else
		raise->vars[0] = 0;

	// set up the fields
	raise->sector = sec;

	// Require a spindash to activate
	if (sourceline->flags & ML_NOCLIMB)
		raise->vars[1] = 1;
	else
		raise->vars[1] = 0;

	raise->vars[2] = P_AproxDistance(sourceline->dx, sourceline->dy);
	raise->vars[2] = FixedDiv(raise->vars[2], NEWTICRATERATIO*4*FRACUNIT);
	raise->vars[3] = raise->vars[2];

	raise->vars[5] = P_FindHighestCeilingSurrounding(sec);
	raise->vars[4] = raise->vars[5]
		- (sec->ceilingheight - sec->floorheight);

	raise->vars[7] = P_FindLowestCeilingSurrounding(sec);
	raise->vars[6] = raise->vars[7]
		- (sec->ceilingheight - sec->floorheight);

	raise->sourceline = sourceline;
}

// Function to maintain backwards compatibility
static void P_AddOldAirbob(sector_t *sec, line_t *sourceline, boolean noadjust)
{
	levelspecthink_t *airbob;

	airbob = Z_Calloc(sizeof (*airbob), PU_LEVSPEC, NULL);
	P_AddThinker(&airbob->thinker);

	airbob->thinker.function.acp1 = (actionf_p1)T_RaiseSector;

	// set up the fields
	airbob->sector = sec;

	// Require a spindash to activate
	if (sourceline->flags & ML_NOCLIMB)
		airbob->vars[1] = 1;
	else
		airbob->vars[1] = 0;

	airbob->vars[2] = FRACUNIT/NEWTICRATERATIO;

	if (noadjust)
	{
		airbob->vars[7] = airbob->sector->ceilingheight-16*FRACUNIT;
		airbob->vars[6] = airbob->vars[7]
			- (sec->ceilingheight - sec->floorheight);
	}
	else
		airbob->vars[7] = airbob->sector->ceilingheight - P_AproxDistance(sourceline->dx, sourceline->dy);

	airbob->vars[3] = airbob->vars[2];

	if (sourceline->flags & ML_BLOCKMONSTERS)
		airbob->vars[0] = 1;
	else
		airbob->vars[0] = 0;

	airbob->vars[5] = sec->ceilingheight;
	airbob->vars[4] = airbob->vars[5]
			- (sec->ceilingheight - sec->floorheight);

	airbob->sourceline = sourceline;
}

/** Adds a thwomp thinker.
  * Even thwomps need to think!
  *
  * \param sec          Control sector.
  * \param actionsector Target sector.
  * \param sourceline   Control linedef.
  * \sa P_SpawnSpecials, T_ThwompSector
  * \author SSNTails <http://www.ssntails.org>
  */
static inline void P_AddThwompThinker(sector_t *sec, sector_t *actionsector, line_t *sourceline)
{
#define speed vars[1]
#define direction vars[2]
#define distance vars[3]
#define floorwasheight vars[4]
#define ceilingwasheight vars[5]
	levelspecthink_t *thwomp;

	// You *probably* already have a thwomp in this sector. If you've combined it with something
	// else that uses the floordata/ceilingdata, you must be weird.
	if (sec->floordata || sec->ceilingdata)
		return;

	// create and initialize new elevator thinker
	thwomp = Z_Calloc(sizeof (*thwomp), PU_LEVSPEC, NULL);
	P_AddThinker(&thwomp->thinker);

	thwomp->thinker.function.acp1 = (actionf_p1)T_ThwompSector;

	// set up the fields according to the type of elevator action
	thwomp->sector = sec;
	thwomp->vars[0] = actionsector->tag;
	thwomp->floorwasheight = thwomp->sector->floorheight;
	thwomp->ceilingwasheight = thwomp->sector->ceilingheight;
	thwomp->direction = 0;
	thwomp->distance = 1;
	thwomp->sourceline = sourceline;
	thwomp->sector->floordata = thwomp;
	thwomp->sector->ceilingdata = thwomp;
#undef speed
#undef direction
#undef distance
#undef floorwasheight
#undef ceilingwasheight
}

/** Adds a thinker which checks if any MF_ENEMY objects with health are in the defined area.
  * If not, a linedef executor is run once.
  *
  * \param sec          Control sector.
  * \param sourceline   Control linedef.
  * \sa P_SpawnSpecials, T_NoEnemiesSector
  * \author SSNTails <http://www.ssntails.org>
  */
static inline void P_AddNoEnemiesThinker(sector_t *sec, line_t *sourceline)
{
	levelspecthink_t *nobaddies;

	// create and initialize new elevator thinker
	nobaddies = Z_Calloc(sizeof (*nobaddies), PU_LEVSPEC, NULL);
	P_AddThinker(&nobaddies->thinker);

	nobaddies->thinker.function.acp1 = (actionf_p1)T_NoEnemiesSector;

	nobaddies->sector = sec;
	nobaddies->sourceline = sourceline;
}

/** Adds a camera scanner.
  *
  * \param sourcesec    Control sector.
  * \param actionsector Target sector.
  * \param angle        Angle of the source line.
  * \sa P_SpawnSpecials, T_CameraScanner
  * \author SSNTails <http://www.ssntails.org>
  */
static inline void P_AddCameraScanner(sector_t *sourcesec, sector_t *actionsector, angle_t angle)
{
	elevator_t *elevator; // Why not? LOL

	// create and initialize new elevator thinker
	elevator = Z_Calloc(sizeof (*elevator), PU_LEVSPEC, NULL);
	P_AddThinker(&elevator->thinker);

	elevator->thinker.function.acp1 = (actionf_p1)T_CameraScanner;
	elevator->type = elevateBounce;

	// set up the fields according to the type of elevator action
	elevator->sector = sourcesec;
	elevator->actionsector = actionsector;
	elevator->distance = FixedMul(AngleFixed(angle),1);
}

/** Flashes a laser block.
  *
  * \param flash Thinker structure for this laser.
  * \sa EV_AddLaserThinker
  * \author SSNTails <http://www.ssntails.org>
  */
void T_LaserFlash(laserthink_t *flash)
{
	msecnode_t *node;
	mobj_t *thing;
	sector_t *sourcesec;
	fixed_t zplusheight;

	if (leveltime & 1)
		flash->ffloor->flags |= FF_RENDERALL;
	else
		flash->ffloor->flags &= ~FF_RENDERALL;

	sourcesec = flash->ffloor->master->frontsector; // Less to type!

	// Seek out objects to DESTROY! MUAHAHHAHAHAA!!!*cough*
	for (node = flash->sector->touching_thinglist; node; node = node->m_snext)
	{
		thing = node->m_thing;

		zplusheight = thing->z + thing->height;

		if (thing->flags & MF_SHOOTABLE && ((thing->z < sourcesec->ceilingheight
			&& thing->z > sourcesec->floorheight) || (zplusheight < sourcesec->ceilingheight
			&& zplusheight > sourcesec->floorheight) || (thing->z < sourcesec->floorheight
			&& zplusheight > sourcesec->ceilingheight)))
		{
			P_DamageMobj(thing, NULL, NULL, 1);
		}
	}
}

/** Adds a laser thinker to a 3Dfloor.
  *
  * \param ffloor 3Dfloor to turn into a laser block.
  * \param sector Target sector.
  * \sa T_LaserFlash
  * \author SSNTails <http://www.ssntails.org>
  */
static inline void EV_AddLaserThinker(ffloor_t *ffloor, sector_t *sector)
{
	laserthink_t *flash;

	if (!ffloor)
		return;

	flash = Z_Calloc(sizeof (*flash), PU_LEVSPEC, NULL);

	P_AddThinker(&flash->thinker);

	flash->thinker.function.acp1 = (actionf_p1)T_LaserFlash;
	flash->ffloor = ffloor;
	flash->sector = sector; // For finding mobjs
}

//
// axtoi
//
// Converts an ASCII Hex string into an integer. Thanks, Borland!
//
// This probably shouldn't be here, but in the utility files...?
//
static int axtoi(char *hexStg)
{
	int n = 0;
	int m = 0;
	int count;
	int intValue = 0;
	int digit[5];
	while (n < 4)
	{
		if (hexStg[n] == '\0')
			break;
		if (hexStg[n] > 0x29 && hexStg[n] < 0x40) // 0-9
			digit[n] = (hexStg[n] & 0x0f);
		else if (hexStg[n] >= 'a' && hexStg[n] <= 'f') // a-f
			digit[n] = (hexStg[n] & 0x0f) + 9;
		else if (hexStg[n] >= 'A' && hexStg[n] <= 'F') // A-F
			digit[n] = (hexStg[n] & 0x0f) + 9;
		else
			break;
		n++;
	}
	count = n;
	m = n - 1;
	n = 0;
	while (n < count)
	{
		intValue = intValue | (digit[n] << (m << 2));
		m--;
		n++;
	}
	return intValue;
}

#ifdef SRB2TODO
//
// P_RunLevelLoadExecutors
//
// After loading/spawning all other specials
// and items, execute these.
//
static void P_RunLevelLoadExecutors(void)
{
	size_t i;

	for (i = 0; i < numlines; i++)
	{
		if (lines[i].special == 399)
			P_LinedefExecute(lines[i].tag, NULL, NULL);
	}
}
#endif

/** After the map has loaded, scans for specials that spawn 3Dfloors and
  * thinkers.
  *
  * \todo Split up into multiple functions.
  * \todo Get rid of all the magic numbers.
  * \sa P_SpawnPrecipitation, P_SpawnFriction, P_SpawnPushers, P_SpawnScrollers
  */
void P_SpawnSpecials(void)
{
	sector_t *sector;
	size_t i;
	long j;

	// Set the default gravity. Custom gravity overrides this setting.
	gravity = FRACUNIT/2;

#ifndef NOEMERALDS
	// Defaults in case levels don't have them set.
	sstimer = 90*TICRATE + 6;
	totalrings = 1;
#endif

	CheckForBustableBlocks = CheckForBouncySector = CheckForQuicksand = CheckForMarioBlocks = CheckForFloatBob = CheckForReverseGravity = false;

	// Init special SECTORs.
	sector = sectors;
	for (i = 0; i < numsectors; i++, sector++)
	{
		if (!sector->special)
			continue;

		switch (sector->special)
		{
#ifdef DOORS // sector->special case 15: P_SpawnDoorCloseIn30
			case 15:
				// Door close in 30 seconds
				P_SpawnDoorCloseIn30(sector);
				break;
#endif
			case 4:	// Spikes
				P_AddSpikeThinker(sector, sector-sectors);
				break;

			case 14: // Bouncy sector
				CheckForBouncySector = true;
				break;

			case 2:
				// STROBE FAST
				P_SpawnStrobeFlash(sector, FASTDARK, 0);
				break;

#ifndef NOEMERALDS
			case 990: // Time for special stage
				sstimer = (sector->floorheight>>FRACBITS) * TICRATE + 6; // Time to finish
				totalrings = sector->ceilingheight>>FRACBITS; // Ring count for special stage
				break;
#endif

			case 991: // Custom global gravity!
				gravity = sector->floorheight/1000;
				break;

			case 994: // Circuit finish line
				circuitmap = true;
				break;

			case 3:	// STROBE SLOW
				P_SpawnStrobeFlash(sector, SLOWDARK, 0);
				break;

			case 8: // GLOWING LIGHT
				P_SpawnGlowingLight(sector);
				break;

			case 12: // SYNC STROBE SLOW
				P_SpawnStrobeFlash(sector, SLOWDARK, 1);
				break;

			case 13: // SYNC STROBE FAST
				P_SpawnStrobeFlash(sector, FASTDARK, 1);
				break;

			case 17: // Fade light levels in tagged sectors to new value
				P_SpawnFireFlicker(sector);
				break;
		}
	}

	if (xmasmode || mapheaderinfo[gamemap-1].weather == 2) // snow
		curWeather = PRECIP_SNOW;
	else if (mapheaderinfo[gamemap-1].weather == 3) // rain
		curWeather = PRECIP_RAIN;
	else if (mapheaderinfo[gamemap-1].weather == 1) // storm
		curWeather = PRECIP_STORM;
	else if (mapheaderinfo[gamemap-1].weather == 5) // storm w/o rain
		curWeather = PRECIP_STORM_NORAIN;
	else
		curWeather = PRECIP_NONE;

	P_InitTagLists();   // Create xref tables for tags
	P_SpawnScrollers(); // Add generalized scrollers
	P_SpawnFriction();  // Friction model using linedefs
	P_SpawnPushers();   // Pusher model using linedefs

	// Look for disable linedefs
	for (i = 0; i < numlines; i++)
	{
		if (lines[i].special == 73)
		{
			for (j = -1; (j = P_FindLineFromLineTag(&lines[i], j)) >= 0;)
			{
				lines[j].tag = 0;
				lines[j].special = 0;
			}
			lines[i].special = 0;
			lines[i].tag = 0;
		}
	}

	// Init line EFFECTs
	for (i = 0; i < numlines; i++)
	{
		// Disable special lines in certain difficulty modes.

		// actually set the line specials to 0, otherwise linedef executors aren't affected
		if ((lines[i].flags & ML_NOEASY) && gameskill <= sk_easy)
		{
			lines[i].special = 0;
			continue;
		}
		if ((lines[i].flags & ML_NONORMAL) && gameskill == sk_medium)
		{
			lines[i].special = 0;
			continue;
		}
		if ((lines[i].flags & ML_NOHARD) && gameskill >= sk_hard)
		{
			lines[i].special = 0;
			continue;
		}

		// set line specials to 0 here too, same reason as above
		if (!(netgame || multiplayer))
		{
#ifdef TMNTMOVES // Is there any reason to have line disablers?
			if (players[consoleplayer].charability == TM_LEO && (lines[i].flags & ML_NOLEO))
			{
				lines[i].special = 0;
				continue;
			}
			if (players[consoleplayer].charability == TM_DON && (lines[i].flags & ML_NODON))
			{
				lines[i].special = 0;
				continue;
			}
			if (players[consoleplayer].charability == TM_RAPH && (lines[i].flags & ML_NORAPH))
			{
				lines[i].special = 0;
				continue;
			}
			if (players[consoleplayer].charability == TM_MIKE && (lines[i].flags & ML_NOMIKE))
			{
				lines[i].special = 0;
				continue;
			}
#else
			if (players[consoleplayer].charability == 0 && (lines[i].flags & ML_NOSONIC))
			{
				lines[i].special = 0;
				continue;
			}
			if (players[consoleplayer].charability == 1 && (lines[i].flags & ML_NOTAILS))
			{
				lines[i].special = 0;
				continue;
			}
			if (players[consoleplayer].charability == 2 && (lines[i].flags & ML_NOKNUX))
			{
				lines[i].special = 0;
				continue;
			}
#endif
		}

		lines[i].special &= 255;

		switch (lines[i].special)
		{
			long s;
			size_t sec;
			ffloortype_e ffloorflags;

			case 64: // Definable gravity per sector
				sec = sides[*lines[i].sidenum].sector - sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
				{
					sectors[s].gravity = &sectors[sec].floorheight; // This allows it to change in realtime!
#ifdef SRB2TODO
					if (lines[i].flags & ML_NOCLIMB)
						sectors[s].verticalflip = true;
					else
#endif
						sectors[s].verticalflip = false;

					CheckForReverseGravity = sectors[s].verticalflip;
				}
				break;

			case 71: // Custom exit
				break;

			case 65: // Speed pad (combines with sector special 976 or 977)
				break;

			case 63: // Change camera info
				sec = sides[*lines[i].sidenum].sector - sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
					P_AddCameraScanner(&sectors[sec], &sectors[s], R_PointToAngle2(lines[i].v2->x, lines[i].v2->y, lines[i].v1->x, lines[i].v1->y));
				break;

#ifdef PARANOIA
			case 73: // Disable tags if level not cleared
				I_Error("Failed to catch a disable linedef");
				break;
#endif

			case 66: // Flat alignment
#ifdef SRB2TODO
				if (lines[i].flags & ML_PASSUSE) // Align angle
				{
					if (!(lines[i].flags & ML_ALLTRIGGER)) // Align floor unless ALLTRIGGER flag is set
					{
						for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
							sectors[s].floorpic_angle = R_PointToAngle2(lines[i].v1->x, lines[i].v1->y, lines[i].v2->x, lines[i].v2->y);
					}

					if (!(lines[i].flags & ML_BOUNCY)) // Align ceiling unless BOUNCY flag is set
					{
						for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
							sectors[s].ceilingpic_angle = R_PointToAngle2(lines[i].v1->x, lines[i].v1->y, lines[i].v2->x, lines[i].v2->y);
					}
				}
				else // Do offsets
#endif
				{
					if (!(lines[i].flags & ML_BLOCKMONSTERS)) // Align floor unless BLOCKMONSTERS flag is set
					{
						for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
						{
							sectors[s].floor_xoffs += lines[i].dx;
							sectors[s].floor_yoffs += lines[i].dy;
						}
					}

					if (!(lines[i].flags & ML_NOCLIMB)) // Align ceiling unless NOCLIMB flag is set
					{
						for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
						{
							sectors[s].ceiling_xoffs += lines[i].dx;
							sectors[s].ceiling_yoffs += lines[i].dy;
						}
					}
				}
				break;

#ifdef SRB2TODO
			case 17: // Sector Parameters
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
				{
					if (lines[i].flags & ML_NOCLIMB)
						sectors[s].flipspecial = FLIPSPECIAL_CEILONLY;
					else if (lines[i].flags & ML_PASSUSE)
						sectors[s].flipspecial = FLIPSPECIAL_BOTH;
					else
						sectors[s].flipspecial = FLIPSPECIAL_FLOORONLY;
				}
				break;
#endif

			case 26: // Insta-Lower Sector
				EV_DoFloor(&lines[i], instantLower);
				break;

			case 24: // Instant raise for ceilings
				EV_DoCeiling(&lines[i], instantRaise);
				break;

			case 88: // Continuously Falling sector
				EV_DoContinuousFall(lines[i].frontsector, lines[i].backsector, P_AproxDistance(lines[i].dx, lines[i].dy), (lines[i].flags & ML_NOCLIMB));
				break;

			case 2: // New super cool and awesome moving floor and ceiling type
			case 3: // New super cool and awesome moving floor type
				if (lines[i].backsector)
					EV_DoFloor(&lines[i], bounceFloor);
				if (lines[i].special == 3)
					break;
			case 4: // New super cool and awesome moving ceiling type
				if (lines[i].backsector)
					EV_DoCeiling(&lines[i], bounceCeiling);
				break;

			case 6: // New super cool and awesome moving floor and ceiling crush type
			case 7: // New super cool and awesome moving floor crush type
				if (lines[i].backsector)
					EV_DoFloor(&lines[i], bounceFloorCrush);
#ifndef SRB2TODO
				if (lines[i].special == 3)
					break;
#endif
			case 8: // New super cool and awesome moving ceiling crush type
				if (lines[i].backsector)
					EV_DoCeiling(&lines[i], bounceCeilingCrush);
				break;

			case 232: // Activate floating platform
				EV_DoElevator(&lines[i], elevateContinuous, false);
				break;

			case 233: // Floating platform with adjustable speed
				EV_DoElevator(&lines[i], elevateContinuous, true);
				break;

			case 43: // Crusher!
				EV_DoCrush(&lines[i], crushAndRaise);
				break;

			case 50: // Crusher (up and then down)!
				EV_DoCrush(&lines[i], fastCrushAndRaise);
				break;

			case 242: // support for drawn heights coming from different sector
				sec = sides[*lines[i].sidenum].sector-sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
					sectors[s].heightsec = (long)sec;
				break;

#ifdef SRB2TODO
			case 165: // Bridge Thinker
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
					P_AddBridgeThinker(&lines[i], &sectors[s]);
				break;
#endif

			case 25: // FOF (solid, opaque, shadows)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL);
				break;

			case 33: // FOF (solid, opaque, no shadows)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_NOSHADE|FF_CUTLEVEL);
				break;

			case 44: // TL block: FOF (solid, translucent)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_NOSHADE|FF_TRANSLUCENT|FF_EXTRA|FF_CUTEXTRA);
				break;

			case 69: // Solid FOF with no floor/ceiling (quite possibly useless)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERSIDES|FF_NOSHADE|FF_CUTLEVEL);
				break;

			case 51: // 3D Floor type that doesn't draw sides
				// If line has no-climb set, give it shadows, otherwise don't
				ffloorflags = FF_EXISTS|FF_SOLID|FF_RENDERPLANES|FF_CUTLEVEL;
				if (!(lines[i].flags & ML_NOCLIMB))
					ffloorflags |= FF_NOSHADE;

				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 57: // FOF (solid, invisible)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_NOSHADE);
				break;

			case 48: // Opaque water
				ffloorflags = FF_EXISTS|FF_RENDERALL|FF_SWIMMABLE|FF_BOTHPLANES|FF_ALLSIDES|FF_CUTEXTRA|FF_EXTRA|FF_CUTSPRITES;
				if (lines[i].flags & ML_NOCLIMB)
					ffloorflags |= FF_DOUBLESHADOW;
				if (lines[i].flags & ML_PASSUSE)
					ffloorflags |= FF_COLORMAPONLY;
				if (lines[i].flags & ML_ALLTRIGGER)
					ffloorflags |= FF_RIPPLE;
				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 45: // TL water
				ffloorflags = FF_EXISTS|FF_RENDERALL|FF_TRANSLUCENT|FF_SWIMMABLE|FF_BOTHPLANES|FF_ALLSIDES|FF_CUTEXTRA|FF_EXTRA|FF_CUTSPRITES;
				if (lines[i].flags & ML_NOCLIMB)
					ffloorflags |= FF_DOUBLESHADOW;
				if (lines[i].flags & ML_PASSUSE)
					ffloorflags |= FF_COLORMAPONLY;
				if (lines[i].flags & ML_ALLTRIGGER)
					ffloorflags |= FF_RIPPLE;
				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 75: // Opaque water, no sides
				ffloorflags = FF_EXISTS|FF_RENDERPLANES|FF_SWIMMABLE|FF_BOTHPLANES|FF_CUTEXTRA|FF_EXTRA|FF_CUTSPRITES;
				if (lines[i].flags & ML_NOCLIMB)
					ffloorflags |= FF_DOUBLESHADOW;
				if (lines[i].flags & ML_PASSUSE)
					ffloorflags |= FF_COLORMAPONLY;
				if (lines[i].flags & ML_ALLTRIGGER)
					ffloorflags |= FF_RIPPLE;
				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 74: // TL water, no sides
				ffloorflags = FF_EXISTS|FF_RENDERPLANES|FF_TRANSLUCENT|FF_SWIMMABLE|FF_BOTHPLANES|FF_CUTEXTRA|FF_EXTRA|FF_CUTSPRITES;
				if (lines[i].flags & ML_NOCLIMB)
					ffloorflags |= FF_DOUBLESHADOW;
				if (lines[i].flags & ML_PASSUSE)
					ffloorflags |= FF_COLORMAPONLY;
				if (lines[i].flags & ML_ALLTRIGGER)
					ffloorflags |= FF_RIPPLE;
				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 59: // 'Platform' - You can jump up through it
				// If line has no-climb set, don't give it shadows, otherwise do
				ffloorflags = FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_PLATFORM|FF_BOTHPLANES|FF_ALLSIDES;
				if (lines[i].flags & ML_NOCLIMB)
					ffloorflags |= FF_NOSHADE;

				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 81: // Translucent "platform"
				// If line has no-climb set, don't give it shadows, otherwise do
				ffloorflags = FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_PLATFORM|FF_TRANSLUCENT|FF_BOTHPLANES|FF_ALLSIDES;
				if (lines[i].flags & ML_NOCLIMB)
					ffloorflags |= FF_NOSHADE;

				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 77: // Translucent "platform" with no sides
				ffloorflags = FF_EXISTS|FF_SOLID|FF_CUTLEVEL|FF_RENDERPLANES|FF_TRANSLUCENT|FF_PLATFORM|FF_BOTHPLANES;
				if (lines[i].flags & ML_NOCLIMB) // shade it unless no-climb
					ffloorflags |= FF_NOSHADE;
				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 38: // Air bobbing platform
			case 68: // Adjustable air bobbing platform
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL);
				lines[i].flags |= ML_BLOCKMONSTERS;
				P_AddOldAirbob(lines[i].frontsector, lines + i, (lines[i].special != 68));
				break;
			case 72: // Adjustable air bobbing platform in reverse
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL);
				P_AddOldAirbob(lines[i].frontsector, lines + i, true);
				break;

			case 34: // Float/bob platform
				sec = sides[*lines[i].sidenum].sector - sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
				{
					P_AddFakeFloor(&sectors[s], &sectors[sec], lines + i,
						FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_FLOATBOB);
				}
				break;

			case 36: // Crumbling platform
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_CRUMBLE);
				break;

			case 35: // Crumbling platform that will not return
				P_AddFakeFloorsByLine(i,
					FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_CRUMBLE|FF_NORETURN);
				break;

			case 79: // "Platform" that crumbles and returns
				ffloorflags = FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_PLATFORM|FF_CRUMBLE|FF_BOTHPLANES|FF_ALLSIDES;
				if (lines[i].flags & ML_NOCLIMB) // shade it unless no-climb
					ffloorflags |= FF_NOSHADE;

				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 80: // "Platform" that crumbles and doesn't return
				ffloorflags = FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_PLATFORM|FF_CRUMBLE|FF_NORETURN|FF_BOTHPLANES|FF_ALLSIDES;
				if (lines[i].flags & ML_NOCLIMB) // shade it unless no-climb
					ffloorflags |= FF_NOSHADE;

				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 82: // Translucent "platform" that crumbles and returns
				ffloorflags = FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_PLATFORM|FF_CRUMBLE|FF_TRANSLUCENT|FF_BOTHPLANES|FF_ALLSIDES;
				if (lines[i].flags & ML_NOCLIMB) // shade it unless no-climb
					ffloorflags |= FF_NOSHADE;

				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 83: // Translucent "platform" that crumbles and doesn't return
				ffloorflags = FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_PLATFORM|FF_CRUMBLE|FF_NORETURN|FF_TRANSLUCENT|FF_BOTHPLANES|FF_ALLSIDES;
				if (lines[i].flags & ML_NOCLIMB) // shade it unless no-climb
					ffloorflags |= FF_NOSHADE;

				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 39: // Air bobbing platform that will crumble and bob on the water when it falls and hits
				sec = sides[*lines[i].sidenum].sector - sectors;
				lines[i].flags |= ML_BLOCKMONSTERS;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
				{
					P_AddFakeFloor(&sectors[s], &sectors[sec], lines + i,
						FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_FLOATBOB|FF_CRUMBLE);
				}
				P_AddOldAirbob(lines[i].frontsector, lines + i, true);
				break;

			case 1: // Air bobbing platform that will crumble and bob on
			        // the water when it falls and hits, then never return
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_FLOATBOB|FF_CRUMBLE|FF_NORETURN);
				lines[i].flags |= ML_BLOCKMONSTERS;
				P_AddOldAirbob(lines[i].frontsector, lines + i, true);
				break;

			case 37: // Crumbling platform that will float when it hits water
				sec = sides[*lines[i].sidenum].sector - sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
				{
					P_AddFakeFloor(&sectors[s], &sectors[sec], lines + i,
						FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_CRUMBLE|FF_FLOATBOB);
				}
				break;

			case 42: // Crumbling platform that will float when it hits water, but not return
				sec = sides[*lines[i].sidenum].sector - sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
				{
					P_AddFakeFloor(&sectors[s], &sectors[sec], lines + i,
						FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_CRUMBLE|FF_FLOATBOB|FF_NORETURN);
				}
				break;

			case 40: // Air bobbing platform that will crumble
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_CRUMBLE);
				lines[i].flags |= ML_BLOCKMONSTERS;
				P_AddOldAirbob(lines[i].frontsector, lines + i, true);
				break;

			case 89: // Rising Platform FOF (solid, opaque, shadows)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL);
				P_AddRaiseThinker(lines[i].frontsector, &lines[i]);
				break;

			case 90: // Rising Platform FOF (solid, opaque, no shadows)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_NOSHADE|FF_CUTLEVEL);
				P_AddRaiseThinker(lines[i].frontsector, &lines[i]);
				break;

			case 91: // Rising Platform TL block: FOF (solid, translucent)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_NOSHADE|FF_TRANSLUCENT|FF_EXTRA|FF_CUTEXTRA);
				P_AddRaiseThinker(lines[i].frontsector, &lines[i]);
				break;

			case 94: // Rising Platform FOF (solid, invisible)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_NOSHADE);
				P_AddRaiseThinker(lines[i].frontsector, &lines[i]);
				break;

			case 92: // Rising Platform 'Platform' - You can jump up through it
				// If line has no-climb set, don't give it shadows, otherwise do
				ffloorflags = FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_PLATFORM|FF_BOTHPLANES|FF_ALLSIDES;
				if (lines[i].flags & ML_NOCLIMB)
					ffloorflags |= FF_NOSHADE;

				P_AddFakeFloorsByLine(i, ffloorflags);
				P_AddRaiseThinker(lines[i].frontsector, &lines[i]);
				break;

			case 93: // Rising Platform Translucent "platform"
				// If line has no-climb set, don't give it shadows, otherwise do
				ffloorflags = FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_PLATFORM|FF_TRANSLUCENT|FF_BOTHPLANES|FF_ALLSIDES;
				if (lines[i].flags & ML_NOCLIMB)
					ffloorflags |= FF_NOSHADE;

				P_AddFakeFloorsByLine(i, ffloorflags);
				P_AddRaiseThinker(lines[i].frontsector, &lines[i]);
				break;

#ifdef SLOPENESS
			case 243:
				sec = sides[*lines[i].sidenum].sector-sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
				{
					size_t counting;

					sectors[s].floorangle = ANG45;
					for (counting = 0; counting < sectors[s].linecount/2; counting++)
					{
						sectors[s].lines[counting]->v1->z = sectors[sec].floorheight;
						CONS_Printf("Set it to %d\n", sectors[s].lines[counting]->v1->z>>FRACBITS);
					}

					for (counting = sectors[s].linecount/2; counting < sectors[s].linecount; counting++)
					{
						sectors[s].lines[counting]->v1->z = sectors[sec].ceilingheight;
						CONS_Printf("Set it to %d\n", sectors[s].lines[counting]->v1->z>>FRACBITS);
					}
					sectors[s].special = 16384;
					CONS_Printf("Found & Set slope!\n");
				}
				break;
#endif

			case 49: // Double light effect
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_CUTSPRITES|FF_DOUBLESHADOW);
				break;

			case 47: // Light effect
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_CUTSPRITES);
				break;

			case 46: // Fog
				sec = sides[*lines[i].sidenum].sector - sectors;
				// SoM: Because it's fog, check for an extra colormap and set
				// the fog flag...
				if (sectors[sec].extra_colormap)
					sectors[sec].extra_colormap->fog = 1;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
					P_AddFakeFloor(&sectors[s], &sectors[sec], lines + i,
						FF_EXISTS|FF_RENDERALL|FF_FOG|FF_BOTHPLANES|FF_INVERTPLANES|FF_ALLSIDES|FF_INVERTSIDES|FF_CUTEXTRA|FF_EXTRA|FF_DOUBLESHADOW|FF_CUTSPRITES);
				break;

			case 62: // Like opaque water, but not swimmable. (Good for snow effect on FOFs)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_RENDERALL|FF_BOTHPLANES|FF_ALLSIDES|FF_CUTEXTRA|FF_EXTRA|FF_CUTSPRITES);
				break;

			case 52: // FOF (intangible, translucent)
				// If line has no-climb set, give it shadows, otherwise don't
				ffloorflags = FF_EXISTS|FF_RENDERALL|FF_TRANSLUCENT|FF_EXTRA|FF_CUTEXTRA|FF_CUTSPRITES;
				if (!(lines[i].flags & ML_NOCLIMB))
					ffloorflags |= FF_NOSHADE;

				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 67: // FOF with no floor/ceiling (good for GFZGRASS effect on FOFs)
				// If line has no-climb set, give it shadows, otherwise don't
				ffloorflags = FF_EXISTS|FF_RENDERSIDES|FF_ALLSIDES;
				if (!(lines[i].flags & ML_NOCLIMB))
					ffloorflags |= FF_NOSHADE|FF_CUTSPRITES;

				P_AddFakeFloorsByLine(i, ffloorflags);
				break;

			case 58: // FOF (intangible, invisible) - for combining specials in a sector
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_NOSHADE);
				break;

			case 41: // Mario Block
				sec = sides[*lines[i].sidenum].sector - sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
				{
					P_AddFakeFloor(&sectors[s], &sectors[sec], lines + i,
						FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL|FF_MARIO);
				}
				break;

			case 54: // A THWOMP!
				sec = sides[*lines[i].sidenum].sector - sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
				{
					P_AddThwompThinker(&sectors[sec], &sectors[s], &lines[i]);
					P_AddFakeFloor(&sectors[s], &sectors[sec], lines + i,
						FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_CUTLEVEL);
				}
				break;

			case 76: // Shatter block (breaks when touched)
				if (lines[i].flags & ML_NOCLIMB)
					P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_BUSTUP|FF_SHATTER|FF_SHATTERBOTTOM);
				else
					P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_BUSTUP|FF_SHATTER);
				break;

			case 86: // Translucent shatter block (see 76)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_BUSTUP|FF_SHATTER|FF_TRANSLUCENT);
				break;

			case 55: // Bustable block
				if (lines[i].flags & ML_NOCLIMB)
					P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_BUSTUP|FF_ONLYKNUX);
				else
					P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_BUSTUP);
				break;

			case 78: // Spin bust block (breaks when jumped or spun downwards onto)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_BUSTUP|FF_SPINBUST);
				break;

			case 84: // Translucent spin bust block (see 78)
				P_AddFakeFloorsByLine(i, FF_EXISTS|FF_SOLID|FF_RENDERALL|FF_BUSTUP|FF_SPINBUST|FF_TRANSLUCENT);
				break;

			case 56: // Quicksand
				if (lines[i].flags & ML_ALLTRIGGER)
					P_AddFakeFloorsByLine(i, FF_EXISTS|FF_QUICKSAND|FF_RENDERALL|FF_ALLSIDES|FF_CUTSPRITES|FF_RIPPLE);
				else
					P_AddFakeFloorsByLine(i, FF_EXISTS|FF_QUICKSAND|FF_RENDERALL|FF_ALLSIDES|FF_CUTSPRITES);
				break;

			case 53: // Laser block
				sec = sides[*lines[i].sidenum].sector - sectors;

				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
					EV_AddLaserThinker(P_AddFakeFloor(&sectors[s], &sectors[sec], lines + i,
						FF_EXISTS|FF_RENDERALL|FF_NOSHADE|FF_EXTRA|FF_CUTEXTRA), &sectors[s]);
				break;

			case 87: // Make-Your-Own FOF!
				if (lines[i].sidenum[1] != 0xffff)
				{
					byte *data = W_CacheLumpNum(lastloadedmaplumpnum + ML_SIDEDEFS,PU_STATIC);
					unsigned short b;

					for (b = 0; b < (short)numsides; b++)
					{
						register mapsidedef_t *msd = (mapsidedef_t *)data + b;

						if (b == lines[i].sidenum[1])
						{
							if ((msd->toptexture[0] >= '0' && msd->toptexture[0] <= '9')
								|| (msd->toptexture[0] >= 'A' && msd->toptexture[0] <= 'F'))
							{
								ffloortype_e FOF_Flags = axtoi(msd->toptexture);

								P_AddFakeFloorsByLine(i, FOF_Flags);
								break;
							}
							else
								I_Error("Make-Your-Own-FOF (tag %d) needs a value in the linedef's second side upper texture field.", lines[i].tag);
						}
					}
					Z_Free(data);
				}
				else
					I_Error("Make-Your-Own FOF (tag %d) found without a 2nd linedef side!", lines[i].tag);
				break;

			case 95: // Linedef executor (combines with sector special 974/975) and commands
			case 96:
			case 97:
			case 98:
			case 99:

			// Charability linedef executors
			case 19:
			case 20:
			case 21:
				break;

			case 9: // Race-only linedef executor. Triggers once.
				if (gametype != GT_RACE)
					lines[i].special = 0;
				break;

			// Linedef executor triggers for CTF teams.
			case 10:
			case 11:
			case 12:
			case 13:
				if (gametype != GT_CTF)
					lines[i].special = 0;
				break;

			// No More Enemies Linedef Exec
			case 15:
				sec = sides[*lines[i].sidenum].sector - sectors;
				P_AddNoEnemiesThinker(&sectors[sec], &lines[i]);
				break;

			case 101:
			case 102:
			case 103:
			case 104:
			case 105:
			case 106:
			case 107:
			case 108:
			case 109:
			case 110:
			case 111:
			case 112:
			case 113:
			case 114:
			case 115:
			case 116:
			case 117:
			case 118:
			case 119:
			case 120:
			case 121:
			case 122:
			case 123:
			case 124:
			case 125:
#ifdef DOORS // Line Types
			case 130: // doorraise
			case 131: // doorlower
			case 132: // doorclose
			case 133: // dooropen
			case 134: // dooropenclose
			case 135: // doorwaitopen
			case 136: // doorwaitclose

			case 140: // Exit level, visa switches.
			case 141: // Change Light Level

			case 150: // Switch: Linedef Executor Trigger (Once)
			case 151: // Switch: Linedef Executor Trigger (Repeatedly)
			case 152: // Switch: Linedef Executor Trigger (Once Button)
			case 153: // Switch: Linedef Executor Trigger (Repeatedly Button)
#endif
				break;

#ifdef SRB2TODO
			case 399: // Linedef execute on map load
				// This is handled in P_RunLevelLoadExecutors.
				break;
#endif

			// 85 is used for a scroller
			// 100 is used for a scroller
#ifdef KOTHLIGHT // setup the KOTH light.
			case 170: // KOTH light thingy (KOTH fog block).
				sec = sides[*lines[i].sidenum].sector - sectors;
				// Lights control sector.
				// Only need one of each control sector.
				if (numkothsectors < MAX_KOTH_CONTROLSECTORS)
				{
					int x;
					for(x = 0; x < numkothsectors; x++)
					{
						if (kothsectors[x] == sec)
							break;
					}
					if (x == numkothsectors)
					{
						kothsectors[numkothsectors] = sec;
						numkothsectors++;
					}
				}
				else
				{
					CONS_Printf("Can't add KOTH sector: max %d\n", MAX_KOTH_CONTROLSECTORS);
					break;
				}

				// SoM: Because it's fog, check for an extra colormap and set
				// the fog flag...
				if (sectors[sec].extra_colormap)
					sectors[sec].extra_colormap->fog = 1;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
				{
					EV_DoKOTHLight(&sectors[s], &sectors[sec], P_AddFakeFloor(&sectors[s], &sectors[sec], lines + i,
						FF_EXISTS|FF_RENDERALL|FF_FOG|FF_BOTHPLANES|FF_INVERTPLANES|FF_ALLSIDES|FF_INVERTSIDES|FF_CUTEXTRA|FF_EXTRA|FF_DOUBLESHADOW|FF_CUTSPRITES));
				}
				break;
#endif

			// 200-205 are used for scrollers
			// 214-218 are used for scrollers
			// 223 is used for friction
			// 224 is used for wind
			// 225 is used for current
			// 226 is used for push/pull
			// 227 is used for upwards current
			// 228 is used for downwards current
			// 229 is used for upwards wind
			// 230 is used for downwards wind
			// 245-255 are used for scrollers

			case 213: // floor lighting independently (e.g. lava)
				sec = sides[*lines[i].sidenum].sector-sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
					sectors[s].floorlightsec = (long)sec;
				break;

			case 5: // ceiling lighting independently
				sec = sides[*lines[i].sidenum].sector-sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
					sectors[s].ceilinglightsec = (long)sec;
				break;

			case 60: // Adjustable pulsating light
				sec = sides[*lines[i].sidenum].sector - sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
					P_SpawnAdjustableGlowingLight(&sectors[sec], &sectors[s],
						P_AproxDistance(lines[i].dx, lines[i].dy)>>FRACBITS);
				break;

			case 61: // Adjustable flickering light
				sec = sides[*lines[i].sidenum].sector - sectors;
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
					P_SpawnAdjustableFireFlicker(&sectors[sec], &sectors[s],
						P_AproxDistance(lines[i].dx, lines[i].dy)>>FRACBITS);
				break;
			case 16: // HACK! Copy colormaps. Just plain colormaps.
				for (s = -1; (s = P_FindSectorFromLineTag(lines + i, s)) >= 0 ;)
					sectors[s].midmap = lines[i].frontsector->midmap;
				break;

			default:
				break;
		}
	}

#ifdef POLYOBJECTS
	// haleyjd 02/20/06: spawn polyobjects
	Polyobj_InitLevel();

	for (i = 0; i < numlines; i++)
	{
		switch (lines[i].special)
		{
			case 30: // Polyobj_Flag
				EV_DoPolyObjFlag(&lines[i]);
				break;
		}
	}
#endif

#ifdef SRB2TODO
	P_RunLevelLoadExecutors();
#endif
}

/** Adds 3Dfloors as appropriate based on a common control linedef.
  *
  * \param line        Control linedef to use.
  * \param ffloorflags 3Dfloor flags to use.
  * \sa P_SpawnSpecials, P_AddFakeFloor
  * \author Graue <graue@oceanbase.org>
  */
static void P_AddFakeFloorsByLine(size_t line, ffloortype_e ffloorflags)
{
	long s;
	size_t sec = sides[*lines[line].sidenum].sector-sectors;

	for (s = -1; (s = P_FindSectorFromLineTag(lines+line, s)) >= 0 ;)
		P_AddFakeFloor(&sectors[s], &sectors[sec], lines+line, ffloorflags);
}

/*
 SoM: 3/8/2000: General scrolling functions.
 T_Scroll,
 Add_Scroller,
 Add_WallScroller,
 P_SpawnScrollers
*/

/** Processes an active scroller.
  * This function, with the help of r_plane.c and r_bsp.c, supports generalized
  * scrolling floors and walls, with optional mobj-carrying properties, e.g.
  * conveyor belts, rivers, etc. A linedef with a special type affects all
  * tagged sectors the same way, by creating scrolling and/or object-carrying
  * properties. Multiple linedefs may be used on the same sector and are
  * cumulative, although the special case of scrolling a floor and carrying
  * things on it requires only one linedef.
  *
  * The linedef's direction determines the scrolling direction, and the
  * linedef's length determines the scrolling speed. This was designed so an
  * edge around a sector can be used to control the direction of the sector's
  * scrolling, which is usually what is desired.
  *
  * \param s Thinker for the scroller to process.
  * \todo Split up into multiple functions.
  * \todo Use attached lists to make ::sc_carry_ceiling case faster and
  *       cleaner.
  * \sa Add_Scroller, Add_WallScroller, P_SpawnScrollers
  * \author Steven McGranahan
  * \author Graue <graue@oceanbase.org>
  */
void T_Scroll(scroll_t *s)
{
	fixed_t dx = s->dx, dy = s->dy;
	boolean is3dblock = false;

	if (cv_objectplace.value)
		return;

	if (s->control != -1)
	{ // compute scroll amounts based on a sector's height changes
		fixed_t height = sectors[s->control].floorheight +
			sectors[s->control].ceilingheight;
		fixed_t delta = height - s->last_height;
		s->last_height = height;
		dx = FixedMul(dx, delta);
		dy = FixedMul(dy, delta);
	}

	if (s->accel)
	{
		s->vdx = dx += s->vdx;
		s->vdy = dy += s->vdy;
	}

	if (!(dx | dy)) // no-op if both (x,y) offsets 0
		return;

	switch (s->type)
	{
		side_t *side;
		sector_t *sec;
		fixed_t height;
		msecnode_t *node;
		mobj_t *thing;
		line_t *line;
		size_t i;
		long sect;

		case sc_side: // scroll wall texture
			side = sides + s->affectee;
			side->textureoffset += dx;
			side->rowoffset += dy;
			break;

		case sc_floor: // scroll floor texture
			sec = sectors + s->affectee;
			sec->floor_xoffs += dx;
			sec->floor_yoffs += dy;
			break;

		case sc_ceiling: // scroll ceiling texture
			sec = sectors + s->affectee;
			sec->ceiling_xoffs += dx;
			sec->ceiling_yoffs += dy;
			break;

		case sc_carry:
			sec = sectors + s->affectee;
			height = sec->floorheight;

			// sec is the control sector, find the real sector(s) to use
			for (i = 0; i < sec->linecount; i++)
			{
				line = sec->lines[i];
				switch (line->special)
				{
					case 25: // 3D floor: solid, opaque, shadowcasting
					case 33: // 3D floor: solid, opaque, no shadows
					case 44: // 3D floor: solid, translucent
					case 57: // 3D floor: solid, invisible
					case 69: // 3D floor: solid, sides only
					case 51: // 3D floor: solid, no sides
					case 48: // Opaque water
					case 45: // TL water
					case 75: // Opaque water, no sides
					case 74: // TL water, no sides
					case 59: // 'Platform' - You can jump up through it
					case 81: // Translucent "platform"
					case 77: // Translucent "platform" with no sides
					case 38: // Air bobbing platform
					case 68: // Adjustable air bobbing platform
					case 72: // Adjustable air bobbing platform in reverse
					case 34: // Float/bob platform
					case 36: // Crumbling platform
					case 35: // Crumbling platform that will not return
					case 79: // "Platform" that crumbles and returns
					case 80: // "Platform" that crumbles and doesn't return
					case 82: // Translucent "platform" that crumbles and returns
					case 83: // Translucent "platform" that crumbles and doesn't return
					case 39: // Air bobbing platform that will crumble and bob on the water when it falls and hits
					case 1: // Air bobbing platform that will crumble and bob on
					case 37: // Crumbling platform that will float when it hits water
					case 42: // Crumbling platform that will float when it hits water, but not return
					case 40: // Air bobbing platform that will crumble
					case 89: // Rising Platform FOF (solid, opaque, shadows)
					case 90: // Rising Platform FOF (solid, opaque, no shadows)
					case 91: // Rising Platform TL block: FOF (solid, translucent)
					case 94: // Rising Platform FOF (solid, invisible)
					case 92: // Rising Platform 'Platform' - You can jump up through it
					case 93: // Rising Platform Translucent "platform"
					case 49: // Double light effect
					case 47: // Light effect
					case 46: // Fog
					case 62: // Like opaque water, but not swimmable. (Good for snow effect on FOFs)
					case 52: // FOF (intangible, translucent)
					case 67: // FOF with no floor/ceiling (good for GFZGRASS effect on FOFs)
					case 58: // FOF (intangible, invisible) - for combining specials in a sector
					case 41: // Mario Block
					case 54: // A THWOMP!
					case 76: // Shatter block (breaks when touched)
					case 86: // Translucent shatter block (see 76)
					case 55: // Bustable block
					case 78: // Spin bust block (breaks when jumped or spun downwards onto)
					case 84: // Translucent spin bust block (see 78)
					case 56: // Quicksand
					case 53: // Laser block
					case 87: // Make-Your-Own FOF!
						is3dblock = true;
						break;
					default: // not a solid 3D blocks
						is3dblock = false;
					break;
				}

				if (!is3dblock)
					continue;

				for (sect = -1; (sect = P_FindSectorFromTag(line->tag, sect)) >= 0 ;)
				{
					sector_t *psec;
					psec = sectors + sect;

					for (node = psec->touching_thinglist; node; node = node->m_snext)
					{
						thing = node->m_thing;

						if (thing->flags2 & MF2_PUSHED) // Already pushed this tic by an exclusive pusher.
							continue;

						if (!(thing->flags & MF_NOCLIP)) // Thing must be clipped
						if (!(thing->flags & MF_NOGRAVITY || thing->z+thing->height != height)) // Thing must a) be non-floating and have z+height == height
						{
							// Move objects only if on floor
							// non-floating, and clipped.
							thing->momx += dx;
							thing->momy += dy;
							if (thing->player)
							{
								thing->player->cmomx += dx;
								thing->player->cmomy += dy;
								thing->player->cmomx = FixedMul(thing->player->cmomx, 0xe800);
								thing->player->cmomy = FixedMul(thing->player->cmomy, 0xe800);
							}

							if (s->exclusive)
								thing->flags2 |= MF2_PUSHED;
						}
					} // end of for loop through touching_thinglist
				} // end of loop through sectors
			}

			if (!is3dblock)
			{
				for (node = sec->touching_thinglist; node; node = node->m_snext)
				{
					thing = node->m_thing;

					if (thing->flags2 & MF2_PUSHED)
						continue;

					if (!((thing = node->m_thing)->flags & MF_NOCLIP) &&
						(!(thing->flags & MF_NOGRAVITY || thing->z > height)))
					{
						// Move objects only if on floor or underwater,
						// non-floating, and clipped.
						thing->momx += dx;
						thing->momy += dy;
						if (thing->player)
						{
							thing->player->cmomx += dx;
							thing->player->cmomy += dy;
							thing->player->cmomx = FixedMul(thing->player->cmomx, 0xe800);
							thing->player->cmomy = FixedMul(thing->player->cmomy, 0xe800);
						}

						if (s->exclusive)
							thing->flags2 |= MF2_PUSHED;
					}
				}
			}
			break;

		case sc_carry_ceiling: // carry on ceiling (FOF scrolling)
			sec = sectors + s->affectee;
			height = sec->ceilingheight;

			// sec is the control sector, find the real sector(s) to use
			for (i = 0; i < sec->linecount; i++)
			{
				line = sec->lines[i];
				switch (line->special)
				{
					case 25: // 3D floor: solid, opaque, shadowcasting
					case 33: // 3D floor: solid, opaque, no shadows
					case 44: // 3D floor: solid, translucent
					case 51: // 3D floor: solid, no sides
					case 57: // 3D floor: solid, invisible
					case 69: // 3D floor: solid, sides only
						is3dblock = true;
						break;
					default: // Ignore specials that are not solid 3D blocks
						is3dblock = false;
					break;
				}

				if (!is3dblock)
					continue;

				for (sect = -1; (sect = P_FindSectorFromTag(line->tag, sect)) >= 0 ;)
				{
					sector_t *psec;
					psec = sectors + sect;

					for (node = psec->touching_thinglist; node; node = node->m_snext)
					{
						thing = node->m_thing;

						if (thing->flags2 & MF2_PUSHED)
							continue;

						if (!(thing->flags & MF_NOCLIP)) // Thing must be clipped
						if (!(thing->flags & MF_NOGRAVITY || thing->z != height))// Thing must a) be non-floating and have z == height
						{
							// Move objects only if on floor or underwater,
							// non-floating, and clipped.
							thing->momx += dx;
							thing->momy += dy;
							if (thing->player)
							{
								thing->player->cmomx += dx;
								thing->player->cmomy += dy;
								thing->player->cmomx = FixedMul(thing->player->cmomx, 0xe800);
								thing->player->cmomy = FixedMul(thing->player->cmomy, 0xe800);
							}

							if (s->exclusive)
								thing->flags2 |= MF2_PUSHED;
						}
					} // end of for loop through touching_thinglist
				} // end of loop through sectors
			}

			if (!is3dblock)
			{
				for (node = sec->touching_thinglist; node; node = node->m_snext)
				{
					thing = node->m_thing;

					if (thing->flags2 & MF2_PUSHED)
						continue;

					if (!((thing = node->m_thing)->flags & MF_NOCLIP) &&
						(!(thing->flags & MF_NOGRAVITY || thing->z < height)))
					{
						// Move objects only if on floor or underwater,
						// non-floating, and clipped.
						thing->momx += dx;
						thing->momy += dy;
						if (thing->player)
						{
							thing->player->cmomx += dx;
							thing->player->cmomy += dy;
							thing->player->cmomx = FixedMul(thing->player->cmomx, 0xe800);
							thing->player->cmomy = FixedMul(thing->player->cmomy, 0xe800);
						}

						if (s->exclusive)
							thing->flags2 |= MF2_PUSHED;
					}
				}
			}
			break; // end of sc_carry_ceiling
	} // end of switch
}

/** Adds a generalized scroller to the thinker list.
  *
  * \param type     The enumerated type of scrolling.
  * \param dx       x speed of scrolling or its acceleration.
  * \param dy       y speed of scrolling or its acceleration.
  * \param control  Sector whose heights control this scroller's effect
  *                 remotely, or -1 if there is no control sector.
  * \param affectee Index of the affected object, sector or sidedef.
  * \param accel    Nonzero for an accelerative effect.
  * \sa Add_WallScroller, P_SpawnScrollers, T_Scroll
  */
static void Add_Scroller(int type, fixed_t dx, fixed_t dy, int control, int affectee, int accel, int exclusive)
{
	scroll_t *s = Z_Calloc(sizeof *s, PU_LEVSPEC, NULL);
	s->thinker.function.acp1 = (actionf_p1)T_Scroll;
	s->type = type;
	s->dx = dx;
	s->dy = dy;
	s->accel = accel;
	s->exclusive = exclusive;
	s->vdx = s->vdy = 0;
	if ((s->control = control) != -1)
		s->last_height = sectors[control].floorheight + sectors[control].ceilingheight;
	s->affectee = affectee;
	P_AddThinker(&s->thinker);
}

/** Adds a wall scroller.
  * Scroll amount is rotated with respect to wall's linedef first, so that
  * scrolling towards the wall in a perpendicular direction is translated into
  * vertical motion, while scrolling along the wall in a parallel direction is
  * translated into horizontal motion.
  *
  * \param dx      x speed of scrolling or its acceleration.
  * \param dy      y speed of scrolling or its acceleration.
  * \param l       Line whose front side will scroll.
  * \param control Sector whose heights control this scroller's effect
  *                remotely, or -1 if there is no control sector.
  * \param accel   Nonzero for an accelerative effect.
  * \sa Add_Scroller, P_SpawnScrollers
  */
static void Add_WallScroller(fixed_t dx, fixed_t dy, const line_t *l, int control, int accel)
{
	fixed_t x = abs(l->dx), y = abs(l->dy), d;
	if (y > x)
		d = x, x = y, y = d;
	d = FixedDiv(x, FINESINE((tantoangle[FixedDiv(y, x) >> DBITS] + ANG90) >> ANGLETOFINESHIFT));
	x = -FixedDiv(FixedMul(dy, l->dy) + FixedMul(dx, l->dx), d);
	y = -FixedDiv(FixedMul(dx, l->dy) - FixedMul(dy, l->dx), d);
	Add_Scroller(sc_side, x, y, control, *l->sidenum, accel, 0);
}

// Amount (dx, dy) vector linedef is shifted right to get scroll amount
#define SCROLL_SHIFT 5

// Factor to scale scrolling effect into mobj-carrying properties = 3/32.
// (This is so scrolling floors and objects on them can move at same speed.)
#define CARRYFACTOR ((3*FRACUNIT)/32)

/** Initializes the scrollers.
  *
  * \todo Get rid of all the magic numbers.
  * \sa P_SpawnSpecials, Add_Scroller, Add_WallScroller
  */
static void P_SpawnScrollers(void)
{
	size_t i;
	line_t *l = lines;

	for (i = 0; i < numlines; i++, l++)
	{
		fixed_t dx = l->dx >> SCROLL_SHIFT; // direction and speed of scrolling
		fixed_t dy = l->dy >> SCROLL_SHIFT;
		int control = -1, accel = 0; // no control sector or acceleration
		int special = l->special;

		// Types 245-249 are same as 250-254 except that the
		// first side's sector's heights cause scrolling when they change, and
		// this linedef controls the direction and speed of the scrolling. The
		// most complicated linedef since donuts, but powerful :)

		if (special >= 245 && special <= 249) // displacement scrollers
		{
			special += 250-245;
			control = (int)(sides[*l->sidenum].sector - sectors);
		}
		else if (special >= 214 && special <= 218) // accelerative scrollers
		{
			accel = 1;
			special += 250-214;
			control = (int)(sides[*l->sidenum].sector - sectors);
		}
		else if (special == 200 || special == 201) // displacement scrollers
		{
			special += 2;
			control = (int)(sides[*l->sidenum].sector - sectors);
		}
		else if (special == 204 || special == 205) // accelerative scrollers
		{
			accel = 1;
			special -= 2;
			control = (int)(sides[*l->sidenum].sector - sectors);
		}

		switch (special)
		{
			register long s;

			case 250: // scroll effect ceiling
			case 202: // scroll and carry objects on ceiling
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
					Add_Scroller(sc_ceiling, -dx, dy, control, s, accel, l->flags & ML_NOCLIMB);
				if (special != 202)
					break;

			case 203:	// carry objects on ceiling
				dx = FixedMul(dx, CARRYFACTOR);
				dy = FixedMul(dy, CARRYFACTOR);
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
					Add_Scroller(sc_carry_ceiling, dx, dy, control, s, accel, l->flags & ML_NOCLIMB);
				break;

			case 251: // scroll effect floor
			case 253: // scroll and carry objects on floor
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
					Add_Scroller(sc_floor, -dx, dy, control, s, accel, l->flags & ML_NOCLIMB);
				if (special != 253)
					break;

			case 252:	// carry objects on floor
				dx = FixedMul(dx, CARRYFACTOR);
				dy = FixedMul(dy, CARRYFACTOR);
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
					Add_Scroller(sc_carry, dx, dy, control, s, accel, l->flags & ML_NOCLIMB);
				break;

			// scroll wall according to linedef
			// (same direction and speed as scrolling floors)
			case 254:
				for (s = -1; (s = P_FindLineFromLineTag(l, s)) >= 0 ;)
					if (s != (int)i)
						Add_WallScroller(dx, dy, lines+s, control, accel);
				break;

			case 255:
				s = lines[i].sidenum[0];
				Add_Scroller(sc_side, -sides[s].textureoffset, sides[s].rowoffset, -1, s, accel, 0);
				break;

			case 100: // scroll first side
				Add_Scroller(sc_side, FRACUNIT, 0, -1, lines[i].sidenum[0], accel, 0);
				break;

			case 85: // jff 1/30/98 2-way scroll
				Add_Scroller(sc_side, -FRACUNIT, 0, -1, lines[i].sidenum[0], accel, 0);
				break;
		}
	}
}

/*
 SoM: 3/8/2000: Friction functions start.
 Add_Friction,
 T_Friction,
 P_SpawnFriction
*/

/** Adds friction thinker.
  *
  * \param friction      Friction value, 0xe800 is normal.
  * \param movefactor    Inertia factor.
  * \param affectee      Target sector.
  * \param roverfriction FOF or not
  * \sa T_Friction, P_SpawnFriction
  */
static void Add_Friction(long friction, long movefactor, long affectee, long referrer)
{
	friction_t *f = Z_Calloc(sizeof *f, PU_LEVSPEC, NULL);

	f->thinker.function.acp1 = (actionf_p1)T_Friction;
	f->friction = friction;
	f->movefactor = movefactor;
	f->affectee = affectee;

	if (referrer != -1)
	{
		f->roverfriction = true;
		f->referrer = referrer;
	}
	else
		f->roverfriction = false;

	P_AddThinker(&f->thinker);
}

/** Applies friction to all things in a sector.
  *
  * \param f Friction thinker.
  * \sa Add_Friction
  */
void T_Friction(friction_t *f)
{
	sector_t *sec;
	mobj_t *thing;
	msecnode_t *node;

	sec = sectors + f->affectee;

	// Make sure the sector type hasn't changed
	if (!(sec->special&PUSH_MASK))
		return;

	// Assign the friction value to players on the floor, non-floating,
	// and clipped. Normally the object's friction value is kept at
	// ORIG_FRICTION and this thinker changes it for icy or muddy floors.

	// When the object is straddling sectors with the same
	// floorheight that have different frictions, use the lowest
	// friction value (muddy has precedence over icy).

	node = sec->touching_thinglist; // things touching this sector
	while (node)
	{
		thing = node->m_thing;
		// apparently, all I had to do was comment out part of the next line and
		// friction works for all mobj's
		// (or at least MF_PUSHABLEs, which is all I care about anyway)
		if (!(thing->flags & (MF_NOGRAVITY | MF_NOCLIP)) && thing->z == thing->floorz)
		{
			if (f->roverfriction)
			{
				sector_t *referrer = &sectors[f->referrer];

				if (thing->floorz != referrer->ceilingheight)
					continue;

				if ((thing->friction == ORIG_FRICTION) // normal friction?
					|| (f->friction < thing->friction))
				{
					thing->friction = f->friction;
					thing->movefactor = f->movefactor;
				}
			}
			else if (sec->floorheight == thing->floorz && (thing->friction == ORIG_FRICTION // normal friction?
				|| f->friction < thing->friction))
			{
				thing->friction = f->friction;
				thing->movefactor = f->movefactor;
			}
		}
		node = node->m_snext;
	}
}

/** Spawns all friction effects.
  *
  * \sa P_SpawnSpecials, Add_Friction
  */
static void P_SpawnFriction(void)
{
	size_t i;
	line_t *l = lines;
	register long s;
	fixed_t length; // line length controls magnitude
	fixed_t friction; // friction value to be applied during movement
	int movefactor; // applied to each player move to simulate inertia

	for (i = 0; i < numlines; i++, l++)
		if (l->special == 223)
		{
			length = P_AproxDistance(l->dx, l->dy)>>FRACBITS;
			friction = (0x1EB8*length)/0x80 + 0xD000;

			if (friction > FRACUNIT)
				friction = FRACUNIT;
			if (friction < 0)
				friction = 0;

			// The following check might seem odd. At the time of movement,
			// the move distance is multiplied by 'friction/0x10000', so a
			// higher friction value actually means 'less friction'.

			if (friction > ORIG_FRICTION) // ice
				movefactor = ((0x10092 - friction)*(0x70))/0x158;
			else
				movefactor = ((friction - 0xDB34)*(0xA))/0x80;

			// killough 8/28/98: prevent odd situations
			if (movefactor < 32)
				movefactor = 32;

			for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
				Add_Friction(friction, movefactor, s, -1);
		}
}

/*
 SoM: 3/8/2000: Push/Pull/Wind/Current functions.
 Add_Pusher,
 PIT_PushThing,
 T_Pusher,
 P_GetPushThing,
 P_SpawnPushers
*/

#define PUSH_FACTOR 7

/** Adds a pusher.
  *
  * \param type     Type of push/pull effect.
  * \param x_mag    X magnitude.
  * \param y_mag    Y magnitude.
  * \param source   For a point pusher/puller, the source object.
  * \param affectee Target sector.
  * \param referrer What sector set it
  * \sa T_Pusher, P_GetPushThing, P_SpawnPushers
  */
static void Add_Pusher(pushertype_e type, fixed_t x_mag, fixed_t y_mag, mobj_t *source, long affectee, long referrer, int exclusive)
{
	pusher_t *p = Z_Calloc(sizeof *p, PU_LEVSPEC, NULL);

	p->thinker.function.acp1 = (actionf_p1)T_Pusher;
	p->source = source;
	p->type = type;
	p->x_mag = x_mag>>FRACBITS;
	p->y_mag = y_mag>>FRACBITS;
	p->exclusive = exclusive;

	if (referrer != -1)
	{
		p->roverpusher = true;
		p->referrer = referrer;
	}
	else
		p->roverpusher = false;

	// "The right triangle of the square of the length of the hypotenuse is equal to the sum of the squares of the lengths of the other two sides."
	// "Bah! Stupid brains! Don't you know anything besides the Pythagorean Theorem?" - Earthworm Jim
	if (type == p_downcurrent || type == p_upcurrent || type == p_upwind || type == p_downwind)
		p->magnitude = P_AproxDistance(p->x_mag,p->y_mag)<<(FRACBITS-PUSH_FACTOR);
	else
		p->magnitude = P_AproxDistance(p->x_mag,p->y_mag);
	if (source) // point source exist?
	{
		p->radius = (p->magnitude)<<(FRACBITS+1); // where force goes to zero
		p->x = p->source->x;
		p->y = p->source->y;
		p->z = p->source->z;
	}
	p->affectee = affectee;
	P_AddThinker(&p->thinker);
}


// PIT_PushThing determines the angle and magnitude of the effect.
// The object's x and y momentum values are changed.
static pusher_t *tmpusher; // pusher structure for blockmap searches

/** Applies a point pusher/puller to a thing.
  *
  * \param thing Thing to be pushed.
  * \return True if the thing was pushed.
  * \todo Make a more robust P_BlockThingsIterator() so the hidden parameter
  *       ::tmpusher won't need to be used.
  * \sa T_Pusher
  */
static inline boolean PIT_PushThing(mobj_t *thing)
{
	if (thing->flags2 & MF2_PUSHED)
		return false;

	if (thing->player && !(thing->flags & (MF_NOGRAVITY | MF_NOCLIP)))
	{
		int dist;
		int speed;
		int sx, sy, sz;

		sx = tmpusher->x;
		sy = tmpusher->y;
		sz = tmpusher->z;

		// don't fade wrt Z if health & 2 (mapthing has multi flag)
		if (tmpusher->source->health & 2)
			dist = P_AproxDistance(thing->x - sx,thing->y - sy);
		else
		{
			// Make sure the Z is in range
			if (thing->z < sz - tmpusher->radius || thing->z > sz + tmpusher->radius)
				return false;

			dist = P_AproxDistance(P_AproxDistance(thing->x - sx, thing->y - sy),
				thing->z - sz);
		}

		speed = (tmpusher->magnitude - ((dist>>FRACBITS)>>1))<<(FRACBITS - PUSH_FACTOR - 1);

		// If speed <= 0, you're outside the effective radius. You also have
		// to be able to see the push/pull source point.

		// Written with bits and pieces of P_HomingAttack
		if ((speed > 0) && (P_CheckSight(thing, tmpusher->source)))
		{
			// only push wrt Z if health & 1 (mapthing has ambush flag)
			if (tmpusher->source->health & 1)
			{
				fixed_t tmpmomx, tmpmomy, tmpmomz;

				tmpmomx = FixedMul(FixedDiv(sx - thing->x, dist), speed);
				tmpmomy = FixedMul(FixedDiv(sy - thing->y, dist), speed);
				tmpmomz = FixedMul(FixedDiv(sz - thing->z, dist), speed);
				if (tmpusher->source->type == MT_PUSH) // away!
				{
					tmpmomx *= -1;
					tmpmomy *= -1;
					tmpmomz *= -1;
				}

				thing->momx += tmpmomx;
				thing->momy += tmpmomy;
				thing->momz += tmpmomz;

				if (thing->player)
				{
					thing->player->cmomx += tmpmomx;
					thing->player->cmomy += tmpmomy;
					thing->player->cmomx = FixedMul(thing->player->cmomx, 0xe800);
					thing->player->cmomy = FixedMul(thing->player->cmomy, 0xe800);
				}
			}
			else
			{
				angle_t pushangle;

				pushangle = R_PointToAngle2(thing->x, thing->y, sx, sy);
				if (tmpusher->source->type == MT_PUSH)
					pushangle += ANG180; // away
				pushangle >>= ANGLETOFINESHIFT;
				thing->momx += FixedMul(speed, FINECOSINE(pushangle));
				thing->momy += FixedMul(speed, FINESINE(pushangle));

				if (thing->player)
				{
					thing->player->cmomx += FixedMul(speed, FINECOSINE(pushangle));
					thing->player->cmomy += FixedMul(speed, FINESINE(pushangle));
					thing->player->cmomx = FixedMul(thing->player->cmomx, 0xe800);
					thing->player->cmomy = FixedMul(thing->player->cmomy, 0xe800);
				}
			}

		}
	}

	if (tmpusher->exclusive)
		thing->flags2 |= MF2_PUSHED;

	return true;
}

/** Applies a pusher to all affected objects.
  *
  * \param p Thinker for the pusher effect.
  * \todo Split up into multiple functions.
  * \sa Add_Pusher, PIT_PushThing
  */
void T_Pusher(pusher_t *p)
{
	sector_t *sec;
	mobj_t *thing;
	msecnode_t *node;
	int xspeed = 0,yspeed = 0;
	int xl, xh, yl, yh, bx, by;
	int radius;
	//int ht = 0;
	boolean inFOF;
	boolean touching;
	boolean foundfloor = false;
	boolean moved;

	xspeed = yspeed = 0;

	sec = sectors + p->affectee;

	// Be sure the special sector type is still turned on. If so, proceed.
	// Else, bail out; the sector type has been changed on us.

	if (p->roverpusher)
	{
		if (sec->ffloors)
		{
			ffloor_t *rover;

			for (rover = sec->ffloors; rover; rover = rover->next)
			{
				// Do some small extra checks here to possibly save unneeded work.
				if (!(rover->master->frontsector->special & PUSH_MASK) || rover->master->frontsector->special == 983)
					continue;

				if (&sectors[p->referrer] != rover->master->frontsector)
					continue;

				foundfloor = true;
			}
		}
	}
	else if (!(sec->special & PUSH_MASK))
		return;

	if (p->roverpusher && foundfloor == false) // Not even a 3d floor has the PUSH_MASK.
		return;

	// For constant pushers (wind/current) there are 3 situations:
	//
	// 1) Affected Thing is above the floor.
	//
	//    Apply the full force if wind, no force if current.
	//
	// 2) Affected Thing is on the ground.
	//
	//    Apply half force if wind, full force if current.
	//
	// 3) Affected Thing is below the ground (underwater effect).
	//
	//    Apply no force if wind, full force if current.
	//
	// Apply the effect to clipped players only for now.
	//
	// In Phase II, you can apply these effects to Things other than players.

	if (p->type == p_push)
	{

		// Seek out all pushable things within the force radius of this
		// point pusher. Crosses sectors, so use blockmap.

		tmpusher = p; // MT_PUSH/MT_PULL point source
		radius = p->radius; // where force goes to zero
		tmbbox[BOXTOP]    = p->y + radius;
		tmbbox[BOXBOTTOM] = p->y - radius;
		tmbbox[BOXRIGHT]  = p->x + radius;
		tmbbox[BOXLEFT]   = p->x - radius;

		xl = (unsigned)(tmbbox[BOXLEFT] - bmaporgx - MAXRADIUS)>>MAPBLOCKSHIFT;
		xh = (unsigned)(tmbbox[BOXRIGHT] - bmaporgx + MAXRADIUS)>>MAPBLOCKSHIFT;
		yl = (unsigned)(tmbbox[BOXBOTTOM] - bmaporgy - MAXRADIUS)>>MAPBLOCKSHIFT;
		yh = (unsigned)(tmbbox[BOXTOP] - bmaporgy + MAXRADIUS)>>MAPBLOCKSHIFT;
		for (bx = xl; bx <= xh; bx++)
			for (by = yl; by <= yh; by++)
				P_BlockThingsIterator(bx,by, PIT_PushThing);
		return;
	}

	// constant pushers p_wind and p_current
	node = sec->touching_thinglist; // things touching this sector
	for (; node; node = node->m_snext)
	{
		thing = node->m_thing;
		if (thing->flags & (MF_NOGRAVITY | MF_NOCLIP)
			&& !(thing->type == MT_SMALLBUBBLE
											|| thing->type == MT_MEDIUMBUBBLE
											|| thing->type == MT_EXTRALARGEBUBBLE))
			continue;

		if (!(thing->flags & MF_PUSHABLE) && !(thing->type == MT_PLAYER
											|| thing->type == MT_SMALLBUBBLE
											|| thing->type == MT_MEDIUMBUBBLE
											|| thing->type == MT_EXTRALARGEBUBBLE))
			continue;

		if (thing->flags2 & MF2_PUSHED)
			continue;

		inFOF = touching = moved = false;

		// Find the area that the 'thing' is in
		if (p->roverpusher)
		{
			if ((!inFOF || !touching) // Only if both aren't true
				&& sec->ffloors)
			{
				ffloor_t *rover;

				for (rover = sec->ffloors; rover; rover = rover->next)
				{
					if (&sectors[p->referrer] != rover->master->frontsector)
						continue;

					if (*rover->topheight < thing->z || *rover->bottomheight > (thing->z + (thing->height >> 1)))
						continue;

					if (!(rover->master->frontsector->special & PUSH_MASK) || rover->master->frontsector->special == 983)
						continue;

					if (thing->z + thing->height > *rover->topheight)
						touching = true;

					if (thing->z + (thing->height >> 1) < *rover->topheight)
						inFOF = true;
				}
			}
		}
		else // Treat the entire sector as one big FOF
		{
			if (thing->z == thing->subsector->sector->floorheight)
				touching = true;
			else if (p->type != p_current)
				inFOF = true;
		}

		if (!touching && !inFOF) // Object is out of range of effect
			continue;

		if (p->type == p_wind)
		{
			if (touching) // on ground
			{
				xspeed = (p->x_mag)>>1; // half force
				yspeed = (p->y_mag)>>1;
				moved = true;
			}
			else if (inFOF)
			{
				xspeed = (p->x_mag); // full force
				yspeed = (p->y_mag);
				moved = true;
			}
		}
		else if (p->type == p_upwind)
		{
			if (touching) // on ground
			{
				thing->momz += (p->magnitude)>>1;
				moved = true;
			}
			else if (inFOF)
			{
				thing->momz += p->magnitude;
				moved = true;
			}
		}
		else if (p->type == p_downwind)
		{
			if (touching) // on ground
			{
				thing->momz -= (p->magnitude)>>1;
				moved = true;
			}
			else if (inFOF)
			{
				thing->momz -= p->magnitude;
				moved = true;
			}
		}
		else // p_current
		{
			if (!touching && !inFOF) // Not in water at all
				xspeed = yspeed = 0; // no force
			else // underwater / touching water
			{
				if (p->type == p_upcurrent)
					thing->momz += p->magnitude;
				else if (p->type == p_downcurrent)
					thing->momz -= p->magnitude;
				else
				{
					xspeed = p->x_mag; // full force
					yspeed = p->y_mag;
				}
				moved = true;
			}
		}

		if (!(thing->player && thing->state == &states[thing->info->painstate] && thing->player->powers[pw_flashing])
			&& p->type != p_downcurrent && p->type != p_upcurrent
			&& p->type != p_upwind && p->type != p_downwind)
		{
			thing->momx += xspeed<<(FRACBITS-PUSH_FACTOR);
			thing->momy += yspeed<<(FRACBITS-PUSH_FACTOR);
			if (thing->player)
			{
				thing->player->cmomx += xspeed<<(FRACBITS-PUSH_FACTOR);
				thing->player->cmomy += yspeed<<(FRACBITS-PUSH_FACTOR);
				thing->player->cmomx = FixedMul(thing->player->cmomx, ORIG_FRICTION);
				thing->player->cmomy = FixedMul(thing->player->cmomy, ORIG_FRICTION);
			}
		}

		if (moved)
		{
			if (p->exclusive)
				thing->flags2 |= MF2_PUSHED;
		}
	}
}


/** Gets a push/pull object.
  *
  * \param s Sector number to look in.
  * \return Pointer to the first ::MT_PUSH or ::MT_PULL object found in the
  *         sector.
  * \sa P_GetTeleportDestThing, P_GetStarpostThing, P_GetAltViewThing
  */
mobj_t *P_GetPushThing(ULONG s)
{
	mobj_t *thing;
	sector_t *sec;

	sec = sectors + s;
	thing = sec->thinglist;
	while (thing)
	{
		switch (thing->type)
		{
			case MT_PUSH:
			case MT_PULL:
				return thing;
			default:
				break;
		}
		thing = thing->snext;
	}
	return NULL;
}

/** Spawns pushers.
  *
  * \todo Remove magic numbers.
  * \sa P_SpawnSpecials, Add_Pusher
  */
static void P_SpawnPushers(void)
{
	size_t i;
	line_t *l = lines;
	register long s;
	mobj_t *thing;

	for (i = 0; i < numlines; i++, l++)
		switch (l->special)
		{
			case 224: // wind
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
					Add_Pusher(p_wind, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB);
				break;
			case 225: // current
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
					Add_Pusher(p_current, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB);
				break;
			case 226: // push/pull
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
				{
					thing = P_GetPushThing(s);
					if (thing) // No MT_P* means no effect
						Add_Pusher(p_push, l->dx, l->dy, thing, s, -1, l->flags & ML_NOCLIMB);
				}
				break;
			case 227: // current up
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
					Add_Pusher(p_upcurrent, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB);
				break;
			case 228: // current down
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
					Add_Pusher(p_downcurrent, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB);
				break;
			case 229: // wind up
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
					Add_Pusher(p_upwind, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB);
				break;
			case 230: // wind down
				for (s = -1; (s = P_FindSectorFromLineTag(l, s)) >= 0 ;)
					Add_Pusher(p_downwind, l->dx, l->dy, NULL, s, -1, l->flags & ML_NOCLIMB);
				break;
		}
}