File: sexp.cpp

package info (click to toggle)
freespace2 3.7.4%2Brepack-1.1
  • links: PTS, VCS
  • area: non-free
  • in suites: bullseye
  • size: 22,268 kB
  • sloc: cpp: 393,535; ansic: 4,106; makefile: 1,091; xml: 181; sh: 137
file content (34000 lines) | stat: -rwxr-xr-x 948,654 bytes parent folder | download | duplicates (2)
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
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
/*
 * Copyright (C) Volition, Inc. 1999.  All rights reserved.
 *
 * All source code herein is the property of Volition, Inc. You may not sell 
 * or otherwise commercially exploit the source or things you created based on the 
 * source.
 *
*/



//	Parse a symbolic expression.
//	These are identical to Lisp functions.
//	It uses a very baggy format, allocating 16 characters per token, regardless
//	of how many are used.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <limits.h>
#if defined _MSC_VER && _MSC_VER < 1600
	#include "globalincs/msvc/stdint.h"
#else
	#include <stdint.h>
#endif

#include "ai/aigoals.h"
#include "asteroid/asteroid.h"
#include "autopilot/autopilot.h"
#include "camera/camera.h"
#include "cmdline/cmdline.h"
#include "debugconsole/console.h"
#include "fireball/fireballs.h"		// for explosion stuff
#include "freespace2/freespace.h"
#include "gamesequence/gamesequence.h"
#include "gamesnd/eventmusic.h"		// for change-soundtrack
#include "gamesnd/gamesnd.h"
#include "globalincs/alphacolors.h"
#include "globalincs/linklist.h"
#include "globalincs/systemvars.h"
#include "globalincs/version.h"
#include "graphics/2d.h"
#include "graphics/font.h"
#include "hud/hud.h"
#include "hud/hudartillery.h"
#include "hud/hudconfig.h"
#include "hud/hudescort.h"
#include "hud/hudets.h"
#include "hud/hudmessage.h"
#include "hud/hudparse.h"
#include "hud/hudshield.h"
#include "hud/hudsquadmsg.h"		// for the order sexp
#include "iff_defs/iff_defs.h"
#include "io/keycontrol.h"
#include "io/timer.h"
#include "jumpnode/jumpnode.h"
#include "localization/localize.h"
#include "math/fvi.h"
#include "menuui/techmenu.h"		// for intel stuff
#include "mission/missionbriefcommon.h"
#include "mission/missioncampaign.h"
#include "mission/missiongoals.h"
#include "mission/missionlog.h"
#include "mission/missionmessage.h"
#include "mission/missionparse.h"		// for p_object definition
#include "mission/missiontraining.h"
#include "missionui/redalert.h"
#include "mod_table/mod_table.h"
#include "nebula/neb.h"
#include "nebula/neblightning.h"
#include "network/multi.h"
#include "network/multi_obj.h"
#include "network/multi_sexp.h"
#include "network/multi_team.h"
#include "network/multimsgs.h"
#include "network/multiutil.h"
#include "object/objcollide.h"
#include "object/objectdock.h"
#include "object/objectshield.h"
#include "object/objectsnd.h"
#include "object/waypoint.h"
#include "parse/generic_log.h"
#include "parse/lua.h"
#include "parse/parselo.h"
#include "parse/scripting.h"
#include "parse/sexp.h"
#include "playerman/player.h"
#include "render/3d.h"
#include "ship/afterburner.h"
#include "ship/awacs.h"
#include "ship/ship.h"
#include "ship/shiphit.h"
#include "sound/audiostr.h"
#include "sound/ds.h"
#include "sound/sound.h"
#include "starfield/starfield.h"
#include "starfield/supernova.h"
#include "stats/medals.h"
#include "weapon/beam.h"
#include "weapon/emp.h"
#include "weapon/shockwave.h"
#include "weapon/weapon.h"

#ifndef NDEBUG
#include "hud/hudmessage.h"
#endif





#define TRUE	1
#define FALSE	0


sexp_oper Operators[] = {
//   Operator, Identity, Min / Max arguments
	//Arithmetic Category
	{ "+",								OP_PLUS,								2,	INT_MAX,	SEXP_ARITHMETIC_OPERATOR,	},
	{ "-",								OP_MINUS,								2,	INT_MAX,	SEXP_ARITHMETIC_OPERATOR,	},
	{ "*",								OP_MUL,									2,	INT_MAX,	SEXP_ARITHMETIC_OPERATOR,	},
	{ "/",								OP_DIV,									2,	INT_MAX,	SEXP_ARITHMETIC_OPERATOR,	},
	{ "mod",							OP_MOD,									2,	INT_MAX,	SEXP_ARITHMETIC_OPERATOR,	},
	{ "rand",							OP_RAND,								2,	3,			SEXP_ARITHMETIC_OPERATOR,	},
	{ "rand-multiple",					OP_RAND_MULTIPLE,						2,	3,			SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "abs",							OP_ABS,									1,	1,			SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "min",							OP_MIN,									1,	INT_MAX,	SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "max",							OP_MAX,									1,	INT_MAX,	SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "avg",							OP_AVG,									1,	INT_MAX,	SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "pow",							OP_POW,									2,	2,			SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "signum",							OP_SIGNUM,								1,	1,			SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "set-bit",						OP_SET_BIT,								2,	2,			SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "unset-bit",						OP_UNSET_BIT,							2,	2,			SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "is-bit-set",						OP_IS_BIT_SET,							2,	2,			SEXP_BOOLEAN_OPERATOR,		},	// Goober5000
	{ "bitwise-and",					OP_BITWISE_AND,							2,	INT_MAX,	SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "bitwise-or",						OP_BITWISE_OR,							2,	INT_MAX,	SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "bitwise-not",					OP_BITWISE_NOT,							1,	1,			SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000
	{ "bitwise-xor",					OP_BITWISE_XOR,							2,	2,			SEXP_ARITHMETIC_OPERATOR,	},	// Goober5000

	//Logical Category
	{ "true",							OP_TRUE,								0,	0,			SEXP_BOOLEAN_OPERATOR,	},
	{ "false",							OP_FALSE,								0,	0,			SEXP_BOOLEAN_OPERATOR,	},
	{ "and",							OP_AND,									2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "and-in-sequence",				OP_AND_IN_SEQUENCE,						2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "or",								OP_OR,									2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "not",							OP_NOT,									1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "xor",							OP_XOR,									2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	// Goober5000
	{ "=",								OP_EQUALS,								2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "!=",								OP_NOT_EQUAL,							2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	// Goober5000
	{ ">",								OP_GREATER_THAN,						2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ ">=",								OP_GREATER_OR_EQUAL,					2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	// Goober5000
	{ "<",								OP_LESS_THAN,							2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "<=",								OP_LESS_OR_EQUAL,						2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	// Goober5000
	{ "string-equals",					OP_STRING_EQUALS,						2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "string-greater-than",			OP_STRING_GREATER_THAN,					2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "string-less-than",				OP_STRING_LESS_THAN,					2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "perform-actions",				OP_PERFORM_ACTIONS,						2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	// Goober5000
	{ "has-time-elapsed",				OP_HAS_TIME_ELAPSED,					1,	1,			SEXP_BOOLEAN_OPERATOR,	},

	//Event/Goals Category
	{ "is-goal-true-delay",				OP_GOAL_TRUE_DELAY,						2,	2,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-goal-false-delay",			OP_GOAL_FALSE_DELAY,					2,	2,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-goal-incomplete",				OP_GOAL_INCOMPLETE,						1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-event-true",					OP_EVENT_TRUE,							1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-event-true-delay",			OP_EVENT_TRUE_DELAY,					2,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-event-true-msecs-delay",		OP_EVENT_TRUE_MSECS_DELAY,				2,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-event-false",					OP_EVENT_FALSE,							1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-event-false-delay",			OP_EVENT_FALSE_DELAY,					2,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-event-false-msecs-delay",		OP_EVENT_FALSE_MSECS_DELAY,				2,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-event-incomplete",			OP_EVENT_INCOMPLETE,					1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-previous-goal-true",			OP_PREVIOUS_GOAL_TRUE,					2,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-previous-goal-false",			OP_PREVIOUS_GOAL_FALSE,					2,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-previous-goal-incomplete",	OP_PREVIOUS_GOAL_INCOMPLETE,			2,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-previous-event-true",			OP_PREVIOUS_EVENT_TRUE,					2,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-previous-event-false",		OP_PREVIOUS_EVENT_FALSE,				2,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-previous-event-incomplete",	OP_PREVIOUS_EVENT_INCOMPLETE,			2,	3,			SEXP_BOOLEAN_OPERATOR,	},

	//Objectives Category
	{ "is-destroyed",					OP_IS_DESTROYED,						1,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "is-destroyed-delay",				OP_IS_DESTROYED_DELAY,					2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "was-destroyed-by-delay",			OP_WAS_DESTROYED_BY_DELAY,				3,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,  },
	{ "is-subsystem-destroyed",			OP_IS_SUBSYSTEM_DESTROYED,				2,	2,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-subsystem-destroyed-delay",	OP_IS_SUBSYSTEM_DESTROYED_DELAY,		3,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-disabled",					OP_IS_DISABLED,							1,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "is-disabled-delay",				OP_IS_DISABLED_DELAY,					2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "is-disarmed",					OP_IS_DISARMED,							1,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "is-disarmed-delay",				OP_IS_DISARMED_DELAY,					2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "has-docked",						OP_HAS_DOCKED,							3,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "has-docked-delay",				OP_HAS_DOCKED_DELAY,					4,	4,			SEXP_BOOLEAN_OPERATOR,	},
	{ "has-undocked",					OP_HAS_UNDOCKED,						3,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "has-undocked-delay",				OP_HAS_UNDOCKED_DELAY,					4,	4,			SEXP_BOOLEAN_OPERATOR,	},
	{ "has-arrived",					OP_HAS_ARRIVED,							1,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "has-arrived-delay",				OP_HAS_ARRIVED_DELAY,					2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "has-departed",					OP_HAS_DEPARTED,						1,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "has-departed-delay",				OP_HAS_DEPARTED_DELAY,					2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "are-waypoints-done",				OP_WAYPOINTS_DONE,						2,	2,			SEXP_BOOLEAN_OPERATOR,	},
	{ "are-waypoints-done-delay",		OP_WAYPOINTS_DONE_DELAY,				3,	4,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-nav-visited",					OP_NAV_IS_VISITED,						1,	1,			SEXP_BOOLEAN_OPERATOR,	}, // Kazan
	{ "ship-type-destroyed",			OP_SHIP_TYPE_DESTROYED,					2,	2,			SEXP_BOOLEAN_OPERATOR,	},
	{ "percent-ships-destroyed",		OP_PERCENT_SHIPS_DESTROYED,				2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "percent-ships-disabled",			OP_PERCENT_SHIPS_DISABLED,				2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "percent-ships-disarmed",			OP_PERCENT_SHIPS_DISARMED,				2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "percent-ships-departed",			OP_PERCENT_SHIPS_DEPARTED,				2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "percent-ships-arrived",			OP_PERCENT_SHIPS_ARRIVED,				2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "depart-node-delay",				OP_DEPART_NODE_DELAY,					3,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	
	{ "destroyed-or-departed-delay",	OP_DESTROYED_DEPARTED_DELAY,			2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	

	//Status Category
	//Mission Sub-Category
	{ "num-ships-in-battle",			OP_NUM_SHIPS_IN_BATTLE,					0,	INT_MAX,	SEXP_INTEGER_OPERATOR,	},	//phreak modified by FUBAR
	{ "num-ships-in-wing",				OP_NUM_SHIPS_IN_WING,					1,	INT_MAX,	SEXP_INTEGER_OPERATOR,	},	// Karajorma
	{ "directive-value",				OP_DIRECTIVE_VALUE,						1,	2,			SEXP_INTEGER_OPERATOR,	},	// Karajorma

	//Player Sub-Category
	{ "was-promotion-granted",			OP_WAS_PROMOTION_GRANTED,				0,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "was-medal-granted",				OP_WAS_MEDAL_GRANTED,					0,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "skill-level-at-least",			OP_SKILL_LEVEL_AT_LEAST,				1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "num_kills",						OP_NUM_KILLS,							1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "num_assists",					OP_NUM_ASSISTS,							1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "num_type_kills",					OP_NUM_TYPE_KILLS,						2,	2,			SEXP_INTEGER_OPERATOR,	},
	{ "num_class_kills",				OP_NUM_CLASS_KILLS,						2,	2,			SEXP_INTEGER_OPERATOR,	},
	{ "ship_score",						OP_SHIP_SCORE,							1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "time-elapsed-last-order",		OP_LAST_ORDER_TIME,						2,	2,			SEXP_INTEGER_OPERATOR,	},
	{ "player-is-cheating",				OP_PLAYER_IS_CHEATING_BASTARD,			0,  0,			SEXP_BOOLEAN_OPERATOR,  },

	//Multiplayer Sub-Category
	{ "num-players",					OP_NUM_PLAYERS,							0,	0,			SEXP_INTEGER_OPERATOR,	},
	{ "team-score",						OP_TEAM_SCORE,							1,	1,			SEXP_INTEGER_OPERATOR,	}, 
	{ "ship-deaths",					OP_SHIP_DEATHS,							1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "respawns-left",					OP_RESPAWNS_LEFT,						1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "is-player",						OP_IS_PLAYER,							2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	// Karajorma

	//Ship Status Sub-Category
	{ "is-in-mission",					OP_IS_IN_MISSION,						1,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	// Goober5000
	{ "is-ship-visible",				OP_IS_SHIP_VISIBLE,						1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-ship-stealthy",				OP_IS_SHIP_STEALTHY,					1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-friendly-stealth-visible",	OP_IS_FRIENDLY_STEALTH_VISIBLE,			1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-iff",							OP_IS_IFF,								2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "is-ai-class",					OP_IS_AI_CLASS,							2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "is-ship-type",					OP_IS_SHIP_TYPE,						2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "is-ship-class",					OP_IS_SHIP_CLASS,						2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "is-facing",						OP_IS_FACING,							3,	4,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is_tagged",						OP_IS_TAGGED,							1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "has-been-tagged-delay",			OP_HAS_BEEN_TAGGED_DELAY,				2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "are-ship-flags-set",				OP_ARE_SHIP_FLAGS_SET,					2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	// Karajorma

	//Shields, Engines and Weapons Sub-Category
	{ "has-primary-weapon",				OP_HAS_PRIMARY_WEAPON,					3,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	// Karajorma
	{ "has-secondary-weapon",			OP_HAS_SECONDARY_WEAPON,				3,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},	// Karajorma
	{ "is-primary-selected",			OP_IS_PRIMARY_SELECTED,					2,	2,			SEXP_BOOLEAN_OPERATOR,	},
	{ "is-secondary-selected",			OP_IS_SECONDARY_SELECTED,				2,	2,			SEXP_BOOLEAN_OPERATOR,	},
	{ "primary-fired-since",			OP_PRIMARY_FIRED_SINCE,					3,	3,			SEXP_INTEGER_OPERATOR,	},	// Karajorma
	{ "secondary-fired-since",			OP_SECONDARY_FIRED_SINCE,				3,	3,			SEXP_INTEGER_OPERATOR,	},	// Karajorma
	{ "primary-ammo-pct",				OP_PRIMARY_AMMO_PCT,					2,	2,			SEXP_INTEGER_OPERATOR,	},
	{ "secondary-ammo-pct",				OP_SECONDARY_AMMO_PCT,					2,	2,			SEXP_INTEGER_OPERATOR,	},
	{ "get-primary-ammo",				OP_GET_PRIMARY_AMMO,					2,	2,			SEXP_INTEGER_OPERATOR,	}, // Karajorma
	{ "get-secondary-ammo",				OP_GET_SECONDARY_AMMO,					2,	2,			SEXP_INTEGER_OPERATOR,	}, // Karajorma
	{ "get-num-countermeasures",		OP_GET_NUM_COUNTERMEASURES,				1,	1,			SEXP_INTEGER_OPERATOR,	}, // Karajorma
	{ "weapon-energy-pct",				OP_WEAPON_ENERGY_LEFT,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "afterburner-energy-pct",			OP_AFTERBURNER_LEFT,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "shield-recharge-pct",			OP_SHIELD_RECHARGE_PCT,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "weapon-recharge-pct",			OP_WEAPON_RECHARGE_PCT,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "engine-recharge-pct",			OP_ENGINE_RECHARGE_PCT,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "shield-quad-low",				OP_SHIELD_QUAD_LOW,						2,	2,			SEXP_INTEGER_OPERATOR,	},
	{ "get-throttle-speed",				OP_GET_THROTTLE_SPEED,					1,	1,			SEXP_INTEGER_OPERATOR,	}, // Karajorma
	{ "current-speed",					OP_CURRENT_SPEED,						1,	1,			SEXP_INTEGER_OPERATOR,	},

	//Cargo Sub-Category
	{ "is-cargo-known",					OP_IS_CARGO_KNOWN,						1,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "is-cargo-known-delay",			OP_CARGO_KNOWN_DELAY,					2,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "cap-subsys-cargo-known-delay",	OP_CAP_SUBSYS_CARGO_KNOWN_DELAY,		3,	INT_MAX,	SEXP_BOOLEAN_OPERATOR,	},
	{ "is-cargo",						OP_IS_CARGO,							2,	3,			SEXP_BOOLEAN_OPERATOR,	},

	//Damage Sub-Category
	{ "shields-left",					OP_SHIELDS_LEFT,						1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "hits-left",						OP_HITS_LEFT,							1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "hits-left-subsystem",			OP_HITS_LEFT_SUBSYSTEM,					2,	3,			SEXP_INTEGER_OPERATOR,	},
	{ "hits-left-subsystem-generic",	OP_HITS_LEFT_SUBSYSTEM_GENERIC,			2,	2,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "hits-left-subsystem-specific",	OP_HITS_LEFT_SUBSYSTEM_SPECIFIC,		2,	2,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "sim-hits-left",					OP_SIM_HITS_LEFT,						1,	1,			SEXP_INTEGER_OPERATOR,	}, // Turey
	{ "get-damage-caused",				OP_GET_DAMAGE_CAUSED,					2,	INT_MAX,	SEXP_INTEGER_OPERATOR,	},

	//Distance and Coordinates Sub-Category
	{ "distance",						OP_DISTANCE,							2,	2,			SEXP_INTEGER_OPERATOR,	},
	{ "distance-ship-subsystem",		OP_DISTANCE_SUBSYSTEM,					3,	3,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "distance-to-nav",				OP_NAV_DISTANCE,						1,	1,			SEXP_INTEGER_OPERATOR,	},	// Kazan
	{ "num-within-box",					OP_NUM_WITHIN_BOX,						7,	INT_MAX,	SEXP_INTEGER_OPERATOR,	},	//WMC
	{ "is-in-box",						OP_IS_IN_BOX,							7,	8,			SEXP_INTEGER_OPERATOR,	},	//Sushi
	{ "special-warp-dist",				OP_SPECIAL_WARP_DISTANCE,				1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "get-object-x",					OP_GET_OBJECT_X,						1,	5,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "get-object-y",					OP_GET_OBJECT_Y,						1,	5,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "get-object-z",					OP_GET_OBJECT_Z,						1,	5,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "get-object-pitch",				OP_GET_OBJECT_PITCH,					1,	1,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "get-object-bank",				OP_GET_OBJECT_BANK,						1,	1,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "get-object-heading",				OP_GET_OBJECT_HEADING,					1,	1,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "get-object-speed-x",				OP_GET_OBJECT_SPEED_X,					1,	2,			SEXP_INTEGER_OPERATOR,	},
	{ "get-object-speed-y",				OP_GET_OBJECT_SPEED_Y,					1,	2,			SEXP_INTEGER_OPERATOR,	},
	{ "get-object-speed-z",				OP_GET_OBJECT_SPEED_Z,					1,	2,			SEXP_INTEGER_OPERATOR,	},

	//Variables Sub-Category
	{ "string-to-int",					OP_STRING_TO_INT,						1,	1,			SEXP_INTEGER_OPERATOR,	}, // Karajorma
	{ "string-get-length",				OP_STRING_GET_LENGTH,					1,	1,			SEXP_INTEGER_OPERATOR,	}, // Goober5000

	//Other Sub-Category
	{ "script-eval-num",				OP_SCRIPT_EVAL_NUM,						1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "script-eval-string",				OP_SCRIPT_EVAL_STRING,					2,	2,			SEXP_ACTION_OPERATOR,	},

	//Time Category
	{ "time-ship-destroyed",			OP_TIME_SHIP_DESTROYED,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "time-ship-arrived",				OP_TIME_SHIP_ARRIVED,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "time-ship-departed",				OP_TIME_SHIP_DEPARTED,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "time-wing-destroyed",			OP_TIME_WING_DESTROYED,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "time-wing-arrived",				OP_TIME_WING_ARRIVED,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "time-wing-departed",				OP_TIME_WING_DEPARTED,					1,	1,			SEXP_INTEGER_OPERATOR,	},
	{ "mission-time",					OP_MISSION_TIME,						0,	0,			SEXP_INTEGER_OPERATOR,	},
	{ "mission-time-msecs",				OP_MISSION_TIME_MSECS,					0,	0,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "time-docked",					OP_TIME_DOCKED,							3,	3,			SEXP_INTEGER_OPERATOR,	},
	{ "time-undocked",					OP_TIME_UNDOCKED,						3,	3,			SEXP_INTEGER_OPERATOR,	},

	//Conditionals Category
	{ "cond",							OP_COND,								1,	INT_MAX,	SEXP_CONDITIONAL_OPERATOR,},
	{ "when",							OP_WHEN,								2,	INT_MAX,	SEXP_CONDITIONAL_OPERATOR,},
	{ "when-argument",					OP_WHEN_ARGUMENT,						3,	INT_MAX,	SEXP_CONDITIONAL_OPERATOR,},	// Goober5000
	{ "every-time",						OP_EVERY_TIME,							2,	INT_MAX,	SEXP_CONDITIONAL_OPERATOR,},	// Goober5000
	{ "every-time-argument",			OP_EVERY_TIME_ARGUMENT,					3,	INT_MAX,	SEXP_CONDITIONAL_OPERATOR,},	// Goober5000
	{ "if-then-else",					OP_IF_THEN_ELSE,						3,	INT_MAX,	SEXP_CONDITIONAL_OPERATOR,},	// Goober5000
	{ "any-of",							OP_ANY_OF,								1,	INT_MAX,	SEXP_ARGUMENT_OPERATOR,	},	// Goober5000
	{ "every-of",						OP_EVERY_OF,							1,	INT_MAX,	SEXP_ARGUMENT_OPERATOR,	},	// Goober5000
	{ "random-of",						OP_RANDOM_OF,							1,	INT_MAX,	SEXP_ARGUMENT_OPERATOR,	},	// Goober5000
	{ "random-multiple-of",				OP_RANDOM_MULTIPLE_OF,					1,	INT_MAX,	SEXP_ARGUMENT_OPERATOR,	},	// Karajorma
	{ "number-of",						OP_NUMBER_OF,							2,	INT_MAX,	SEXP_ARGUMENT_OPERATOR,	},	// Goober5000
	{ "in-sequence",					OP_IN_SEQUENCE,							1,	INT_MAX,	SEXP_ARGUMENT_OPERATOR,	},	// Karajorma
	{ "for-counter",					OP_FOR_COUNTER,							2,	3,			SEXP_ARGUMENT_OPERATOR,	},	// Goober5000
	{ "invalidate-argument",			OP_INVALIDATE_ARGUMENT,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,		},	// Goober5000
	{ "invalidate-all-arguments",		OP_INVALIDATE_ALL_ARGUMENTS,			0,	0,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "validate-argument",				OP_VALIDATE_ARGUMENT,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "validate-all-arguments",			OP_VALIDATE_ALL_ARGUMENTS,				0,	0,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "do-for-valid-arguments",			OP_DO_FOR_VALID_ARGUMENTS,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "num-valid-arguments",			OP_NUM_VALID_ARGUMENTS,					0,	0,			SEXP_ACTION_OPERATOR,	},	// Karajorma

	//Change Category
	//Messaging Sub-Category
	{ "send-message",					OP_SEND_MESSAGE,						3,	3,			SEXP_ACTION_OPERATOR,	},
	{ "send-message-list",				OP_SEND_MESSAGE_LIST,					4,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "send-random-message",			OP_SEND_RANDOM_MESSAGE,					3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "scramble-messages",				OP_SCRAMBLE_MESSAGES,					0,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "unscramble-messages",			OP_UNSCRAMBLE_MESSAGES,					0,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "disable-builtin-messages",		OP_DISABLE_BUILTIN_MESSAGES,			0,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "enable-builtin-messages",		OP_ENABLE_BUILTIN_MESSAGES,				0,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-persona",					OP_SET_PERSONA,							2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-death-message",				OP_SET_DEATH_MESSAGE,					1,	1,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-mission-mood",				OP_SET_MISSION_MOOD,					1,	1,			SEXP_ACTION_OPERATOR,	},	// Karajorma


	//AI Control Sub-Category
	{ "add-goal",						OP_ADD_GOAL,							2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "remove-goal",					OP_REMOVE_GOAL,							2,	2,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "add-ship-goal",					OP_ADD_SHIP_GOAL,						2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "add-wing-goal",					OP_ADD_WING_GOAL,						2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "clear-goals",					OP_CLEAR_GOALS,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "clear-ship-goals",				OP_CLEAR_SHIP_GOALS,					1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "clear-wing-goals",				OP_CLEAR_WING_GOALS,					1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "good-rearm-time",				OP_GOOD_REARM_TIME,						2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "good-secondary-time",			OP_GOOD_SECONDARY_TIME,					4,	4,			SEXP_ACTION_OPERATOR,	},
	{ "change-ai-class",				OP_CHANGE_AI_CLASS,						2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "player-use-ai",					OP_PLAYER_USE_AI,						0,	0,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "player-not-use-ai",				OP_PLAYER_NOT_USE_AI,					0,	0,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-player-orders",				OP_SET_PLAYER_ORDERS,					3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "cap-waypoint-speed",				OP_CAP_WAYPOINT_SPEED,					2,	2,			SEXP_ACTION_OPERATOR,	},

	//Ship Status Sub-Category
	{ "protect-ship",					OP_PROTECT_SHIP,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "unprotect-ship",					OP_UNPROTECT_SHIP,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "beam-protect-ship",				OP_BEAM_PROTECT_SHIP,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "beam-unprotect-ship",			OP_BEAM_UNPROTECT_SHIP,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "turret-protect-ship",			OP_TURRET_PROTECT_SHIP,					2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "turret-unprotect-ship",			OP_TURRET_UNPROTECT_SHIP,				2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "ship-invisible",					OP_SHIP_INVISIBLE,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ship-visible",					OP_SHIP_VISIBLE,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ship-stealthy",					OP_SHIP_STEALTHY,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ship-unstealthy",				OP_SHIP_UNSTEALTHY,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "friendly-stealth-invisible",		OP_FRIENDLY_STEALTH_INVISIBLE,			1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "friendly-stealth-visible",		OP_FRIENDLY_STEALTH_VISIBLE,			1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "primitive-sensors-set-range",	OP_PRIMITIVE_SENSORS_SET_RANGE,			2,	2,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "ship-targetable-as-bomb",		OP_SHIP_BOMB_TARGETABLE,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ship-untargetable-as-bomb",		OP_SHIP_BOMB_UNTARGETABLE,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "kamikaze",						OP_KAMIKAZE,							2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Sesquipedalian
	{ "change-iff",						OP_CHANGE_IFF,							2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "change-iff-color",				OP_CHANGE_IFF_COLOR,					6,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "add-remove-escort",				OP_ADD_REMOVE_ESCORT,					2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "ship-change-alt-name",			OP_SHIP_CHANGE_ALT_NAME,				2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "ship-change-callsign",			OP_SHIP_CHANGE_CALLSIGN,				2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// FUBAR
	{ "ship-tag",						OP_SHIP_TAG,							3,	8,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "ship-untag",						OP_SHIP_UNTAG,							1,	1,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-arrival-info",				OP_SET_ARRIVAL_INFO,					2,	7,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-departure-info",				OP_SET_DEPARTURE_INFO,					2,	6,			SEXP_ACTION_OPERATOR,	},	// Goober5000

	//Shields, Engines and Weapons Sub-Category
	{ "set-weapon-energy",				OP_SET_WEAPON_ENERGY,					2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-shield-energy",				OP_SET_SHIELD_ENERGY,					2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-player-throttle-speed",		OP_SET_PLAYER_THROTTLE_SPEED,			2,	2,			SEXP_ACTION_OPERATOR,	},	// CommanderDJ
	{ "set-afterburner-energy",			OP_SET_AFTERBURNER_ENERGY,				2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-subspace-drive",				OP_SET_SUBSPACE_DRIVE,					2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "set-primary-weapon",				OP_SET_PRIMARY_WEAPON,					3,	5,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-secondary-weapon",			OP_SET_SECONDARY_WEAPON,				3,	5,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-primary-ammo",				OP_SET_PRIMARY_AMMO,					3,	4,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-secondary-ammo",				OP_SET_SECONDARY_AMMO,					3,	4,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-num-countermeasures",		OP_SET_NUM_COUNTERMEASURES,				2,	2,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "lock-primary-weapon",			OP_LOCK_PRIMARY_WEAPON,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "unlock-primary-weapon",			OP_UNLOCK_PRIMARY_WEAPON,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "lock-secondary-weapon",			OP_LOCK_SECONDARY_WEAPON,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "unlock-secondary-weapon",		OP_UNLOCK_SECONDARY_WEAPON,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "lock-afterburner",				OP_LOCK_AFTERBURNER,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// KeldorKatarn
	{ "unlock-afterburner",				OP_UNLOCK_AFTERBURNER,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// KeldorKatarn
	{ "shields-on",						OP_SHIELDS_ON,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Sesquipedalian
	{ "shields-off",					OP_SHIELDS_OFF,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Sesquipedalian
	{ "force-glide",					OP_FORCE_GLIDE,							2,	2,			SEXP_ACTION_OPERATOR,	},	// The E
	{ "disable-ets",					OP_DISABLE_ETS,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// The E
	{ "enable-ets",						OP_ENABLE_ETS,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// The E
	{ "break-warp",						OP_WARP_BROKEN,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "fix-warp",						OP_WARP_NOT_BROKEN,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "never-warp",						OP_WARP_NEVER,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "allow-warp",						OP_WARP_ALLOWED,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "special-warpout-name",			OP_SET_SPECIAL_WARPOUT_NAME,			2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "get-ets-value",					OP_GET_ETS_VALUE,						2,	2,			SEXP_ACTION_OPERATOR,	},	// niffiwan
	{ "set-ets-values",					OP_SET_ETS_VALUES,						4,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// niffiwan

	//Subsystems and Health Sub-Category
	{ "ship-invulnerable",				OP_SHIP_INVULNERABLE,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ship-vulnerable",				OP_SHIP_VULNERABLE,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ship-guardian",					OP_SHIP_GUARDIAN,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ship-no-guardian",				OP_SHIP_NO_GUARDIAN,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ship-guardian-threshold",		OP_SHIP_GUARDIAN_THRESHOLD,				2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ship-subsys-guardian-threshold",	OP_SHIP_SUBSYS_GUARDIAN_THRESHOLD,		3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "self-destruct",					OP_SELF_DESTRUCT,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "destroy-instantly",				OP_DESTROY_INSTANTLY,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Admiral MS
	{ "destroy-subsys-instantly",		OP_DESTROY_SUBSYS_INSTANTLY,			2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Admiral MS
	{ "sabotage-subsystem",				OP_SABOTAGE_SUBSYSTEM,					3,	3,			SEXP_ACTION_OPERATOR,	},
	{ "repair-subsystem",				OP_REPAIR_SUBSYSTEM,					3,	4,			SEXP_ACTION_OPERATOR,	},
	{ "ship-copy-damage",				OP_SHIP_COPY_DAMAGE,					2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-subsystem-strength",			OP_SET_SUBSYSTEM_STRNGTH,				3,	4,			SEXP_ACTION_OPERATOR,	},
	{ "subsys-set-random",				OP_SUBSYS_SET_RANDOM,					3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "lock-rotating-subsystem",		OP_LOCK_ROTATING_SUBSYSTEM,				2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "free-rotating-subsystem",		OP_FREE_ROTATING_SUBSYSTEM,				2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "reverse-rotating-subsystem",		OP_REVERSE_ROTATING_SUBSYSTEM,			2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "rotating-subsys-set-turn-time",	OP_ROTATING_SUBSYS_SET_TURN_TIME,		3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "trigger-submodel-animation",		OP_TRIGGER_SUBMODEL_ANIMATION,			4,	6,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "change-subsystem-name",			OP_CHANGE_SUBSYSTEM_NAME,				3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "ship-subsys-targetable",			OP_SHIP_SUBSYS_TARGETABLE,				2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "ship-subsys-untargetable",		OP_SHIP_SUBSYS_UNTARGETABLE,			2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "ship-subsys-no-replace",			OP_SHIP_SUBSYS_NO_REPLACE,				3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// FUBAR
	{ "ship-subsys-no-live-debris",		OP_SHIP_SUBSYS_NO_LIVE_DEBRIS,			3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// FUBAR
	{ "ship-subsys-vanish",				OP_SHIP_SUBSYS_VANISHED,				3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// FUBAR
	{ "ship-subsys-ignore_if_dead",		OP_SHIP_SUBSYS_IGNORE_IF_DEAD,			3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// FUBAR
	{ "awacs-set-radius",				OP_AWACS_SET_RADIUS,					3,	3,			SEXP_ACTION_OPERATOR,	},
	{ "alter-ship-flag",				OP_ALTER_SHIP_FLAG,						3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma 

	//Cargo Sub-Category
	{ "transfer-cargo",					OP_TRANSFER_CARGO,						2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "exchange-cargo",					OP_EXCHANGE_CARGO,						2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "set-cargo",						OP_SET_CARGO,							2,	3,			SEXP_ACTION_OPERATOR,	},
	{ "jettison-cargo-delay",			OP_JETTISON_CARGO,						2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "set-docked",						OP_SET_DOCKED,							4,	4,			SEXP_ACTION_OPERATOR,	},	// Sushi
	{ "cargo-no-deplete",				OP_CARGO_NO_DEPLETE,					1,	2,			SEXP_ACTION_OPERATOR,	},
	{ "set-scanned",					OP_SET_SCANNED,							1,	2,			SEXP_ACTION_OPERATOR,	},
	{ "set-unscanned",					OP_SET_UNSCANNED,						1,	2,			SEXP_ACTION_OPERATOR,	},
	
	//Armor and Damage Types Sub-Category
	{ "set-armor-type",					OP_SET_ARMOR_TYPE,						4,	INT_MAX,	SEXP_ACTION_OPERATOR,	},  // FUBAR
	{ "weapon-set-damage-type",			OP_WEAPON_SET_DAMAGE_TYPE,				4,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// FUBAR
	{ "ship-set-damage-type",			OP_SHIP_SET_DAMAGE_TYPE,				4,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// FUBAR
	{ "ship-set-shockwave-damage-type",	OP_SHIP_SHOCKWAVE_SET_DAMAGE_TYPE,		3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// FUBAR
	{ "field-set-damage-type",			OP_FIELD_SET_DAMAGE_TYPE,				2,	2,			SEXP_ACTION_OPERATOR,	},	// FUBAR

	//Beams and Turrets Sub-Category
	{ "fire-beam",						OP_BEAM_FIRE,							3,	5,			SEXP_ACTION_OPERATOR,	},
	{ "fire-beam-at-coordinates",		OP_BEAM_FIRE_COORDS,					5,	9,			SEXP_ACTION_OPERATOR,	},
	{ "beam-create",					OP_BEAM_FLOATING_FIRE,					7,	14,			SEXP_ACTION_OPERATOR,	},
	{ "beam-free",						OP_BEAM_FREE,							2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "beam-free-all",					OP_BEAM_FREE_ALL,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "beam-lock",						OP_BEAM_LOCK,							2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "beam-lock-all",					OP_BEAM_LOCK_ALL,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "turret-free",					OP_TURRET_FREE,							2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "turret-free-all",				OP_TURRET_FREE_ALL,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "turret-lock",					OP_TURRET_LOCK,							2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "turret-lock-all",				OP_TURRET_LOCK_ALL,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "turret-tagged-only",				OP_TURRET_TAGGED_ONLY_ALL,				1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "turret-tagged-clear",			OP_TURRET_TAGGED_CLEAR_ALL,				1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "turret-tagged-specific",			OP_TURRET_TAGGED_SPECIFIC,				2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//phreak
	{ "turret-tagged-clear-specific",	OP_TURRET_TAGGED_CLEAR_SPECIFIC,		2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//phreak
	{ "turret-change-weapon",			OP_TURRET_CHANGE_WEAPON,				5,	5,			SEXP_ACTION_OPERATOR,	},	//WMC
	{ "turret-set-direction-preference",OP_TURRET_SET_DIRECTION_PREFERENCE,		3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//FUBAR
	{ "turret-set-rate-of-fire",		OP_TURRET_SET_RATE_OF_FIRE,				3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//FUBAR
	{ "turret-set-optimum-range",		OP_TURRET_SET_OPTIMUM_RANGE,			3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//FUBAR
	{ "turret-set-target-priorities",	OP_TURRET_SET_TARGET_PRIORITIES,		3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//FUBAR
	{ "turret-set-target-order",		OP_TURRET_SET_TARGET_ORDER,				2,	2+NUM_TURRET_ORDER_TYPES,	SEXP_ACTION_OPERATOR,	},	//WMC
	{ "ship-turret-target-order",		OP_SHIP_TURRET_TARGET_ORDER,			1,	1+NUM_TURRET_ORDER_TYPES,	SEXP_ACTION_OPERATOR,	},	//WMC
	{ "turret-subsys-target-disable",	OP_TURRET_SUBSYS_TARGET_DISABLE,		2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "turret-subsys-target-enable",	OP_TURRET_SUBSYS_TARGET_ENABLE,			2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "turret-set-primary-ammo",		OP_TURRET_SET_PRIMARY_AMMO,				4,	4,			SEXP_ACTION_OPERATOR,	},	// DahBlount
	{ "turret-set-secondary-ammo",		OP_TURRET_SET_SECONDARY_AMMO,			4,	4,			SEXP_ACTION_OPERATOR,	},	// DahBlount
	{ "turret-get-primary-ammo",		OP_TURRET_GET_PRIMARY_AMMO,				3,	3,			SEXP_INTEGER_OPERATOR,	},	// DahBlount
	{ "turret-get-secondary-ammo",		OP_TURRET_GET_SECONDARY_AMMO,			3,	3,			SEXP_INTEGER_OPERATOR,	},	// DahBlount
	
	//Models and Textures Sub-Category
	{ "change-ship-class",				OP_CHANGE_SHIP_CLASS,					2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "deactivate-glow-maps",			OP_DEACTIVATE_GLOW_MAPS,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//-Bobboau
	{ "activate-glow-maps",				OP_ACTIVATE_GLOW_MAPS,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//-Bobboau
	{ "deactivate-glow-points",			OP_DEACTIVATE_GLOW_POINTS,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//-Bobboau
	{ "activate-glow-points",			OP_ACTIVATE_GLOW_POINTS,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//-Bobboau
	{ "deactivate-glow-point-bank",		OP_DEACTIVATE_GLOW_POINT_BANK,			2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//-Bobboau
	{ "activate-glow-point-bank",		OP_ACTIVATE_GLOW_POINT_BANK,			2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//-Bobboau
	{ "set-thrusters-status",			OP_SET_THRUSTERS,						2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// The E
	{ "don't-collide-invisible",		OP_DONT_COLLIDE_INVISIBLE,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "collide-invisible",				OP_COLLIDE_INVISIBLE,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "add-to-collision-group",			OP_ADD_TO_COLGROUP,						2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// The E
	{ "remove-from-collision-group",	OP_REMOVE_FROM_COLGROUP,				2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "get-collision-group",			OP_GET_COLGROUP_ID,						1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "change-team-color",				OP_CHANGE_TEAM_COLOR,					3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// The E

	//Coordinate Manipulation Sub-Category
	{ "set-object-position",			OP_SET_OBJECT_POSITION,					4,	4,			SEXP_ACTION_OPERATOR,	},	// WMC
	{ "set-object-orientation",			OP_SET_OBJECT_ORIENTATION,				4,	4,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-object-facing",				OP_SET_OBJECT_FACING,					4,	6,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-object-facing-object",		OP_SET_OBJECT_FACING_OBJECT,			2,	4,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-object-speed-x",				OP_SET_OBJECT_SPEED_X,					2,	3,			SEXP_ACTION_OPERATOR,	},	// WMC
	{ "set-object-speed-y",				OP_SET_OBJECT_SPEED_Y,					2,	3,			SEXP_ACTION_OPERATOR,	},	// WMC
	{ "set-object-speed-z",				OP_SET_OBJECT_SPEED_Z,					2,	3,			SEXP_ACTION_OPERATOR,	},	// WMC
	{ "ship-maneuver",					OP_SHIP_MANEUVER,						10, 10,			SEXP_ACTION_OPERATOR,	},	// Wanderer
	{ "ship-rot-maneuver",				OP_SHIP_ROT_MANEUVER,					6,	6,			SEXP_ACTION_OPERATOR,	},	// Wanderer
	{ "ship-lat-maneuver",				OP_SHIP_LAT_MANEUVER,					6,	6,			SEXP_ACTION_OPERATOR,	},	// Wanderer
	{ "set-immobile",					OP_SET_IMMOBILE,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-mobile",						OP_SET_MOBILE,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000

	//Mission and Campaign Sub-Category
	{ "invalidate-goal",				OP_INVALIDATE_GOAL,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "validate-goal",					OP_VALIDATE_GOAL,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "red-alert",						OP_RED_ALERT,							0,	0,			SEXP_ACTION_OPERATOR,	},
	{ "end-mission",					OP_END_MISSION,							0,	3,			SEXP_ACTION_OPERATOR,	},	//-Sesquipedalian
	{ "force-jump",						OP_FORCE_JUMP,							0,	0,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "next-mission",					OP_NEXT_MISSION,						1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "end-campaign",					OP_END_CAMPAIGN,						0,	1,			SEXP_ACTION_OPERATOR,	},
	{ "end-of-campaign",				OP_END_OF_CAMPAIGN,						0,	0,			SEXP_ACTION_OPERATOR,	},
	{ "set-debriefing-toggled",			OP_SET_DEBRIEFING_TOGGLED,				1,	1,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "allow-treason",					OP_ALLOW_TREASON,						1,	1,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "grant-promotion",				OP_GRANT_PROMOTION,						0,	0,			SEXP_ACTION_OPERATOR,	},
	{ "grant-medal",					OP_GRANT_MEDAL,							1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "allow-ship",						OP_ALLOW_SHIP,							1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "allow-weapon",					OP_ALLOW_WEAPON,						1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "tech-add-ships",					OP_TECH_ADD_SHIP,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "tech-add-weapons",				OP_TECH_ADD_WEAPON,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "tech-add-intel",					OP_TECH_ADD_INTEL,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "tech-add-intel-xstr",			OP_TECH_ADD_INTEL_XSTR,					2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "tech-reset-to-default",			OP_TECH_RESET_TO_DEFAULT,				0,	0,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "change-player-score",			OP_CHANGE_PLAYER_SCORE,					2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "change-team-score",				OP_CHANGE_TEAM_SCORE,					2,	2,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-respawns",					OP_SET_RESPAWNS,						2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma

	//Music and Sound Sub-Category
	{ "change-soundtrack",				OP_CHANGE_SOUNDTRACK,					1,	1,			SEXP_ACTION_OPERATOR,	},	// Goober5000	
	{ "play-sound-from-table",			OP_PLAY_SOUND_FROM_TABLE,				4,	4,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "play-sound-from-file",			OP_PLAY_SOUND_FROM_FILE,				1,	3,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "close-sound-from-file",			OP_CLOSE_SOUND_FROM_FILE,				1,	1,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "pause-sound-from-file",			OP_PAUSE_SOUND_FROM_FILE,				1,	1,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-sound-environment",			OP_SET_SOUND_ENVIRONMENT,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Taylor
	{ "update-sound-environment",		OP_UPDATE_SOUND_ENVIRONMENT,			2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Taylor
	{ "adjust-audio-volume",			OP_ADJUST_AUDIO_VOLUME,					1,	3,			SEXP_ACTION_OPERATOR,	},

	//HUD Sub-Category
	{ "hud-disable",					OP_HUD_DISABLE,							1,	1,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "hud-disable-except-messages",	OP_HUD_DISABLE_EXCEPT_MESSAGES,			1,	1,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "hud-set-custom-gauge-active",	OP_HUD_SET_CUSTOM_GAUGE_ACTIVE,			2, 	INT_MAX, 	SEXP_ACTION_OPERATOR,	},
	{ "hud-set-retail-gauge-active",	OP_HUD_SET_RETAIL_GAUGE_ACTIVE,			2, 	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "hud-set-text",					OP_HUD_SET_TEXT,						2,	2,			SEXP_ACTION_OPERATOR,	},	//WMCoolmon
	{ "hud-set-text-num",				OP_HUD_SET_TEXT_NUM,					2,	2,			SEXP_ACTION_OPERATOR,	},	//WMCoolmon
	{ "hud-set-message",				OP_HUD_SET_MESSAGE,						2,	2,			SEXP_ACTION_OPERATOR,	},	//The E
	{ "hud-set-directive",				OP_HUD_SET_DIRECTIVE,					2,	2,			SEXP_ACTION_OPERATOR,	},	//The E
	{ "hud-set-frame",					OP_HUD_SET_FRAME,						2,	2,			SEXP_ACTION_OPERATOR,	},	//WMCoolmon
	{ "hud-set-coords",					OP_HUD_SET_COORDS,						3,	3,			SEXP_ACTION_OPERATOR,	},	//WMCoolmon
	{ "hud-set-color",					OP_HUD_SET_COLOR,						4,	4,			SEXP_ACTION_OPERATOR,	},	//WMCoolmon
	{ "hud-display-gauge",				OP_HUD_DISPLAY_GAUGE,					2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "hud-gauge-set-active",			OP_HUD_GAUGE_SET_ACTIVE,				2,	2,			SEXP_ACTION_OPERATOR,	},	//Deprecated
	{ "hud-activate-gauge-type",		OP_HUD_ACTIVATE_GAUGE_TYPE,				2,	2,			SEXP_ACTION_OPERATOR,	},	//Deprecated
	{ "hud-clear-messages",				OP_HUD_CLEAR_MESSAGES,					0,	0,			SEXP_ACTION_OPERATOR,	},	// swifty
	{ "hud-set-max-targeting-range",	OP_HUD_SET_MAX_TARGETING_RANGE,			1,	1,			SEXP_ACTION_OPERATOR,	},	// Goober5000

	//Nav Sub-Category
	{ "add-nav-waypoint",				OP_NAV_ADD_WAYPOINT,					3,	4,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "add-nav-ship",					OP_NAV_ADD_SHIP,						2,	2,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "del-nav",						OP_NAV_DEL,								1,	1,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "hide-nav",						OP_NAV_HIDE,							1,	1,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "restrict-nav",					OP_NAV_RESTRICT,						1,	1,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "unhide-nav",						OP_NAV_UNHIDE,							1,	1,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "unrestrict-nav",					OP_NAV_UNRESTRICT,						1,	1,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "set-nav-visited",				OP_NAV_SET_VISITED,						1,	1,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "unset-nav-visited",				OP_NAV_UNSET_VISITED,					1,	1,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "set-nav-carry",					OP_NAV_SET_CARRY,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//kazan
	{ "unset-nav-carry",				OP_NAV_UNSET_CARRY,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//kazan
	{ "set-nav-needslink",				OP_NAV_SET_NEEDSLINK,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//kazan
	{ "unset-nav-needslink",			OP_NAV_UNSET_NEEDSLINK,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//kazan
	{ "is-nav-linked",					OP_NAV_ISLINKED,						1,	1,			SEXP_BOOLEAN_OPERATOR,	},	//kazan
	{ "use-nav-cinematics",				OP_NAV_USECINEMATICS,					1,	1,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "use-autopilot",					OP_NAV_USEAP,							1,	1,			SEXP_ACTION_OPERATOR,	},	//kazan
	{ "select-nav",						OP_NAV_SELECT,							1,	1,			SEXP_ACTION_OPERATOR,	},	//Talon1024
	{ "unselect-nav",					OP_NAV_UNSELECT,						0,	0,			SEXP_ACTION_OPERATOR,	},	//Talon1024

	//Cutscene Sub-Category
	{ "set-cutscene-bars",				OP_CUTSCENES_SET_CUTSCENE_BARS,			0,	1,			SEXP_ACTION_OPERATOR,	},
	{ "unset-cutscene-bars",			OP_CUTSCENES_UNSET_CUTSCENE_BARS,		0,	1,			SEXP_ACTION_OPERATOR,	},
	{ "fade-in",						OP_CUTSCENES_FADE_IN,					0,	4,			SEXP_ACTION_OPERATOR,	},
	{ "fade-out",						OP_CUTSCENES_FADE_OUT,					0,	4,			SEXP_ACTION_OPERATOR,	},
	{ "set-camera",						OP_CUTSCENES_SET_CAMERA,				0,	1,			SEXP_ACTION_OPERATOR,	},
	{ "set-camera-position",			OP_CUTSCENES_SET_CAMERA_POSITION,		3,	6,			SEXP_ACTION_OPERATOR,	},
	{ "set-camera-facing",				OP_CUTSCENES_SET_CAMERA_FACING,			3,	6,			SEXP_ACTION_OPERATOR,	},
	{ "set-camera-facing-object",		OP_CUTSCENES_SET_CAMERA_FACING_OBJECT,	1,	4,			SEXP_ACTION_OPERATOR,	},
	{ "set-camera-rotation",			OP_CUTSCENES_SET_CAMERA_ROTATION,		3,	6,			SEXP_ACTION_OPERATOR,	},
	{ "set-camera-host",				OP_CUTSCENES_SET_CAMERA_HOST,			1,	2,			SEXP_ACTION_OPERATOR,	},
	{ "set-camera-target",				OP_CUTSCENES_SET_CAMERA_TARGET,			1,	2,			SEXP_ACTION_OPERATOR,	},
	{ "set-camera-fov",					OP_CUTSCENES_SET_CAMERA_FOV,			1,	5,			SEXP_ACTION_OPERATOR,	},
	{ "set-fov",						OP_CUTSCENES_SET_FOV,					1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "get-fov",						OP_CUTSCENES_GET_FOV,					0,	0,			SEXP_INTEGER_OPERATOR,	},
	{ "reset-fov",						OP_CUTSCENES_RESET_FOV,					0,	0,			SEXP_ACTION_OPERATOR,	},
	{ "reset-camera",					OP_CUTSCENES_RESET_CAMERA,				0,	1,			SEXP_ACTION_OPERATOR,	},
	{ "show-subtitle",					OP_CUTSCENES_SHOW_SUBTITLE,				4,	13,			SEXP_ACTION_OPERATOR,	},
	{ "show-subtitle-text",				OP_CUTSCENES_SHOW_SUBTITLE_TEXT,		6,	13,			SEXP_ACTION_OPERATOR,	},
	{ "show-subtitle-image",			OP_CUTSCENES_SHOW_SUBTITLE_IMAGE,		8,	10,			SEXP_ACTION_OPERATOR,	},
	{ "clear-subtitles",				OP_CLEAR_SUBTITLES,						0,	0,			SEXP_ACTION_OPERATOR,	},
	{ "lock-perspective",				OP_CUTSCENES_FORCE_PERSPECTIVE,			1,	2,			SEXP_ACTION_OPERATOR,	},
	{ "set-camera-shudder",				OP_SET_CAMERA_SHUDDER,					2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "supernova-start",				OP_SUPERNOVA_START,						1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "supernova-stop",					OP_SUPERNOVA_STOP,						0,	0,			SEXP_ACTION_OPERATOR,	},	//CommanderDJ
	{ "set-motion-debris-override",		OP_SET_MOTION_DEBRIS,					1,  1,			SEXP_ACTION_OPERATOR,	},	// The E

	//Background and Nebula Sub-Category
	{ "mission-set-nebula",				OP_MISSION_SET_NEBULA,					1,	1,			SEXP_ACTION_OPERATOR,	},	// Sesquipedalian
	{ "mission-set-subspace",			OP_MISSION_SET_SUBSPACE,				1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "add-background-bitmap",			OP_ADD_BACKGROUND_BITMAP,				8,	9,			SEXP_ACTION_OPERATOR,	},	// phreak
	{ "remove-background-bitmap",		OP_REMOVE_BACKGROUND_BITMAP,			1,	1,			SEXP_ACTION_OPERATOR,	},	// phreak
	{ "add-sun-bitmap",					OP_ADD_SUN_BITMAP,						5,	6,			SEXP_ACTION_OPERATOR,	},	// phreak
	{ "remove-sun-bitmap",				OP_REMOVE_SUN_BITMAP,					1,	1,			SEXP_ACTION_OPERATOR,	},	// phreak
	{ "nebula-change-storm",			OP_NEBULA_CHANGE_STORM,					1,	1,			SEXP_ACTION_OPERATOR,	},	// phreak
	{ "nebula-toggle-poof",				OP_NEBULA_TOGGLE_POOF,					2,	2,			SEXP_ACTION_OPERATOR,	},	// phreak
	{ "nebula-change-pattern",			OP_NEBULA_CHANGE_PATTERN,				1,	1,			SEXP_ACTION_OPERATOR,	},	// Axem
	{ "set-skybox-model",				OP_SET_SKYBOX_MODEL,					1,	8,			SEXP_ACTION_OPERATOR,	},	// taylor
	{ "set-skybox-orientation",			OP_SET_SKYBOX_ORIENT,					3,	3,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-ambient-light",				OP_SET_AMBIENT_LIGHT,					3,	3,			SEXP_ACTION_OPERATOR,	},	// Karajorma

	//Jump Node Sub-Category
	{ "set-jumpnode-name",				OP_JUMP_NODE_SET_JUMPNODE_NAME,			2,	2,			SEXP_ACTION_OPERATOR,	},	//CommanderDJ
	{ "set-jumpnode-color",				OP_JUMP_NODE_SET_JUMPNODE_COLOR,		5,	5,			SEXP_ACTION_OPERATOR,	},
	{ "set-jumpnode-model",				OP_JUMP_NODE_SET_JUMPNODE_MODEL,		3,	3,			SEXP_ACTION_OPERATOR,	},
	{ "show-jumpnode",					OP_JUMP_NODE_SHOW_JUMPNODE,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "hide-jumpnode",					OP_JUMP_NODE_HIDE_JUMPNODE,				1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},

	//Special Effects Sub-Category
	{ "set-post-effect",				OP_SET_POST_EFFECT,						2,	2,			SEXP_ACTION_OPERATOR,	},	// Hery
	{ "ship-effect",					OP_SHIP_EFFECT,							3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Valathil
	{ "ship-create",					OP_SHIP_CREATE,							5,	8,			SEXP_ACTION_OPERATOR,	},	// WMC
	{ "weapon-create",					OP_WEAPON_CREATE,						5,	10,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "ship-vanish",					OP_SHIP_VANISH,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ship-vaporize",					OP_SHIP_VAPORIZE,						1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "ship-no-vaporize",				OP_SHIP_NO_VAPORIZE,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-explosion-option",			OP_SET_EXPLOSION_OPTION,				3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "explosion-effect",				OP_EXPLOSION_EFFECT,					11,	13,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "warp-effect",					OP_WARP_EFFECT,							12, 12,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "remove-weapons",					OP_REMOVE_WEAPONS,						0,	1,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "set-time-compression",			OP_CUTSCENES_SET_TIME_COMPRESSION,		1,	3,			SEXP_ACTION_OPERATOR,	},
	{ "reset-time-compression",			OP_CUTSCENES_RESET_TIME_COMPRESSION,	0,	0,			SEXP_ACTION_OPERATOR,	},
	{ "call-ssm-strike",				OP_CALL_SSM_STRIKE,						3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// X3N0-Life-Form

	//Variable Category
	{ "modify-variable",				OP_MODIFY_VARIABLE,						2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "get-variable-by-index",			OP_GET_VARIABLE_BY_INDEX,				1,	1,			SEXP_INTEGER_OPERATOR,	},	// Goober5000
	{ "set-variable-by-index",			OP_SET_VARIABLE_BY_INDEX,				2,	2,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "copy-variable-from-index",		OP_COPY_VARIABLE_FROM_INDEX,			2,	2,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "copy-variable-between-indexes",	OP_COPY_VARIABLE_BETWEEN_INDEXES,		2,	2,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "int-to-string",					OP_INT_TO_STRING,						2,	2,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "string-concatenate",				OP_STRING_CONCATENATE,					3,	3,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "string-get-substring",			OP_STRING_GET_SUBSTRING,				4,	4,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "string-set-substring",			OP_STRING_SET_SUBSTRING,				5,	5,			SEXP_ACTION_OPERATOR,	},	// Goober5000  

	//Other Sub-Category
	{ "damaged-escort-priority",		OP_DAMAGED_ESCORT_LIST,					3,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	//phreak
	{ "damaged-escort-priority-all",	OP_DAMAGED_ESCORT_LIST_ALL,				1,	MAX_COMPLETE_ESCORT_LIST,	SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "set-support-ship",				OP_SET_SUPPORT_SHIP,					6,	7,			SEXP_ACTION_OPERATOR,	},	// Goober5000
	{ "script-eval",					OP_SCRIPT_EVAL,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "script-eval-block",				OP_SCRIPT_EVAL_BLOCK,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "multi-eval",						OP_SCRIPT_EVAL_MULTI,					2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "debug",							OP_DEBUG,								2,	2,			SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "do-nothing",						OP_NOP,									0,	0,			SEXP_ACTION_OPERATOR,	},
	
	//AI Goals Category
	{ "ai-chase",						OP_AI_CHASE,							2,	3,			SEXP_GOAL_OPERATOR,	},
	{ "ai-chase-wing",					OP_AI_CHASE_WING,						2,	3,			SEXP_GOAL_OPERATOR,	},
	{ "ai-chase-any",					OP_AI_CHASE_ANY,						1,	1,			SEXP_GOAL_OPERATOR,	},
	{ "ai-guard",						OP_AI_GUARD,							2,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-guard-wing",					OP_AI_GUARD_WING,						2,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-destroy-subsystem",			OP_AI_DESTROY_SUBSYS,					3,	4,			SEXP_GOAL_OPERATOR,	},
	{ "ai-disable-ship",				OP_AI_DISABLE_SHIP,						2,	3,			SEXP_GOAL_OPERATOR,	},
	{ "ai-disarm-ship",					OP_AI_DISARM_SHIP,						2,	3,			SEXP_GOAL_OPERATOR,	},
	{ "ai-warp",						OP_AI_WARP,								2,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-warp-out",					OP_AI_WARP_OUT,							1,	1,			SEXP_GOAL_OPERATOR,	},
	{ "ai-dock",						OP_AI_DOCK,								4,	4,			SEXP_GOAL_OPERATOR,	},
	{ "ai-undock",						OP_AI_UNDOCK,							1,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-waypoints",					OP_AI_WAYPOINTS,						2,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-waypoints-once",				OP_AI_WAYPOINTS_ONCE,					2,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-ignore",						OP_AI_IGNORE,							2,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-ignore-new",					OP_AI_IGNORE_NEW,						2,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-stay-near-ship",				OP_AI_STAY_NEAR_SHIP,					2,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-evade-ship",					OP_AI_EVADE_SHIP,						2,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-keep-safe-distance",			OP_AI_KEEP_SAFE_DISTANCE,				1,	1,			SEXP_GOAL_OPERATOR,	},
	{ "ai-stay-still",					OP_AI_STAY_STILL,						2,	2,			SEXP_GOAL_OPERATOR,	},
	{ "ai-play-dead",					OP_AI_PLAY_DEAD,						1,	1,			SEXP_GOAL_OPERATOR,	},
	{ "ai-form-on-wing",				OP_AI_FORM_ON_WING,						1,	1,			SEXP_GOAL_OPERATOR,	},

	{ "goals",							OP_GOALS_ID,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},

	//Training Category
	{ "key-pressed",					OP_KEY_PRESSED,							1,	2,			SEXP_BOOLEAN_OPERATOR,	},
	{ "key-reset",						OP_KEY_RESET,							1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "key-reset-multiple",				OP_KEY_RESET_MULTIPLE,					1,	INT_MAX,	SEXP_ACTION_OPERATOR,	},
	{ "ignore-key",						OP_IGNORE_KEY,							2,	INT_MAX,	SEXP_ACTION_OPERATOR,	},	// Karajorma
	{ "targeted",						OP_TARGETED,							1,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "node-targeted",					OP_NODE_TARGETED,						1,	2,			SEXP_BOOLEAN_OPERATOR,	},	// FUBAR
	{ "missile-locked",					OP_MISSILE_LOCKED,						1,	3,			SEXP_BOOLEAN_OPERATOR,	},	// Sesquipedalian
	{ "speed",							OP_SPEED,								1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "facing",							OP_FACING,								2,	2,			SEXP_BOOLEAN_OPERATOR,	},
	{ "facing-waypoint",				OP_FACING2,								2,	2,			SEXP_BOOLEAN_OPERATOR,	},
	{ "order",							OP_ORDER,								2,	3,			SEXP_BOOLEAN_OPERATOR,	},
	{ "query-orders",					OP_QUERY_ORDERS,						3,	6,			SEXP_BOOLEAN_OPERATOR,	}, // Karajorma
	{ "reset-orders",					OP_RESET_ORDERS,						0,	0,			SEXP_ACTION_OPERATOR,	}, // Karajorma
	{ "waypoint-missed",				OP_WAYPOINT_MISSED,						0,	0,			SEXP_BOOLEAN_OPERATOR,	},
	{ "waypoint-twice",					OP_WAYPOINT_TWICE,						0,	0,			SEXP_BOOLEAN_OPERATOR,	},
	{ "path-flown",						OP_PATH_FLOWN,							0,	0,			SEXP_BOOLEAN_OPERATOR,	},
	{ "training-msg",					OP_TRAINING_MSG,						1,	4,			SEXP_ACTION_OPERATOR,	},
	{ "flash-hud-gauge",				OP_FLASH_HUD_GAUGE,						1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "primaries-depleted",				OP_PRIMARIES_DEPLETED,					1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "secondaries-depleted",			OP_SECONDARIES_DEPLETED,				1,	1,			SEXP_BOOLEAN_OPERATOR,	},
	{ "special-check",					OP_SPECIAL_CHECK,						1,	1,			SEXP_ACTION_OPERATOR,	},
	{ "set-training-context-fly-path",	OP_SET_TRAINING_CONTEXT_FLY_PATH,		2,	2,			SEXP_ACTION_OPERATOR,	},
	{ "set-training-context-speed",		OP_SET_TRAINING_CONTEXT_SPEED,			2,	2,			SEXP_ACTION_OPERATOR,	},
};

sexp_ai_goal_link Sexp_ai_goal_links[] = {
	{ AI_GOAL_CHASE, OP_AI_CHASE },
	{ AI_GOAL_CHASE_WING, OP_AI_CHASE_WING },
	{ AI_GOAL_DOCK, OP_AI_DOCK },
	{ AI_GOAL_UNDOCK, OP_AI_UNDOCK },
	{ AI_GOAL_WARP, OP_AI_WARP_OUT },
	{ AI_GOAL_WARP, OP_AI_WARP },
	{ AI_GOAL_WAYPOINTS, OP_AI_WAYPOINTS },
	{ AI_GOAL_WAYPOINTS_ONCE, OP_AI_WAYPOINTS_ONCE },
	{ AI_GOAL_DESTROY_SUBSYSTEM, OP_AI_DESTROY_SUBSYS },
	{ AI_GOAL_DISABLE_SHIP, OP_AI_DISABLE_SHIP },
	{ AI_GOAL_DISARM_SHIP, OP_AI_DISARM_SHIP },
	{ AI_GOAL_GUARD, OP_AI_GUARD },
	{ AI_GOAL_CHASE_ANY, OP_AI_CHASE_ANY },
	{ AI_GOAL_GUARD_WING, OP_AI_GUARD_WING },
	{ AI_GOAL_EVADE_SHIP, OP_AI_EVADE_SHIP },
	{ AI_GOAL_STAY_NEAR_SHIP, OP_AI_STAY_NEAR_SHIP },
	{ AI_GOAL_KEEP_SAFE_DISTANCE, OP_AI_KEEP_SAFE_DISTANCE },
	{ AI_GOAL_IGNORE, OP_AI_IGNORE },
	{ AI_GOAL_IGNORE_NEW, OP_AI_IGNORE_NEW },
	{ AI_GOAL_STAY_STILL, OP_AI_STAY_STILL },
	{ AI_GOAL_PLAY_DEAD, OP_AI_PLAY_DEAD },
	{ AI_GOAL_FORM_ON_WING, OP_AI_FORM_ON_WING }
};

char *HUD_gauge_text[NUM_HUD_GAUGES] = 
{
	"LEAD_INDICATOR",
	"ORIENTATION_TEE",
	"HOSTILE_TRIANGLE",
	"TARGET_TRIANGLE",
	"MISSION_TIME",
	"RETICLE_CIRCLE",
	"THROTTLE_GAUGE",
	"RADAR",
	"TARGET_MONITOR",
	"CENTER_RETICLE",
	"TARGET_MONITOR_EXTRA_DATA",
	"TARGET_SHIELD_ICON",
	"PLAYER_SHIELD_ICON",
	"ETS_GAUGE",
	"AUTO_TARGET",
	"AUTO_SPEED",
	"WEAPONS_GAUGE",
	"ESCORT_VIEW",
	"DIRECTIVES_VIEW",
	"THREAT_GAUGE",
	"AFTERBURNER_ENERGY",
	"WEAPONS_ENERGY",
	"WEAPON_LINKING_GAUGE",
	"TARGER_MINI_ICON",
	"OFFSCREEN_INDICATOR",
	"TALKING_HEAD",
	"DAMAGE_GAUGE",
	"MESSAGE_LINES",
	"MISSILE_WARNING_ARROW",
	"CMEASURE_GAUGE",
	"OBJECTIVES_NOTIFY_GAUGE",
	"WINGMEN_STATUS",
	"OFFSCREEN RANGE",
	"KILLS GAUGE",
	"ATTACKING TARGET COUNT",
	"TEXT FLASH",
	"MESSAGE BOX",
	"SUPPORT GUAGE",
	"LAG GUAGE"
};


void sexp_set_skybox_model_preload(char *name); // taylor
int Num_skybox_flags = 6;
char *Skybox_flags[] = {
	"force-clamp",
	"add-lighting",
	"no-transparency",
	"add-zbuffer",
	"add-culling",
	"no-glowmaps",
};

int	Directive_count;
int	Sexp_useful_number;  // a variable to pass useful info in from external modules
int	Locked_sexp_true, Locked_sexp_false;
int	Num_operators = sizeof(Operators) / sizeof(sexp_oper);
int	Num_sexp_ai_goal_links = sizeof(Sexp_ai_goal_links) / sizeof(sexp_ai_goal_link);
int	Sexp_clipboard = -1;  // used by Fred
int	Training_context = 0;
int	Training_context_speed_set;
int	Training_context_speed_min;
int	Training_context_speed_max;
int	Training_context_speed_timestamp;
waypoint_list *Training_context_path;
int Training_context_goal_waypoint;
int Training_context_at_waypoint;
float	Training_context_distance;

#define SEXP_NODE_INCREMENT	250
int Num_sexp_nodes = 0;
sexp_node *Sexp_nodes = NULL;

sexp_variable Sexp_variables[MAX_SEXP_VARIABLES];
sexp_variable Block_variables[MAX_SEXP_VARIABLES];			// used for compatibility with retail. 

int Num_special_expl_blocks;

SCP_vector<int> Current_sexp_operator;

int Players_target = UNINITIALIZED;
int Players_mlocked = UNINITIALIZED; // for is-missile-locked - Sesquipedalian
ship_subsys *Players_targeted_subsys;
int Players_target_timestamp;
int Players_mlocked_timestamp;

// for play-music - Goober5000
int	Sexp_music_handle = -1;
void sexp_stop_music(int fade = 1);

// for sound environments - Goober5000/Taylor
#define SEO_VOLUME		0
#define SEO_DECAY_TIME	1
#define SEO_DAMPING		2
int sexp_sound_environment_option_lookup(char *text);
char *Sound_environment_option[] = { "volume", "decay time", "damping" };
int Num_sound_environment_options = 3;

// for adjust-audio-volume - The E
char *Adjust_audio_options[] = { "Music", "Voice", "Effects" };
int Num_adjust_audio_options = 3;
int audio_volume_option_lookup(char *text);

int hud_gauge_type_lookup(char* name);

// for explosions - Goober5000
#define EO_DAMAGE			0
#define EO_BLAST			1
#define EO_INNER_RADIUS		2
#define EO_OUTER_RADIUS		3
#define EO_SHOCKWAVE_SPEED	4
#define EO_DEATH_ROLL_TIME	5
int sexp_explosion_option_lookup(char *text);
char *Explosion_option[] = { "damage", "blast", "inner radius", "outer radius", "shockwave speed", "death roll time" };
int Num_explosion_options = 6;

int get_sexp();
void build_extended_sexp_string(SCP_string &accumulator, int cur_node, int level, int mode);
void update_sexp_references(const char *old_name, const char *new_name, int format, int node);
int sexp_determine_team(char *subj);
int extract_sexp_variable_index(int node);
void init_sexp_vars();
int eval_num(int node);

// for handling variables
void add_block_variable(const char *text, const char *var_name, int type, int index);
void sexp_modify_variable(int node);
int sexp_get_variable_by_index(int node);
void sexp_set_variable_by_index(int node);
void sexp_copy_variable_from_index(int node);
void sexp_copy_variable_between_indexes(int node);

SCP_vector<char*> Sexp_replacement_arguments;
int Sexp_current_argument_nesting_level;
SCP_vector<char*> Applicable_arguments_temp;

// Goober5000
arg_item Sexp_applicable_argument_list;
bool is_blank_argument_op(int op_const);
bool is_blank_of_op(int op_const);

int get_handler_for_x_of_operator(int node);

//Karajorma
int get_generic_subsys(char *subsy_name);
bool ship_class_unchanged(int ship_index); 
void multi_sexp_modify_variable();

int get_effect_from_name(char* name);

#define NO_OPERATOR_INDEX_DEFINED		-2
#define NOT_A_SEXP_OPERATOR				-1

// Karajorma - some useful helper methods
player * get_player_from_ship_node(int node, bool test_respawns = false);
ship * sexp_get_ship_from_node(int node);

// hud-display-gauge magic values
#define SEXP_HUD_GAUGE_WARPOUT "warpout"

// event log stuff
SCP_vector<SCP_string> *Current_event_log_buffer;
SCP_vector<SCP_string> *Current_event_log_variable_buffer;
SCP_vector<SCP_string> *Current_event_log_argument_buffer;
// Goober5000 - arg_item class stuff, borrowed from sexp_list_item class stuff -------------
void arg_item::add_data(char *str)
{
	arg_item *item, *ptr;

	// create item
	item = new arg_item;
	item->text = str;
	item->nesting_level = Sexp_current_argument_nesting_level;

	// prepend item to existing list
	ptr = this->next;
	this->next = item;
	item->next = ptr;
}

void arg_item::add_data_dup(char *str)
{
	arg_item *item, *ptr;

	// create item
	item = new arg_item;
	item->text = vm_strdup(str);
	item->flags |= ARG_ITEM_F_DUP;
	item->nesting_level = Sexp_current_argument_nesting_level;

	// prepend item to existing list
	ptr = this->next;
	this->next = item;
	item->next = ptr;
}

void arg_item::add_data_set_dup(char *str)
{
	arg_item *item, *ptr;

	// create item
	item = new arg_item;
	item->text = str;
	item->flags |= ARG_ITEM_F_DUP;
	item->nesting_level = Sexp_current_argument_nesting_level;

	// prepend item to existing list
	ptr = this->next;
	this->next = item;
	item->next = ptr;
}

arg_item* arg_item::get_next()
{
	if (this->next != NULL) {
		if (this->next->nesting_level >= Sexp_current_argument_nesting_level) {
			return this->next; 
		}
	}

	return NULL;
}

void arg_item::expunge()
{
	arg_item *ptr;

	// contiually delete first item of list
	while (this->next != NULL)
	{
		ptr = this->next->next;

		if (this->next->flags & ARG_ITEM_F_DUP)
			vm_free(this->next->text);
		delete this->next;

		this->next = ptr;
	}
}

void arg_item::clear_nesting_level()
{
	arg_item *ptr;

	// contiually delete first item of list
	while (this->next != NULL && this->next->nesting_level >= Sexp_current_argument_nesting_level )
	{
		ptr = this->next->next;

		if (this->next->flags & ARG_ITEM_F_DUP)
			vm_free(this->next->text);
		delete this->next;

		this->next = ptr;
	}
}

int arg_item::is_empty()
{
	return (this->next == NULL);
}
//-------------------------------------------------------------------------------------------------

void sexp_nodes_init()
{
	if (Num_sexp_nodes == 0 || Sexp_nodes == NULL)
		return;

	nprintf(("SEXP", "Reinitializing sexp nodes...\n"));
	nprintf(("SEXP", "Entered function with %d nodes.\n", Num_sexp_nodes));

	// usually, the persistent nodes are grouped at the beginning of the array;
	// so we ought to be able to free all the subsequent nodes
	int i, last_persistent_node = -1;

	for (i = 0; i < Num_sexp_nodes; i++)
	{
		if (Sexp_nodes[i].type & SEXP_FLAG_PERSISTENT)
			last_persistent_node = i;					// keep track of it
		else
			Sexp_nodes[i].type = SEXP_NOT_USED;			// it's not needed
	}

	nprintf(("SEXP", "Last persistent node index is %d.\n", last_persistent_node));

	// if all the persistent nodes are gone, free all the nodes
	if (last_persistent_node == -1)
	{
		vm_free(Sexp_nodes);
		Sexp_nodes = NULL;
		Num_sexp_nodes = 0;
	}
	// if there's enough of a difference to make it worthwhile, free some nodes
	else if (Num_sexp_nodes - (last_persistent_node + 1) > 2 * SEXP_NODE_INCREMENT)
	{
		// round it up to the next evenly divisible size
		Num_sexp_nodes = (last_persistent_node + 1);
		Num_sexp_nodes += SEXP_NODE_INCREMENT - (Num_sexp_nodes % SEXP_NODE_INCREMENT);

		Sexp_nodes = (sexp_node *) vm_realloc(Sexp_nodes, sizeof(sexp_node) * Num_sexp_nodes);
		Verify(Sexp_nodes != NULL);
	}

	nprintf(("SEXP", "Exited function with %d nodes.\n", Num_sexp_nodes));
}

static void sexp_nodes_close()
{
	// free all sexp nodes... should only be done on game shutdown
	if (Sexp_nodes != NULL)
	{
		vm_free(Sexp_nodes);
		Sexp_nodes = NULL;
		Num_sexp_nodes = 0;
	}
}

void init_sexp()
{
	// Goober5000
	Sexp_replacement_arguments.clear();
	Sexp_applicable_argument_list.expunge();
	Sexp_current_argument_nesting_level = 0;
	initalise_sexp_packet();

	static bool done_sexp_atexit = false;
	if (!done_sexp_atexit)
	{
		atexit(sexp_nodes_close);
		done_sexp_atexit = true;
	}

	sexp_nodes_init();
	init_sexp_vars();
	Locked_sexp_false = Locked_sexp_true = -1;

	Locked_sexp_false = alloc_sexp("false", SEXP_LIST, SEXP_ATOM_OPERATOR, -1, -1);
	Assert(Locked_sexp_false != -1);
	Sexp_nodes[Locked_sexp_false].type = SEXP_ATOM;  // fix bypassing value
	Sexp_nodes[Locked_sexp_false].value = SEXP_KNOWN_FALSE;

	Locked_sexp_true = alloc_sexp("true", SEXP_LIST, SEXP_ATOM_OPERATOR, -1, -1);
	Assert(Locked_sexp_true != -1);
	Sexp_nodes[Locked_sexp_true].type = SEXP_ATOM;  // fix bypassing value
	Sexp_nodes[Locked_sexp_true].value = SEXP_KNOWN_TRUE;
}

/**
 * Allocate an sexp node.
 */
int alloc_sexp(char *text, int type, int subtype, int first, int rest)
{
	int node;
	int sexp_const = get_operator_const(text);

	if ((sexp_const == OP_TRUE) && (type == SEXP_ATOM) && (subtype == SEXP_ATOM_OPERATOR))
		return Locked_sexp_true;

	else if ((sexp_const == OP_FALSE) && (type == SEXP_ATOM) && (subtype == SEXP_ATOM_OPERATOR))
		return Locked_sexp_false;

	node = find_free_sexp();

	// need more sexp nodes?
	if (node == Num_sexp_nodes || node == -1)
	{
		int old_size = Num_sexp_nodes;

		Assert(SEXP_NODE_INCREMENT > 0);

		// allocate in blocks of SEXP_NODE_INCREMENT
		Num_sexp_nodes += SEXP_NODE_INCREMENT;
		Sexp_nodes = (sexp_node *) vm_realloc(Sexp_nodes, sizeof(sexp_node) * Num_sexp_nodes);

		Verify(Sexp_nodes != NULL);
		nprintf(("SEXP", "Bumping dynamic sexp node limit from %d to %d...\n", old_size, Num_sexp_nodes));

		// clear all the new sexp nodes we just allocated
		memset(&Sexp_nodes[old_size], 0, sizeof(sexp_node) * SEXP_NODE_INCREMENT); //-V512

		// our new sexp is the first out of the ones we just created
		node = old_size;
	}

	Assert(node != Locked_sexp_true);
	Assert(node != Locked_sexp_false);
	Assert(strlen(text) < TOKEN_LENGTH);
	Assert(type >= 0);

	strcpy_s(Sexp_nodes[node].text, text);
	Sexp_nodes[node].type = type;
	Sexp_nodes[node].subtype = subtype;
	Sexp_nodes[node].first = first;
	Sexp_nodes[node].rest = rest;
	Sexp_nodes[node].value = SEXP_UNKNOWN;
	Sexp_nodes[node].flags = SNF_DEFAULT_VALUE;	// Goober5000
	Sexp_nodes[node].op_index = NO_OPERATOR_INDEX_DEFINED;

	return node;
}

static int Sexp_hwm = 0;

int count_free_sexp_nodes()
{
	int i, f = 0, p = 0;

	for (i = 0; i < Num_sexp_nodes; i++)
	{
		if (Sexp_nodes[i].type == SEXP_NOT_USED)
			f++;
		else if (Sexp_nodes[i].type & SEXP_FLAG_PERSISTENT)
			p++;
	}

	if (Num_sexp_nodes - f > Sexp_hwm)
	{
		nprintf(("Sexp", "Sexp nodes: Free=%d, Used=%d, Persistent=%d\n", f, Num_sexp_nodes - f, p));
		Sexp_hwm = Num_sexp_nodes - f;
	}

	return f;
}

/**
 * Find the next free sexp and return its index.
 */
int find_free_sexp()
{
	int i;

	// sanity
	if (Num_sexp_nodes == 0 || Sexp_nodes == NULL)
		return -1;

	for (i = 0; i < Num_sexp_nodes; i++)
	{
		if (Sexp_nodes[i].type == SEXP_NOT_USED)
			return i;
	}

	return -1;
}

/**
 * Mark a whole sexp tree with the persistent flag so that it won't get re-used between missions
 */
void sexp_mark_persistent(int n)
{
	if (n == -1){
		return;
	}

	// total hack because of the true/false locked sexps -- we should make those persistent as well
	if ( (n == Locked_sexp_true) || (n == Locked_sexp_false) ){
		return;
	}

	Assert( !(Sexp_nodes[n].type & SEXP_FLAG_PERSISTENT) );
	Sexp_nodes[n].type |= SEXP_FLAG_PERSISTENT;

	sexp_mark_persistent(Sexp_nodes[n].first);
	sexp_mark_persistent(Sexp_nodes[n].rest);

}

/**
 * Remove the persistent flag from all nodes in the tree
 */
void sexp_unmark_persistent(int n)
{
	if (n == -1){
		return;
	}

	if ( (n == Locked_sexp_true) || (n == Locked_sexp_false) ){
		return;
	}

	Assert( Sexp_nodes[n].type & SEXP_FLAG_PERSISTENT );
	Sexp_nodes[n].type &= ~SEXP_FLAG_PERSISTENT;

	sexp_unmark_persistent(Sexp_nodes[n].first);
	sexp_unmark_persistent(Sexp_nodes[n].rest);
}

/**
 * Free up the specified sexp node,  Leaves link chains untouched.
 */
int free_one_sexp(int num)
{
	Assert((num >= 0) && (num < Num_sexp_nodes));
	Assert(Sexp_nodes[num].type != SEXP_NOT_USED);  // make sure it is actually used
	Assert(!(Sexp_nodes[num].type & SEXP_FLAG_PERSISTENT));

	if ((num == Locked_sexp_true) || (num == Locked_sexp_false))
		return 0;

	Sexp_nodes[num].type = SEXP_NOT_USED;
	return 1;
}

/**
 * Free a used sexp node, so it can be reused later.  
 *
 * Should only be called on an atom or a list, and not an operator.  If on a list, the 
 * list and everything in it will be freed (including the operator).
 */
int free_sexp(int num)
{
	int i, rest, count = 0;

	Assert((num >= 0) && (num < Num_sexp_nodes));
	Assert(Sexp_nodes[num].type != SEXP_NOT_USED);  // make sure it is actually used
	Assert(!(Sexp_nodes[num].type & SEXP_FLAG_PERSISTENT));

	if ((num == Locked_sexp_true) || (num == Locked_sexp_false))
		return 0;

	Sexp_nodes[num].type = SEXP_NOT_USED;
	count++;

	i = Sexp_nodes[num].first;
	while (i != -1)
	{
		count += free_sexp(i);
		i = Sexp_nodes[i].rest;
	}

	rest = Sexp_nodes[num].rest;
	for (i = 0; i < Num_sexp_nodes; i++)
	{
		if (Sexp_nodes[i].first == num)
			Sexp_nodes[i].first = rest;

		if (Sexp_nodes[i].rest == num)
			Sexp_nodes[i].rest = rest;
	}

	return count;  // total elements freed up.
}

/**
 * Free up an entire sexp tree.  
 * 
 * Because the root node is an operator, instead of a list, we can't simply call free_sexp().  
 * This function should only be called on the root node of an sexp, otherwise the linking will get screwed up.
 */
int free_sexp2(int num)
{	
	int i, count = 0;

	if ((num == -1) || (num == Locked_sexp_true) || (num == Locked_sexp_false)){
		return 0;
	}

	i = Sexp_nodes[num].rest;
	while (i != -1) {
		count += free_sexp(i);
		i = Sexp_nodes[i].rest;
	}

	count += free_sexp(num);
	return count;
}

/**
 * Reset the status of all the nodes in a tree, forcing them to all be evaulated again.
 */
void flush_sexp_tree(int node)
{
	if (node < 0){
		return;
	}

	Sexp_nodes[node].value = SEXP_UNKNOWN;
	flush_sexp_tree(Sexp_nodes[node].first);
	flush_sexp_tree(Sexp_nodes[node].rest);
}

int verify_sexp_tree(int node)
{
	if (node == -1){
		return 0;
	}

	if ((Sexp_nodes[node].type == SEXP_NOT_USED) ||
		(Sexp_nodes[node].first == node) ||
		(Sexp_nodes[node].rest == node)) {
		Error(LOCATION, "Sexp node is corrupt");
		return -1;
	}

	if (Sexp_nodes[node].first != -1){
		verify_sexp_tree(Sexp_nodes[node].first);
	}
	if (Sexp_nodes[node].rest != -1){
		verify_sexp_tree(Sexp_nodes[node].rest);
	}

	return 0;
}

/**
 * @todo CASE OF SEXP VARIABLES - ONLY 1 COPY OF VARIABLE
 */
int dup_sexp_chain(int node)
{
	int cur, first, rest;

	if (node == -1){
		return -1;
	}

	// TODO - CASE OF SEXP VARIABLES - ONLY 1 COPY OF VARIABLE
	first = dup_sexp_chain(Sexp_nodes[node].first);
	rest = dup_sexp_chain(Sexp_nodes[node].rest);
	cur = alloc_sexp(Sexp_nodes[node].text, Sexp_nodes[node].type, Sexp_nodes[node].subtype, first, rest);

	if (cur == -1) {
		if (first != -1){
			free_sexp(first);
		}
		if (rest != -1){
			free_sexp(rest);
		}
	}

	return cur;
}

/**
 * Compare SEXP chains
 * @return 1 if they are the same, 0 if different
 */
int cmp_sexp_chains(int node1, int node2)
{
	if ((node1 == -1) && (node2 == -1)){
		return 1;
	}

	if ((node1 == -1) || (node2 == -1)){
		return 0;
	}

	// DA: 1/7/99 Need to check the actual Sexp_node.text, not possible variable, which can be equal
	if (stricmp(Sexp_nodes[node1].text, Sexp_nodes[node2].text)){
		return 0;
	}

	if (!cmp_sexp_chains(Sexp_nodes[node1].first, Sexp_nodes[node2].first)){
		return 0;
	}

	if (!cmp_sexp_chains(Sexp_nodes[node1].rest, Sexp_nodes[node2].rest)){
		return 0;
	}

	return 1;
}

/**
 * Determine if an sexp node is within the given sexp chain.
 */
int query_node_in_sexp(int node, int sexp)
{
	if (sexp == -1){
		return 0;
	}
	if (node == sexp){
		return 1;
	}

	if (query_node_in_sexp(node, Sexp_nodes[sexp].first)){
		return 1;
	}
	if (query_node_in_sexp(node, Sexp_nodes[sexp].rest)){
		return 1;
	}

	return 0;
}

/**
 * Find the index of the list associated with an operator
 */
int find_sexp_list(int num)
{
	int i;

	for (i = 0; i < Num_sexp_nodes; i++)
	{
		if (Sexp_nodes[i].first == num)
			return i;
	}

	// not found
	return -1;
}

/**
 * Find node of operator that item is an argument of.
 */
int find_parent_operator(int node)
{
	int i;
	Assert((node >= 0) && (node < Num_sexp_nodes));

	if (Sexp_nodes[node].subtype == SEXP_ATOM_OPERATOR)
	{
		node = find_sexp_list(node);

		// are we already at the top of the list?  this will happen for non-standard sexps
		// (sexps that fire instantly instead of using a conditional) such as:
		// $Formula: ( do-nothing ) 
		if (node < 0)
			return -1;
	}

	// iterate backwards through the sexps nodes (i.e. do the inverse of CDR)
	while (Sexp_nodes[node].subtype != SEXP_ATOM_OPERATOR)
	{
		for (i = 0; i < Num_sexp_nodes; i++)
		{
			if (Sexp_nodes[i].rest == node)
				break;
		}

		if (i == Num_sexp_nodes)
			return -1;  // not found, probably at top node already.

		node = i;
	}

	return node;
}

/**
 * Determine if an sexpression node is the top level node of an sexpression tree.
 *
 * Top level nodes do not have their node id in anyone elses first or rest index.
 */
int is_sexp_top_level( int node )
{
	int i;

	Assert((node >= 0) && (node < Num_sexp_nodes));

	if (Sexp_nodes[node].type == SEXP_NOT_USED)
		return 0;

	for (i = 0; i < Num_sexp_nodes; i++)
	{
		if ((Sexp_nodes[i].type == SEXP_NOT_USED) || (i == node ))				// don't check myself or unused nodes
			continue;

		if ((Sexp_nodes[i].first == node) || (Sexp_nodes[i].rest == node))
			return 0;
	}

	return 1;
}

/**
 * Find argument number
 */
int find_argnum(int parent, int arg)
{
	int n, tally;

	n = CDR(parent);
	tally = 0;
	
	while (CAR(n) != arg)
	{
		if (n == -1)
			return -1;

		tally++;
		n = CDR(n);
	}

	return tally;
}

/**
 * From an operator name, return its index in the array Operators
 */
int get_operator_index(const char *token)
{
	int	i;
	Assertion(token != NULL, "get_operator_index(char*) called with a null token; get a coder!\n");

	for (i=0; i<Num_operators; i++){
		if (!stricmp(token, Operators[i].text)){
			return i;
		}
	}

	return NOT_A_SEXP_OPERATOR;
}

/**
 * From a sexp node, return the index in the array Operators or NOT_A_SEXP_OPERATOR if not an operator
 */
int get_operator_index(int node)
{
	Assertion(node >= 0 && node < Num_sexp_nodes, "Passed an out-of-range node index (%d) to get_operator_index(int)!", node);

	if (!Fred_running && (Sexp_nodes[node].op_index != NO_OPERATOR_INDEX_DEFINED) ) {
		return Sexp_nodes[node].op_index;
	}

	int index = get_operator_index(Sexp_nodes[node].text); 
	Sexp_nodes[node].op_index = index;
	return index;
}


/**
 * From an operator name, return its constant (the number it was define'd with)
 */
int get_operator_const(const char *token)
{
	int	idx = get_operator_index(token);

	if (idx == NOT_A_SEXP_OPERATOR)
		return 0;

	return Operators[idx].value;
}

int get_operator_const(int node)
{
	if (!Fred_running && Sexp_nodes[node].op_index >= 0) {
		return Operators[Sexp_nodes[node].op_index].value;
	}

	int	idx = get_operator_index(node);

	if (idx == NOT_A_SEXP_OPERATOR)
		return 0;

	return Operators[idx].value;
}

int query_sexp_args_count(int node, bool only_valid_args = false)
{
	int count = 0;
	int n = CDR(node);

	for ( ; n != -1; n = CDR(n))
	{
		if (only_valid_args && !(Sexp_nodes[n].flags & SNF_ARGUMENT_VALID))
			continue;

		count++;
	}

	return count;
}

/**
 * Needed to fix bug with sexps like send-message list which have arguments that need to be supplied as a block
 * 
 * @return 0 if the number of arguments for the supplied operation is wrong, 1 otherwise.
 */
int check_operator_argument_count(int count, int op)
{
	if (count < Operators[op].min || count > Operators[op].max)
		return 0;

	//send-message-list has arguments as blocks of 4
	if (op == OP_SEND_MESSAGE_LIST)
		if (count % 4 != 0)
			return 0;

	return 1;
}

/**
 * Check SEXP syntax
 * @return 0 if ok, negative if there's an error in expression..
 * See the returns types in sexp.h
 */
int check_sexp_syntax(int node, int return_type, int recursive, int *bad_node, int mode)
{
	int i = 0, z, t, type, argnum = 0, count, op, type2 = 0, op2;
	int op_node;
	int var_index = -1;
	size_t st;

	Assert(node >= 0 && node < Num_sexp_nodes);
	Assert(Sexp_nodes[node].type != SEXP_NOT_USED);
	if (Sexp_nodes[node].subtype == SEXP_ATOM_NUMBER && return_type == OPR_BOOL) {
		// special case Mark seems to want supported
		Assert(Sexp_nodes[node].first == -1);  // only lists should have a first pointer
		if (Sexp_nodes[node].rest != -1)  // anything after the number?
			return SEXP_CHECK_NONOP_ARGS; // if so, it's a syntax error

		return 0;
	}

	op_node = node;		// save the node of the operator since we need to get to other args.
	if (bad_node)
		*bad_node = op_node;

	if (Sexp_nodes[op_node].subtype != SEXP_ATOM_OPERATOR)
		return SEXP_CHECK_OP_EXPECTED;  // not an operator, which it should always be

	op = get_operator_index(CTEXT(op_node));
	if (op == -1)
		return SEXP_CHECK_UNKNOWN_OP;  // unrecognized operator

	// check that types match - except that OPR_AMBIGUOUS matches everything
	if (return_type != OPR_AMBIGUOUS)
	{
		// get the return type of the next thing
		z = query_operator_return_type(op);
		if (z == OPR_POSITIVE && return_type == OPR_NUMBER)
		{
			// positive data type can map to number data type just fine
		}
		// Goober5000's number hack
		else if (z == OPR_NUMBER && return_type == OPR_POSITIVE)
		{
			// this isn't kosher, but we hack it to make it work
		}
		else if (z != return_type)
		{
			// anything else is a mismatch
			return SEXP_CHECK_TYPE_MISMATCH;
		}
	}

	count = query_sexp_args_count(op_node);

	if (!check_operator_argument_count(count, op))
		return SEXP_CHECK_BAD_ARG_COUNT;  // incorrect number of arguments

	// Goober5000 - if this is a list of stuff that has the special argument as
	// an item in the list, assume it's valid
	if (special_argument_appears_in_sexp_list(op_node))
		return 0;

	node = Sexp_nodes[op_node].rest;
	while (node != -1) {
		type = query_operator_argument_type(op, argnum);
		Assert(Sexp_nodes[node].type != SEXP_NOT_USED);
		if (bad_node)
			*bad_node = node;

		if (Sexp_nodes[node].subtype == SEXP_ATOM_LIST) {
			i = Sexp_nodes[node].first;
			if (bad_node)
				*bad_node = i;
			
			// be sure to check to see if this node is a list of stuff and not an actual operator type
			// thing.  (i.e. in the case of a cond statement, the conditional will fall into this if
			// statement.  MORE TO DO HERE!!!!
			if (Sexp_nodes[i].subtype == SEXP_ATOM_LIST)
				return 0;

			op2 = get_operator_index(CTEXT(i));
			if (op2 == -1)
				return SEXP_CHECK_UNKNOWN_OP;

			type2 = query_operator_return_type(op2);
			if (recursive) {
				switch (type) {
					case OPF_NUMBER:
						t = OPR_NUMBER;
						break;

					case OPF_POSITIVE:
						t = OPR_POSITIVE;
						break;

					case OPF_BOOL:
						t = OPR_BOOL;
						break;

					case OPF_NULL:
						t = OPR_NULL;
						break;

					// Goober5000
					case OPF_FLEXIBLE_ARGUMENT:
						t = OPR_FLEXIBLE_ARGUMENT;
						break;

					case OPF_AI_GOAL:
						t = OPR_AI_GOAL;
						break;

					// special case for modify-variable
					case OPF_AMBIGUOUS:
						t = OPR_AMBIGUOUS;
						break;

					default:
						return SEXP_CHECK_UNKNOWN_TYPE;  // no other return types available
				}

				if ((z = check_sexp_syntax(i, t, recursive, bad_node)) != 0) {
					return z;
				}
			}

		} else if (Sexp_nodes[node].subtype == SEXP_ATOM_NUMBER) {
			char *ptr;

			type2 = OPR_POSITIVE;
			ptr = CTEXT(node);
			if (*ptr == '-') {
				type2 = OPR_NUMBER;
				ptr++;
			}

			if (type == OPF_BOOL)  // allow numbers to be used where boolean is required.
				type2 = OPR_BOOL;

			while (*ptr) {
				if (!isdigit(*ptr))
					return SEXP_CHECK_INVALID_NUM;  // not a valid number

				ptr++;
			}

			i = atoi(CTEXT(node));
			z = get_operator_const(CTEXT(op_node));
			if ( (z == OP_HAS_DOCKED_DELAY) || (z == OP_HAS_UNDOCKED_DELAY) )
				if ( (argnum == 2) && (i < 1) )
					return SEXP_CHECK_NUM_RANGE_INVALID;

			// valid color range 0 to 255 - FUBAR
			if ((z == OP_CHANGE_IFF_COLOR)  && ((argnum >= 2) && (argnum <= 4)))
			{
				if ( i < 0 || i > 255) 
				{
					return SEXP_CHECK_NUM_RANGE_INVALID;
				}
			}

			z = get_operator_index(CTEXT(op_node));
			if ( (query_operator_return_type(z) == OPR_AI_GOAL) && (argnum == Operators[op].min - 1) )
				if ( (i < 0) || (i > 200) )
					return SEXP_CHECK_NUM_RANGE_INVALID;

		} else if (Sexp_nodes[node].subtype == SEXP_ATOM_STRING) {
			type2 = SEXP_ATOM_STRING;

		} else {
			Assert(0);
		}

		// variables should only be typechecked. 
		if ((Sexp_nodes[node].type & SEXP_FLAG_VARIABLE) && (type != OPF_VARIABLE_NAME)) {
			var_index = get_index_sexp_variable_from_node(node);
			Assert(var_index != -1);
	
			switch (type) {
				case OPF_NUMBER:
				case OPF_POSITIVE:
					if (!(Sexp_variables[var_index].type & SEXP_VARIABLE_NUMBER)) 
						return SEXP_CHECK_INVALID_VARIABLE_TYPE; 
				break;

                case OPF_AMBIGUOUS:
                    break;

				default: 
					if (!(Sexp_variables[var_index].type & SEXP_VARIABLE_STRING)) 
						return SEXP_CHECK_INVALID_VARIABLE_TYPE; 
			}			
			node = Sexp_nodes[node].rest;
			argnum++;
			continue; 
		}

		switch (type) {
			case OPF_NAV_POINT:
				if (type2 != SEXP_ATOM_STRING){
					return SEXP_CHECK_TYPE_MISMATCH;
				}
				break;

			case OPF_NUMBER:
				if ((type2 != OPR_NUMBER) && (type2 != OPR_POSITIVE)){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				break;

			case OPF_POSITIVE:
				if (type2 == OPR_NUMBER){
					// Goober5000's number hack
					break;
					// return SEXP_CHECK_NEGATIVE_NUM;
				}

				if (type2 != OPR_POSITIVE){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				break;

			case OPF_SHIP_NOT_PLAYER:
				if (type2 != SEXP_ATOM_STRING){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (ship_name_lookup(CTEXT(node), 0) < 0)
				{
					if (Fred_running || !mission_parse_get_arrival_ship(CTEXT(node)))
					{
						return SEXP_CHECK_INVALID_SHIP;
					}
				}

				break;

			case OPF_SHIP_OR_NONE:
				if (type2 != SEXP_ATOM_STRING)
				{
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (stricmp(CTEXT(node), SEXP_NONE_STRING))		// none is okay
				{
					if (ship_name_lookup(CTEXT(node), 1) < 0)
					{
						if (Fred_running || !mission_parse_get_arrival_ship(CTEXT(node)))
						{
							return SEXP_CHECK_INVALID_SHIP;
						}
					}
				}

				break;

			case OPF_SHIP:
			case OPF_SHIP_POINT:
				if (type2 != SEXP_ATOM_STRING){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (ship_name_lookup(CTEXT(node), 1) < 0) {
					if (Fred_running || !mission_parse_get_arrival_ship(CTEXT(node)))
					{
						if (type == OPF_SHIP)
						{													// return invalid ship if not also looking for point
							return SEXP_CHECK_INVALID_SHIP;
						}

						if (find_matching_waypoint(CTEXT(node)) == NULL)
						{
							if (verify_vector(CTEXT(node)))					// verify return non-zero on invalid point
							{
								return SEXP_CHECK_INVALID_POINT;
							}
						}
					}
				}

				break;

			case OPF_WING:
				if (type2 != SEXP_ATOM_STRING){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (wing_name_lookup(CTEXT(node), 1) < 0){
					return SEXP_CHECK_INVALID_WING;
				}

				break;

			case OPF_SHIP_WING:
			case OPF_SHIP_WING_WHOLETEAM:
			case OPF_SHIP_WING_SHIPONTEAM_POINT:
			case OPF_SHIP_WING_POINT:
			case OPF_SHIP_WING_POINT_OR_NONE:
			case OPF_ORDER_RECIPIENT:
				if ( type2 != SEXP_ATOM_STRING ){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (type == OPF_ORDER_RECIPIENT) {
					if (!strcmp ("<all fighters>", CTEXT(node))) {
						break;
					}
				}

				// all of these have ships and wings in common
				if (ship_name_lookup(CTEXT(node), 1) >= 0 || wing_name_lookup(CTEXT(node), 1) >= 0) {
					break;
				}
				// also check arrival list if we're running the game
				if (!Fred_running && mission_parse_get_arrival_ship(CTEXT(node))) {
					break;
				}

				// none is okay for _OR_NONE
				if (type == OPF_SHIP_WING_POINT_OR_NONE && !stricmp(CTEXT(node), SEXP_NONE_STRING))	{
					break;
				}

				// two different ways of checking teams
				if ((type == OPF_SHIP_WING_WHOLETEAM) && iff_lookup(CTEXT(node)) >= 0) {
					break;
				}
				if ((type == OPF_SHIP_WING_SHIPONTEAM_POINT) && sexp_determine_team(CTEXT(node)) >= 0)	{
					break;
						}

				// only other possibility is waypoints
				if (type == OPF_SHIP_WING_SHIPONTEAM_POINT || type == OPF_SHIP_WING_POINT || type == OPF_SHIP_WING_POINT_OR_NONE) {
						if (find_matching_waypoint(CTEXT(node)) == NULL){
							if (verify_vector(CTEXT(node))){  // non-zero on verify vector mean invalid!
									return SEXP_CHECK_INVALID_POINT;
								}
							}
					break;
				}

				// nothing left
				return SEXP_CHECK_INVALID_SHIP_WING;

			case OPF_AWACS_SUBSYSTEM:
			case OPF_ROTATING_SUBSYSTEM:
			case OPF_SUBSYSTEM:
			case OPF_SUBSYSTEM_OR_NONE:
			case OPF_SUBSYS_OR_GENERIC:
			{
				char *shipname;
				int shipnum,ship_class;
				int ship_index;				

				if (type2 != SEXP_ATOM_STRING){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				// none is okay for subsys_or_none
				if (type == OPF_SUBSYSTEM_OR_NONE && !stricmp(CTEXT(node), SEXP_NONE_STRING))
				{
					break;
				}

				//  subsys_or_generic has a few extra options it accepts
				if (type == OPF_SUBSYS_OR_GENERIC && (!(stricmp(CTEXT(node), SEXP_ALL_ENGINES_STRING)) || !(stricmp(CTEXT(node), SEXP_ALL_TURRETS_STRING)) )) {
					break;
				}

				// we must get the model of the ship that is part of this sexpression and find a subsystem
				// with that name.  This code assumes by default that the ship is *always* the first name
				// in the sexpression.  If this is ever not the case, the code here must be changed to
				// get the correct ship name.
				switch(get_operator_const(CTEXT(op_node)))
				{
					case OP_CAP_SUBSYS_CARGO_KNOWN_DELAY:
					case OP_DISTANCE_SUBSYSTEM:
					case OP_SET_CARGO:
					case OP_IS_CARGO:
					case OP_CHANGE_AI_CLASS:
					case OP_IS_AI_CLASS:
					case OP_MISSILE_LOCKED:
					case OP_SHIP_SUBSYS_GUARDIAN_THRESHOLD:
						ship_index = CDR(CDR(op_node));
						break;

					case OP_BEAM_FIRE:
						if(argnum == 1){
							ship_index = CDR(op_node);
						} else {
							ship_index = CDR(CDR(CDR(op_node)));
						}
						break;

					case OP_BEAM_FLOATING_FIRE:
						ship_index = CDDDDDR(CDDR(op_node));
						break;

					case OP_QUERY_ORDERS:
						ship_index = CDR(CDR(CDR(CDR(op_node))));
						break;
	
					case OP_WEAPON_CREATE:
						ship_index = CDDDDDR(CDDDDR(op_node));
						break;

					default :
						ship_index = CDR(op_node);
						break;
				}

				shipname = CTEXT(ship_index);
				shipnum = ship_name_lookup(shipname, 1);
				if (shipnum >= 0)
				{
					ship_class = Ships[shipnum].ship_info_index;
				}
				else
				{
					// must try to find the ship in the arrival list
					p_object *p_objp = mission_parse_get_arrival_ship(shipname);

					if (!p_objp)
					{
						if (type == OPF_SUBSYSTEM_OR_NONE)
							break;
						else
							return SEXP_CHECK_INVALID_SHIP;
					}

					ship_class = p_objp->ship_class;
				}

				// check for the special "hull" value
				if ( (Operators[op].value == OP_SABOTAGE_SUBSYSTEM) || (Operators[op].value == OP_REPAIR_SUBSYSTEM) || (Operators[op].value == OP_SET_SUBSYSTEM_STRNGTH) || (Operators[op].value == OP_SET_ARMOR_TYPE) || (Operators[op].value == OP_BEAM_FIRE)) {
					if ( !stricmp( CTEXT(node), SEXP_HULL_STRING) || !stricmp( CTEXT(node), SEXP_SIM_HULL_STRING) ){
						break;
					}
				}
				// check for special "shields" value for armor types
				if (Operators[op].value == OP_SET_ARMOR_TYPE) {
					if ( !stricmp( CTEXT(node), SEXP_SHIELD_STRING) || !stricmp( CTEXT(node), SEXP_SIM_HULL_STRING) ){
						break;
					}
				}

				for (i=0; i<Ship_info[ship_class].n_subsystems; i++)
				{
					if (!subsystem_stricmp(Ship_info[ship_class].subsystems[i].subobj_name, CTEXT(node)))
					{
						break;
					}
				}

				if (i == Ship_info[ship_class].n_subsystems)
				{
					return SEXP_CHECK_INVALID_SUBSYS;
				}

				if(Fred_running)
				{
					// if we're checking for an AWACS subsystem and this is not an awacs subsystem
					if((type == OPF_AWACS_SUBSYSTEM) && !(Ship_info[ship_class].subsystems[i].flags & MSS_FLAG_AWACS))
					{
						return SEXP_CHECK_INVALID_SUBSYS;
					}

					// rotating subsystem, like above - Goober5000
					if ((type == OPF_ROTATING_SUBSYSTEM) && !(Ship_info[ship_class].subsystems[i].flags & MSS_FLAG_ROTATES))
					{
						return SEXP_CHECK_INVALID_SUBSYS;
					}
				}

				break;
			}

			case OPF_SUBSYSTEM_TYPE:
				for (i = 0; i < SUBSYSTEM_MAX; i++)
				{
					if (!stricmp(CTEXT(node), Subsystem_types[i]))
						break;
				}

				if (i == SUBSYSTEM_MAX)
					return SEXP_CHECK_INVALID_SUBSYS_TYPE;

				break;

			case OPF_POINT:
				if (type2 != SEXP_ATOM_STRING)
				{
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (find_matching_waypoint(CTEXT(node)) == NULL)
				{
					if (verify_vector(CTEXT(node)))
					{
						return SEXP_CHECK_INVALID_POINT;
					}
				}

				break;

			case OPF_IFF:
				if (type2 != SEXP_ATOM_STRING)
				{
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (iff_lookup(CTEXT(node)) < 0)
				{
					return SEXP_CHECK_INVALID_IFF;
				}

				break;

			case OPF_AI_CLASS:
				if (type2 != SEXP_ATOM_STRING)
				{
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				for (i=0; i<Num_ai_classes; i++)
				{
					if (!stricmp(Ai_class_names[i], CTEXT(node)))
					{
						break;
					}
				}

				if (i == Num_ai_classes)
				{
					return SEXP_CHECK_INVALID_AI_CLASS;
				}

				break;

			case OPF_ARRIVAL_LOCATION:
				if (type2 != SEXP_ATOM_STRING)
				{
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				for (i=0; i<MAX_ARRIVAL_NAMES; i++)
				{
					if (!stricmp(Arrival_location_names[i], CTEXT(node)))
					{
						break;
					}
				}

				if (i == MAX_ARRIVAL_NAMES)
				{
					return SEXP_CHECK_INVALID_ARRIVAL_LOCATION;
				}

				break;

			case OPF_DEPARTURE_LOCATION:
				if (type2 != SEXP_ATOM_STRING)
				{
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				for (i=0; i<MAX_DEPARTURE_NAMES; i++)
				{
					if (!stricmp(Departure_location_names[i], CTEXT(node)))
					{
						break;
					}
				}

				if (i == MAX_DEPARTURE_NAMES)
				{
					return SEXP_CHECK_INVALID_DEPARTURE_LOCATION;
				}

				break;

			case OPF_ARRIVAL_ANCHOR_ALL:
				if (type2 != SEXP_ATOM_STRING)
				{
					return SEXP_CHECK_TYPE_MISMATCH;
				}
				else
				{
					int get_special_anchor(char *name);
					int valid = 0;

					// <any friendly>, etc.
					if (get_special_anchor(CTEXT(node)) >= 0)
					{
						valid = 1;
					}

					if (ship_name_lookup(CTEXT(node), 1) >= 0)
					{
						valid = 1;
					}

					if (!Fred_running && mission_parse_get_arrival_ship(CTEXT(node)))
					{
						valid = 1;
					}

					if (!valid)
					{
						return SEXP_CHECK_INVALID_ARRIVAL_ANCHOR_ALL;
					}
				}

				break;

			case OPF_SOUNDTRACK_NAME:
				if (type2 != SEXP_ATOM_STRING){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (!stricmp(CTEXT(node), "<No Music>"))
					break;

				if (Cmdline_freespace_no_music)
					break;

				for (i=0; i<Num_soundtracks; i++)
				{
					if (!stricmp(CTEXT(node), Soundtracks[i].name))
					{
						break;
					}
				}

				if (i == Num_soundtracks)
					return SEXP_CHECK_INVALID_SOUNDTRACK_NAME;

				break;

			case OPF_SHIP_WITH_BAY:
			{
				char *name = CTEXT(node);
				p_object *p_objp;
				int shipnum = -1;

				if (type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;

				if (!stricmp(name, "<no anchor>"))
					break;

				shipnum = ship_name_lookup(name, 1);
				if (shipnum < 0)
				{
					if (Fred_running)
						return SEXP_CHECK_INVALID_SHIP;

					p_objp = mission_parse_get_arrival_ship(name);
					if (p_objp == NULL)
						return SEXP_CHECK_INVALID_SHIP;

					// Goober5000 - since we can't check POFs for ships which have yet to arrive
					// (not without a bit of work anyway), just assume they're okay
					break;
				}

				// ship exists at this point

				// now determine if this ship has a docking bay
				if (!ship_has_dock_bay(shipnum))
					return SEXP_CHECK_INVALID_SHIP_WITH_BAY;

				break;
			}

			case OPF_SUPPORT_SHIP_CLASS:
				if (type2 != SEXP_ATOM_STRING){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (!stricmp(CTEXT(node), "<species support ship class>"))
					break;

				if (!stricmp(CTEXT(node), "<any support ship class>"))
					break;

				i = -1;
				for ( auto it = Ship_info.cbegin(); it != Ship_info.cend(); ++it ) {
					if ( !stricmp(CTEXT(node), it->name) )
					{
						if (it->flags & SIF_SUPPORT)
						{
							i = std::distance(Ship_info.cbegin(), it);
							break;
						}
					}
				}

				if ( i == -1 )
					return SEXP_CHECK_INVALID_SUPPORT_SHIP_CLASS;

				break;

			case OPF_BOOL:
				if (type2 != OPR_BOOL){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				break;

			case OPF_AI_ORDER:
				if ( type2 != SEXP_ATOM_STRING ){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				break;

			case OPF_NULL:
				if (type2 != OPR_NULL){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				break;

			case OPF_SSM_CLASS:
				if ( type2 != SEXP_ATOM_STRING ) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (ssm_info_lookup(CTEXT(node)) < 0) {
					return SEXP_CHECK_INVALID_SSM_CLASS;
				}

				break;

			// Goober5000
			case OPF_FLEXIBLE_ARGUMENT:
				if (type2 != OPR_FLEXIBLE_ARGUMENT) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}
				break;

			// Goober5000
			case OPF_ANYTHING:
				break;

			case OPF_AI_GOAL:
				if (type2 != OPR_AI_GOAL){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (Fred_running) {
					int ship_num, ship2, w = 0;

					// if it's the "goals" operator, this is part of initial orders, so just assume it's okay
					if (get_operator_const(Sexp_nodes[op_node].text) == OP_GOALS_ID) {
						break;
					}

					ship_num = ship_name_lookup(CTEXT(Sexp_nodes[op_node].rest), 1);	// Goober5000 - include players
					if (ship_num < 0) {
						w = wing_name_lookup(CTEXT(Sexp_nodes[op_node].rest));
						if (w < 0) {
							if (bad_node){
								*bad_node = Sexp_nodes[op_node].rest;
							}

							return SEXP_CHECK_INVALID_SHIP;  // should have already been caught earlier, but just in case..
						}
					}

					Assert(Sexp_nodes[node].subtype == SEXP_ATOM_LIST);
					z = Sexp_nodes[node].first;
					Assert(Sexp_nodes[z].subtype != SEXP_ATOM_LIST);
					z = get_operator_const(CTEXT(z));
					if (ship_num >= 0) {
						if (!query_sexp_ai_goal_valid(z, ship_num)){
							return SEXP_CHECK_ORDER_NOT_ALLOWED;
						}

					} else {
						for (i=0; i<Wings[w].wave_count; i++){
							if (!query_sexp_ai_goal_valid(z, Wings[w].ship_index[i])){
								return SEXP_CHECK_ORDER_NOT_ALLOWED;
							}
						}
					}

					if ((z == OP_AI_DOCK) && (Sexp_nodes[node].rest >= 0)) {
						ship2 = ship_name_lookup(CTEXT(Sexp_nodes[node].rest), 1);	// Goober5000 - include players
						if ((ship_num < 0) || !ship_docking_valid(ship_num, ship2)){
							return SEXP_CHECK_DOCKING_NOT_ALLOWED;
						}
					}
				}

				// we should check the syntax of the actual goal!!!!
				z = Sexp_nodes[node].first;
				if ((z = check_sexp_syntax(z, OPR_AI_GOAL, recursive, bad_node)) != 0){
					return z;
				}

				break;

			case OPF_SHIP_TYPE:
				if (type2 != SEXP_ATOM_STRING){
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				i = ship_type_name_lookup(CTEXT(node));

				if (i < 0){
					return SEXP_CHECK_INVALID_SHIP_TYPE;
				}

				break;

			case OPF_WAYPOINT_PATH:
				if (find_matching_waypoint_list(CTEXT(node)) == NULL) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}
				break;

			case OPF_MESSAGE:
				if (type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;

				if (Fred_running) {
					for (i=0; i<Num_messages; i++)
						if (!stricmp(Messages[i].name, CTEXT(node)))
							break;

					if (i == Num_messages)
						return SEXP_CHECK_UNKNOWN_MESSAGE;
				}
				
				break;

			case OPF_PRIORITY: {
				if (type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;

				if (Fred_running) {  // should still check in Fred though..
					char *name;

					name = CTEXT(node);
					if (!stricmp(name, "low") || !stricmp(name, "normal") || !stricmp(name, "high"))
						break;

					return SEXP_CHECK_INVALID_PRIORITY;
				}

				break;
			}

			case OPF_MISSION_NAME:
				if (type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;

				if (Fred_running) {
					if (mode == SEXP_MODE_CAMPAIGN) {
						for (i=0; i<Campaign.num_missions; i++)
							if (!stricmp(CTEXT(node), Campaign.missions[i].name)) {
								if ((i != Sexp_useful_number) && (Campaign.missions[i].level >= Campaign.missions[Sexp_useful_number].level))
									return SEXP_CHECK_INVALID_LEVEL;

								break;
							}

						if (i == Campaign.num_missions)
							return SEXP_CHECK_INVALID_MISSION_NAME;

					} else {
						// mwa -- put the following if statement to prevent Fred errors for possibly valid
						// conditions.  We should do something else here!!!
						if ( (Operators[op].value == OP_PREVIOUS_EVENT_TRUE) || (Operators[op].value == OP_PREVIOUS_EVENT_FALSE) || (Operators[op].value == OP_PREVIOUS_EVENT_INCOMPLETE)
							|| (Operators[op].value == OP_PREVIOUS_GOAL_TRUE) || (Operators[op].value == OP_PREVIOUS_GOAL_FALSE) || (Operators[op].value == OP_PREVIOUS_GOAL_INCOMPLETE) )
							break;

						if (!(*Mission_filename) || stricmp(Mission_filename, CTEXT(node)))
							return SEXP_CHECK_INVALID_MISSION_NAME;
					}
				}

				break;

			case OPF_GOAL_NAME:
				if (type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;

				// we only need to check the campaign list if running in Fred and are in campaign mode.
				// otherwise, check the set of current goals
				if ( Fred_running && (mode == SEXP_MODE_CAMPAIGN) ) {
					z = find_parent_operator(node);
					Assert(z >= 0);
					z = Sexp_nodes[z].rest;  // first argument of operator should be mission name
					Assert(z >= 0);
					for (i=0; i<Campaign.num_missions; i++)
						if (!stricmp(CTEXT(z), Campaign.missions[i].name))
							break;

					// read the goal/event list from the mission file if both num_goals and num_events
					// are < 0
					if ((Campaign.missions[i].num_goals <= 0) && (Campaign.missions[i].num_events <= 0) )
						read_mission_goal_list(i);
					
					if (i < Campaign.num_missions) {
						for (t=0; t<Campaign.missions[i].num_goals; t++)
							if (!stricmp(CTEXT(node), Campaign.missions[i].goals[t].name))
								break;

						if (t == Campaign.missions[i].num_goals)
							return SEXP_CHECK_INVALID_GOAL_NAME;
					}
				} else {
					// MWA -- short circuit evaluation of these things for now.
					if ( (Operators[op].value == OP_PREVIOUS_GOAL_TRUE) || (Operators[op].value == OP_PREVIOUS_GOAL_FALSE) || (Operators[op].value == OP_PREVIOUS_GOAL_INCOMPLETE) )
						break;

					for (i=0; i<Num_goals; i++)
						if (!stricmp(CTEXT(node), Mission_goals[i].name))
							break;

					if (i == Num_goals)
						return SEXP_CHECK_INVALID_GOAL_NAME;
				}

				break;

			case OPF_EVENT_NAME:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				// like above checking for goals, check events in the campaign only if in Fred
				// and only if in campaign mode.  Otherwise, check the current set of events
				if ( Fred_running && (mode == SEXP_MODE_CAMPAIGN) ) {
					z = find_parent_operator(node);
					Assert(z >= 0);
					z = Sexp_nodes[z].rest;  // first argument of operator should be mission name
					Assert(z >= 0);
					for (i=0; i<Campaign.num_missions; i++)
						if (!stricmp(CTEXT(z), Campaign.missions[i].name))
							break;

					// read the goal/event list from the mission file if both num_goals and num_events
					// are < 0
					if ((Campaign.missions[i].num_goals <= 0) && (Campaign.missions[i].num_events <= 0) )
						read_mission_goal_list(i);
					
					if (i < Campaign.num_missions) {
						for (t=0; t<Campaign.missions[i].num_events; t++)
							if (!stricmp(CTEXT(node), Campaign.missions[i].events[t].name))
								break;

						if (t == Campaign.missions[i].num_events)
							return SEXP_CHECK_INVALID_EVENT_NAME;
					}
				} else {
					// MWA -- short circuit evaluation of these things for now.
					if ( (Operators[op].value == OP_PREVIOUS_EVENT_TRUE) || (Operators[op].value == OP_PREVIOUS_EVENT_FALSE) || (Operators[op].value == OP_PREVIOUS_EVENT_INCOMPLETE) )
						break;

					for ( i = 0; i < Num_mission_events; i++ ) {
						if ( !stricmp(CTEXT(node), Mission_events[i].name) )
							break;
					}
					if ( i == Num_mission_events )
						return SEXP_CHECK_INVALID_EVENT_NAME;
				}
				break;

			case OPF_DOCKER_POINT:
				if (type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;

				// This makes massive assumptions about the structure of the SEXP using it. If you add any 
				// new SEXPs that use this OPF, you will probably need to edit this section to accommodate them.
				if (Fred_running) {
					int ship_num, model;

					// Look for the node containing the docker ship as its first argument. For set-docked, we want 
					// the current SEXP. Otherwise (for ai-dock), we want its parent.
					if (get_operator_const(Sexp_nodes[op_node].text) == OP_SET_DOCKED) {
						z = op_node;
					}
					else {
						z = find_parent_operator(op_node);
					
						// if it's the "goals" operator, this is part of initial orders, so just assume it's okay
						if (get_operator_const(Sexp_nodes[z].text) == OP_GOALS_ID) {
							break;
						}
					}

					// look for the ship this goal is being assigned to
					ship_num = ship_name_lookup(CTEXT(Sexp_nodes[z].rest), 1);
					if (ship_num < 0) {
						if (bad_node)
							*bad_node = Sexp_nodes[z].rest;

						return SEXP_CHECK_INVALID_SHIP;  // should have already been caught earlier, but just in case..
					}

					model = Ship_info[Ships[ship_num].ship_info_index].model_num;
					z = model_get_num_dock_points(model);
					for (i=0; i<z; i++)
						if (!stricmp(CTEXT(node), model_get_dock_name(model, i)))
							break;

					if (i == z)
						return SEXP_CHECK_INVALID_DOCKER_POINT;
				}

				break;

			case OPF_DOCKEE_POINT:
				if (type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;

				// This makes massive assumptions about the structure of the SEXP using it. If you add any 
				// new SEXPs that use this OPF, you will probably need to edit this section to accommodate them.
				if (Fred_running) {
					int ship_num, model;

					// If we're using set-docked, we want to look up the ship from the third SEXP argument.
					if (get_operator_const(Sexp_nodes[op_node].text) == OP_SET_DOCKED) {
						//Navigate to the third argument
						z = op_node;
						for (i = 0; i < 3; i++)
							z = Sexp_nodes[z].rest;

						ship_num = ship_name_lookup(Sexp_nodes[z].text, 1);
					}
					else {
						ship_num = ship_name_lookup(CTEXT(Sexp_nodes[op_node].rest), 1);
					}

					if (ship_num < 0) {
						if (bad_node)
							*bad_node = Sexp_nodes[op_node].rest;

						return SEXP_CHECK_INVALID_SHIP;  // should have already been caught earlier, but just in case..
					}

					model = Ship_info[Ships[ship_num].ship_info_index].model_num;
					z = model_get_num_dock_points(model);
					for (i=0; i<z; i++)
						if (!stricmp(CTEXT(node), model_get_dock_name(model, i)))
							break;

					if (i == z)
						return SEXP_CHECK_INVALID_DOCKEE_POINT;
				}

				break;

			case OPF_WHO_FROM:
				if (type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;

				if (*CTEXT(node) != '#') {  // not a manual source?
					if ( stricmp(CTEXT(node), "<any wingman>"))  
						if ( stricmp(CTEXT(node), "<none>") ) // not a special token?
							if ((ship_name_lookup(CTEXT(node), TRUE) < 0) && (wing_name_lookup(CTEXT(node), 1) < 0))  // is it in the mission?
								if (Fred_running || !mission_parse_get_arrival_ship(CTEXT(node)))
									return SEXP_CHECK_INVALID_MSG_SOURCE;
				}

				break;

			//Karajorma
			case OPF_PERSONA:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				for (i=0; i < Num_personas ; i++) {
					if (!strcmp(CTEXT(node), Personas[i].name)) {
						break;
					}
				}

				if (i == Num_personas) {
					return SEXP_CHECK_INVALID_PERSONA_NAME; 
				}
				break;

			case OPF_MISSION_MOOD:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				for (i = 0; i < (int)Builtin_moods.size(); i++) {
					if (!strcmp(Builtin_moods[i].c_str(), CTEXT(node))) {
						break;
					}
				}

				if (i == (int)Builtin_moods.size()) {
					return SEXP_CHECK_INVALID_MISSION_MOOD;
				}

				break;

			case OPF_SHIP_FLAG:
				{
				bool found = false;
				for ( i = 0; i < MAX_OBJECT_FLAG_NAMES; i++) {
					if (!stricmp(Object_flag_names[i].flag_name, CTEXT(node))) {
						found = true;
						break;
					}
				}

				if (!found) {
					for ( i = 0; i < MAX_SHIP_FLAG_NAMES; i++) {
						if (!stricmp(Ship_flag_names[i].flag_name, CTEXT(node))) {
							found = true;
							break;
						}
					}
				}

				if (!found) {
					for ( i = 0; i < MAX_AI_FLAG_NAMES; i++) {
						if (!stricmp(Ai_flag_names[i].flag_name, CTEXT(node))) {
							found = true;
							break;
						}
					}
				}

				if (!found) {
					return SEXP_CHECK_INVALID_SHIP_FLAG;
				}

				break;
				}

			case OPF_TEAM_COLOR:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (!stricmp(CTEXT(node), "none"))
					break;

				if (Team_Colors.find(CTEXT(node)) == Team_Colors.end())
					return SEXP_CHECK_INVALID_TEAM_COLOR;
				
				break;

			case OPF_FONT:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				for (i = 0; i < Num_fonts; i++) {
					if (!stricmp(CTEXT(node), Fonts[i].filename)) {
						break;
					}
				}

				if (i == Num_fonts) {
					return SEXP_CHECK_INVALID_FONT;
				}
				break;
				
			case OPF_SOUND_ENVIRONMENT:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (stricmp(CTEXT(node), SEXP_NONE_STRING) && ds_eax_get_preset_id(CTEXT(node)) < 0) {
					return SEXP_CHECK_INVALID_SOUND_ENVIRONMENT;
				}
				break;

			case OPF_AUDIO_VOLUME_OPTION:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (audio_volume_option_lookup(CTEXT(node)) == -1)
					return SEXP_CHECK_INVALID_AUDIO_VOLUME_OPTION;
				break;

			case OPF_HUD_GAUGE:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (hud_gauge_type_lookup(CTEXT(node)) == -1)
					return SEXP_CHECK_INVALID_HUD_GAUGE;
				break;

			case OPF_SOUND_ENVIRONMENT_OPTION:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (sexp_sound_environment_option_lookup(CTEXT(node)) < 0) {
					return SEXP_CHECK_INVALID_SOUND_ENVIRONMENT_OPTION; 
				}
				break;

			case OPF_EXPLOSION_OPTION:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (sexp_explosion_option_lookup(CTEXT(node)) < 0) {
					return SEXP_CHECK_INVALID_EXPLOSION_OPTION; 
				}
				break;

			case OPF_KEYPRESS:
				if (type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;

				break;

			case OPF_CARGO:
			case OPF_STRING:
			case OPF_MESSAGE_OR_STRING:
				if (type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;
				break;

			case OPF_SKILL_LEVEL:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				for (i = 0; i < NUM_SKILL_LEVELS; i++) {
					if ( !stricmp(CTEXT(node), Skill_level_names(i, 0)) )
						break;
				}
				if ( i == NUM_SKILL_LEVELS )
					return SEXP_CHECK_INVALID_SKILL_LEVEL;
				break;

			case OPF_MEDAL_NAME:
				if ( type2 != SEXP_ATOM_STRING)
					return SEXP_CHECK_TYPE_MISMATCH;

				for (i = 0; i < Num_medals; i++) {
					if ( !stricmp(CTEXT(node), Medals[i].name) )
						break;
				}

				if ( i == Num_medals )
					return SEXP_CHECK_INVALID_MEDAL_NAME;
				break;

			case OPF_HUGE_WEAPON:
			case OPF_WEAPON_NAME:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				for (i = 0; i < Num_weapon_types; i++ ) {
					if ( !stricmp(CTEXT(node), Weapon_info[i].name) )
						break;
				}

				if ( i == Num_weapon_types )
					return SEXP_CHECK_INVALID_WEAPON_NAME;

				// we need to be sure that for huge weapons, the WIF_HUGE flag is set
				if ( type == OPF_HUGE_WEAPON ) {
					if ( !(Weapon_info[i].wi_flags & WIF_HUGE) )
						return SEXP_CHECK_INVALID_WEAPON_NAME;
				}

				break;

			// Goober5000
			case OPF_INTEL_NAME:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				for (i = 0; i < Intel_info_size; i++ ) {
					if ( !stricmp(CTEXT(node), Intel_info[i].name) )
						break;
				}

				if ( i == Intel_info_size )
					return SEXP_CHECK_INVALID_INTEL_NAME;
				
				break;

			case OPF_TURRET_TARGET_ORDER:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				for (i = 0; i < NUM_TURRET_ORDER_TYPES; i++ ) {
					if ( !stricmp(CTEXT(node), Turret_target_order_names[i]) )
						break;
				}

				if ( i == NUM_TURRET_ORDER_TYPES )
					return SEXP_CHECK_INVALID_TURRET_TARGET_ORDER;
				
				break;

			case OPF_ARMOR_TYPE:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				if (!stricmp(CTEXT(node), SEXP_NONE_STRING))
					break;

				for (st = 0; st < Armor_types.size(); st++ ) {
					if ( !stricmp(CTEXT(node), Armor_types[st].GetNamePtr()) )
						break;
				}

				if ( st == Armor_types.size() )
					return SEXP_CHECK_INVALID_ARMOR_TYPE;
				
				break;

			case OPF_DAMAGE_TYPE:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				if (!stricmp(CTEXT(node), SEXP_NONE_STRING))
					break;

				for (st = 0; st < Damage_types.size(); st++ ) {
					if ( !stricmp(CTEXT(node), Damage_types[st].name) )
						break;
				}

				if ( st == Damage_types.size() )
					return SEXP_CHECK_INVALID_DAMAGE_TYPE;
				
				break;

			case OPF_ANIMATION_TYPE:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				i = model_anim_match_type(CTEXT(node));
				if ( i == TRIGGER_TYPE_NONE )
					return SEXP_CHECK_INVALID_ANIMATION_TYPE;

				break;
	
			case OPF_TARGET_PRIORITIES:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;
	
				for(st = 0; st < Ai_tp_list.size(); st++) {
					if ( !stricmp(CTEXT(node), Ai_tp_list[st].name) )
						break;
				}

				if ( st == Ai_tp_list.size() )
					return SEXP_CHECK_INVALID_TARGET_PRIORITIES;
				
				break;
	
			case OPF_SHIP_CLASS_NAME:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				if (ship_info_lookup(CTEXT(node)) < 0)
					return SEXP_CHECK_INVALID_SHIP_CLASS_NAME;

				break;

			case OPF_HUD_GAUGE_NAME:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				for ( i = 0; i < NUM_HUD_GAUGES; i++ ) {
					if ( !stricmp(CTEXT(node), HUD_gauge_text[i]) )
						break;
				}

				// if we reached the end of the list, then the name is invalid
				if ( i == NUM_HUD_GAUGES )
					return SEXP_CHECK_INVALID_GAUGE_NAME;
				
				break;

			case OPF_SKYBOX_MODEL_NAME:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				if ( stricmp(CTEXT(node), NOX("default")) && !strstr(CTEXT(node), NOX(".pof")) )
					return SEXP_CHECK_INVALID_SKYBOX_NAME;

				break;

			case OPF_SKYBOX_FLAGS:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				for ( i = 0; i < Num_skybox_flags; ++i ) {
					if ( !stricmp( CTEXT(node), Skybox_flags[i]) )
						break;
				}

				// if we reached the end of the list, then the flag is invalid
				if ( i == Num_skybox_flags )
					return SEXP_CHECK_INVALID_SKYBOX_FLAG;

				break;

			case OPF_JUMP_NODE_NAME:
				if ( type2 != SEXP_ATOM_STRING )
					return SEXP_CHECK_TYPE_MISMATCH;

				if (jumpnode_get_by_name(CTEXT(node)) == NULL)
					return SEXP_CHECK_INVALID_JUMP_NODE;

				break;


			case OPF_VARIABLE_NAME:
				var_index = get_index_sexp_variable_from_node(node);
				if ( var_index  == -1) {
					return SEXP_CHECK_INVALID_VARIABLE;
				}

				switch (Operators[op].value)
				{
					// some SEXPs demand a number variable
					case OP_ADD_BACKGROUND_BITMAP:
					case OP_ADD_SUN_BITMAP:
						if (!(Sexp_variables[var_index].type & SEXP_VARIABLE_NUMBER)) 
							return SEXP_CHECK_INVALID_VARIABLE_TYPE;
						break;

					// some demand a string variable
					case OP_STRING_CONCATENATE:
					case OP_INT_TO_STRING:
					case OP_STRING_GET_SUBSTRING:
					case OP_STRING_SET_SUBSTRING:
					case OP_SCRIPT_EVAL_STRING:
						if (!(Sexp_variables[var_index].type & SEXP_VARIABLE_STRING)) 
							return SEXP_CHECK_INVALID_VARIABLE_TYPE;
						break;

					default:
						break;
				}

				// otherwise anything goes
				break;

			case OPF_AMBIGUOUS:
				// type checking for modify-variable
				// string or number -- anything goes
				break;

			case OPF_BACKGROUND_BITMAP:
			case OPF_SUN_BITMAP:
			case OPF_NEBULA_STORM_TYPE:
			case OPF_NEBULA_POOF:
			case OPF_NEBULA_PATTERN:
			case OPF_POST_EFFECT:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}
				break;

			case OPF_HUD_ELEMENT:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				} else {
					char *gauge = CTEXT(node);
					if ( strcmp(SEXP_HUD_GAUGE_WARPOUT, gauge) == 0 ) {
						break;
					}
				}
				return SEXP_CHECK_INVALID_HUD_ELEMENT;

			case OPF_WEAPON_BANK_NUMBER:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (!stricmp(CTEXT(node), SEXP_ALL_BANKS_STRING)) {
					break;
				}

				// if we haven't specified all banks we need to check the number of the bank is legal
				else {
					int num_banks = atoi(CTEXT(node));
					if ((num_banks >= MAX_SHIP_PRIMARY_BANKS) && (num_banks >= MAX_SHIP_SECONDARY_BANKS)) {
						return SEXP_CHECK_NUM_RANGE_INVALID;
					}
				}
				break;

			case OPF_SHIP_EFFECT:
				if (type2 != SEXP_ATOM_STRING) {
					return SEXP_CHECK_TYPE_MISMATCH;
				}

				if (get_effect_from_name(CTEXT(node)) == -1 ) {
					return SEXP_CHECK_INVALID_SHIP_EFFECT;
				}
				break;

			case OPF_GAME_SND:
				if (type2 == SEXP_ATOM_NUMBER)
				{
					if (gamesnd_get_by_tbl_index(atoi(CTEXT(node))) < 0)
					{
						return SEXP_CHECK_NUM_RANGE_INVALID;
					}
				}
				else if (type2 == SEXP_ATOM_STRING)
				{
					if (stricmp(CTEXT(node), SEXP_NONE_STRING) && gamesnd_get_by_name(CTEXT(node)) < 0)
					{
						return SEXP_CHECK_INVALID_GAME_SND;
					}
				}
				break;

			default:
				Error(LOCATION, "Unhandled argument format");
		}

		node = Sexp_nodes[node].rest;
		argnum++;
	}

	return 0;
}

// Goober5000
void get_unformatted_sexp_variable_name(char *unformatted, char *formatted_pre)
{
	int end_index;
	char *formatted;

	// Goober5000 - trim @ if needed
	if (formatted_pre[0] == SEXP_VARIABLE_CHAR)
		formatted = formatted_pre+1;
	else
		formatted = formatted_pre;

	// get variable name (up to '['
	end_index = strcspn(formatted, "[");
	Assert( (end_index != 0) && (end_index < TOKEN_LENGTH-1) );
	strncpy(unformatted, formatted, end_index);
	unformatted[end_index] = '\0';
}

/**
 * Get text to stuff into Sexp_node in case of variable
 *
 * If Fred_running - stuff Sexp_variables[].variable_name
 * otherwise - stuff index into Sexp_variables array.
 */
void get_sexp_text_for_variable(char *text, char *token)
{
	int sexp_var_index;
	
	get_unformatted_sexp_variable_name(text, token);

	if ( !Fred_running ) {
		// freespace - get index into Sexp_variables array
		sexp_var_index = get_index_sexp_variable_name(text);
		Assert(sexp_var_index != -1);
		sprintf(text, "%d", sexp_var_index);
	}
}

// Goober5000
void do_preload_for_arguments(void (*preloader)(char *), int arg_node, int arg_handler_node)
{
	// we have a special argument
	if (!strcmp(Sexp_nodes[arg_node].text, SEXP_ARGUMENT_STRING))
	{
		int n;

		// we might not be handling it, either because this is not a *_of operator
		// or because we've disabled preloading for special arguments
		if (arg_handler_node < 0)
			return;

		// preload for each argument
		for (n = CDR(arg_handler_node); n != -1; n = CDR(n))
		{
			preloader(CTEXT(n));
		}
	}
	// we don't
	else
	{
		// preload for just the one argument
		preloader(CTEXT(arg_node));
	}
}

// Goober5000
void preload_change_ship_class(char *text)
{
	int idx;
	ship_info *sip;

	idx = ship_info_lookup(text);
	if (idx < 0)
		return;

	// preload the model, just in case there is no other ship of this class in the mission
	// (this eliminates the slight pause during a mission when changing to a previously unloaded model)
	sip = &Ship_info[idx];
	sip->model_num = model_load(sip->pof_file, sip->n_subsystems, &sip->subsystems[0]);

	if (sip->model_num >= 0)
		model_page_in_textures(sip->model_num, idx);
}

// Goober5000
void preload_turret_change_weapon(char *text)
{
	int idx;

	idx = weapon_info_lookup(text);
	if (idx < 0)
		return;

	weapon_mark_as_used(idx);
}

/**
 * Returns the first sexp index of data this function allocates. (start of this sexp)
 *
 * NOTE: On entry into this function, Mp points to the first character past the opening parenthesis.
 */
int get_sexp()
{
	int start, node, last, op, count;
	char token[TOKEN_LENGTH];
	char variable_text[TOKEN_LENGTH];

	Assert(*(Mp-1) == '(');

	// start - the node allocated in first instance of function
	// node - the node allocated in current instance of function
	// count - number of nodes allocated this instance of function [do we set last.rest or .first]
	// variable - whether string or number is a variable referencing Sexp_variables

	// initialization
	start = last = -1;
	count = 0;

	ignore_white_space();
	while (*Mp != ')') {
		// end of string or end of file
		if (*Mp == '\0' || *Mp == EOF_CHAR) {
			Error(LOCATION, "Unexpected end of sexp!");
			return -1;
		}

		// Sexp list
		if (*Mp == '(') {
			Mp++;
			node = alloc_sexp("", SEXP_LIST, SEXP_ATOM_LIST, get_sexp(), -1);
		}

		// Sexp string
		else if (*Mp == '\"') {
			int len = strcspn(Mp + 1, "\"");
			// was closing quote not found?
			if (*(Mp + 1 + len) != '\"') {
				Error(LOCATION, "Unexpected end of quoted string embedded in sexp!");
				return -1;
			}

			// check if string variable
			if ( *(Mp + 1) == SEXP_VARIABLE_CHAR ) {
				char variable_token[2*TOKEN_LENGTH+2];	// variable_token[contents_token]

				// reduce length by 1 for end \"
				int length = len - 1;
				if (length >= 2*TOKEN_LENGTH+2) {
					Error(LOCATION, "Variable token %s is too long. Needs to be %d characters or shorter.", Mp, 2*TOKEN_LENGTH+2 - 1);
					return -1;
				}

				// start copying after skipping 1st char (i.e. variable char)
				strncpy(variable_token, Mp + 2, length);
				variable_token[length] = 0;

				get_sexp_text_for_variable(variable_text, variable_token);
				node = alloc_sexp(variable_text, (SEXP_ATOM | SEXP_FLAG_VARIABLE), SEXP_ATOM_STRING, -1, -1);
			} else {
				// token is too long?
				if (len >= TOKEN_LENGTH) {
					Error(LOCATION, "Token %s is too long. Needs to be %d characters or shorter.", Mp, TOKEN_LENGTH - 1);
					return -1;
				}

				strncpy(token, Mp + 1, len);
				token[len] = 0;
				node = alloc_sexp(token, SEXP_ATOM, SEXP_ATOM_STRING, -1, -1);
			}

			// bump past closing \" by 1 char
			Mp += (len + 2);

		}

		// Sexp operator or number
		else {
			int len = 0;
			bool variable = false;
			while (*Mp != ')' && !is_white_space(*Mp)) {
				// numeric variable?
				if ( (len == 0) && (*Mp == SEXP_VARIABLE_CHAR) ) {
					variable = true;
					Mp++;
					continue;
				}

				// end of string or end of file?
				if (*Mp == '\0' || *Mp == EOF_CHAR) {
					Error(LOCATION, "Unexpected end of sexp!");
					return -1;
				}

				// token is too long?
				if (len >= TOKEN_LENGTH - 1) {
					token[TOKEN_LENGTH - 1] = '\0';
					Error(LOCATION, "Token %s is too long. Needs to be %d characters or shorter.", token, TOKEN_LENGTH - 1);
					return -1;
				}

				// build the token
				token[len++] = *Mp++;
			}
			token[len] = 0;

			// maybe replace deprecated names
			if (!stricmp(token, "set-ship-position"))
				strcpy_s(token, "set-object-position");
			else if (!stricmp(token, "set-ship-facing"))
				strcpy_s(token, "set-object-facing");
			else if (!stricmp(token, "set-ship-facing-object"))
				strcpy_s(token, "set-object-facing-object");
			else if (!stricmp(token, "ai-chase-any-except"))
				strcpy_s(token, "ai-chase-any");
			else if (!stricmp(token, "change-ship-model"))
				strcpy_s(token, "change-ship-class");
			else if (!stricmp(token, "radar-set-max-range"))
				strcpy_s(token, "hud-set-max-targeting-range");
			else if (!stricmp(token, "ship-subsys-vanished"))
				strcpy_s(token, "ship-subsys-vanish");
			else if (!stricmp(token, "directive-is-variable"))
				strcpy_s(token, "directive-value");
			else if (!stricmp(token, "variable-array-get"))
				strcpy_s(token, "get-variable-by-index");
			else if (!stricmp(token, "variable-array-set"))
				strcpy_s(token, "set-variable-by-index");

			op = get_operator_index(token);
			if (op >= 0) {
				node = alloc_sexp(token, SEXP_ATOM, SEXP_ATOM_OPERATOR, -1, -1);
			} else {
				if ( variable ) {
					// convert token text for variable
					get_sexp_text_for_variable(variable_text, token);

					node = alloc_sexp(variable_text, (SEXP_ATOM | SEXP_FLAG_VARIABLE), SEXP_ATOM_NUMBER, -1, -1);
				} else {
					node = alloc_sexp(token, SEXP_ATOM, SEXP_ATOM_NUMBER, -1, -1);
				}
			}
		}

		// update links
		if (count++) {
			Assert(last != -1);
			Sexp_nodes[last].rest = node;
		} else {
			start = node;
		}

		Assert(node != -1);  // ran out of nodes.  Time to raise the MAX!
		last = node;
		ignore_white_space();
	}

	Mp++;  // skip past the ')'

	
	// Goober5000 - backwards compatibility for removed ai-chase-any-except
	if (get_operator_const(CTEXT(start)) == OP_AI_CHASE_ANY)
	{
		// if there is more than one argument, free the extras
		int n = CDR(CDR(start));
		if (n >= 0)
		{
			// free the entire rest of the argument list
			free_sexp2(n);	
		}
	}

	// Goober5000 - preload stuff for certain sexps
	if (!Fred_running)
	{
		int n, parent, arg_handler = -1;

		// see if we're using special arguments
		parent = find_parent_operator(start);
		if (parent >= 0 && is_blank_argument_op(get_operator_const(CTEXT(parent))))
		{
			// get the first op of the parent, which should be a *_of operator
			arg_handler = CADR(parent);
			if (arg_handler >= 0 && !is_blank_of_op(get_operator_const(CTEXT(arg_handler))))
				arg_handler = -1;
		}

		// DISABLE ARGUMENT PRELOADING FOR NOW
		// see Mantis #925 for discussion
		// Also, the preloader will have to be moved to a different function (after the parsing is finished)
		// in order to work properly with special arguments.  The current node is an orphan until get_sexp
		// completes, at which time it will be linked into the sexp node list; this means that it is
		// impossible to get the parent node.
		arg_handler = -1;

		// preload according to sexp
		op = get_operator_const(CTEXT(start));
		switch (op)
		{
			case OP_CHANGE_SHIP_CLASS:
				// ship class is argument #1
				n = CDR(start);
				do_preload_for_arguments(preload_change_ship_class, n, arg_handler);
				break;

			case OP_SHIP_CREATE:
				// ship class is argument #2
				n = CDDR(start);
				// page in ship classes of dynamically created ships
				// preload_change_ship_class doesn't require a class change, so we can use that here -zookeeper
				do_preload_for_arguments(preload_change_ship_class, n, arg_handler);
				break;

			case OP_SET_SPECIAL_WARPOUT_NAME:
				// set flag for taylor
				Knossos_warp_ani_used = 1;
				break;

			case OP_MISSION_SET_NEBULA:
				// set flag for WMC
				Nebula_sexp_used = true;
				Dynamic_environment = true;
				break;
				
			case OP_MISSION_SET_SUBSPACE:
				Dynamic_environment = true;
				break;

			case OP_WARP_EFFECT:
				// type of warp is argument #11
				n = CDDDDDR(start);
				n = CDDDDDR(n);
				n = CDR(n);

				// set flag for taylor
				if (CAR(n) != -1 || !strcmp(Sexp_nodes[n].text, SEXP_ARGUMENT_STRING))	// if it's evaluating a sexp or a special argument
					Knossos_warp_ani_used = 1;												// set flag just in case
				else if (atoi(CTEXT(n)) == 1)											// if it's the Knossos type
					Knossos_warp_ani_used = 1;												// set flag for sure
				break;

			case OP_SET_SKYBOX_MODEL:
				// model is argument #1
				n = CDR(start);
				do_preload_for_arguments(sexp_set_skybox_model_preload, n, arg_handler);
				Dynamic_environment = true;
				break;

			case OP_TURRET_CHANGE_WEAPON:
				// weapon to change to is arg #3
				n = CDDDR(start);
				do_preload_for_arguments(preload_turret_change_weapon, n, arg_handler);
				break;

			case OP_ADD_SUN_BITMAP:
				n = CDR(start);
				do_preload_for_arguments(stars_preload_sun_bitmap, n, arg_handler);
				Dynamic_environment = true;
				break;

			case OP_ADD_BACKGROUND_BITMAP:
				n = CDR(start);
				do_preload_for_arguments(stars_preload_background_bitmap, n, arg_handler);
				Dynamic_environment = true;
				break;

			case OP_TECH_ADD_INTEL_XSTR:
				// do XSTR translation for each entry in the list
				// we don't use the do_preload function because the preloader needs to access two nodes at a time
				// also we're not using CTEXT or eval_num here because XSTR should really be constant, and
				// also because we can't really run sexp stuff in a preloader
				n = CDR(start);
				while (n >= 0)
				{
					if (CDR(n) < 0)
						break;

					int id = atoi(Sexp_nodes[CDR(n)].text);
					Assert(id < 10000000);
					char xstr[NAME_LENGTH + 20];
					sprintf(xstr, "XSTR(\"%s\", %d)", Sexp_nodes[n].text, id);

					memset(Sexp_nodes[n].text, 0, NAME_LENGTH*sizeof(char));
					lcl_ext_localize(xstr, Sexp_nodes[n].text, NAME_LENGTH - 1);

					n = CDDR(n);
				}
				break;
		}
	}

	return start;
}


/**
 * Stuffs a list of sexp variables
 */
int stuff_sexp_variable_list()
{	
	int count;
	char var_name[TOKEN_LENGTH];
	char default_value[TOKEN_LENGTH];
	char str_type[TOKEN_LENGTH];
	char persistent[TOKEN_LENGTH];
	char network[TOKEN_LENGTH];
	int index;
	int type;

	count = 0;
	required_string("$Variables:");
	ignore_white_space();

	// check for start of list
	if (*Mp != '(') {
        error_display(1, "Reading sexp variable list.  Found [%c].  Expecting '('.\n", *Mp);
        throw parse::ParseException("Syntax error");
	}

	Mp++;
	ignore_white_space();

	while (*Mp != ')') {
		Assert(count < MAX_SEXP_VARIABLES);

		// get index - for debug
		stuff_int(&index);
		ignore_gray_space();

		// get var_name
		get_string(var_name);
		ignore_gray_space();

		// get default_value;
		get_string(default_value);
		ignore_gray_space();

		// get type
		get_string(str_type);
		ignore_white_space();

		// determine type
		if (!stricmp(str_type, "number")) {
			type = SEXP_VARIABLE_NUMBER;
		} else if (!stricmp(str_type, "string")) {
			type = SEXP_VARIABLE_STRING;
		} else if (!stricmp(str_type, "block")) {
			// Goober5000 - This looks dangerous... these flags are needed for certain things, but it
			// looks like BLOCK_*_SIZE is the only thing that keeps a block from running off the end
			// of its boundary.
			type = SEXP_VARIABLE_BLOCK;
		} else {
			type = SEXP_VARIABLE_UNKNOWN;
			Error(LOCATION, "SEXP variable '%s' is an unknown type!", var_name);
		}

		// possibly get network-variable
		if (check_for_string("\"network-variable\"")) {
			// eat it
			get_string(network);
			ignore_white_space();

			// set type
			type |= SEXP_VARIABLE_NETWORK;
		}

		// possibly get player-persistent
		if (check_for_string("\"player-persistent\"")) {
			// eat it
			get_string(persistent);
			ignore_white_space();

			// set type
			type |= SEXP_VARIABLE_PLAYER_PERSISTENT;
		// possibly get campaign-persistent
		} else if (check_for_string("\"campaign-persistent\"")) {
			// eat it
			get_string(persistent);
			ignore_white_space();

			// set type
			type |= SEXP_VARIABLE_CAMPAIGN_PERSISTENT;
		// trap error
		} else if (check_for_string("\"")) {
			// eat garbage
			get_string(persistent);
			ignore_white_space();

			// notify of error
			Error(LOCATION, "Error parsing sexp variables - unknown persistence type encountered.  You can continue from here without trouble.");
		}

		// check if variable name already exists
		if ( (type & SEXP_VARIABLE_NUMBER) || (type & SEXP_VARIABLE_STRING) ) {
			Assert(get_index_sexp_variable_name(var_name) == -1);
		}

		if ( type & SEXP_VARIABLE_BLOCK ) {
			add_block_variable(default_value, var_name, type, index);
		}
		else {			
			count++;
			sexp_add_variable(default_value, var_name, type, index);
		}
	}

	Mp++;

	return count;
}

bool has_special_explosion_block_index(ship *shipp, int *index)
{
	int current_index;

	for ( current_index = (MAX_SEXP_VARIABLES - BLOCK_EXP_SIZE) ; current_index >= (MAX_SEXP_VARIABLES - (BLOCK_EXP_SIZE * Num_special_expl_blocks)) ; current_index = (current_index - BLOCK_EXP_SIZE) ) {
		if ( 
			(atoi(Block_variables[current_index+INNER_RAD].text) == shipp->special_exp_inner) &&
			(atoi(Block_variables[current_index+OUTER_RAD].text) == shipp->special_exp_outer) &&
			(atoi(Block_variables[current_index+DAMAGE].text) == shipp->special_exp_damage) &&
			(atoi(Block_variables[current_index+BLAST].text) == shipp->special_exp_blast) &&
			(atoi(Block_variables[current_index+PROPAGATE].text) == (shipp->use_shockwave ? 1:0) ) &&
			(atoi(Block_variables[current_index+SHOCK_SPEED].text) == shipp->special_exp_shockwave_speed)
			) {
				*index = current_index;
				return true;
		}
	}	

	// if we got here, this ship's special explosions aren't represented in the Block_variables array
	*index = current_index;
	return false;
}

bool generate_special_explosion_block_variables()
{
	ship *shipp; 
	ship_obj *sop;
	int current_index;
	bool already_added = false; 
	int num_sexp_variables;
	int i;

	// since we're (re)generating the block variable index, we don't start off with any block variables 
	Num_special_expl_blocks = 0;

	// get the number of sexp_variables we currently have. We must not try to add a block variable with an index below this.
	num_sexp_variables = sexp_variable_count();

	for ( sop = GET_FIRST(&Ship_obj_list); sop != END_OF_LIST(&Ship_obj_list); sop = GET_NEXT(sop) ) {
		shipp=&Ships[Objects[sop->objnum].instance];

		if (!(shipp->use_special_explosion)) {
			continue;
		}

		already_added = has_special_explosion_block_index(shipp, &current_index);

		// if we can't add an index for this add this ship to the list of those which failed
		if (current_index < num_sexp_variables) {
			// fail list code goes here
			continue;
		}

		//if we haven't added this entry already, do so
		if (!already_added) {
			sprintf(Block_variables[current_index+INNER_RAD].text, "%d", shipp->special_exp_inner);
			sprintf(Block_variables[current_index+OUTER_RAD].text, "%d", shipp->special_exp_outer);
			sprintf(Block_variables[current_index+DAMAGE].text, "%d", shipp->special_exp_damage);
			sprintf(Block_variables[current_index+BLAST].text, "%d", shipp->special_exp_blast);
			sprintf(Block_variables[current_index+PROPAGATE].text, "%d", (shipp->use_shockwave ? 1:0) );
			sprintf(Block_variables[current_index+SHOCK_SPEED].text, "%d", shipp->special_exp_shockwave_speed);

			// add the names
			for (i = current_index; i < (current_index + BLOCK_EXP_SIZE); i++ ) {
				sprintf(Block_variables[i].variable_name, "%s", shipp->ship_name); 
			}

			Num_special_expl_blocks++;
		}			
	}

	return true;
}

int num_block_variables()
{
	return Num_special_expl_blocks * BLOCK_EXP_SIZE;
}

/**
 * Stuff SEXP text string
 */
void stuff_sexp_text_string(SCP_string &dest, int node, int mode)
{
	Assert( (node >= 0) && (node < Num_sexp_nodes) );

	if (Sexp_nodes[node].type & SEXP_FLAG_VARIABLE) {

		int sexp_variables_index = get_index_sexp_variable_name(Sexp_nodes[node].text);
		Assertion(sexp_variables_index != -1, "Couldn't find variable: %s\n", Sexp_nodes[node].text);
		Assert( (Sexp_variables[sexp_variables_index].type & SEXP_VARIABLE_NUMBER) || (Sexp_variables[sexp_variables_index].type & SEXP_VARIABLE_STRING) );

		// number
		if (Sexp_nodes[node].subtype == SEXP_ATOM_NUMBER) {
			Assert(Sexp_variables[sexp_variables_index].type & SEXP_VARIABLE_NUMBER);
		
			// Error check - can be Fred or FreeSpace
			if (mode == SEXP_ERROR_CHECK_MODE) {
				if ( Fred_running ) {
					sprintf(dest, "%s[%s] ", Sexp_nodes[node].text, Sexp_variables[sexp_variables_index].text);
				} else {
					sprintf(dest, "%s[%s] ", Sexp_variables[sexp_variables_index].variable_name, Sexp_variables[sexp_variables_index].text);
				}
			} else {
				// Save as string - only  Fred
				Assert(mode == SEXP_SAVE_MODE);
				sprintf(dest, "@%s[%s] ", Sexp_nodes[node].text, Sexp_variables[sexp_variables_index].text);
			}
		} else {
			// string
			Assert(Sexp_nodes[node].subtype == SEXP_ATOM_STRING);
			Assert(Sexp_variables[sexp_variables_index].type & SEXP_VARIABLE_STRING);

			// Error check - can be Fred or FreeSpace
			if (mode == SEXP_ERROR_CHECK_MODE) {
				if ( Fred_running ) {
					sprintf(dest, "%s[%s] ", Sexp_variables[sexp_variables_index].variable_name, Sexp_variables[sexp_variables_index].text);
				} else {
					sprintf(dest, "%s[%s] ", Sexp_nodes[node].text, Sexp_variables[sexp_variables_index].text);
				}
			} else {
				// Save as string - only Fred
				Assert(mode == SEXP_SAVE_MODE);
				sprintf(dest, "\"@%s[%s]\" ", Sexp_nodes[node].text, Sexp_variables[sexp_variables_index].text);
			}
		}
	} else {
		// not a variable
		if (Sexp_nodes[node].subtype == SEXP_ATOM_STRING) {
			sprintf(dest, "\"%s\" ", CTEXT(node));
		} else {
			sprintf(dest, "%s ", CTEXT(node));
		}
	}
}

int build_sexp_string(SCP_string &accumulator, int cur_node, int level, int mode)
{
	SCP_string buf;
	int node, old_length = accumulator.length();

	accumulator += "( ";
	node = cur_node;
	while (node != -1) {
		Assert(node >= 0 && node < Num_sexp_nodes);
		if (Sexp_nodes[node].first == -1) {
			// build text to string
			stuff_sexp_text_string(buf, node, mode);
			accumulator += buf;

		} else {
			build_sexp_string(accumulator, Sexp_nodes[node].first, level + 1, mode);
		}

		node = Sexp_nodes[node].rest;
	}

	accumulator += ") ";
	if ((accumulator.length() - old_length) > 40) {
		accumulator.resize(old_length);
		build_extended_sexp_string(accumulator, cur_node, level, mode);
		return 1;
	}

	return 0;
}

void build_extended_sexp_string(SCP_string &accumulator, int cur_node, int level, int mode)
{
	SCP_string buf;
	int i, flag = 0, node;

	accumulator += "( ";
	node = cur_node;
	while (node != -1) {
		// not the first line?
		if (flag) {
			for (i=0; i<level + 1; i++)
				accumulator += "   ";
		}

		flag = 1;
		Assert(node >= 0 && node < Num_sexp_nodes);
		if (Sexp_nodes[node].first == -1) {
			stuff_sexp_text_string(buf, node, mode);
			accumulator += buf;

		} else {
			build_sexp_string(accumulator, Sexp_nodes[node].first, level + 1, mode);
		}

		accumulator += "\n";
		node = Sexp_nodes[node].rest;
	}

	for (i=0; i<level; i++)
		accumulator += "   ";

	accumulator += ")";
}

void convert_sexp_to_string(SCP_string &dest, int cur_node, int mode)
{
	if (cur_node >= 0) {
		dest = "";
		build_sexp_string(dest, cur_node, 0, mode);
	} else {
		dest = "( )";
	}
}


// ----------------------------------------------------------------------------------- 
// Helper methods for getting data from nodes. Cause it's stupid to keep re-rolling this stuff for every single SEXP
// -----------------------------------------------------------------------------------

/**
 * Takes a SEXP node which contains the name of a ship and returns the player for that ship or NULL if it is an AI ship
 */
player * get_player_from_ship_node(int node, bool test_respawns)
{
	int sindex, np_index = -1;	
	p_object *p_objp;
	
	Assert (node != -1);

	sindex = ship_name_lookup(CTEXT(node));

	// singleplayer
	if (!(Game_mode & GM_MULTIPLAYER)){	
		if(sindex >= 0){
			if(Player_obj == &Objects[Ships[sindex].objnum]){
				return Player;
			}
		}
		return NULL; 
	}
	// multiplayer
	else {
		if(sindex >= 0){
			if(Ships[sindex].objnum >= 0) {
				// try and find the player
				np_index = multi_find_player_by_object(&Objects[Ships[sindex].objnum]);
			}
		}
		if (test_respawns && np_index < 0) {
			// Respawning ships don't have an objnum so we need to take a different approach 
			p_objp = mission_parse_get_arrival_ship(CTEXT(node));
			if (p_objp != NULL) {
				np_index = multi_find_player_by_parse_object(p_objp);
			}
		}

		if((np_index >= 0) && (np_index < MAX_PLAYERS)){
			return Net_players[np_index].m_player; 
		}

		return NULL; 
	}
}

/**
 * Given a node, returns a pointer to the ship or NULL if this isn't the name of a ship
 */
ship * sexp_get_ship_from_node(int node)
{
	int sindex;
	ship *shipp = NULL;

	sindex = ship_name_lookup( CTEXT(node) );

	if (sindex < 0) {
		return shipp;
	}

	if (Ships[sindex].objnum < 0) {
		return shipp;
	}

	shipp = &Ships[sindex]; 
	return shipp;
}

/**
 * Determine if the named ship or wing hasn't arrived yet (wing or ship must be on arrival list)
 */
int sexp_query_has_yet_to_arrive(char *name)
{
	int i;

	if (ship_query_state(name) < 0)
		return 1;

	i = wing_name_lookup(name, 1);

	// has not arrived yet
	if ((i >= 0) && (Wings[i].num_waves >= 0) && !Wings[i].total_arrived_count){
		return 1;
	}

	return 0;
}

// arithmetic functions
int add_sexps(int n)
{
	int	sum = 0, val;

	if (n != -1) {
		if ( CAR(n) != -1) {
			sum = eval_sexp( CAR(n) );
			// be sure to check for the NAN value when doing arithmetic -- this value should
			// get propagated to the next highest function.
			if ( Sexp_nodes[CAR(n)].value == SEXP_NAN )
				return SEXP_NAN;
			else if ( Sexp_nodes[CAR(n)].value == SEXP_NAN_FOREVER )
				return SEXP_NAN_FOREVER;
		}
		else
			sum = atoi( CTEXT(n) );

		while (CDR(n) != -1) {
			val = eval_sexp( CDR(n) );
			// be sure to check for the NAN value when doing arithmetic -- this value should
			// get propagated to the next highest function.
			if ( Sexp_nodes[CDR(n)].value == SEXP_NAN )
				return SEXP_NAN;
			else if ( Sexp_nodes[CDR(n)].value == SEXP_NAN_FOREVER )
				return SEXP_NAN_FOREVER;
			sum += val;
			n = CDR(n);
		}
	}

	return sum;
}

int sub_sexps(int n)
{
	int	sum = 0;

	if (n != -1) { 
		if (Sexp_nodes[n].first != -1)
			sum = eval_sexp(CAR(n));
		else
			sum = atoi(CTEXT(n));

		while (CDR(n) != -1) {
			sum -= eval_sexp(CDR(n));
			n = CDR(n);
		}
	}

	return sum;
}

int mul_sexps(int n)
{
	int	sum = 0;

	if (n != -1) {
		if (Sexp_nodes[n].first != -1)
			sum = eval_sexp(Sexp_nodes[n].first);
		else
			sum = atoi(CTEXT(n));

		while (Sexp_nodes[n].rest != -1) {
			sum *= eval_sexp(Sexp_nodes[n].rest);
			n = Sexp_nodes[n].rest;
		}
	}

	return sum;
}

int div_sexps(int n)
{
	int	sum = 0;

	if (n != -1) {
		if (Sexp_nodes[n].first != -1)
			sum = eval_sexp(Sexp_nodes[n].first);
		else
			sum = atoi(CTEXT(n));

		while (Sexp_nodes[n].rest != -1) {
			int div = eval_sexp(Sexp_nodes[n].rest);
			n = Sexp_nodes[n].rest;
			if (div == 0) {
				Warning(LOCATION, "Division by zero in sexp. Please check all uses of the / operator for possible causes.\n");
				Int3();
				continue;
			} 
			sum /= div;
		}
	}

	return sum;
}

int mod_sexps(int n)
{
	int	sum = 0;

	if (n != -1) {
		if (Sexp_nodes[n].first != -1)
			sum = eval_sexp(Sexp_nodes[n].first);
		else
			sum = atoi(CTEXT(n));

		while (Sexp_nodes[n].rest != -1) {
			sum = sum % eval_sexp(Sexp_nodes[n].rest);
			n = Sexp_nodes[n].rest;
		}
	}

	return sum;
}

int rand_internal(int low, int high, int seed = 0)
{
	int diff;

	// maybe seed it
	if (seed > 0)
		srand(seed);

	// get diff - don't allow negative or zero
	diff = high - low;
	if (diff < 0)
		diff = 0;

	return (low + rand32() % (diff + 1));
}

// Goober5000
int abs_sexp(int n)
{
	return abs(eval_num(n));
}

// Goober5000
int min_sexp(int n)
{
	int temp, min_val = INT_MAX;

	while (n != -1)
	{
		temp = eval_num(n);

		if (temp < min_val)
			min_val = temp;

		n = CDR(n);
	}

	return min_val;
}

// Goober5000
int max_sexp(int n)
{
	int temp, max_val = INT_MIN;

	while (n != -1)
	{
		temp = eval_num(n);

		if (temp > max_val)
			max_val = temp;

		n = CDR(n);
	}

	return max_val;
}

// Goober5000
int avg_sexp(int n)
{
	int num = 0, avg_val = 0;

	while (n != -1)
	{
		avg_val += eval_num(n);
		num++;

		n = CDR(n);
	}

	return (int) floor(((double) avg_val / num) + 0.5);
}

// Goober5000
int pow_sexp(int node)
{
	int num_1 = eval_num(node);
	int num_2 = eval_num(CDR(node));

	// this is disallowed in FRED, but can still happen through careless arithmetic
	if (num_2 < 0)
	{
		Warning(LOCATION, "Power function pow(%d, %d) attempted to raise to a negative power!", num_1, num_2);
		return 0;
	}

	double pow_result = pow(static_cast<double>(num_1), num_2);

	if (pow_result > static_cast<double>(INT_MAX))
	{
		nprintf(("SEXP", "Power function pow(%d, %d) is greater than INT_MAX!  Returning INT_MAX.", num_1, num_2));
		return INT_MAX;
	}
	else if (pow_result < static_cast<double>(INT_MIN))
	{
		nprintf(("SEXP", "Power function pow(%d, %d) is less than INT_MIN!  Returning INT_MIN.", num_1, num_2));
		return INT_MIN;
	}

	return static_cast<int>(pow_result);
}

// Goober5000
int signum_sexp(int node)
{
	int num = eval_num(node);

	if (num == 0)
		return 0;

	if (num < 0)
		return -1;

	// hurr durr math
	Assert(num > 0);
	return 1;
}

// Goober5000
int sexp_set_bit(int node, bool set_it)
{
	int val = eval_num(node);
	int bit_index = eval_num(CDR(node));

	if (bit_index < 0 || bit_index > 31)
	{
		Warning(LOCATION, "Bit index %d out of range!  Must be between 0 and 31.", bit_index);
		return SEXP_NAN;
	}

	if (set_it)
		return val | (1<<bit_index);
	else
		return val & ~(1<<bit_index);
}

// Goober5000
int sexp_is_bit_set(int node)
{
	int val = eval_num(node);
	int bit_index = eval_num(CDR(node));

	if (bit_index < 0 || bit_index > 31)
	{
		Warning(LOCATION, "Bit index %d out of range!  Must be between 0 and 31.", bit_index);
		return SEXP_NAN;
	}

	if (val & (1<<bit_index))
		return SEXP_TRUE;
	else
		return SEXP_FALSE;
}

// Goober5000
int sexp_bitwise_and(int node)
{
	int val = eval_num(node);

	for (int n = CDR(node); n != -1; n = CDR(n))
		val &= eval_num(n);

	return val;
}

// Goober5000
int sexp_bitwise_or(int node)
{
	int val = eval_num(node);

	for (int n = CDR(node); n != -1; n = CDR(n))
		val |= eval_num(n);

	return val;
}

// Goober5000
int sexp_bitwise_not(int node)
{
	int result = ~(eval_num(node));

	// clear the sign bit
	return result & INT_MAX;
}

// Goober5000
int sexp_bitwise_xor(int node)
{
	return eval_num(node) ^ eval_num(CDR(node));
}

// seeding added by Karajorma and Goober5000
int rand_sexp(int n, bool multiple)
{
	int low, high, rand_num, seed;

	if (n < 0)
	{
		Int3();
		return 0;
	}

	// when getting a saved value
	if (Sexp_nodes[n].value == SEXP_NUM_EVAL)
	{
		// don't regenerate new random number
		return atoi(CTEXT(n));
	}

	low = eval_num(n);

	// get high
	high = eval_num(CDR(n));
			
	// is there a seed provided?
	if (CDDR(n) != -1)
		seed = eval_num(CDDR(n));
	else
		seed = 0;

	// get the random number
	rand_num = rand_internal(low, high, seed);

	// when saving the value
	if (!multiple)
	{
		// set .value and .text so random number is generated only once.
		Sexp_nodes[n].value = SEXP_NUM_EVAL;
		sprintf(Sexp_nodes[n].text, "%d", rand_num);
	}
	// if this is multiple with a nonzero seed provided
	else if (seed > 0)
	{
		// Set the seed to a new seeded random value. This will ensure that the next time the method
		// is called it will return a predictable but different number from the previous time. 
		sprintf(Sexp_nodes[CDDR(n)].text, "%d", rand_internal(1, INT_MAX, seed));
	}

	return rand_num;
}

// boolean evaluation functions.  Evaluate all sexpressions in the 'or' operator.  Needed to mark
// entries in the mission log as essential so when pruning the log, we know which entries we might
// need to keep.
int sexp_or(int n)
{
	int all_false, result;

	all_false = 1;
	result = 0;
	if (n != -1)
	{
		if (CAR(n) != -1)
		{
			result |= is_sexp_true(CAR(n));
			if ( Sexp_nodes[CAR(n)].value == SEXP_KNOWN_TRUE )
				return SEXP_KNOWN_TRUE;								// if one of the OR clauses is TRUE, whole clause is true
			if ( Sexp_nodes[CAR(n)].value != SEXP_KNOWN_FALSE )		// if the value is still unknown, they all can't be false
				all_false = 0;
		}
		else
			result |= atoi(CTEXT(n));

		while (CDR(n) != -1)
		{
			result |= is_sexp_true(CDR(n));
			if ( Sexp_nodes[CDR(n)].value == SEXP_KNOWN_TRUE )
				return SEXP_KNOWN_TRUE;								// if one of the OR clauses is TRUE, whole clause is true
			if ( Sexp_nodes[CDR(n)].value != SEXP_KNOWN_FALSE )		// if the value is still unknown, they all can't be false
				all_false = 0;

			n = CDR(n);
		}
	}

	if (all_false)
		return SEXP_KNOWN_FALSE;

	return result;
}

// this function does the 'and' operator.  It will short circuit evaluation  *but* it will still
// evaluate other members of the and construct.  I do this because I need events in the mission log
// to get marked as essential for goal purposes, and evaluation is pretty much the only way
int sexp_and(int n)
{
	int all_true, result;

	result = -1;
	all_true = 1;
	if (n != -1)
	{
		if (CAR(n) != -1)
		{
			result &= is_sexp_true(CAR(n));
			if ( Sexp_nodes[CAR(n)].value == SEXP_KNOWN_FALSE || Sexp_nodes[CAR(n)].value == SEXP_NAN_FOREVER )
				return SEXP_KNOWN_FALSE;							// if one of the AND clauses is FALSE, whole clause is false
			if ( Sexp_nodes[CAR(n)].value != SEXP_KNOWN_TRUE )		// if the value is still unknown, they all can't be true
				all_true = 0;
		}
		else
			result &= atoi(CTEXT(n));

		while (CDR(n) != -1)
		{
			int new_result;

			new_result = is_sexp_true(CDR(n));
			result &= new_result;
			if ( Sexp_nodes[CDR(n)].value == SEXP_KNOWN_FALSE || Sexp_nodes[CDR(n)].value == SEXP_NAN_FOREVER )
				return SEXP_KNOWN_FALSE;							// if one of the AND clauses is FALSE, whole clause is false
			if ( Sexp_nodes[CDR(n)].value != SEXP_KNOWN_TRUE )		// if the value is still unknown, they all can't be true
				all_true = 0;

			n = CDR(n);
		}
	}

	if (all_true)
		return SEXP_KNOWN_TRUE;

	return result;
}

// this version of the 'and' operator determines whether or not it's arguments become true
// in the order in which they are specified in the when statement.  Should be a simple matter of 
// seeing if anything evaluates to true later than something that evalueated to false
int sexp_and_in_sequence(int n)
{
	int result = -1;
	int all_true;

	all_true = 1;											// represents whether or not all nodes we have seen so far are true
	if (n != -1)
	{
		if (CAR(n) != -1)
		{
			result &= is_sexp_true(CAR(n));
			if ( Sexp_nodes[CAR(n)].value == SEXP_KNOWN_FALSE || Sexp_nodes[CAR(n)].value == SEXP_NAN_FOREVER )
				return SEXP_KNOWN_FALSE;														// if one of the AND clauses is FALSE, whole clause is false
			if ( Sexp_nodes[CAR(n)].value != SEXP_KNOWN_TRUE )		// if value is true, mark our all_true variable for later checking
				all_true = 0;
		}
		else
			result &= atoi(CTEXT(n));

		// a little test -- if the previous sexpressions was true, then mark the node itself as always
		// true.  I did this because of the distance function.  It might become true, then when waiting for
		// the second evalation, it might become false, rendering this function false.  So, when one becomes
		// true -- mark it true forever.
		if ( result )
			Sexp_nodes[CAR(n)].value = SEXP_KNOWN_TRUE;

		while (CDR(n) != -1)
		{
			int next_result;

			next_result = is_sexp_true(CDR(n));
			if ( next_result && !result )				// if current result is true, and our running result is false, thngs didn't become true in order
				return SEXP_KNOWN_FALSE;
			result &= next_result;
			if ( Sexp_nodes[CDR(n)].value == SEXP_KNOWN_FALSE || Sexp_nodes[CDR(n)].value == SEXP_NAN_FOREVER )
				return SEXP_KNOWN_FALSE;															// if one of the OR clauses is TRUE, whole clause is true
			if ( Sexp_nodes[CDR(n)].value != SEXP_KNOWN_TRUE )				// if the value is still unknown, they all can't be false
				all_true = 0;

			// see comment above for explanation of next lines
			if ( result )
				Sexp_nodes[CDR(n)].value = SEXP_KNOWN_TRUE;

			n = CDR(n);
		}
	}

	if ( all_true )
		return SEXP_KNOWN_TRUE;

	return result;
}

// for these four basic boolean operations (not, <, >, and =), we have special cases that we must deal
// with.  We have sexpressions operators that might return a NAN type return value (such as the distance
// between two ships when one of the ships is destroyed or departed).  These operations need to check for
// this special NAN value and adjust their return types accordingly.  NAN values represent false return values
int sexp_not(int n)
{
	int result = 0;

	if (n != -1)
	{
		if (CAR(n) != -1)
		{
			result = is_sexp_true(CAR(n));
			if ( Sexp_nodes[CAR(n)].value == SEXP_KNOWN_FALSE || Sexp_nodes[CAR(n)].value == SEXP_NAN_FOREVER )
				return SEXP_KNOWN_TRUE;												// not KNOWN_FALSE == KNOWN_TRUE;
			else if ( Sexp_nodes[CAR(n)].value == SEXP_KNOWN_TRUE )		// not KNOWN_TRUE == KNOWN_FALSE
				return SEXP_KNOWN_FALSE;
			else if ( Sexp_nodes[CAR(n)].value == SEXP_NAN )				// not NAN == TRUE (I think)
				return SEXP_TRUE;
		}
		else
			result = atoi(CTEXT(n));
	}

	return !result;
}

int sexp_xor(int node)
{
	int num_true = 0;

	for (int n = node; n != -1; n = CDR(n))
	{
		if (is_sexp_true(n))
			num_true++;
	}

	return (num_true == 1);
}

// Goober5000
int sexp_number_compare(int n, int op)
{
	int first_node = n;
	int current_node;
	int first_number = eval_sexp(first_node);
	int current_number;

	// bail on NANs
	if (CAR(first_node) != -1)
	{
		if (Sexp_nodes[CAR(first_node)].value == SEXP_NAN) return SEXP_FALSE;
		if (Sexp_nodes[CAR(first_node)].value == SEXP_NAN_FOREVER) return SEXP_KNOWN_FALSE;
	}
	if (CDR(first_node) != -1)
	{
		if (Sexp_nodes[CDR(first_node)].value == SEXP_NAN) return SEXP_FALSE;
		if (Sexp_nodes[CDR(first_node)].value == SEXP_NAN_FOREVER) return SEXP_KNOWN_FALSE;
	}

	// compare first node with each of the others
	for (current_node = CDR(first_node); current_node != -1; current_node = CDR(current_node))
	{
		// bail on NANs
		if (CAR(current_node) != -1)
		{
			if (Sexp_nodes[CAR(current_node)].value == SEXP_NAN) return SEXP_FALSE;
			if (Sexp_nodes[CAR(current_node)].value == SEXP_NAN_FOREVER) return SEXP_KNOWN_FALSE;
		}
		if (CDR(current_node) != -1)
		{
			if (Sexp_nodes[CDR(current_node)].value == SEXP_NAN) return SEXP_FALSE;
			if (Sexp_nodes[CDR(current_node)].value == SEXP_NAN_FOREVER) return SEXP_KNOWN_FALSE;
		}

		current_number = eval_sexp(current_node);

		// must satisfy our particular operator
		switch(op)
		{
			case OP_EQUALS:
				if (first_number != current_number) return SEXP_FALSE;
				break;

			case OP_NOT_EQUAL:
				if (first_number == current_number) return SEXP_FALSE;
				break;

			case OP_GREATER_THAN:
				if (first_number <= current_number) return SEXP_FALSE;
				break;

			case OP_GREATER_OR_EQUAL:
				if (first_number < current_number) return SEXP_FALSE;
				break;

			case OP_LESS_THAN:
				if (first_number >= current_number) return SEXP_FALSE;
				break;

			case OP_LESS_OR_EQUAL:
				if (first_number > current_number) return SEXP_FALSE;
				break;

			default:
				Warning(LOCATION, "Unhandled comparison case!  Operator = %d", op);
				break;
		}
	}

	// it satisfies the operator for all the arguments
	return SEXP_TRUE;
}

// Goober5000
int sexp_string_compare(int n, int op)
{
	int first_node = n;
	int current_node;
	int val;
	char *first_string = CTEXT(first_node);

	// compare first node with each of the others
	for (current_node = CDR(first_node); current_node != -1; current_node = CDR(current_node))
	{
		val = strcmp(first_string, CTEXT(current_node));

		// must satisfy our particular operator
		switch(op)
		{
			case OP_STRING_EQUALS:
				if (val != 0) return SEXP_FALSE;
				break;

			case OP_STRING_GREATER_THAN:
				if (val <= 0) return SEXP_FALSE;
				break;

			case OP_STRING_LESS_THAN:
				if (val >= 0) return SEXP_FALSE;
				break;
		}
	}

	// it satisfies the operator for all the arguments
	return SEXP_TRUE;
}

#define OSWPT_TYPE_NONE				0
#define OSWPT_TYPE_SHIP				1
#define OSWPT_TYPE_WING				2
#define OSWPT_TYPE_WAYPOINT			3
#define OSWPT_TYPE_SHIP_ON_TEAM		4	// e.g. <any friendly>
#define OSWPT_TYPE_WHOLE_TEAM		5	// e.g. Friendly
#define OSWPT_TYPE_PARSE_OBJECT		6	// a "ship" that hasn't arrived yet
#define OSWPT_TYPE_EXITED			7
#define OSWPT_TYPE_WING_NOT_PRESENT	8	// a wing that hasn't arrived yet or is between waves

// Goober5000
typedef struct object_ship_wing_point_team
{
	char *object_name;
	int type;

	p_object *p_objp;
	object *objp;
	ship *shipp;
	wing *wingp;
	waypoint *waypointp;
	int team;

	void clear();
}
object_ship_wing_point_team;

void object_ship_wing_point_team::clear()
{
	object_name = NULL;
	type = OSWPT_TYPE_NONE;

	p_objp = NULL;
	objp = NULL;
	shipp = NULL;
	waypointp = NULL;
	wingp = NULL;
	team = -1;
}

void sexp_object_ship_wing_point_team_set_ship(object_ship_wing_point_team *oswpt, ship *shipp, bool set_parse_flag_too = false);
void sexp_object_ship_wing_point_team_set_ship(object_ship_wing_point_team *oswpt, ship_obj *so, bool set_parse_flag_too = false);
void sexp_get_object_ship_wing_point_team(object_ship_wing_point_team *oswpt, char *object_name, bool set_parse_flag_too = false); 

void object_ship_wing_point_team_set_ship(object_ship_wing_point_team *oswpt, ship *shipp, bool set_parse_flag_too)
{
	oswpt->clear(); 
	
	oswpt->shipp = shipp;
	oswpt->object_name = oswpt->shipp->ship_name; 
	oswpt->objp = &Objects[shipp->objnum];
	oswpt->type = OSWPT_TYPE_SHIP;

	if (set_parse_flag_too) {
		oswpt->p_objp = mission_parse_get_arrival_ship(oswpt->object_name);
	}
}


void object_ship_wing_point_team_set_ship(object_ship_wing_point_team *oswpt, ship_obj *so, bool set_parse_flag_too)
{
	object_ship_wing_point_team_set_ship(oswpt, &Ships[Objects[so->objnum].instance], set_parse_flag_too); 
}


// Goober5000
void sexp_get_object_ship_wing_point_team(object_ship_wing_point_team *oswpt, char *object_name, bool set_parse_flag_too)
{
	int team, ship_num, wing_num;
	waypoint *wpt;
	p_object *p_objp;

	Assert(oswpt != NULL);
	Assert(object_name != NULL);

	oswpt->clear(); 
	oswpt->object_name = object_name;

	if(!stricmp(object_name, SEXP_NONE_STRING))
	{
		oswpt->type = OSWPT_TYPE_NONE;
		return;
	}

	// check to see if ship destroyed or departed.  In either case, do nothing.
	if (mission_log_get_time(LOG_SHIP_DEPARTED, object_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, object_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, object_name, NULL, NULL))
	{
		oswpt->type = OSWPT_TYPE_EXITED;
		return;
	}

	// the object might be the name of a wing.  Check to see if the wing is destroyed or departed.
	if (mission_log_get_time(LOG_WING_DESTROYED, object_name, NULL, NULL) || mission_log_get_time(LOG_WING_DEPARTED, object_name, NULL, NULL)) 
	{
		oswpt->type = OSWPT_TYPE_EXITED;
		return;
	}


	// check if we have a ship for a target
	ship_num = ship_name_lookup(object_name);
	if (ship_num >= 0)
	{
		oswpt->type = OSWPT_TYPE_SHIP;

		oswpt->shipp = &Ships[ship_num];
		oswpt->objp = &Objects[oswpt->shipp->objnum];

		if (!set_parse_flag_too) {
			return;
		}
	}


	// check to see if we have a parse object instead
	p_objp = mission_parse_get_arrival_ship(object_name);
	if (p_objp != NULL)
	{
		if (oswpt->type != OSWPT_TYPE_SHIP) {
			oswpt->type = OSWPT_TYPE_PARSE_OBJECT;
		}

		oswpt->p_objp = p_objp;

		return;
	}


	// check if we have a wing for a target
	wing_num = wing_name_lookup(object_name, 1);
	if (wing_num >= 0)
	{
		wing *wingp = &Wings[wing_num];

		// make sure that at least one ship exists
		if (wingp->current_count > 0)
		{
			oswpt->type = OSWPT_TYPE_WING;
			oswpt->wingp = wingp;

			// point to wing leader if he is valid
			if ((wingp->special_ship >= 0) && (wingp->ship_index[wingp->special_ship] >= 0))
			{
				oswpt->shipp = &Ships[wingp->ship_index[wingp->special_ship]];
				oswpt->objp = &Objects[oswpt->shipp->objnum];
			}
			// boo... well, just point to ship at index 0
			else
			{
				oswpt->shipp = &Ships[wingp->ship_index[0]];
				oswpt->objp = &Objects[oswpt->shipp->objnum];
				Warning(LOCATION, "Substituting ship '%s' at index 0 for nonexistent wing leader at index %d!", oswpt->shipp->ship_name, oswpt->wingp->special_ship);
			}
		}
		// it's still a valid wing even if nobody is here
		else
		{
			oswpt->type = OSWPT_TYPE_WING_NOT_PRESENT;
			oswpt->wingp = wingp;
		}

		return;
	}


	// check if we have a point for a target
	wpt = find_matching_waypoint(object_name);
	if ((wpt != NULL) && (wpt->get_objnum() >= 0))
	{
		oswpt->type = OSWPT_TYPE_WAYPOINT;

		oswpt->waypointp = wpt;
		oswpt->objp = &Objects[wpt->get_objnum()];

		return;
	}


	// check if we have an "<any team>" type
	team = sexp_determine_team(object_name);
	if (team >= 0)
	{
		oswpt->type = OSWPT_TYPE_SHIP_ON_TEAM;
				oswpt->team = team;
		}


	// check if we have a whole-team type
	team = iff_lookup(object_name);
	if (team >= 0)
	{
		oswpt->type = OSWPT_TYPE_WHOLE_TEAM;
		oswpt->team = team;
	}


	// we apparently don't have anything legal
	return;
}

/**
 * Return the number of ships of a given team in the area battle
 */
int sexp_num_ships_in_battle(int n)
{
	int count=0;
	ship_obj	*so;
	ship		*shipp;
	object_ship_wing_point_team oswpt1;
	if ( n == -1) {
    	for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
		    shipp=&Ships[Objects[so->objnum].instance];
		    count++;
	    }

	    return count;
	}

	while (n != -1) {
		sexp_get_object_ship_wing_point_team(&oswpt1, CTEXT(n));

	    switch (oswpt1.type){
 		    case OSWPT_TYPE_WHOLE_TEAM:
				  for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
					  shipp=&Ships[Objects[so->objnum].instance];
				  if (shipp->team == oswpt1.team) {
						 count++;
					  }
				  }
			  break;

  		    case OSWPT_TYPE_SHIP:
			  count++;
			  break;

		    case OSWPT_TYPE_WING:
			  count += oswpt1.wingp->current_count;
			  break;
	    }

        n = CDR(n); 
	}

	return count;
}

/** 
 * Return the number of ships of a given wing or wings in the battle area
 */
int sexp_num_ships_in_wing(int n)
{
	char *name;
	int num_ships = 0 ;

	// A wing name must be provided, Assert that there is one.
	Assert ( n != -1 );

	//Cycle through the list of ships given
	while (n != -1)
	{
		// Get the name of the wing
		name = CTEXT(n);

		int wingnum;
		wingnum = wing_name_lookup( name, 0 );

		//If the wing exists add the number of ships in it to the total
		if (wingnum > -1)
		{
			num_ships += Wings[wingnum].current_count ;
		}

		//get the next node
		n = CDR (n) ; 
	}

	return num_ships ;
}

/**
 * Gets the 'real' speed of an object, taking into account docking
 */
int sexp_get_real_speed(object *obj)
{
	return fl2i(dock_calc_docked_speed(obj));
}

/**
 * Gets the current speed of the specified object
 *
 * Uses a lot of code shamelessly ripped from get_object_coordinates
 */
int sexp_current_speed(int n)
{
	object_ship_wing_point_team oswpt;
	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));

	switch (oswpt.type)
	{
		case OSWPT_TYPE_EXITED:
			return SEXP_NAN;

		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WING:
			return sexp_get_real_speed(oswpt.objp);
	}

	return 0;
}

/**
 * Evaluate if given ship is destroyed.
 * @return true if the ship in the expression has been destroyed.
 */
int sexp_is_destroyed(int n, fix *latest_time)
{
	char	*name;
	int	count, num_destroyed, wing_index;
	fix	time;

	Assert ( n != -1 );

	count = 0;
	num_destroyed = 0;
	wing_index = -1;
	while (n != -1) {
		count++;
		name = CTEXT(n);

		if (sexp_query_has_yet_to_arrive(name))
			return SEXP_CANT_EVAL;

		// check to see if this ship/wing has departed.  If so, then function is known false
		if ( mission_log_get_time (LOG_SHIP_DEPARTED, name, NULL, NULL) || mission_log_get_time (LOG_WING_DEPARTED, name, NULL, NULL) )
			return SEXP_KNOWN_FALSE;

		// check the mission log.  If ship/wing not destroyed, immediately return SEXP_FALSE.
		if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, &time) || mission_log_get_time(LOG_WING_DESTROYED, name, NULL, &time) || mission_log_get_time(LOG_SELF_DESTRUCTED, name, NULL, &time)) {
			num_destroyed++;
			if ( latest_time && (time > *latest_time) )
				*latest_time = time;
		} else {
			// ship or wing isn't destroyed -- add to directive count
			if ( (wing_index = wing_name_lookup( name, 1 )) >= 0 ) {
				Directive_count += Wings[wing_index].current_count;
			} else
				Directive_count++;
		}

		// move to next ship/wing in list
		n = CDR(n);
	}

	// special case to mark a directive for destroy wing objectives true after a short amount
	// of time when there are more waves for this wing.
	if ( (count == 1) && (wing_index >= 0) && (Directive_count == 0) ) {
		if ( Wings[wing_index].current_wave < Wings[wing_index].num_waves )
			Directive_count =	DIRECTIVE_WING_ZERO;
	}

	if ( count == num_destroyed )
		return SEXP_KNOWN_TRUE;
	else
		return SEXP_FALSE;
}

/**
 * Return true if the subsystem of the given ship has been destroyed
 */
int sexp_is_subsystem_destroyed(int n)
{
	char *ship_name, *subsys_name;

	Assert( n != -1 );
	
	ship_name = CTEXT(n);
	subsys_name = CTEXT(CDR(n));

	if (sexp_query_has_yet_to_arrive(ship_name))
		return SEXP_CANT_EVAL;

	// if the ship has departed, no way to destroy it's subsystem.
	if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL ))
		return SEXP_KNOWN_FALSE;
	
	if ( mission_log_get_time(LOG_SHIP_SUBSYS_DESTROYED, ship_name, subsys_name, NULL) )
		return SEXP_KNOWN_TRUE;

	return SEXP_FALSE;

}

/**
 * Determine if a ship has arrived onto the scene
 */
int sexp_has_arrived(int n, fix *latest_time)
{
	char *name;
	int	count, num_arrived;
	fix	time;

	count = 0;
	num_arrived = 0;
	while ( n != -1 ) {
		count++;
		name = CTEXT(n);
		// if there is no log entry for this ship/wing for arrival, sexpression is false
		if ( mission_log_get_time(LOG_SHIP_ARRIVED, name, NULL, &time) || mission_log_get_time(LOG_WING_ARRIVED, name, NULL, &time) ) {
			num_arrived++;
			if ( latest_time && (time > *latest_time) )
				*latest_time = time;
		}
		n = CDR(n);
	}

	if ( count == num_arrived )
		return SEXP_KNOWN_TRUE;
	else
		return SEXP_FALSE;
}

/**
 * Determine if a ship/wing has departed
 */
int sexp_has_departed(int n, fix *latest_time)
{
	char *name;
	int count, num_departed;
	fix time;

	count = 0;
	num_departed = 0;
	while ( n != -1 ) {
		count++;
		name = CTEXT(n);

		if (sexp_query_has_yet_to_arrive(name))
			return SEXP_CANT_EVAL;

		// if ship/wing destroyed, sexpression is known false.  Also, if there is no departure log entry, then
		// the sexpression is not true.
		if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, NULL) || mission_log_get_time(LOG_WING_DESTROYED, name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, name, NULL, NULL))
			return SEXP_KNOWN_FALSE;
		else if ( mission_log_get_time(LOG_SHIP_DEPARTED, name, NULL, &time) || mission_log_get_time(LOG_WING_DEPARTED, name, NULL, &time) ) {
			num_departed++;
			if ( latest_time && (time > *latest_time) )
				*latest_time = time;
		}
		n = CDR(n);
	}

	if ( count == num_departed )
		return SEXP_KNOWN_TRUE;
	else
		return SEXP_FALSE;
}

/**
 * Determine if a ship is disabled
 */
int sexp_is_disabled( int n, fix *latest_time )
{
	char *name;
	int count, num_disabled;
	fix time;

	count = 0;
	num_disabled = 0;
	while ( n != -1 ) {
		count++;
		name = CTEXT(n);

		if (sexp_query_has_yet_to_arrive(name))
			return SEXP_CANT_EVAL;

		// if ship/wing destroyed, sexpression is known false.  Also, if there is no disable log entry, then
		// the sexpression is not true.
		if ( mission_log_get_time(LOG_SHIP_DEPARTED, name, NULL, &time) || mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, &time) || mission_log_get_time(LOG_SELF_DESTRUCTED, name, NULL, &time) )
			return SEXP_KNOWN_FALSE;
		else if ( mission_log_get_time(LOG_SHIP_DISABLED, name, NULL, &time) ) {
			num_disabled++;
			if ( latest_time && (time > *latest_time) )
				*latest_time = time;
		}
		n = CDR(n);
	}

	if ( count == num_disabled )
		return SEXP_KNOWN_TRUE;
	else
		return SEXP_FALSE;
}

/**
 * Determine if a ship is done flying waypoints
 */
int sexp_are_waypoints_done(int n)
{
	char *ship_name, *waypoint_name;

	ship_name = CTEXT(n);
	waypoint_name = CTEXT(CDR(n));

	if (sexp_query_has_yet_to_arrive(ship_name))
		return SEXP_CANT_EVAL;

	// a destroyed or departed ship will never reach their goal -- return known false
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) )
		return SEXP_KNOWN_FALSE;
	else if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) )
		return SEXP_KNOWN_FALSE;

	// now check the log for the waypoints done entry
	if ( mission_log_get_time(LOG_WAYPOINTS_DONE, ship_name, waypoint_name, NULL) )
		return SEXP_KNOWN_TRUE;

	return SEXP_FALSE;
}


/**
 * Determine if ships are disarmed
 */
int sexp_is_disarmed( int n, fix *latest_time )
{
	char *name;
	int count, num_disarmed;
	fix time;

	count = 0;
	num_disarmed = 0;
	while ( n != -1 ) {
		count++;
		name = CTEXT(n);

		if (sexp_query_has_yet_to_arrive(name))
			return SEXP_CANT_EVAL;

		// if ship/wing destroyed, sexpression is known false.  Also, if there is no disarm log entry, then
		// the sexpression is not true.
		if ( mission_log_get_time(LOG_SHIP_DEPARTED, name, NULL, &time) || mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, &time) || mission_log_get_time(LOG_SELF_DESTRUCTED, name, NULL, &time) )
			return SEXP_KNOWN_FALSE;
		else if ( mission_log_get_time(LOG_SHIP_DISARMED, name, NULL, &time) ) {
			num_disarmed++;
			if ( latest_time && (time > *latest_time) )
				*latest_time = time;
		}
		n = CDR(n);
	}

	if ( count == num_disarmed )
		return SEXP_KNOWN_TRUE;
	else
		return SEXP_FALSE;
}

// the following functions are similar to the above objective functions but return true/false
// if N seconds have elasped after the corresponding function is true.
int sexp_is_destroyed_delay(int n)
{
	fix delay, time;
	int val;

	Assert ( n >= 0 );

	time = 0;

	delay = i2f(eval_num(n));

	// check value of is_destroyed function.  KNOWN_FALSE should be returned immediately
	val = sexp_is_destroyed( CDR(n), &time );
	if ( val == SEXP_KNOWN_FALSE )
		return val;

	if ( val == SEXP_CANT_EVAL )
		return SEXP_CANT_EVAL;

	if ( val ) {

		if ( (Missiontime - time) >= delay )
			return SEXP_KNOWN_TRUE;
	}

	return SEXP_FALSE;
}


// First ship is the destroyer, rest of the arguments are the destroyed ships.
int sexp_was_destroyed_by(int n, fix* latest_time)
{
	char* destroyer_ship_name;
	char* destroyed_ship_name;
	int count = 0, num_destroyed;
	fix time;

	Assert(n != -1);

	destroyer_ship_name = CTEXT(n);

	num_destroyed = 0;

	for (n = CDR(n); n != -1; n = CDR(n))
	{
		count++;
		destroyed_ship_name = CTEXT(n);

		if (sexp_query_has_yet_to_arrive(destroyed_ship_name))
			return SEXP_CANT_EVAL;

		// check to see if this ship/wing has departed.  If so, then function is known false
		if (mission_log_get_time(LOG_SHIP_DEPARTED, destroyed_ship_name, NULL, NULL))
			return SEXP_KNOWN_FALSE;

		// check the mission log.  If ship/wing not destroyed, immediately return SEXP_FALSE.
		if (mission_log_get_time(LOG_SHIP_DESTROYED, destroyed_ship_name, destroyer_ship_name, &time))
		{
			num_destroyed++;
			if (latest_time && (time > *latest_time))
				*latest_time = time;
		}
	}

	if (count == num_destroyed)
		return SEXP_KNOWN_TRUE;
	else
		return SEXP_FALSE;
}

int sexp_was_destroyed_by_delay(int n)
{
	fix delay, time;
	int val;

	Assert(n >= 0);

	time = 0;

	delay = i2f(eval_num(n));

	// check value of is_destroyed function.  KNOWN_FALSE should be returned immediately
	val = sexp_was_destroyed_by(CDR(n), &time);
	if (val == SEXP_KNOWN_FALSE)
		return val;

	if (val == SEXP_CANT_EVAL)
		return SEXP_CANT_EVAL;

	if (val)
	{

		if ((Missiontime - time) >= delay)
			return SEXP_KNOWN_TRUE;
	}

	return SEXP_FALSE;
}

int sexp_is_subsystem_destroyed_delay(int n)
{
	char *ship_name, *subsys_name;
	fix delay, time;

	Assert( n != -1 );
	
	ship_name = CTEXT(n);
	subsys_name = CTEXT(CDR(n));
	delay = i2f(eval_num(CDR(CDR(n))));

	if (sexp_query_has_yet_to_arrive(ship_name))
		return SEXP_CANT_EVAL;

	// if the ship has departed, no way to destroy it's subsystem.
	if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL ))
		return SEXP_KNOWN_FALSE;

	if ( mission_log_get_time(LOG_SHIP_SUBSYS_DESTROYED, ship_name, subsys_name, &time) ) {
		if ( (Missiontime - time) >= delay )
			return SEXP_KNOWN_TRUE;
	}

	return SEXP_FALSE;
}

int sexp_is_disabled_delay(int n)
{
	fix delay, time;
	int val;

	Assert ( n >= 0 );

	time = 0;
	delay = i2f(eval_num(n));

	// check value of is_disable for known false and return immediately if it is.
	val = sexp_is_disabled( CDR(n), &time );
	if ( val == SEXP_KNOWN_FALSE )
		return val;

	if ( val == SEXP_CANT_EVAL )
		return SEXP_CANT_EVAL;

	if ( val ) {
		if ( (Missiontime - time) >= delay )
			return SEXP_KNOWN_TRUE;
	}

	return SEXP_FALSE;
}

int sexp_is_disarmed_delay(int n)
{
	fix delay, time;
	int val;

	Assert ( n >= 0 );

	time = 0;
	delay = i2f(eval_num(n));
	
	// check value of is_disarmed for a known false value and return that immediately if it is
	val = sexp_is_disarmed( CDR(n), &time );
	if ( val == SEXP_KNOWN_FALSE )
		return val;

	if ( val == SEXP_CANT_EVAL )
		return SEXP_CANT_EVAL;

	if ( val ) {
		if ( (Missiontime - time) >= delay )
			return SEXP_KNOWN_TRUE;
	}

	return SEXP_FALSE;
}

int sexp_has_docked_or_undocked(int n, int op_num)
{
	Assert(op_num == OP_HAS_DOCKED || op_num == OP_HAS_UNDOCKED || op_num == OP_HAS_DOCKED_DELAY || op_num == OP_HAS_UNDOCKED_DELAY);

	char *docker = CTEXT(n);
	char *dockee = CTEXT(CDR(n));
	int count = eval_num(CDR(CDR(n)));		// count of times that we should look for

	if (count <= 0)
	{
		Warning(LOCATION, "Has-%sdocked%s count should be at least 1!  This has been automatically adjusted.", (op_num == OP_HAS_UNDOCKED || op_num == OP_HAS_UNDOCKED_DELAY ? "un" : ""), (op_num == OP_HAS_DOCKED_DELAY || op_num == OP_HAS_UNDOCKED_DELAY ? "-delay" : ""));
		count = 1;
	}

	if (sexp_query_has_yet_to_arrive(docker))
		return SEXP_CANT_EVAL;

	if (sexp_query_has_yet_to_arrive(dockee))
		return SEXP_CANT_EVAL;

	if (op_num == OP_HAS_DOCKED_DELAY || op_num == OP_HAS_UNDOCKED_DELAY)
	{
		fix delay = i2f(eval_num(CDR(CDR(CDR(n)))));
		fix time;

		if ( mission_log_get_time_indexed(op_num == OP_HAS_DOCKED_DELAY ? LOG_SHIP_DOCKED : LOG_SHIP_UNDOCKED, docker, dockee, count, &time) )
		{
	if ( (Missiontime - time) >= delay )
		return SEXP_KNOWN_TRUE;
}
	}
	else
	{
		if ( mission_log_get_time_indexed(op_num == OP_HAS_DOCKED ? LOG_SHIP_DOCKED : LOG_SHIP_UNDOCKED, docker, dockee, count, NULL) )
			return SEXP_KNOWN_TRUE;
	}

		if ( mission_log_get_time(LOG_SHIP_DESTROYED, docker, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, dockee, NULL, NULL) )
			return SEXP_KNOWN_FALSE;

		if ( mission_log_get_time(LOG_SELF_DESTRUCTED, docker, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, dockee, NULL, NULL) )
			return SEXP_KNOWN_FALSE;

		return SEXP_FALSE;
	}

int sexp_has_arrived_delay(int n)
{
	fix delay, time;
	int val;

	Assert ( n >= 0 );

	time = 0;
	delay = i2f(eval_num(n));

	// check return value from arrived function.  if can never arrive, then return that value here as well
	val = sexp_has_arrived( CDR(n), &time );
	if ( val == SEXP_KNOWN_FALSE )
		return val;

	if ( val == SEXP_CANT_EVAL )
		return SEXP_CANT_EVAL;

	if ( val ) {
		if ( (Missiontime - time) >= delay )
			return SEXP_KNOWN_TRUE;
	}

	return SEXP_FALSE;
}

int sexp_has_departed_delay(int n)
{
	fix delay, time;
	int val;

	Assert ( n >= 0 );

	time = 0;
	delay = i2f(eval_num(n));

	// must first check to see if the departed function could ever be true/false or is true or false.
	// if it can never be true, return that value
	val = sexp_has_departed( CDR(n), &time);
	if ( val == SEXP_KNOWN_FALSE )
		return val;

	if ( val == SEXP_CANT_EVAL )
		return SEXP_CANT_EVAL;

	if ( val ) {
		if ( (Missiontime - time) >= delay )
			return SEXP_KNOWN_TRUE;
	}

	return SEXP_FALSE;
}

/**
 * Determine if a ship is done flying waypoints after N seconds
 */
int sexp_are_waypoints_done_delay(int node)
{
	char *ship_name, *waypoint_name;
	int count, n = node;
	fix time, delay;

	ship_name = CTEXT(n);
	n = CDR(n);
	waypoint_name = CTEXT(n);
	n = CDR(n);
	delay = i2f(eval_num(n));
	n = CDR(n);
	count = (n >= 0) ? eval_num(n) : 1;
	if (count <= 0)
	{
		Warning(LOCATION, "Are-waypoints-done-delay count should be at least 1!  This has been automatically adjusted.");
		count = 1;
	}

	if (sexp_query_has_yet_to_arrive(ship_name))
		return SEXP_CANT_EVAL;

	// a destroyed or departed ship will never reach their goal -- return known false
	// 
	// Not checking the entries below.  Ships which warp out after reaching their goal (or getting
	// destroyed after their goal), but after reaching their waypoints, may have this goal incorrectly
	// marked false!!!!

	// now check the log for the waypoints done entry
	if ( mission_log_get_time_indexed(LOG_WAYPOINTS_DONE, ship_name, waypoint_name, count, &time) ) {
		if ( (Missiontime - time) >= delay )
			return SEXP_KNOWN_TRUE;
	} else {
		if ( mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) )
			return SEXP_KNOWN_FALSE;
		else if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) )
			return SEXP_KNOWN_FALSE;
	}

	return SEXP_FALSE;
}

/**
 * Determine is all of a given ship type are destroyed
 */
int sexp_ship_type_destroyed(int n)
{
	int percent;
	int type;
	char *shiptype;

	percent = eval_num(n);
	shiptype = CTEXT(CDR(n));

	type = ship_type_name_lookup(shiptype);

	// bogus if we reach the end of this array!!!!
	if ( type < 0 ) {
		Warning(LOCATION, "Invalid shiptype passed to ship-type-destroyed");
		return SEXP_FALSE;
	}

	if ( type >= (int)Ship_type_counts.size() || Ship_type_counts[type].total == 0 )
		return SEXP_FALSE;

	//We are safe from array indexing probs b/c of previous if.
	// determine if the percentage of killed/total is >= percentage given in the expression
	if ( (Ship_type_counts[type].killed * 100 / Ship_type_counts[type].total) >= percent)
		return SEXP_KNOWN_TRUE;
	
	return SEXP_FALSE;
}


// following are time based functions
int sexp_has_time_elapsed(int n)
{
	int time = eval_num(n);

	if ( f2i(Missiontime) >= time )
		return SEXP_KNOWN_TRUE;

	return SEXP_FALSE;
}

/**
 * Returns the time into the mission
 */
int sexp_mission_time()
{
	return f2i(Missiontime);
}

/**
 * Returns the time into the mission, in milliseconds
 */
int sexp_mission_time_msecs()
{
	// multiplying by 1000 can go over the limit for LONG_MAX so cast to long long int first
	return f2i((longlong)Missiontime * 1000);
}

/**
 * Returns percent of length of distance to special warpout plane
 */
int sexp_special_warp_dist( int n)
{
	char *ship_name;
	int shipnum;

	// get shipname
	ship_name = CTEXT(n);

	// check to see if either ship was destroyed or departed.  If so, then make this node known false
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) ) {
		return SEXP_NAN_FOREVER;
	}

	// get ship name
	shipnum = ship_name_lookup(ship_name);
	if (shipnum < 0) {
		return SEXP_NAN;
	}

	// check that ship has warpout_objnum
	if (Ships[shipnum].special_warpout_objnum < 0) {
		return SEXP_NAN;
	}
	
	Assert( (Ships[shipnum].special_warpout_objnum >= 0) && (Ships[shipnum].special_warpout_objnum < MAX_OBJECTS));
	if ( (Ships[shipnum].special_warpout_objnum < 0) && (Ships[shipnum].special_warpout_objnum >= MAX_OBJECTS) ) {
		return SEXP_NAN;
	}

	// check the special warpout device is valid
	int valid = FALSE;
	object *ship_objp = &Objects[Ships[shipnum].objnum];
	object *warp_objp = &Objects[Ships[shipnum].special_warpout_objnum];
	if (warp_objp->type == OBJ_SHIP) {
		if (Ship_info[Ships[warp_objp->instance].ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
			valid = TRUE;
		}
	}

	if (!valid) {
		return SEXP_NAN;
	}

	// check if within 45 degree half-angle cone of facing 
	float dot = fl_abs(vm_vec_dot(&warp_objp->orient.vec.fvec, &ship_objp->orient.vec.fvec));
	if (dot < 0.707f) {
		return SEXP_NAN;
	}

	// get distance
	vec3d hit_pt;
	float dist = fvi_ray_plane(&hit_pt, &warp_objp->pos, &warp_objp->orient.vec.fvec, &ship_objp->pos, &ship_objp->orient.vec.fvec, 0.0f);
	polymodel *pm = model_get(Ship_info[Ships[shipnum].ship_info_index].model_num);
	dist += pm->mins.xyz.z;

	// return as a percent of length
	return (int) (100.0f * dist / ship_class_get_length(&Ship_info[Ships[shipnum].ship_info_index]));
}


int sexp_time_destroyed(int n)
{
	fix time;

	if ( !mission_log_get_time( LOG_SHIP_DESTROYED, CTEXT(n), NULL, &time)
		&& !mission_log_get_time( LOG_SELF_DESTRUCTED, CTEXT(n), NULL, &time) ) {		// returns 0 when not found
		return SEXP_NAN;
	}
	
	return f2i(time);
}

int sexp_time_wing_destroyed(int n)
{
	fix time;

	if ( !mission_log_get_time( LOG_WING_DESTROYED, CTEXT(n), NULL, &time) ){
		return SEXP_NAN;
	}
	
	return f2i(time);
}

int sexp_time_docked(int n)
{
	fix time;
	char *docker = CTEXT(n);
	char *dockee = CTEXT(CDR(n));
	int count = eval_num(CDR(CDR(n)));

	Assert ( count > 0 );
	if ( !mission_log_get_time_indexed(LOG_SHIP_DOCKED, docker, dockee, count, &time) ){
		return SEXP_NAN;
	}

	return f2i(time);
}

int sexp_time_undocked(int n)
{
	fix time;
	char *docker = CTEXT(n);
	char *dockee = CTEXT(CDR(n));
	int count = eval_num(CDR(CDR(n)));

	Assert ( count > 0 );
	if ( !mission_log_get_time_indexed(LOG_SHIP_UNDOCKED, docker, dockee, count, &time) ){
		return SEXP_NAN;
	}

	return f2i(time);
}

int sexp_time_ship_arrived(int n)
{
	fix time;

	Assert( n != -1 );
	if ( !mission_log_get_time( LOG_SHIP_ARRIVED, CTEXT(n), NULL, &time ) ){
		return SEXP_NAN;
	}

	return f2i(time);
}

int sexp_time_wing_arrived(int n)
{
	fix time;

	Assert( n != -1 );
	if ( !mission_log_get_time( LOG_WING_ARRIVED, CTEXT(n), NULL, &time ) ){
		return SEXP_NAN;
	}

	return f2i(time);
}

int sexp_time_ship_departed(int n)
{
	fix time;

	Assert( n != -1 );
	if ( !mission_log_get_time( LOG_SHIP_DEPARTED, CTEXT(n), NULL, &time ) ){
		return SEXP_NAN;
	}

	return f2i(time);
}

int sexp_time_wing_departed(int n)
{
	fix time;

	Assert( n != -1 );
	if ( !mission_log_get_time(LOG_WING_DEPARTED, CTEXT(n), NULL, &time ) ){
		return SEXP_NAN;
	}

	return f2i(time);
}

void sexp_set_energy_pct (int node, int op_num)
{
	int sindex;
	float new_pct; 
	char *shipname;
	ship * shipp; 
	ship_info * sip; 

	Assert (node > -1);
	new_pct = eval_num(node) / 100.0f;

	// deal with ridiculous percentages
    CLAMP(new_pct, 0.0f, 1.0f);
	
	// only need to send a packet for afterburners because shields and weapon energy are sent from server to clients
	if (MULTIPLAYER_MASTER && (op_num == OP_SET_AFTERBURNER_ENERGY)) {
		multi_start_callback();
		multi_send_float(new_pct); 
	}

	node = CDR(node); 

	while (node > -1) {
		// get the ship
		shipname = CTEXT(node);

		sindex = ship_name_lookup( shipname );
		if ( sindex == -1 ){					// hmm.. if true, must not have arrived yet
			node = CDR(node);
			continue;
		}
		
		shipp = &Ships[sindex]; 
		sip = &Ship_info[Ships[sindex].ship_info_index]; 

		switch (op_num) {
			case OP_SET_AFTERBURNER_ENERGY:
				shipp->afterburner_fuel = sip->afterburner_fuel_capacity * new_pct; 
				break;

			case OP_SET_WEAPON_ENERGY:
				if (!(ship_has_energy_weapons(shipp)) ) {
					node = CDR(node); 
					continue;
				}
				
				shipp->weapon_energy = sip->max_weapon_reserve * new_pct;
				break; 

			case OP_SET_SHIELD_ENERGY:
				if (shipp->ship_max_shield_strength == 0.0f) {
					node = CDR(node); 
					continue;
				}	

				shield_set_strength(&Objects[shipp->objnum], (shipp->ship_max_shield_strength * new_pct));
				break;
		}

		if (MULTIPLAYER_MASTER && (op_num == OP_SET_AFTERBURNER_ENERGY)) {
			multi_send_ship(shipp); 
		}

		node = CDR(node); 
	}

	if (MULTIPLAYER_MASTER && (op_num == OP_SET_AFTERBURNER_ENERGY)) {
		multi_end_callback(); 
	}
}

void multi_sexp_set_energy_pct() 
{
	ship *shipp; 
	float new_pct; 
	ship_info * sip; 

	int op_num = multi_sexp_get_operator(); 

	multi_get_float(new_pct); 
	while (multi_get_ship(shipp)) {
		sip = &Ship_info[shipp->ship_info_index]; 

		switch (op_num) {
			case OP_SET_AFTERBURNER_ENERGY:
				shipp->afterburner_fuel = sip->afterburner_fuel_capacity * new_pct; 
				break;

			case OP_SET_WEAPON_ENERGY:
				shipp->weapon_energy = sip->max_weapon_reserve * new_pct;
				break; 

			case OP_SET_SHIELD_ENERGY:
				shield_set_strength(&Objects[shipp->objnum], (shipp->ship_max_shield_strength * new_pct));
				break;
		}
	}
}


int sexp_get_energy_pct (int node, int op_num)
{
	int sindex;
	float maximum = 0.0f, current = 0.0f; 
	ship * shipp; 
	ship_info * sip; 
	char *shipname;

	// get the ship
	shipname = CTEXT(node);

	sindex = ship_name_lookup( shipname );
	if ( sindex == -1 ){					// has either not arrived yet or has departed
		return SEXP_NAN;
	}

	shipp = &Ships[sindex]; 
	sip = &Ship_info[Ships[sindex].ship_info_index]; 

	switch (op_num) {
		case OP_AFTERBURNER_LEFT:
			maximum = sip->afterburner_fuel_capacity;
			current = shipp->afterburner_fuel;
			break; 
		case OP_WEAPON_ENERGY_LEFT:
			if (ship_has_energy_weapons(shipp)) {
				maximum = sip->max_weapon_reserve; 
				current = shipp->weapon_energy;
			}
			break; 
	}
	if (maximum < WEAPON_RESERVE_THRESHOLD || current < WEAPON_RESERVE_THRESHOLD) {
		return 0;
	}

	return (int)(100 * (current/maximum));
}

/**
 * Return the remaining shields as a percentage of the given ship.
 */
int sexp_shields_left(int n)
{
	int shipnum, percent;
	char *shipname;

	shipname = CTEXT(n);
	
	// if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, shipname, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, shipname, NULL, NULL) ) {
		return SEXP_NAN_FOREVER;
	}

	shipnum = ship_name_lookup( shipname );
	if ( shipnum == -1 ){					// hmm.. if true, must not have arrived yet
		return SEXP_NAN;
	}

	// Goober5000: in case ship has no shields
	if (Ships[shipnum].ship_max_shield_strength == 0.0f)
	{
		return 0;
	}

	// now return the amount of shields left as a percentage of the whole.
	percent = fl2i((get_shield_pct(&Objects[Ships[shipnum].objnum]) * 100.0f) + 0.5f);
	return percent;
}

/**
 * Return the remaining hits left as a percentage of the whole.
 *
 * This hit amount counts for all hits on the ship (hull + subsystems).  Use hits_left_hull to find hull hits remaining.
 */
int sexp_hits_left(int n)
{
	int shipnum, percent;
	char *shipname;

	shipname = CTEXT(n);
	
	// if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, shipname, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, shipname, NULL, NULL) ) {
		return SEXP_NAN_FOREVER;
	}

	shipnum = ship_name_lookup( shipname );
	if ( shipnum == -1 ){					// hmm.. if true, must not have arrived yet
		return SEXP_NAN;
	}

	// now return the amount of hits left as a percentage of the whole.  Subtract the percentage from 100
	// since we are working with total hit points taken, not total remaining.
	ship		*shipp = &Ships[shipnum];
	object	*objp = &Objects[shipp->objnum];
	percent = fl2i((100.0f * get_hull_pct(objp)) + 0.5f);
	return percent;
}

int sexp_sim_hits_left(int n)
{
	int shipnum, percent;
	char *shipname;

	shipname = CTEXT(n);
	
	// if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, shipname, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, shipname, NULL, NULL) ) {
		return SEXP_NAN_FOREVER;
	}

	shipnum = ship_name_lookup( shipname );
	if ( shipnum == -1 ){					// hmm.. if true, must not have arrived yet
		return SEXP_NAN;
	}

	// now return the amount of hits left as a percentage of the whole.  Subtract the percentage from 100
	// since we are working with total hit points taken, not total remaining.
	ship		*shipp = &Ships[shipnum];
	object	*objp = &Objects[shipp->objnum];
	percent = fl2i((100.0f * get_sim_hull_pct(objp)) + 0.5f);
	return percent;
}

/**
 * Determine if ship visible on radar
 * 
 * @return 0 - not visible
 * @return 1 - marginally targetable (jiggly on radar)
 * @return 2 - fully targetable
 */
int sexp_is_ship_visible(int n)
{
	char *shipname;
	int shipnum;
	int ship_is_visible = 0;

	// if multiplayer, bail
	if (Game_mode & GM_MULTIPLAYER) {
		return SEXP_NAN_FOREVER;
	}

	shipname = CTEXT(n);
	
	// if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, shipname, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, shipname, NULL, NULL) ) {
		return SEXP_NAN_FOREVER;
	}

	shipnum = ship_name_lookup( shipname );
	if ( shipnum == -1 ){					// hmm.. if true, must not have arrived yet
		return SEXP_NAN;
	}

	// get ship's *radar* visiblity
	if (Player_ship != NULL)
	{
		if (ship_is_visible_by_team(&Objects[Ships[shipnum].objnum], Player_ship))
		{
			ship_is_visible = 2;
		}
	}

	// only check awacs level if ship is not visible by team
	if (Player_ship != NULL && !ship_is_visible) {
		float awacs_level = awacs_get_level(&Objects[Ships[shipnum].objnum], Player_ship);
		if (awacs_level >= 1.0f) {
			ship_is_visible = 2;
		} else if (awacs_level > 0) {
			ship_is_visible = 1;
		}
	}

	return ship_is_visible;
}

/**
 * Determine if the stealth flag set on this ship
 */
int sexp_is_ship_stealthy(int n)
{
	char *shipname;
	int shipnum;

	shipname = CTEXT(n);
	
	// if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, shipname, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, shipname, NULL, NULL) ) {
		return SEXP_NAN_FOREVER;
	}

	shipnum = ship_name_lookup( shipname );
	if ( shipnum == -1 ) {					// hmm.. if true, must not have arrived yet
		return SEXP_NAN;
	}

	if (Ships[shipnum].flags2 & SF2_STEALTH)
		return SEXP_TRUE;
	else
		return SEXP_FALSE;
}

/**
 * Determine if the friendly stealth ship visible
 */
int sexp_is_friendly_stealth_visible(int n)
{
	char *shipname;
	int shipnum;

	shipname = CTEXT(n);
	
	// if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, shipname, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, shipname, NULL, NULL) ) {
		return SEXP_NAN_FOREVER;
	}

	shipnum = ship_name_lookup( shipname );
	if ( shipnum == -1 ) {					// hmm.. if true, must not have arrived yet
		return SEXP_NAN;
	}

	if (Ships[shipnum].flags2 & SF2_FRIENDLY_STEALTH_INVIS)
		return SEXP_FALSE;
	else
		return SEXP_TRUE;
}

// get multi team v team score
// if not multi team v team return 0
// if invalid team return 0
int sexp_team_score(int node)
{
	// if multi t vs t
	if (Game_mode & GM_MULTIPLAYER) {
		if (Netgame.type_flags & NG_TYPE_TEAM) {

			int team = eval_num(node);

			// Teams can only be 1 or 2 at the moment but we should use Num_teams in case more become possible in the future
			if (team <= 0 || team > Num_teams)
			{
				// invalid team index
				Warning(LOCATION, "sexp-team-score: team %d is not a valid team #", team);
				return 0;
			}

			return Multi_team_score[team - 1];
		}
	}

	return 0;
}


/**
 * Return the remaining hits left on a subsystem as a percentage of the whole.
 *
 * Goober5000 - this sexp is DEPRECATED because it works just like the new hits-left-substem-generic
 */
int sexp_hits_left_subsystem(int n)
{
	int shipnum, percent, type, single_subsystem = 0;
	char *shipname;
	char *subsys_name;

	shipname = CTEXT(n);
	
	// if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, shipname, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, shipname, NULL, NULL) ) {
		return SEXP_NAN_FOREVER;
	}

	shipnum = ship_name_lookup( shipname );
	if ( shipnum == -1 ){					// hmm.. if true, must not have arrived yet
		return SEXP_NAN;
	}

	subsys_name = CTEXT(CDR(n));
	ship_subsys *ss = ship_get_subsys(&Ships[shipnum], subsys_name);
	if (ss != NULL)
		type = ss->system_info->type;
	else
		type = SUBSYSTEM_NONE;

	if ( (type >= 0) && (type < SUBSYSTEM_MAX) ) {
		// check for the optional argument
		n = CDDR(n); 
		if (n >= 0) {
			single_subsystem = is_sexp_true(n);
		}

		// if the third option is present or if this is an unknown subsystem type we only want to find the percentage of the 
		// named subsystem
		if (single_subsystem || (type == SUBSYSTEM_UNKNOWN)) {
			if (ss != NULL) {
				percent = fl2i((ss->current_hits / ss->max_hits * 100.0f) + 0.5f);
				return percent;
			}

			// we reached end of ship subsys list without finding subsys_name
			if (ship_class_unchanged(shipnum)) {
				Error(LOCATION, "Invalid subsystem '%s' passed to hits-left-subsystem", subsys_name);
			}
			return SEXP_NAN;

		// by default we return as a percentage the hits remaining on the subsystem as a whole (i.e. for 3 engines,
		// we are returning the sum of the hits on the 3 engines)
		} else {
			percent = fl2i((ship_get_subsystem_strength(&Ships[shipnum],type) * 100.0f) + 0.5f);
			return percent;
		}
	}
	return SEXP_NAN;			// if for some strange reason, the type field of the subsystem is bogus
}

// Goober5000
int sexp_hits_left_subsystem_generic(int node)
{
	int i, ship_num, subsys_type;
	char *ship_name, *subsys_type_name;

	ship_name = CTEXT(node);
	subsys_type_name = CTEXT(CDR(node));
	
	// if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
	if (mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL)) {
		return SEXP_NAN_FOREVER;
	}

	ship_num = ship_name_lookup(ship_name);
	if (ship_num < 0) {
		return SEXP_NAN;
	}

	// find subsystem type
	subsys_type = -1;
	for (i = 0; i < SUBSYSTEM_MAX; i++)
	{
		if (!stricmp(subsys_type_name, Subsystem_types[i]))
			subsys_type = i;
	}

	// error checking
	if (subsys_type < 0) {
		Warning(LOCATION, "Subsystem type '%s' not recognized in hits-left-subsystem-generic!", subsys_type_name);
		return SEXP_NAN_FOREVER;
	} else if (subsys_type == SUBSYSTEM_NONE) {
		// as you wish...?
		return 0;
	} else if (subsys_type == SUBSYSTEM_UNKNOWN) {
		Warning(LOCATION, "Cannot use SUBSYSTEM_UNKNOWN in hits-left-subsystem-generic!");
		return SEXP_NAN_FOREVER;
	}

	// return as a percentage the hits remaining on the subsystem as a whole (i.e. for 3 engines,
	// we are returning the sum of the hits on the 3 engines)
	return fl2i((ship_get_subsystem_strength(&Ships[ship_num], subsys_type) * 100.0f) + 0.5f);
}

// Goober5000
int sexp_hits_left_subsystem_specific(int node)
{
	int ship_num;
	char *ship_name, *subsys_name;
	ship_subsys *ss;

	ship_name = CTEXT(node);
	subsys_name = CTEXT(CDR(node));
	
	// if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
	if (mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL)) {
		return SEXP_NAN_FOREVER;
	}

	ship_num = ship_name_lookup(ship_name);
	if (ship_num < 0) {
		return SEXP_NAN;
	}

	// find subsystem
	ss = ship_get_subsys(&Ships[ship_num], subsys_name);
	if (ss != NULL) {
		// return as a percentage the hits remaining on this subsystem only
		return fl2i((ss->current_hits / ss->max_hits * 100.0f) + 0.5f);
	}

	// we reached end of ship subsys list without finding subsys_name
	if (ship_class_unchanged(ship_num)) {
		Error(LOCATION, "Invalid subsystem '%s' passed to hits-left-subsystem", subsys_name);
	}
	return SEXP_NAN;
}

int sexp_directive_value(int n)
{	
	int replace_current_value = SEXP_TRUE; 
	int directive_value;

	Assert(n >= 0);

	directive_value = eval_num(n);

	if ((directive_value == SEXP_NAN) || (directive_value == SEXP_NAN_FOREVER)) {
		directive_value = 0;
	}

	n = CDR(n);
	if (n > -1) {
		replace_current_value = eval_sexp(n);
	}

	if (replace_current_value == SEXP_FALSE) { // note: any SEXP_KNOWN_FALSE result will return SEXP_FALSE
		Directive_count += directive_value;
	}
	else {
		Directive_count = directive_value;
	}

		
	return SEXP_TRUE;
}

int sexp_determine_team(char *subj)
{
	int len;
	char team_name[NAME_LENGTH];

	// quick check
	if (strnicmp(subj, "<any ", 5))
		return -1;

	// grab IFF (rest of string except for closing angle bracket)
	len = strlen(subj + 5) - 1;
	strncpy(team_name, subj + 5, len);
	team_name[len] = '\0';

	// find it
	return iff_lookup(team_name);
}

/**
 * Check distance between two given objects
 */
int sexp_distance3(object *objp1, object *objp2)
{
	// if either object isn't present in the mission now
	if (objp1 == NULL || objp2 == NULL)
		return SEXP_NAN;

	if ((objp1->type == OBJ_SHIP) && (objp2->type == OBJ_SHIP))
	{
		if (Player_obj == objp1)
			return (int) hud_find_target_distance(objp2, objp1);
		else
			return (int) hud_find_target_distance(objp1, objp2);
	}
	else
	{
		return (int) vm_vec_dist_quick(&objp1->pos, &objp2->pos);
	}
}

/**
 * Check distance between a given ship and a given subject (ship, wing, any \<team\>).
 */
int sexp_distance2(object *objp1, object_ship_wing_point_team *oswpt2)
{
	int dist, dist_min = 0, inited = 0;

	switch (oswpt2->type)
	{
		// we have a ship-on-team type, so check all ships of that type
		case OSWPT_TYPE_SHIP_ON_TEAM:
		{
			for (ship_obj *so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so))
			{
				if (Ships[Objects[so->objnum].instance].team == oswpt2->team)
				{
					dist = sexp_distance3(objp1, &Objects[so->objnum]);
					if (dist != SEXP_NAN)
					{
						if (!inited || (dist < dist_min))
						{
							dist_min = dist;
							inited = 1;
						}
					}
				}
			}

			// no objects were checked
			if (!inited)
				return SEXP_NAN;

			return dist_min;
		}

		// check ships and points
		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WAYPOINT:
		{
			return sexp_distance3(objp1, oswpt2->objp);
		}

		// check wings
		case OSWPT_TYPE_WING:
		{
			for (int i = 0; i < oswpt2->wingp->current_count; i++)
			{
				dist = sexp_distance3(objp1, &Objects[Ships[oswpt2->wingp->ship_index[i]].objnum]);
				if (dist != SEXP_NAN)
				{
					if (!inited || (dist < dist_min))
					{
						dist_min = dist;
						inited = 1;
					}
				}
			}

			// no objects were checked
			if (!inited)
				return SEXP_NAN;

			return dist_min;
		}
	}

	return SEXP_NAN;
}

/**
 * Returns the distance between two objects.
 *
 * If a wing is specified as one (or both) of the arguments to this function, we are looking for the closest distance
 */
int sexp_distance(int n)
{
	int dist, dist_min = 0, inited = 0;
	object_ship_wing_point_team oswpt1, oswpt2;

	sexp_get_object_ship_wing_point_team(&oswpt1, CTEXT(n));
	sexp_get_object_ship_wing_point_team(&oswpt2, CTEXT(CDR(n)));

	// check to see if either object was destroyed or departed
	if (oswpt1.type == OSWPT_TYPE_EXITED || oswpt2.type == OSWPT_TYPE_EXITED)
		return SEXP_NAN_FOREVER;

	switch (oswpt1.type)
	{
		// we have a ship-on-team type, so check all ships of that type
		case OSWPT_TYPE_SHIP_ON_TEAM:
		{
			for (ship_obj *so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so))
			{
				if (Ships[Objects[so->objnum].instance].team == oswpt1.team)
				{
					dist = sexp_distance2(&Objects[so->objnum], &oswpt2);
					if (dist != SEXP_NAN)
					{
						if (!inited || (dist < dist_min))
						{
							dist_min = dist;
							inited = 1;
						}
					}
				}
			}

			// no objects were checked
			if (!inited)
				return SEXP_NAN;

			return dist_min;
		}

		// check ships and points
		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WAYPOINT:
		{
			return sexp_distance2(oswpt1.objp, &oswpt2);
		}

		// check wings
		case OSWPT_TYPE_WING:
		{
			for (int i = 0; i < oswpt1.wingp->current_count; i++)
			{
				dist = sexp_distance2(&Objects[Ships[oswpt1.wingp->ship_index[i]].objnum], &oswpt2);
				if (dist != SEXP_NAN)
				{
					if (!inited || (dist < dist_min))
					{
						dist_min = dist;
						inited = 1;
					}
				}
			}

			// no objects were checked
			if (!inited)
				return SEXP_NAN;

			return dist_min;
		}
	}

	return SEXP_NAN;
}

/**
 * Locate the subsystem on a ship - Goober5000
 * 
 * Switched to a boolean so that it can report failure to do so
 */
bool sexp_get_subsystem_world_pos(vec3d *subsys_world_pos, int shipnum, char *subsys_name)
{
	Assert(subsys_name);
	Assert(subsys_world_pos);

	if(shipnum < 0)
	{
		Error(LOCATION, "Error - nonexistent ship.\n");
	}

	// find the ship subsystem
	ship_subsys *ss = ship_get_subsys(&Ships[shipnum], subsys_name);
	if (ss != NULL)
	{
		// find world position of subsystem on this object (the ship)
		get_subsystem_world_pos(&Objects[Ships[shipnum].objnum], ss, subsys_world_pos);
		return true;
	}

	// we reached end of ship subsys list without finding subsys_name 
	if (ship_class_unchanged(shipnum)) {
		// this ship should have had the subsystem named as it shouldn't have changed class
		Error(LOCATION, "sexp_get_subsystem_world_pos could not find subsystem '%s'", subsys_name);
	}
	return false;
}

/**
 * Returns the distance between an object and a ship subsystem.
 *
 * If a wing is specified as the object argument to this function, we are looking for the closest distance
 */
int sexp_distance_subsystem(int n)
{
	int ship_with_subsys_num, dist, dist_min = 0, inited = 0;
	char *ship_with_subsys_name, *subsys_name;
	vec3d subsys_pos;
	object_ship_wing_point_team oswpt;

	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));
	ship_with_subsys_name = CTEXT(CDR(n));
	subsys_name = CTEXT(CDR(CDR(n)));

	// for the ship with the subsystem - see if it was destroyed or departed
	if (mission_log_get_time(LOG_SHIP_DESTROYED, ship_with_subsys_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DEPARTED, ship_with_subsys_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_with_subsys_name, NULL, NULL))
		return SEXP_NAN_FOREVER;

	// check the other ship too
	if (oswpt.type == OSWPT_TYPE_EXITED)
		return SEXP_NAN_FOREVER;

	// for the ship with the subsystem - get its index
	ship_with_subsys_num = ship_name_lookup(ship_with_subsys_name);
	if (ship_with_subsys_num < 0)
		return SEXP_NAN;

	// get the subsystem's coordinates or bail if we can't
	if (!sexp_get_subsystem_world_pos(&subsys_pos, ship_with_subsys_num, subsys_name)) 
		return SEXP_NAN;

	switch (oswpt.type)
	{
		// we have a ship-on-team type, so check all ships of that type
		case OSWPT_TYPE_SHIP_ON_TEAM:
		{
			for (ship_obj *so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so))
			{
				if (Ships[Objects[so->objnum].instance].team == oswpt.team)
				{
					dist = (int) vm_vec_dist_quick(&Objects[so->objnum].pos, &subsys_pos);

					if (!inited || (dist < dist_min))
					{
						dist_min = dist;
						inited = 1;
					}
				}
			}

			// no objects were checked
			if (!inited)
				return SEXP_NAN;

			return dist_min;
		}

		// check ships and points
		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WAYPOINT:
		{
			return (int) vm_vec_dist_quick(&oswpt.objp->pos, &subsys_pos);
		}

		// check wings
		case OSWPT_TYPE_WING:
		{
			for (int i = 0; i < oswpt.wingp->current_count; i++)
			{
				dist = (int) vm_vec_dist_quick(&Objects[Ships[oswpt.wingp->ship_index[i]].objnum].pos, &subsys_pos);

				if (!inited || (dist < dist_min))
				{
					dist_min = dist;
					inited = 1;
				}
			}

			// no objects were checked
			if (!inited)
				return SEXP_NAN;

			return dist_min;
		}
	}

	return SEXP_NAN;
}

bool sexp_helper_is_within_box(float *box_vals, vec3d *pos)
{
	int i;
	for(i = 0; i < 3; i++)
	{
		if(pos->a1d[i] < (box_vals[i] - box_vals[i+3])
			|| pos->a1d[i] > (box_vals[i] + box_vals[i+3]))
		{
			return false;
		}
	}

	return true;
}

int sexp_num_within_box(int n)
{
	float box_vals[6];//x,y,z,width,height,depth
	char *ship_wing;
	int i, idx;
	int retval = 0;

	for(i = 0; i < 6; i++)
	{
		box_vals[i] = i2fl(eval_num(n));
		n = CDR(n);
	}

	
	for(;n != -1; n = CDR(n))
	{
		ship_wing = CTEXT(n);

		idx = ship_name_lookup(ship_wing);
		if(idx > -1)
		{
			if(sexp_helper_is_within_box(box_vals, &Objects[Ships[idx].objnum].pos))
				retval++;
		}
		else
		{
			idx = wing_name_lookup(ship_wing);
			if(idx > -1)
			{
				bool wing_check = true;
				for(i = 0; i < Wings[idx].current_count; i++)
				{
					if(!sexp_helper_is_within_box(box_vals, &Objects[Ships[Wings[idx].ship_index[i]].objnum].pos))
					{
						wing_check = false;
						break;
					}
				}

				if(wing_check)
					retval++;
			}
		}
	}

	return retval;
}	

// Goober5000
void sexp_set_object_speed(object *objp, int speed, int axis, int subjective)
{
	Assert(axis >= 0 && axis <= 2);

	if (subjective)
	{
		vec3d subjective_vel;

		// translate objective into subjective velocity
		vm_vec_rotate(&subjective_vel, &objp->phys_info.vel, &objp->orient);

		// set it
		subjective_vel.a1d[axis] = i2fl(speed);

		// translate it back to objective
		vm_vec_unrotate(&objp->phys_info.vel, &subjective_vel, &objp->orient);
	}
	else
	{
		objp->phys_info.vel.a1d[axis] = i2fl(speed);
	}
}

// Goober5000
void sexp_set_object_speed(int n, int axis)
{
	Assert(n >= 0);

	int speed, subjective = 0;
	object_ship_wing_point_team oswpt;

	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));
	n = CDR(n);

	speed = eval_num(n);
	n = CDR(n);

	if (n >= 0)
	{
		subjective = is_sexp_true(n);
		n = CDR(n);
	}

	switch (oswpt.type)
	{
		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WING:
		{
			sexp_set_object_speed(oswpt.objp, speed, axis, subjective);

			//CommanderDJ - we put the multiplayer callback stuff in here to prevent doing unnecessary checks clientside
			multi_start_callback();
			multi_send_object(oswpt.objp);
			multi_send_int(speed);
			multi_send_int(axis);
			multi_send_int(subjective);
			multi_end_callback();

			break;
		}
	}
}

//CommanderDJ
void multi_sexp_set_object_speed()
{
	object *objp;
	int speed = 0, axis = 0, subjective = 0;

	multi_get_object(objp);
	multi_get_int(speed);
	multi_get_int(axis);
	multi_get_int(subjective);

	sexp_set_object_speed(objp, speed, axis, subjective);
}

int sexp_get_object_speed(object *objp, int axis, int subjective)
{
	Assertion(((axis >= 0) && (axis <= 2)), "Axis is out of range (%d)", axis);
	int speed;

	if (subjective)
	{
		// return the speed based on the orentation of the object
		vec3d subjective_vel;
		vm_vec_rotate(&subjective_vel, &objp->phys_info.vel, &objp->orient);
		speed = fl2i(subjective_vel.a1d[axis]);
		vm_vec_unrotate(&objp->phys_info.vel, &subjective_vel, &objp->orient);
	}
	else
	{
		// return the speed according to the grid
		speed = fl2i(objp->phys_info.vel.a1d[axis]);
	}
	return speed;
}

int sexp_get_object_speed(int n, int axis)
{
	Assert(n >= 0);

	int speed, subjective = 0;
	object_ship_wing_point_team oswpt;

	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));
	n = CDR(n);

	if (n >= 0)
	{
		subjective = is_sexp_true(n);
		n = CDR(n);
	}

	switch (oswpt.type)
	{
		case OSWPT_TYPE_EXITED:
			return SEXP_NAN_FOREVER;

		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WING:
			speed = sexp_get_object_speed(oswpt.objp, axis, subjective);
			break;

		default:
			return SEXP_NAN;
	}
	return speed;
}

// Goober5000
int sexp_calculate_coordinate(vec3d *origin, matrix *orient, vec3d *relative_location, int axis)
{
	Assert(origin != NULL);
	Assert(orient != NULL);
	Assert(axis >= 0 && axis <= 2);

	if (relative_location == NULL)
	{
		return fl2i(origin->a1d[axis]);
	}
	else
	{
		vec3d new_world_pos;

		vm_vec_unrotate(&new_world_pos, relative_location, orient);
		vm_vec_add2(&new_world_pos, origin);

		return fl2i(new_world_pos.a1d[axis]);
	}
}

// Goober5000
int sexp_calculate_angle(matrix *orient, int axis)
{
	Assert(orient != NULL);
	Assert(axis >= 0 && axis <= 2);

	angles a;
	vm_extract_angles_matrix_alternate(&a, orient);

	// blugh
	float rad;
	switch (axis)
	{
		case 0:	rad = a.p; break;
		case 1:	rad = a.b; break;
		case 2:	rad = a.h; break;
		default: rad = 0.0f; break;
	}

	float deg = fl_degrees(rad);

	int deg2 = static_cast<int>(deg < 0.0f ? deg - 0.5f : deg + 0.5f);
	if (deg2 < 0)
		deg2 += 360;

	return deg2;
}

// Goober5000
int sexp_get_object_coordinate(int n, int axis) 
{
	Assert(n >= 0);

	char *subsystem_name = NULL;
	vec3d *pos = NULL, *relative_location = NULL, relative_location_buf, subsys_pos_buf;
	object_ship_wing_point_team oswpt;

	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));
	n = CDR(n);

	if (n >= 0)
	{
		subsystem_name = CTEXT(n);
		n = CDR(n);

		if (n >= 0)
		{
			relative_location = &relative_location_buf;

			relative_location->xyz.x = (float) eval_num(n);
			n = CDR(n);
			if (n >= 0) {
				relative_location->xyz.y = (float) eval_num(n);
				n = CDR(n);
				if (n >= 0) {
					relative_location->xyz.z = (float) eval_num(n);
					n = CDR(n);
				}
			}
		}
	}

	switch (oswpt.type)
	{
		case OSWPT_TYPE_EXITED:
			return SEXP_NAN_FOREVER;

		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WING:
		case OSWPT_TYPE_WAYPOINT:
			pos = &oswpt.objp->pos;
			break;

		default:
			return SEXP_NAN;
	}

	// see if we have a subsys
	if (oswpt.objp->type == OBJ_SHIP)
	{
		if ((subsystem_name != NULL) && stricmp(subsystem_name, SEXP_NONE_STRING) && stricmp(subsystem_name, SEXP_HULL_STRING))
		{
			pos = &subsys_pos_buf;
			// get the world pos but bail if we can't get one
			if (!sexp_get_subsystem_world_pos(pos, oswpt.objp->instance, subsystem_name))
				return SEXP_NAN;
		}
	}

	return sexp_calculate_coordinate(pos, &oswpt.objp->orient, relative_location, axis);
}

// Goober5000
int sexp_get_object_angle(int n, int axis) 
{
	Assert(n >= 0);

	object_ship_wing_point_team oswpt;
	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));

	switch (oswpt.type)
	{
		case OSWPT_TYPE_EXITED:
			return SEXP_NAN_FOREVER;

		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WING:
			return sexp_calculate_angle(&oswpt.objp->orient, axis);

		default:
			return SEXP_NAN;
	}
}

void set_object_for_clients(object *objp)
{
	if (!(Game_mode & GM_MULTIPLAYER)) {
		return;
	}

	// Tell the player (if this is a client) that they've moved.
	if ((objp->flags & OF_PLAYER_SHIP) && (objp != Player_obj) ){
		multi_oo_send_changed_object(objp);
	}
}

void sexp_set_object_position(int n) 
{
	vec3d target_vec, orig_leader_vec;
	object_ship_wing_point_team oswpt;

	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));
	n = CDR(n);

	target_vec.xyz.x = i2fl(eval_num(n));
	n = CDR(n);
	target_vec.xyz.y = i2fl(eval_num(n));
	n = CDR(n);
	target_vec.xyz.z = i2fl(eval_num(n));
	n = CDR(n);

	// retime all collision checks so they're performed
	// Goober5000 - only if we have a valid object (don't do this for departed ships, waypoints, etc.)
	if (oswpt.type == OSWPT_TYPE_SHIP || oswpt.type == OSWPT_TYPE_WING)
	{
		if ( Cmdline_old_collision_sys ) {
			obj_all_collisions_retime();
		} else {
			obj_collide_retime_cached_pairs();
		}
	}

	// if this is a nebula mission and a player is being moved far enough,
	// regenerate the nebula
	extern neb2_detail *Nd;

	if ( (oswpt.objp == Player_obj) 
		&& (The_mission.flags & MISSION_FLAG_FULLNEB) 
		&& (vm_vec_dist(&oswpt.objp->pos, &target_vec) >= Nd->cube_inner) )
	{
		neb2_eye_changed();
	}

	switch (oswpt.type)
	{
		case OSWPT_TYPE_SHIP:
		{
			oswpt.objp->pos = target_vec;
			set_object_for_clients(oswpt.objp);
			return;
		}

		case OSWPT_TYPE_WAYPOINT:
		{
			oswpt.objp->pos = target_vec;
			oswpt.waypointp->set_pos(&target_vec);
			multi_start_callback();
			multi_send_ushort(oswpt.objp->net_signature);
			multi_send_float(target_vec.xyz.x);
			multi_send_float(target_vec.xyz.y);
			multi_send_float(target_vec.xyz.z);
			multi_end_callback();		
			return;
		}

		case OSWPT_TYPE_WING:
		{
			// move the wing leader first
			orig_leader_vec = oswpt.objp->pos;
			oswpt.objp->pos = target_vec;
			set_object_for_clients(oswpt.objp);

			// move everything in the wing
			for (int i = 0; i < oswpt.wingp->current_count; i++)
			{
				object *objp = &Objects[Ships[oswpt.wingp->ship_index[i]].objnum];

				if (objp != oswpt.objp)
				{
					vm_vec_sub2(&objp->pos, &orig_leader_vec);
					vm_vec_add2(&objp->pos, &target_vec);
					set_object_for_clients(objp);
				}
			}

			return;
		}
	}
}

// only for waypoints cause they don't get transferred the normal way
void multi_sexp_set_object_position()
{
	object *objp;
	vec3d wp_vec;
	ushort obj_sig;
	multi_get_ushort(obj_sig);
	multi_get_float(wp_vec.xyz.x);
	multi_get_float(wp_vec.xyz.y);
	multi_get_float(wp_vec.xyz.z);
	objp = multi_get_network_object(obj_sig);
	if (objp->type == OBJ_WAYPOINT) {
		objp->pos = wp_vec;
		waypoint *wpt = find_waypoint_with_objnum(OBJ_INDEX(objp));
		wpt->set_pos(&wp_vec);
	}
}

// Goober5000
void sexp_set_object_orientation(int n) 
{
	angles a;
	matrix target_orient;
	object_ship_wing_point_team oswpt;

	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));
	n = CDR(n);

	a.p = fl_radians(eval_num(n) % 360);
	n = CDR(n);
	a.b = fl_radians(eval_num(n) % 360);
	n = CDR(n);
	a.h = fl_radians(eval_num(n) % 360);
	n = CDR(n);

	vm_angles_2_matrix(&target_orient, &a);

	// retime all collision checks so they're performed
	// Goober5000 - only if we have a valid object (don't do this for departed ships, waypoints, etc.)
	if (oswpt.type == OSWPT_TYPE_SHIP || oswpt.type == OSWPT_TYPE_WING)
	{
		if ( Cmdline_old_collision_sys ) {
			obj_all_collisions_retime();
		} else {
			obj_collide_retime_cached_pairs();
		}
	}

	switch (oswpt.type)
	{
		case OSWPT_TYPE_SHIP:
		{
			oswpt.objp->orient = target_orient;
			set_object_for_clients(oswpt.objp);
			return;
		}

		case OSWPT_TYPE_WING:
		{
			// move everything in the wing
			for (int i = 0; i < oswpt.wingp->current_count; i++)
			{
				object *objp = &Objects[Ships[oswpt.wingp->ship_index[i]].objnum];
				objp->orient = target_orient;
				set_object_for_clients(objp);
			}

			return;
		}
	}
}

// Goober5000
// this is different from sexp_set_object_orientation
void sexp_set_object_orient_sub(object *objp, vec3d *location, int turn_time, int bank)
{
	Assert(objp && location);

	vec3d v_orient;
	matrix m_orient;


	// are we doing this via ai? -------------------
	if (turn_time)
	{
		// set flag
		int bankflag = 0;
		if (!bank) 
		{
			bankflag = AITTV_IGNORE_BANK;
		}

		// turn
		ai_turn_towards_vector(location, objp, flFrametime, float(turn_time)/(1000.0f), NULL, NULL, 0.0f, 0, NULL, (AITTV_VIA_SEXP | bankflag));

		// return
		return;
	}


	// calculate orientation matrix ----------------

	vm_vec_sub(&v_orient, location, &objp->pos);

	if (IS_VEC_NULL_SQ_SAFE(&v_orient))
	{
		Warning(LOCATION, "error in sexp setting ship orientation: can't point to self; quitting...\n");
		return;
	}

	vm_vector_2_matrix(&m_orient, &v_orient, NULL, NULL);


	// set orientation -----------------------------
	objp->orient = m_orient;
	// Tell the player (assuming it's a client) that they've moved.
	set_object_for_clients(objp);
}

// Goober5000
void sexp_set_oswpt_facing(object_ship_wing_point_team *oswpt, vec3d *location, int turn_time = 0, int bank = 0)
{
	Assert(oswpt && location);

	switch (oswpt->type)
	{
		case OSWPT_TYPE_SHIP:
			sexp_set_object_orient_sub(oswpt->objp, location, turn_time, bank);
			break;

		case OSWPT_TYPE_WING:
		{
			for (int i = 0; i < oswpt->wingp->current_count; i++)
			{
				object *objp = &Objects[Ships[oswpt->wingp->ship_index[i]].objnum];

				sexp_set_object_orient_sub(objp, location, turn_time, bank);
			}

			break;
		}
	}
}

// Goober5000
void sexp_set_object_facing(int n, bool facing_object)
{
	vec3d *location, location_buf;
	int turn_time, bank;
	object_ship_wing_point_team oswpt1, oswpt2;

	sexp_get_object_ship_wing_point_team(&oswpt1, CTEXT(n));
	n = CDR(n);

	// ensure it's valid
	if (oswpt1.objp == NULL)
		return;

	// get location
	if (facing_object)
	{
		sexp_get_object_ship_wing_point_team(&oswpt2, CTEXT(n));
		n = CDR(n);

		// ensure it's valid
		if (oswpt2.objp == NULL)
			return;

		location = &oswpt2.objp->pos;
	}
	else
	{
		location = &location_buf;

		location->xyz.x = (float) eval_num(n);
		n = CDR(n);
		location->xyz.y = (float) eval_num(n);
		n = CDR(n);
		location->xyz.z = (float) eval_num(n);
		n = CDR(n);
	}

	// get optional turn time and bank
	turn_time = bank = 0;
	if (n != -1)
	{
		turn_time = eval_num(n);
		n = CDR(n);
	}
	if (n != -1)
	{
		bank = eval_num(n);
	}

	sexp_set_oswpt_facing(&oswpt1, location, turn_time, bank);
}

void sexp_set_ship_man(object *objp, int duration, int heading, int pitch, int bank, bool apply_all_rotate, int up, int sideways, int forward, bool apply_all_lat)
{
	if (objp->type != OBJ_SHIP)
		return;

	ship *shipp = &Ships[objp->instance];
	ai_info	*aip = &Ai_info[shipp->ai_index];
	
	aip->ai_override_timestamp = timestamp(duration);
	aip->ai_override_flags = 0;
	
	if (apply_all_rotate) {
		aip->ai_override_flags |= AIORF_FULL;
		aip->ai_override_ci.bank = bank / 100.0f;
		aip->ai_override_ci.pitch = pitch / 100.0f;
		aip->ai_override_ci.heading = heading / 100.0f;
	} else {
		if (bank != 0) {
			aip->ai_override_flags |= AIORF_ROLL;
			aip->ai_override_ci.bank = bank / 100.0f;
		}
		if (pitch != 0) {
			aip->ai_override_flags |= AIORF_PITCH;
			aip->ai_override_ci.pitch = pitch / 100.0f;
		}
		if (heading != 0) {
			aip->ai_override_flags |= AIORF_HEADING;
			aip->ai_override_ci.heading = heading / 100.0f;
		}
	}
	if (apply_all_lat) {
		aip->ai_override_flags |= AIORF_FULL_LAT;
		aip->ai_override_ci.vertical = up / 100.0f;
		aip->ai_override_ci.sideways = sideways / 100.0f;
		aip->ai_override_ci.forward = forward / 100.0f;
	} else {
		if (up != 0) {
			aip->ai_override_flags |= AIORF_UP;
			aip->ai_override_ci.vertical = up / 100.0f;
		}
		if (sideways != 0) {
			aip->ai_override_flags |= AIORF_SIDEWAYS;
			aip->ai_override_ci.sideways = sideways / 100.0f;
		}
		if (forward != 0) {
			aip->ai_override_flags |= AIORF_FORWARD;
			aip->ai_override_ci.forward = forward / 100.0f;
		}
	}
}

void sexp_set_oswpt_maneuver(object_ship_wing_point_team *oswpt, int duration, int heading, int pitch, int bank, bool apply_all_rotate, int up, int sideways, int forward, bool apply_all_lat)
{
	Assert(oswpt);

	switch (oswpt->type)
	{
		case OSWPT_TYPE_SHIP:
			sexp_set_ship_man(oswpt->objp, duration, heading, pitch, bank, apply_all_rotate, up, sideways, forward, apply_all_lat);
			break;

		case OSWPT_TYPE_WING:
		{
			for (int i = 0; i < oswpt->wingp->current_count; i++)
			{
				object *objp = &Objects[Ships[oswpt->wingp->ship_index[i]].objnum];

				sexp_set_ship_man(objp, duration, heading, pitch, bank, apply_all_rotate, up, sideways, forward, apply_all_lat);
			}

			break;
		}
	}
}

void sexp_set_ship_maneuver(int n, int op_num)
{
	int bank = 0, heading = 0, pitch = 0;
	int up = 0, sideways = 0, forward = 0;
	int duration, i, temp;
	bool apply_all_rotate = false, apply_all_lat = false;
	object_ship_wing_point_team oswpt;

	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));

	n = CDR(n);
	duration = eval_num(n);
	if (duration < 2)
		return;

	if (op_num == OP_SHIP_ROT_MANEUVER || op_num == OP_SHIP_MANEUVER) {
		for(i=0;i<3;i++) {
			n = CDR(n);

			temp = eval_num(n);
			if (temp > 100) temp = 100;
			if (temp < -100) temp = -100;

			if (i == 0)
				heading = temp;
			else if (i == 1)
				pitch = temp;
			else
				bank = temp;
		}

		n = CDR(n);
		apply_all_rotate = (is_sexp_true(n) != 0);
	}

	if (op_num == OP_SHIP_LAT_MANEUVER || op_num == OP_SHIP_MANEUVER) {
		for(i=0;i<3;i++) {
			n = CDR(n);

			temp = eval_num(n);
			if (temp > 100) temp = 100;
			if (temp < -100) temp = -100;

			if (i == 0)
				up = temp;
			else if (i == 1)
				sideways = temp;
			else
				forward = temp;
		}

		n = CDR(n);
		apply_all_lat = (is_sexp_true(n) != 0);
	}

	if ((bank == 0) && (pitch == 0) && (heading == 0) && !apply_all_rotate && (up == 0) && (sideways == 0) && (forward == 0) && !apply_all_lat)
		return;

	sexp_set_oswpt_maneuver(&oswpt, duration, heading, pitch, bank, apply_all_rotate, up, sideways, forward, apply_all_lat);
}

/**
 * Determine when the last meaningful order was given to one or more ships.
 * 
 * @return true or false depending on whether or not a meaningful order was received
 */
int sexp_last_order_time(int n)
{
	int instance, i;
	fix time;
	char *name;
	ai_goal *aigp;

	time = i2f(eval_num(n));
	Assert ( time >= 0 );

	n = CDR(n);
	while ( n != -1 ) {
		name = CTEXT(n);
		instance = ship_name_lookup(name);
		if ( instance != -1 ) {
			aigp = Ai_info[Ships[instance].ai_index].goals;
		} else {
			instance = wing_name_lookup(name);
			if ( instance == -1 )						// if we cannot find ship or wing, return SEXP_FALSE
				return SEXP_FALSE;
			aigp = Wings[instance].ai_goals;
		}

		// with the ship, check the ai_goals structure for this ship and determine if there are any
		// orders which are < time seconds since current mission time
		for ( i = 0; i < MAX_AI_GOALS; i++ ) {
			int mode;

			mode = aigp->ai_mode;
			if ( (mode  != AI_GOAL_NONE) && (mode != AI_GOAL_WARP) )
				if ( (aigp->time + time) > Missiontime )
					break;
			aigp++;
		}
		if ( i == MAX_AI_GOALS )
			return SEXP_TRUE;

		n = CDR(n);
	}

	return SEXP_FALSE;
}

/**
 * Return the number of players in the mission
 */
int sexp_num_players()
{
	int count;
	object *objp;

	count = 0;
	for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
		if ( (objp->type == OBJ_SHIP) && (objp->flags & OF_PLAYER_SHIP) )
			count++;
	}

	return count;
}

/**
 * Determine if the current skill level of the game is at least the skill level given in the SEXP
 */
int sexp_skill_level_at_least(int n)
{
	int i;
	char *level_name;

	level_name = CTEXT(n);

	if (level_name == NULL)
		return SEXP_FALSE;

	for (i = 0; i < NUM_SKILL_LEVELS; i++ ) {
		if ( !stricmp(level_name, Skill_level_names(i, 0)) ) {
			if ( Game_skill_level >= i ){
				return SEXP_TRUE;
			} else {
				return SEXP_FALSE;
			}
		}
	}

	// return SEXP_FALSE if not found!!!
	return SEXP_FALSE;
}

int sexp_was_promotion_granted(int n)
{
	if (Player->flags & PLAYER_FLAGS_PROMOTED)
		return SEXP_TRUE;

	return SEXP_FALSE;
}

int sexp_was_medal_granted(int n)
{
	int i;
	char *medal_name;

	if (n < 0) {
		if (Player->stats.m_medal_earned >= 0)
			return SEXP_TRUE;

		return SEXP_FALSE;
	}

	medal_name = CTEXT(n);

	if (medal_name == NULL)
		return SEXP_FALSE;

	for (i=0; i<Num_medals; i++) {
		if (!stricmp(medal_name, Medals[i].name))
			break;
	}

	if ( (i < Num_medals) && (Player->stats.m_medal_earned == i) )
		return SEXP_TRUE;

	return SEXP_FALSE;
}

/**
 * @todo Add code to check the damage ships which have exited have taken
 */
float get_damage_caused(int damaged_ship, int attacker ) 
{
	int sindex, idx;
	float damage_total = 0.0f; 


	// is the ship that took damage in the mission still?
	sindex = ship_get_by_signature(damaged_ship);

	if (sindex >= 0 ) {
		for(idx=0; idx<MAX_DAMAGE_SLOTS; idx++){
			if (Ships[sindex].damage_ship_id[idx] == attacker) {
				damage_total += Ships[sindex].damage_ship[idx];
				break;
			}
		}
	}
	else {
		//TO DO - Add code to check the damage ships which have exited have taken
	
		sindex = ship_find_exited_ship_by_signature(damaged_ship);
		for(idx=0; idx<MAX_DAMAGE_SLOTS; idx++){
			if (Ships_exited[sindex].damage_ship_id[idx] == attacker) {
				damage_total += Ships_exited[sindex].damage_ship[idx];
				break;
			}
		}

	
	}
	return damage_total; 
}

// Karajorma
int sexp_get_damage_caused(int node) 
{
	int sindex, damaged_sig, attacker_sig; 
	float damage_caused = 0.0f;
	char	*name;
	int ship_class;

	name = CTEXT(node);
	sindex = ship_name_lookup(name); 
	if (sindex < 0) {
		// this ship may have exited already.
		sindex = ship_find_exited_ship_by_name(CTEXT(node));
		if (sindex < 0) {
			// this is probably a ship which hasn't arrived and thus can't have taken any damage yet
			return fl2i(damage_caused);
		}
		else {
			damaged_sig = Ships_exited[sindex].obj_signature;
			ship_class = Ships_exited[sindex].ship_class;
		}
	}
	else {
		damaged_sig = Objects[Ships[sindex].objnum].signature ;
		ship_class = Ships[sindex].ship_info_index;
	}


	node = CDR(node);
	Assert (node != -1);

	// go through the list of ships who we think may have attacked the ship
	for ( ; node != -1; node = CDR(node) ) {
		name = CTEXT(node);
		sindex = ship_name_lookup(name); 
		if (sindex < 0) {
			sindex = ship_find_exited_ship_by_name(name);
			if (sindex < 0) {
				continue;
			} else {
			attacker_sig = Ships_exited[sindex].obj_signature; 
		}
		}
		else {
			attacker_sig = Objects[Ships[sindex].objnum].signature ;
		}

		if (attacker_sig < 0) {
			continue;
		}

		damage_caused += get_damage_caused (damaged_sig, attacker_sig);
	}
	
	Assertion((ship_class > -1) && (ship_class < static_cast<int>(Ship_info.size())), "Invalid ship class '%d' passed to sexp_get_damage_caused() (should be >= 0 and < %d); get a coder!\n", ship_class, static_cast<int>(Ship_info.size()));
	return (int) ((damage_caused/Ship_info[ship_class].max_hull_strength) * 100.0f);
}

/**
 * Returns true if the percentage of ships (and ships in wings) departed is at least the percentage given.  
 * 
 * what determine if we should check destroyed or departed status
 * Goober5000 - added disarm and disable
 */
int sexp_percent_ships_arrive_depart_destroy_disarm_disable(int n, int what)
{
	int percent;
	int total, count;
	char *name;

	percent = eval_num(n);

	total = 0;
	count = 0;
	// iterate through the rest of the ships/wings in the list and tally the departures and the
	// total
	for ( n = CDR(n); n != -1; n = CDR(n) ) {
		int wingnum;

		name = CTEXT(n);

		wingnum = wing_name_lookup( name, 1 );
		if ( wingnum != -1 ) {
			// for wings, we can increment the total by the total number of ships that we expect for
			// this wing, and the departures by the number of departures stored for this wing
			total += (Wings[wingnum].wave_count * Wings[wingnum].num_waves);
			if ( what == OP_PERCENT_SHIPS_DEPARTED )
				count += Wings[wingnum].total_departed;
			else if ( what == OP_PERCENT_SHIPS_DESTROYED )
				count += Wings[wingnum].total_destroyed;
			else if ( what == OP_PERCENT_SHIPS_ARRIVED )
				count += Wings[wingnum].total_arrived_count;
			else
				Error(LOCATION, "Invalid status check '%d' for wing '%s' in sexp_percent_ships_arrive_depart_destroy_disarm_disable", what, name);
		} else {
			// must be a ship, so increment the total by 1, then determine if this ship has departed
			total++;
			if ( what == OP_PERCENT_SHIPS_DEPARTED ) {
				if ( mission_log_get_time(LOG_SHIP_DEPARTED, name, NULL, NULL) )
					count++;
			} else if ( what == OP_PERCENT_SHIPS_DESTROYED ) {
				if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, name, NULL, NULL) )
					count++;
			} else if ( what == OP_PERCENT_SHIPS_DISABLED ) {
				if ( mission_log_get_time(LOG_SHIP_DISABLED, name, NULL, NULL) )
					count++;
			} else if ( what == OP_PERCENT_SHIPS_DISARMED ) {
				if ( mission_log_get_time(LOG_SHIP_DISARMED, name, NULL, NULL) )
					count++;
			} else if ( what == OP_PERCENT_SHIPS_ARRIVED ) {
				if ( mission_log_get_time(LOG_SHIP_ARRIVED, name, NULL, NULL) )
					count++;
			} else
				Error(LOCATION, "Invalid status check '%d' for ship '%s' in sexp_percent_ships_depart_destroy_disarm_disable", what, name);

		}
	}

	// now, look at the percentage
	if ( ((count * 100) / total) >= percent )
		return SEXP_KNOWN_TRUE;
	else
		return SEXP_FALSE;
}

/**
 * Determine if a list of ships has departed from within a radius of a given jump node.
 * @return true N seconds after the list of ships have departed
 */
int sexp_depart_node_delay(int n)
{
	int delay, count, num_departed;
	char *jump_node_name, *name;
	fix latest_time, this_time;

	Assert( n >= 0 );

	delay = eval_num(n);
	n = CDR(n);
	jump_node_name = CTEXT(n);

	// iterate through the list of ships
	n = CDR(n);
	latest_time = 0;
	count = 0;
	num_departed = 0;
	while ( n != -1 ) {
		count++;
		name = CTEXT(n);

		if (sexp_query_has_yet_to_arrive(name))
			return SEXP_CANT_EVAL;

		// if ship/wing destroyed, sexpression is known false.  Also, if there is no departure log entry, then
		// the sexpression is not true.
		if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, name, NULL, NULL) )
			return SEXP_KNOWN_FALSE;
		else if ( mission_log_get_time(LOG_SHIP_DEPARTED, name, jump_node_name, &this_time) ) {
			num_departed++;
			if ( this_time > latest_time )
				latest_time = this_time;
		}
		n = CDR(n);
	}

	if ( (count == num_departed) && ((Missiontime - latest_time) >= delay) )
		return SEXP_KNOWN_TRUE;
	else
		return SEXP_FALSE;
}

/**
 * Returns true when the listed ships/wings have all been destroyed or have departed.
 */
int sexp_destroyed_departed_delay(int n)
{
	int count, total;
	fix delay, latest_time;
	char *name;

	Assert( n >= 0 );

	// get the delay
	delay = i2f(eval_num(n));
	n = CDR(n);

	count = 0;					// number destroyed or departed
	total = 0;					// total number of ships/wings to check
	latest_time = 0;
	while ( n != -1 ) {
		int wingnum;
		fix time_gone = 0;

		total++;
		name = CTEXT(n);

		// for wings, check the WF_GONE flag to see if there are no more ships in this wing to arrive.
		wingnum = wing_name_lookup(name, 1);
		if ( wingnum != -1 ) {
			if ( Wings[wingnum].flags & WF_WING_GONE ) {
				// be sure to get the latest time of one of these 
				if ( Wings[wingnum].time_gone > latest_time ){
					time_gone = Wings[wingnum].time_gone;
				}
				count++;
			}
		} else if ( mission_log_get_time(LOG_SHIP_DEPARTED, name, NULL, &time_gone) ) {
			count++;
		} else if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, &time_gone) ) {
			count++;
		} else if ( mission_log_get_time(LOG_SELF_DESTRUCTED, name, NULL, &time_gone) ) {
			count++;
		}

		// check our latest time
		if ( time_gone > latest_time ){
			latest_time = time_gone;
		}

		n = CDR(n);
	}

	if ( (count == total) && (Missiontime > (latest_time + delay)) )
		return SEXP_KNOWN_TRUE;
	else
		return SEXP_FALSE;
}

int sexp_special_warpout_name( int node )
{
	int shipnum, knossos_shipnum;
	char *ship_name, *knossos;

	ship_name = CTEXT(node);
	knossos = CTEXT(CDR(node));

	// check to see if either ship was destroyed or departed.  If so, then make this node known false
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time( LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) ||
		  mission_log_get_time(LOG_SHIP_DESTROYED, knossos, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, knossos, NULL, NULL) || mission_log_get_time( LOG_SELF_DESTRUCTED, knossos, NULL, NULL) ) 
		return SEXP_NAN_FOREVER;

	// get ship name
	shipnum = ship_name_lookup(ship_name);
	if (shipnum < 0) {
		return SEXP_NAN;
	}

	// get knossos ship
	knossos_shipnum = ship_name_lookup(knossos);
	if (knossos_shipnum < 0) {
		return SEXP_NAN;
	}

	// set special warpout objnum
	Ships[shipnum].special_warpout_objnum = Ships[knossos_shipnum].objnum;
	return SEXP_FALSE;
}

/**
 * Determines if N seconds have elapsed since all discovery of all cargo of given ships
 *
 * Goober5000 - I reworked this function to allow for the set-scanned and set-unscanned sexps
 * to work multiple times in a row and also to fix the potential bug where exited ships are
 * checked against their departure time, not against their cargo known time
 */
int sexp_is_cargo_known( int n, int check_delay )
{
	int count, ship_num, num_known, delay;

	char *name;

	Assert ( n >= 0 );

	count = 0;
	num_known = 0;

	// get the delay value (if there is one)
	delay = 0;
	if ( check_delay )
	{
		delay = eval_num(n);
		n = CDR(n);
	}

	while ( n != -1 )
	{
		fix time_known;
		int is_known;

		is_known = 0;

		count++;

		// see if we have already checked this entry
		if ( Sexp_nodes[n].value == SEXP_KNOWN_TRUE )
		{
			num_known++;
		}
		else
		{
			name = CTEXT(n);

			// find the index in the ship array (will be -1 if not in mission)
			ship_num = ship_name_lookup(name);

			// see if the ship has already exited the mission (either through departure or destruction)
			int exited_index = ship_find_exited_ship_by_name(name);
			if (exited_index != -1)
			{
				// if not known, the whole thing is known false
				if ( !(Ships_exited[exited_index].flags & SEF_CARGO_KNOWN) )
					return SEXP_KNOWN_FALSE;

				// check the delay of when we found out
				time_known = Missiontime - Ships_exited[exited_index].time_cargo_revealed;
				if ( f2i(time_known) >= delay )
				{
					is_known = 1;

					// here is the only place in the new sexp that this can be known true
					Sexp_nodes[n].value = SEXP_KNOWN_TRUE;
				}
			}
			// ship either in mission or not arrived yet
			else
			{
				// if ship_name_lookup returns -1, then ship is either exited or yet to arrive,
				// and we've already checked exited
				if ( ship_num != -1 )
				{
					if ( Ships[ship_num].flags & SF_CARGO_REVEALED )
					{
						time_known = Missiontime - Ships[ship_num].time_cargo_revealed;
						if ( f2i(time_known) >= delay )
						{
							is_known = 1;
						}
					}
				}
			}
		}

		// if cargo is known, mark our variable, but not the sexp, because it may change later
		if ( is_known )
		{
			num_known++;
		}

		n = CDR(n);
	}

	Directive_count += count - num_known;
	if ( count == num_known )
		return SEXP_TRUE;
	else
		return SEXP_FALSE;
}

void get_cap_subsys_cargo_flags(int shipnum, char *subsys_name, int *known, fix *time_revealed)
{
	// find the ship subsystem
	ship_subsys *ss = ship_get_subsys(&Ships[shipnum], subsys_name);
	if (ss != NULL)
	{
		// set the flags
		*known = (ss->flags & SSF_CARGO_REVEALED);
		*time_revealed = ss->time_subsys_cargo_revealed;
	}
	// if we didn't find the subsystem, the ship hasn't arrived yet
	else
	{
		*known = -1;
		*time_revealed = 0;
	}
}

// reworked by Goober5000 to allow for set-scanned and set-unscanned to be used more than once
int sexp_cap_subsys_cargo_known_delay(int n)
{
	int delay, count, num_known, ship_num;
	char *ship_name, *subsys_name;

	num_known = 0;
	count = 0;

	Assert( n >= 0 );

	// get delay
	delay = eval_num(n);
	n = CDR(n);

	// get ship name
	ship_name = CTEXT(n);
	n = CDR(n);

	// find the index in the ship array
	ship_num = ship_name_lookup(ship_name);

	while ( n != -1 )
	{
		fix time_known;
		int is_known;

		is_known = 0;
		count++;

		// see if we have already checked this entry
		if ( Sexp_nodes[n].value == SEXP_KNOWN_TRUE )
		{
			num_known++;
		}
		else
		{
			// get subsys name
			subsys_name = CTEXT(n);

			// see if the ship has already exited the mission (either through departure or destruction)
			if (ship_find_exited_ship_by_name(ship_name) != -1)
			{
				// check the delay of when we found out...
				// Since there is no way to keep track of subsystem status once a ship has departed
				// or has been destroyed, check the mission log.  This will work in 99.9999999% of
				// all cases; however, if the mission designer repeatedly sets and resets the scanned
				// status of the subsystem, the mission log will only return the first occurrence of the
				// subsystem cargo being revealed (regardless of whether it was first hidden using
				// set-unscanned).  Normally, ships keep track of cargo data in the subsystem struct,
				// but once/ the ship has left the mission, the subsystem linked list is purged,
				// causing the loss of this information.  I judged the significant rework of the
				// subsystem code not worth the rare instance that this sexp may be required to work
				// in this way, especially since this problem only occurs after the ship departs.  If
				// the mission designer really needs this functionality, he or she can achieve the
				// same result with creative combinations of event chaining and is-event-true.
				if (!mission_log_get_time(LOG_CAP_SUBSYS_CARGO_REVEALED, ship_name, subsys_name, &time_known))
				{
					// if not known, the whole thing is known false
					return SEXP_KNOWN_FALSE;
				}

				if (f2i(Missiontime - time_known) >= delay)
				{
					is_known = 1;

					// here is the only place in the new sexp that this can be known true
					Sexp_nodes[n].value = SEXP_KNOWN_TRUE;
				}
			}
			// ship either in mission or not arrived yet
			else
			{
				// if ship_name_lookup returns -1, then ship is either exited or yet to arrive,
				// and we've already checked exited
				if ( ship_num != -1 )
				{
					int cargo_revealed(0);
					fix time_revealed(0);

					// get flags
					get_cap_subsys_cargo_flags(ship_num, subsys_name, &cargo_revealed, &time_revealed);

					if (cargo_revealed)
					{
						time_known = Missiontime - time_revealed;
						if ( f2i(time_known) >= delay )
						{
							is_known = 1;
						}
					}
				}
			}
		}

		// if cargo is known, mark our variable, but not the sexp, because it may change later
		if (is_known)
		{
			num_known++;
		}

		n = CDR(n);
	}

	Directive_count += count - num_known;
	if ( count == num_known )
		return SEXP_TRUE;
	else
		return SEXP_FALSE;
}

// Goober5000
void sexp_set_scanned_unscanned(int n, int flag)
{
	char *ship_name, *subsys_name;
	int shipnum;
	ship_subsys *ss;

	// get ship name
	ship_name = CTEXT(n);

	// check to see the ship was destroyed or departed - if so, do nothing
	if ( mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) )
	{
		return;
	}

	// get ship number
	shipnum = ship_name_lookup(ship_name);

	// if the ship isn't in the mission, do nothing
	if (shipnum == -1)
	{
		return;
	}

	// check for possible next optional argument: subsystem
	n = CDR(n);

	// if no subsystem specified, just do it for the ship and exit
	if (n == -1)
	{
		if (flag)
			ship_do_cargo_revealed(&Ships[shipnum]);
		else
			ship_do_cargo_hidden(&Ships[shipnum]);

		return;
	}

	// iterate through all subsystems
	while (n != -1)
	{
		subsys_name = CTEXT(n);

		// find the ship subsystem
		ss = ship_get_subsys(&Ships[shipnum], subsys_name);
		if (ss != NULL)
		{
			// do it for the subsystem
			if (flag)
				ship_do_cap_subsys_cargo_revealed(&Ships[shipnum], ss);
			else
				ship_do_cap_subsys_cargo_hidden(&Ships[shipnum], ss);
		}

		// if we didn't find the subsystem -- bad
		if (ss == NULL && ship_class_unchanged(shipnum)) {
			Error(LOCATION, "Couldn't find subsystem '%s' on ship '%s' in sexp_set_scanned_unscanned", subsys_name, ship_name);
		}

		// but if it did, loop again
		n = CDR(n);
	}
}

int sexp_has_been_tagged_delay(int n)
{
	int count, shipnum, num_known, delay;
	char *name;

	Assert ( n >= 0 );

	count = 0;
	num_known = 0;

	// get the delay value
	delay = eval_num(n);

	n = CDR(n);

	while ( n != -1 ) {
		fix time_known;
		int is_known;

		is_known = 0;

		count++;

		// see if we have already checked this entry
		if ( Sexp_nodes[n].value == SEXP_KNOWN_TRUE ) {
			num_known++;
		} else {
			int exited_index;

			name = CTEXT(n);

			// see if the ship has already exited the mission (either through departure or destruction).  If so,
			// grab the status of whether the cargo is known from this list
			exited_index = ship_find_exited_ship_by_name( name );
			if (exited_index != -1 ) {
				if ( !(Ships_exited[exited_index].flags & SEF_BEEN_TAGGED) )
					return SEXP_KNOWN_FALSE;

				// check the delay of when we found out.  We use the ship died time which isn't entirely accurate
				// but won't cause huge delays.
				time_known = Missiontime - Ships_exited[exited_index].time;
				if ( f2i(time_known) >= delay )
					is_known = 1;
			} else {

				// otherwise, ship should still be in the mission.  If ship_name_lookup returns -1, then ship
				// is yet to arrive.
				shipnum = ship_name_lookup( name );
				if ( shipnum != -1 ) {
					if ( Ships[shipnum].time_first_tagged != 0 ) {
						time_known = Missiontime - Ships[shipnum].time_first_tagged;
						if ( f2i(time_known) >= delay )
							is_known = 1;
					}
				}
			}
		}

		// if cargo is known, mark our variable and this sexpression.
		if ( is_known ) {
			num_known++;
			Sexp_nodes[n].value = SEXP_KNOWN_TRUE;
		}

		n = CDR(n);
	}

	Directive_count += count - num_known;
	if ( count == num_known )
		return SEXP_KNOWN_TRUE;
	else
		return SEXP_FALSE;
}

// Karajorma
void eval_when_for_each_special_argument( int cur_node )
{
	arg_item *ptr;

	// loop through all the supplied arguments
	ptr = Sexp_applicable_argument_list.get_next();
	while (ptr != NULL)
	{
		// acquire argument to be used
		Sexp_replacement_arguments.push_back(ptr->text);	

		Sexp_current_argument_nesting_level++;
		Sexp_applicable_argument_list.add_data(ptr->text);

		// execute sexp... CTEXT will insert the argument as necessary
		eval_sexp(cur_node);
		
		// clean up any special sexp stuff
		Sexp_applicable_argument_list.clear_nesting_level();
		Sexp_current_argument_nesting_level--;

		// remove the argument 
		Sexp_replacement_arguments.pop_back(); 

		// continue along argument list
		ptr = ptr->get_next();
	}
}


// Goober5000
void do_action_for_each_special_argument( int cur_node )
{
	arg_item *ptr;

	// loop through all the supplied arguments
	ptr = Sexp_applicable_argument_list.get_next();
	while (ptr != NULL)
	{
		// acquire argument to be used
		Sexp_replacement_arguments.push_back(ptr->text);

		// execute sexp... CTEXT will insert the argument as necessary
		// (since these are all actions, they don't return any meaningful values)
		eval_sexp(cur_node);

		// remove the argument 
		Sexp_replacement_arguments.pop_back(); 
		// continue along argument list
		ptr = ptr->get_next();
	}
}

// Goober5000
int special_argument_appears_in_sexp_tree(int node)
{
	// empty tree
	if (node < 0)
		return 0;

	// special argument?
	if (!strcmp(Sexp_nodes[node].text, SEXP_ARGUMENT_STRING))
		return 1;

	// we don't want to include special arguments if they are nested in a new argument SEXP
	if (Sexp_nodes[node].type == SEXP_ATOM && Sexp_nodes[node].subtype == SEXP_ATOM_OPERATOR) {
		if (is_blank_argument_op(get_operator_const(CTEXT(node)))) {
			return 0; 
		}
	}

	return special_argument_appears_in_sexp_tree(CAR(node))
		|| special_argument_appears_in_sexp_tree(CDR(node));
}

// Goober5000
int special_argument_appears_in_sexp_list(int node)
{
	// look through list
	while (node != -1)
	{
		// special argument?
		if (!strcmp(Sexp_nodes[node].text, SEXP_ARGUMENT_STRING))
			return 1;

		node = CDR(node);
	}

	return 0;
}

// conditional sexpressions follow

// Goober5000
void eval_when_do_one_exp(int exp)
{	
	arg_item *ptr;
	int do_node;

	switch (get_operator_const(CTEXT(exp)))
	{
		// if the op is a conditional then we just evaluate it
		case OP_WHEN:
		case OP_EVERY_TIME:
		case OP_IF_THEN_ELSE:
			// need to account for the possibility this call uses <arguments>
			if (special_argument_appears_in_sexp_tree(exp)) { 
				ptr = Sexp_applicable_argument_list.get_next();
				if (ptr != NULL) {
					eval_when_for_each_special_argument(exp);
				}
				else {
					eval_sexp(exp);
				}
			}
			else {
				eval_sexp(exp);
			}
			break;

		case OP_DO_FOR_VALID_ARGUMENTS:
			if (special_argument_appears_in_sexp_tree(exp)) { 
				Warning(LOCATION, "<Argument> used within Do-for-valid-arguments SEXP. Skipping entire SEXP"); 
				break; 
			}

			do_node = CDR(exp); 
			while (do_node != -1) {
				do_action_for_each_special_argument(do_node); 
				do_node = CDR(do_node); 
			}
			break;

		case OP_WHEN_ARGUMENT:
		case OP_EVERY_TIME_ARGUMENT:
			eval_sexp(exp);
			break; 

		// otherwise we need to check if arguments are used
		default: 
			// if we're using the special argument in this action
			if (special_argument_appears_in_sexp_tree(exp))
			{
				do_action_for_each_special_argument(exp);			// these sexps eval'd only for side effects
			}
			// if not, just evaluate it once as-is
			else
			{
				// Goober5000 - possible bug? (see when val is used below)
				/*val = */eval_sexp(exp);							// these sexps eval'd only for side effects
			}
	}
}


// Karajorma
void eval_when_do_all_exp(int all_actions, int when_op_num)
{
	arg_item *ptr;
	int exp;
	int actions; 
	int op_num;

	bool first_loop = true;

	// loop through all the supplied arguments
	ptr = Sexp_applicable_argument_list.get_next();

	while (ptr != NULL)
	{	
		// acquire argument to be used
		Sexp_replacement_arguments.push_back(ptr->text);
		actions = all_actions; 

		while (actions != -1)
		{	
			exp = CAR(actions);	

			op_num = get_operator_const(CTEXT(exp));

			if (op_num == OP_DO_FOR_VALID_ARGUMENTS) {
				int do_node = CDR(exp); 
				while (do_node != -1) {
					eval_sexp(do_node); 
					do_node = CDR(do_node); 
				}
			}
			else if ( first_loop || special_argument_appears_in_sexp_tree(exp) ) {
				switch (op_num)
				{
					// if the op is a conditional we have to make sure that it can access arguments
					case OP_WHEN:
					case OP_EVERY_TIME:
					case OP_IF_THEN_ELSE:				
						Sexp_current_argument_nesting_level++;
						Sexp_applicable_argument_list.add_data(ptr->text);
						eval_sexp(exp);
						Sexp_applicable_argument_list.clear_nesting_level();
						Sexp_current_argument_nesting_level--;
						break;

					default:
						eval_sexp(exp);
				}
			}
			
			// iterate
			actions = CDR(actions);

			// if-then-else only has one "if" action
			if (when_op_num == OP_IF_THEN_ELSE)
				break;
		}
		
		first_loop = false;

		// remove the argument 
		Sexp_replacement_arguments.pop_back(); 
		// continue along argument list
		ptr = ptr->get_next();
	}
}

/**
 * This is like using when, but it takes a lot of shortcuts.  It's clearer just to separate it out into its own function, especially since it's not supposed to start
 * a new level of special argument handling, like eval_when would do.  It's a lot like the original retail version of eval_when!
 */
int eval_perform_actions(int n)
{
	int cond, val, actions;
	Assert( n >= 0 );

	cond = CAR(n);
	actions = CDR(n);

	// evaluate the conditional to see what value we eventually return
	val = eval_sexp(cond);

	// perform all the actions in the rest of the sexp
	// (Since we are technically inside a condition already, no special argument handling is needed.  The special argument, if any,
	// will have been provided by a higher level of nesting.)
	while (actions != -1)
	{
		// get the operator
		int exp = CAR(actions);
		if (exp != -1)
			eval_sexp(exp);

		// iterate
		actions = CDR(actions);
	}

	// return whatever val was, but don't return known-*
	// note: SEXP_KNOWN_TRUE/SEXP_KNOWN_FALSE are never returned from eval_sexp
	return val;
}
	
/**
 * Evaluates the when conditional
 *
 * @note Goober5000 - added capability for arguments
 * @note Goober5000 - and also if-then-else and perform-actions
 */
int eval_when(int n, int when_op_num)
{
	int arg_handler = -1, cond, val, actions;
	Assert( n >= 0 );
	arg_item *ptr;

	// get the parts of the sexp and evaluate the conditional
	if (is_blank_argument_op(when_op_num))
	{
		arg_handler = CAR(n);
		cond = CADR(n);
		actions = CDDR(n);

		Sexp_current_argument_nesting_level++;
		// evaluate for custom arguments
		val = eval_sexp(arg_handler, cond);
	}
	// normal evaluation
	else
	{
		cond = CAR(n);
		actions = CDR(n);

		// evaluate just as-is
		val = eval_sexp(cond);
	}


	// if value is true, perform the actions in the 'then' part
	if (val == SEXP_TRUE) // note: SEXP_KNOWN_TRUE is never returned from eval_sexp
	{
		// get the operator
		int exp = CAR(actions);

		// if the mod.tbl setting is in effect we want to each evaluate all the SEXPs for 
		// each argument	
		if (True_loop_argument_sexps && special_argument_appears_in_sexp_tree(exp)) {	
			if (exp != -1) {
				eval_when_do_all_exp(actions, when_op_num);
			}
		}
		// without the mod.tbl setting (or if there are no arguments in this SEXP) we loop 
		// through every action performing them for all arguments
		else {
			while (actions != -1)
			{
				// get the operator
				exp = CAR(actions);
				if (exp != -1)
					eval_when_do_one_exp(exp);

				// iterate
				actions = CDR(actions);

				// if-then-else only has one "if" action
				if (when_op_num == OP_IF_THEN_ELSE)
					break;
			}
		}
	}
	// if-then-else has actions to perform under "else"
	else if (val == SEXP_FALSE && when_op_num == OP_IF_THEN_ELSE) // note: SEXP_KNOWN_FALSE is never returned from eval_sexp
	{
		// skip past the "if" action
		actions = CDR(actions);

		// loop through every action
		while (actions != -1)
		{
			// get the operator
			int exp = CAR(actions);
			if (exp != -1)
				eval_when_do_one_exp(exp);

			// iterate
			actions = CDR(actions);
		}

		// invert val so that we behave like a when with opposite results
		// note: SEXP_KNOWN_FALSE is never returned from eval_sexp
		val = SEXP_TRUE;
	}

	if (is_blank_argument_op(when_op_num))
	{
		if (Log_event) {	
			ptr = Sexp_applicable_argument_list.get_next();		
			while(ptr != NULL) {
				// See if we have an argument. 
				Current_event_log_argument_buffer->push_back(ptr->text); 
				ptr = ptr->get_next();
			}
		}	

		// clean up any special sexp stuff
		Sexp_applicable_argument_list.clear_nesting_level();
		Sexp_current_argument_nesting_level--;
	}

	// thanks to MageKing17 for noticing that we need to short-circuit on the correct node!
	int short_circuit_node = (arg_handler >= 0) ? arg_handler : cond;

	if (Sexp_nodes[short_circuit_node].value == SEXP_KNOWN_FALSE || Sexp_nodes[short_circuit_node].value == SEXP_NAN_FOREVER)
		return SEXP_KNOWN_FALSE;  // no need to waste time on this anymore

	// note: val can't be SEXP_KNOWN_FALSE at this point

	return val;
}

/**
 * Evaluate the conditional
 */
int eval_cond(int n)
{
	int cond = 0, node, val = SEXP_FALSE;

	Assert (n >= 0);
	while (n >= 0)
	{
		node = CAR(n);
		cond = CAR(node);
		val = eval_sexp(cond);

		// if the conditional evaluated to true, then we must evaluate the rest of the expression returning
		// the value of this evaluation
		if (val == SEXP_TRUE) // note: any SEXP_KNOWN_TRUE result is returned as SEXP_TRUE
		{
			int actions, exp;

			val = SEXP_FALSE;
			actions = CDR(node);
			while (actions >= 0)
			{
				exp = CAR(actions);
				if (exp >= -1)
					val = eval_sexp(exp);								// these sexp evaled only for side effects

				actions = CDR(actions);
			}

			break;
		}

		// move onto the next cond clause
		n = CDR(n);
	}

	return val;
}

// Goober5000
// NOTE: if you change this function, check to see if the following function should also be changed!
int test_argument_nodes_for_condition(int n, int condition_node, int *num_true, int *num_false, int *num_known_true, int *num_known_false)
{
	int val, num_valid_arguments;
	Assert(n != -1 && condition_node != -1);
	Assert((num_true != NULL) && (num_false != NULL) && (num_known_true != NULL) && (num_known_false != NULL));

	// ensure special argument list is empty
	Sexp_applicable_argument_list.clear_nesting_level();
	Applicable_arguments_temp.clear();

	// ditto for counters
	num_valid_arguments = 0;
	*num_true = 0;
	*num_false = 0;
	*num_known_true = 0;
	*num_known_false = 0;

	// loop through all arguments
	while (n != -1)
	{
		// only eval this argument if it's valid
		if (Sexp_nodes[n].flags & SNF_ARGUMENT_VALID)
		{
			// flush conditional to avoid short-circuiting
			flush_sexp_tree(condition_node);

			// evaluate conditional for current argument
			Sexp_replacement_arguments.push_back(Sexp_nodes[n].text);
			val = eval_sexp(condition_node);
			if ( Sexp_nodes[condition_node].value == SEXP_KNOWN_TRUE ||
					Sexp_nodes[condition_node].value == SEXP_KNOWN_FALSE) {
				val = Sexp_nodes[condition_node].value;
			} else if ( Sexp_nodes[condition_node].value == SEXP_NAN_FOREVER ) {
				// In accordance with SEXP_NAN/SEXP_NAN_FOREVER becoming SEXP_FALSE in eval_sexp()
				val = SEXP_KNOWN_FALSE;
			}

			switch (val)
			{
				case SEXP_TRUE:
					(*num_true)++;
					Applicable_arguments_temp.push_back(Sexp_nodes[n].text);
					break;

				case SEXP_FALSE:
					(*num_false)++;
					break;

				case SEXP_KNOWN_TRUE:
					(*num_known_true)++;
					Applicable_arguments_temp.push_back(Sexp_nodes[n].text);
					break;

				case SEXP_KNOWN_FALSE:
					(*num_known_false)++;
					break;
			}

			// clear argument, but not list, as we'll need it later
			Sexp_replacement_arguments.pop_back();

			// increment
			num_valid_arguments++;
		}

		// continue along argument list
		n = CDR(n);
	}

	// now we write from the temporary store into the real one, reversing the order. We do this because 
	// Sexp_applicable_argument_list is a stack and we want the first argument in the list to be the first one out
	while (!Applicable_arguments_temp.empty())
	{
		Sexp_applicable_argument_list.add_data(Applicable_arguments_temp.back());
		Applicable_arguments_temp.pop_back(); 
	}

	return num_valid_arguments;
}

// Goober5000
// NOTE: if you change this function, check to see if the previous function should also be changed!
int test_argument_vector_for_condition(SCP_vector<char*> argument_vector, bool already_dupped, int condition_node, int *num_true, int *num_false, int *num_known_true, int *num_known_false)
{
	int val, num_valid_arguments;
	Assert(condition_node != -1);
	Assert((num_true != NULL) && (num_false != NULL) && (num_known_true != NULL) && (num_known_false != NULL));

	// ensure special argument list is empty
	Sexp_applicable_argument_list.clear_nesting_level();
	Applicable_arguments_temp.clear();

	// ditto for counters
	num_valid_arguments = 0;
	*num_true = 0;
	*num_false = 0;
	*num_known_true = 0;
	*num_known_false = 0;

	// loop through all arguments
	for (size_t i = 0; i < argument_vector.size(); i++)
	{
		// since we can't see or modify the validity, assume all are valid
		{
			// flush conditional to avoid short-circuiting
			flush_sexp_tree(condition_node);

			// evaluate conditional for current argument
			Sexp_replacement_arguments.push_back(argument_vector[i]);
			val = eval_sexp(condition_node);
			if ( Sexp_nodes[condition_node].value == SEXP_KNOWN_TRUE ||
					Sexp_nodes[condition_node].value == SEXP_KNOWN_FALSE) {
				val = Sexp_nodes[condition_node].value;
			} else if ( Sexp_nodes[condition_node].value == SEXP_NAN_FOREVER ) {
				// In accordance with SEXP_NAN/SEXP_NAN_FOREVER becoming SEXP_FALSE in eval_sexp()
				val = SEXP_KNOWN_FALSE;
			}

			switch (val)
			{
				case SEXP_TRUE:
					(*num_true)++;
					Applicable_arguments_temp.push_back(argument_vector[i]);
					break;

				case SEXP_FALSE:
					(*num_false)++;
					break;

				case SEXP_KNOWN_TRUE:
					(*num_known_true)++;
					Applicable_arguments_temp.push_back(argument_vector[i]);
					break;

				case SEXP_KNOWN_FALSE:
					(*num_known_false)++;
					break;
			}

			// if the argument was already dup'd, but not added as an applicable argument,
			// we need to free it here before we cause a memory leak
			if ((val == SEXP_FALSE || val == SEXP_KNOWN_FALSE) && already_dupped)
				vm_free(argument_vector[i]);

			// clear argument, but not list, as we'll need it later
			Sexp_replacement_arguments.pop_back();

			// increment
			num_valid_arguments++;
		}
	}

	// now we write from the temporary store into the real one, reversing the order. We do this because 
	// Sexp_applicable_argument_list is a stack and we want the first argument in the list to be the first one out
	while (!Applicable_arguments_temp.empty())
	{
		// we need to dup the strings regardless, since we're not using Sexp_nodes[n].text as a string buffer,
		// but we need to know whether the calling function dup'd them, or whether we should dup them here
		if (already_dupped)
			Sexp_applicable_argument_list.add_data_set_dup(Applicable_arguments_temp.back());
		else
			Sexp_applicable_argument_list.add_data_dup(Applicable_arguments_temp.back());

		Applicable_arguments_temp.pop_back(); 
	}

	return num_valid_arguments;
}

// Goober5000
int eval_any_of(int arg_handler_node, int condition_node)
{
	int n, num_valid_arguments, num_true, num_false, num_known_true, num_known_false;
	Assert(arg_handler_node != -1 && condition_node != -1);

	// the arguments should just be data, not operators, so we can skip the CAR
	n = CDR(arg_handler_node);

	// test the whole argument list
	num_valid_arguments = test_argument_nodes_for_condition(n, condition_node, &num_true, &num_false, &num_known_true, &num_known_false);

	// use the sexp_or algorithm
	if (num_known_true || num_true)
		return SEXP_TRUE;
	else if (num_known_false == num_valid_arguments)
		return SEXP_KNOWN_FALSE;
	else
		return SEXP_FALSE;
}

// Goober5000
int eval_every_of(int arg_handler_node, int condition_node)
{
	int n, num_valid_arguments, num_true, num_false, num_known_true, num_known_false;
	Assert(arg_handler_node != -1 && condition_node != -1);

	// the arguments should just be data, not operators, so we can skip the CAR
	n = CDR(arg_handler_node);

	// test the whole argument list
	num_valid_arguments = test_argument_nodes_for_condition(n, condition_node, &num_true, &num_false, &num_known_true, &num_known_false);

	// use the sexp_and algorithm
	if ((!num_valid_arguments) || num_known_false)
		return SEXP_KNOWN_FALSE;
	else if (num_false)
		return SEXP_FALSE;
	else
		return SEXP_TRUE;
}

// Goober5000
int eval_number_of(int arg_handler_node, int condition_node)
{
	int n, num_valid_arguments, num_true, num_false, num_known_true, num_known_false, threshold;
	Assert(arg_handler_node != -1 && condition_node != -1);

	// the arguments should just be data, not operators, so we can skip the CAR
	n = CDR(arg_handler_node);

	// the first argument is the number threshold
	threshold = eval_num(n);
	n = CDR(n);

	// test the whole argument list
	num_valid_arguments = test_argument_nodes_for_condition(n, condition_node, &num_true, &num_false, &num_known_true, &num_known_false);

	// use the sexp_or algorithm, modified
	// (true if at least threshold arguments are true)
	if (num_true + num_known_true >= threshold)
		return SEXP_TRUE;
	else if (num_valid_arguments - num_known_false < threshold)
		return SEXP_KNOWN_FALSE;
	else
		return SEXP_FALSE;
}

// Goober5000
// this works a little differently... we randomly pick one argument to use
// for our condition, but this argument must be saved among sexp calls...
// so we select an argument and set its flag
// addendum: hook karajorma's random-multiple-of into the same sexp
int eval_random_of(int arg_handler_node, int condition_node, bool multiple)
{
	int n = -1, i, val, num_valid_args, random_argument, num_known_false = 0;
	Assert(arg_handler_node != -1 && condition_node != -1);

	// get the number of valid arguments
	num_valid_args = query_sexp_args_count(arg_handler_node, true);

	if (num_valid_args == 0)
	{
		return SEXP_KNOWN_FALSE;	// Not much point in trying to evaluate it again.
	}

	// find which argument we picked, if we picked one
	if (!multiple)
	{
		n = CDR(arg_handler_node);

		// iterate to the argument we previously selected
		for ( ; n != -1; n = CDR(n))
		{
			if (Sexp_nodes[n].flags & SNF_ARGUMENT_SELECT)
				break;
		}
	}

	// if argument not found (or never specified in the first place), we have to pick one
	if (n == -1)
	{
		n = CDR(arg_handler_node);
		int temp_node = n;

		// pick an argument and iterate to it
		random_argument = rand_internal(1, num_valid_args);
		i = 0;
		for (int j = 0; j < num_valid_args; temp_node = CDR(temp_node))
		{
			Assert(n >= 0);

			// count only valid arguments
			if (Sexp_nodes[temp_node].flags & SNF_ARGUMENT_VALID) {
				j++;
				if (i < random_argument && (++i == random_argument)) {
					// Found the node we want, store it for use
					n = temp_node;
				}

				if ((Sexp_nodes[temp_node].value == SEXP_KNOWN_FALSE) || (Sexp_nodes[temp_node].value == SEXP_NAN_FOREVER))
					num_known_false++;
			}
		}

		if (num_known_false == num_valid_args) {
			return SEXP_KNOWN_FALSE;	// We're going nowhere fast.
		}

		// save it, if we're saving
		if (!multiple)
		{
			Sexp_nodes[n].flags |= SNF_ARGUMENT_SELECT;
		}
	}

	// only eval this argument if it's valid
	val = SEXP_FALSE;
	if (Sexp_nodes[n].flags & SNF_ARGUMENT_VALID)
	{
		// flush stuff
		Sexp_applicable_argument_list.clear_nesting_level();
		flush_sexp_tree(condition_node);

		// evaluate conditional for current argument
		Sexp_replacement_arguments.push_back(Sexp_nodes[n].text);
		val = eval_sexp(condition_node);

		// true?
		if (val == SEXP_TRUE)
		{
			Sexp_applicable_argument_list.add_data(Sexp_nodes[n].text);
		} else if ((!multiple || num_valid_args == 1) && (Sexp_nodes[condition_node].value == SEXP_KNOWN_FALSE || Sexp_nodes[condition_node].value == SEXP_NAN_FOREVER)) {
			val = SEXP_KNOWN_FALSE;	// If we can't randomly pick another one and this one is guaranteed never to be true, then give up now.
		}
		
		// clear argument, but not list, as we'll need it later
		Sexp_replacement_arguments.pop_back();
	}

	// true if our selected argument is true
	return val;
}

// Karajorma - this conditional returns the first valid option on its list. 
int eval_in_sequence(int arg_handler_node, int condition_node)
{
	int val = SEXP_FALSE;
	int n = -1 ;
	
	Assert(arg_handler_node != -1 && condition_node != -1);

	// get the first argument
	n = CDR(arg_handler_node);
	Assert (n != -1);

	// loop through the nodes until we find one that is holds a valid argument or run out of nodes
	for (int i=1 ; i<query_sexp_args_count(arg_handler_node) ; i++)
	{
		if (!(Sexp_nodes[n].flags & SNF_ARGUMENT_VALID)) {
			n = CDR(n) ;
		}
		// if we've found a valid node there is no need to continue
		else {
			break; 
		}
	}

	// Only execute if the argument is valid (if all nodes were invalid we would still reach this point)
	if (Sexp_nodes[n].flags & SNF_ARGUMENT_VALID)
	{
		// flush stuff
		Sexp_applicable_argument_list.clear_nesting_level();
		flush_sexp_tree(condition_node);

		// evaluate conditional for current argument
		Sexp_replacement_arguments.push_back(Sexp_nodes[n].text);
		val = eval_sexp(condition_node);

		// true?
		if (val == SEXP_TRUE)
		{
			Sexp_applicable_argument_list.add_data(Sexp_nodes[n].text);
		} else if ((Sexp_nodes[condition_node].value == SEXP_KNOWN_FALSE) || (Sexp_nodes[condition_node].value == SEXP_NAN_FOREVER)) {
			val = SEXP_KNOWN_FALSE;	// If we're wasting our time evaluating this ever again, just go ahead and short-circuit.
		}

		// clear argument, but not list, as we'll need it later
		Sexp_replacement_arguments.pop_back();
	}

	// return the value of the conditional
	return val;
}

// is there a better place to put this?  seems useful...
// credit to http://stackoverflow.com/questions/1903954/is-there-a-standard-sign-function-signum-sgn-in-c-c
template <typename T>
T sign(T t) 
{
    if (t == 0)
        return T(0);
    else
        return (t < 0) ? T(-1) : T(1);
}

// Goober5000
int eval_for_counter(int arg_handler_node, int condition_node)
{
	int n, num_valid_arguments, num_true, num_false, num_known_true, num_known_false;
	int i, counter_start, counter_stop, counter_step;
	char buf[NAME_LENGTH];
	Assert(arg_handler_node != -1 && condition_node != -1);

	// determine the counter parameters
	n = CDR(arg_handler_node);
	counter_start = eval_num(n);
	n = CDR(n);
	counter_stop = eval_num(n);
	n = CDR(n);
	counter_step = (n >= 0) ? eval_num(n) : 1;

	// a bunch of error checking
	if (counter_step == 0)
	{
		Warning(LOCATION, "A counter increment of 0 is illegal!  (start=%d, stop=%d, increment=%d)", counter_start, counter_stop, counter_step);
		return SEXP_KNOWN_FALSE;
	}
	else if (counter_start == counter_stop)
	{
		Warning(LOCATION, "The counter start and stop values are identical!  (start=%d, stop=%d, increment=%d)", counter_start, counter_stop, counter_step);
		return SEXP_KNOWN_FALSE;
	}
	else if (sign(counter_stop - counter_start) != sign(counter_step))
	{
		Warning(LOCATION, "The counter cannot complete with the given values!  (start=%d, stop=%d, increment=%d)", counter_start, counter_stop, counter_step);
		return SEXP_KNOWN_FALSE;
	}

	// build a vector of counter values
	SCP_vector<char*> argument_vector;
	for (i = counter_start; ((counter_step > 0) ? i <= counter_stop : i >= counter_stop); i += counter_step)
	{
		sprintf(buf, "%d", i);
		argument_vector.push_back(vm_strdup(buf));
		// Note: we do not call vm_free() on the contents of argument_vector, and we don't for the very good
		// reason that those pointers are then passed along by test_argument_vector_for_condition(), below.
		// The strings will then be freed by arg_item::expunge() or arg_item::clear_nesting_level(), or even
		// inside test_argument_vector_for_condition() (if the argument doesn't satisfy the condition). So
		// under no circumstances try to free these strings inside this function! It will cause a double-free
		// situation, resulting in a crash at best. -MageKing17
	}

	// test the whole argument vector
	num_valid_arguments = test_argument_vector_for_condition(argument_vector, true, condition_node, &num_true, &num_false, &num_known_true, &num_known_false);

	// use the sexp_or algorithm
	if (num_known_true || num_true)
		return SEXP_TRUE;
	else if (num_known_false == num_valid_arguments)
		return SEXP_KNOWN_FALSE;
	else
		return SEXP_FALSE;
}

void sexp_change_all_argument_validity(int n, bool invalidate)
{
	int arg_handler, arg_n;

	arg_handler = get_handler_for_x_of_operator(n);

	// thanks to woutersmits for finding this loophole
	if (arg_handler < 0)
		return;

	// can't change validity of for-counter
	if (get_operator_const(CTEXT(arg_handler)) == OP_FOR_COUNTER)
		return;
		
	while (n != -1)
	{
		arg_n = CDR(arg_handler);
		while (arg_n != -1) {
			if (invalidate) {
				Sexp_nodes[arg_n].flags &= ~SNF_ARGUMENT_VALID;
			}
			else {
				Sexp_nodes[arg_n].flags |= SNF_ARGUMENT_VALID;
			}
			// iterate
			arg_n = CDR(arg_n);
		}
		
		// iterate
		n = CDR(n);
	}
}

int sexp_num_valid_arguments( int n )
{
	int arg_handler, arg_n;
	int matches = 0;

	arg_handler = get_handler_for_x_of_operator(n);

	// loop through arguments
	arg_n = CDR(arg_handler);
	while (arg_n != -1) {
		if (Sexp_nodes[arg_n].flags & SNF_ARGUMENT_VALID) {
			matches++;
		}

		
		// iterate
		arg_n = CDR(arg_n);
	}

	return matches;
}

// Goober5000
void sexp_change_argument_validity(int n, bool invalidate)
{
	int arg_handler, arg_n;
	bool toggled;

	arg_handler = get_handler_for_x_of_operator(n);

	// thanks to woutersmits for finding this loophole
	if (arg_handler < 0)
		return;

	// can't change validity of for-counter
	if (get_operator_const(CTEXT(arg_handler)) == OP_FOR_COUNTER)
		return;
		
	// loop through arguments
	while (n != -1)
	{
		toggled = false; 

		// first we must check if the arg_handler marks a selection. At the moment random-of is the only one that does this
		arg_n = CDR(arg_handler);
		while (invalidate && (arg_n != -1)) {
			if (Sexp_nodes[arg_n].flags & SNF_ARGUMENT_SELECT) {
				// now check if the selected argument matches the one we want to invalidate
				if (!strcmp(CTEXT(n), CTEXT(arg_n))) {
					// set it as invalid
					Sexp_nodes[arg_n].flags &= ~SNF_ARGUMENT_VALID;
					toggled = true; 
				}
			}

			// iterate
			arg_n = CDR(arg_n);
		}
		
		if (!toggled) {
			// search for argument in arg_handler list
			arg_n = CDR(arg_handler);
			while (arg_n != -1)
			{
				// match?
				if (!strcmp(CTEXT(n), CTEXT(arg_n)))
				{
					if (invalidate) {
						// we need to check if the argument is already invalid as some argument lists may contain duplicates
						if (Sexp_nodes[arg_n].flags & SNF_ARGUMENT_VALID) {
							// set it as invalid
							Sexp_nodes[arg_n].flags &= ~SNF_ARGUMENT_VALID;

							// exit inner loop
							break;
						}
					}
					else {
						if (!(Sexp_nodes[arg_n].flags & SNF_ARGUMENT_VALID)) {
							// set it as valid
							Sexp_nodes[arg_n].flags |= SNF_ARGUMENT_VALID;

							// exit inner loop
							break;
						}
					}
				}

				// iterate
				arg_n = CDR(arg_n);
			}
		}

		// iterate
		n = CDR(n);
	}
}

int get_handler_for_x_of_operator(int n)
{
	int conditional, arg_handler;

	if (n < 0) {
		return -1;
	}

	conditional = n; 
	do {
		// find the conditional sexp
		conditional = find_parent_operator(conditional);
		if (conditional == -1) {
			return -1;
		}
	}
	while (!is_blank_argument_op(get_operator_const(CTEXT(conditional))));

	// get the first op of the parent, which should be a *_of operator
	arg_handler = CADR(conditional);
	if (arg_handler < 0 || !is_blank_of_op(get_operator_const(CTEXT(arg_handler)))) {
		return -1;
	}

	return arg_handler;
}

// Goober5000
bool is_blank_argument_op(int op_const)
{
	switch (op_const)
	{
		case OP_WHEN_ARGUMENT:
		case OP_EVERY_TIME_ARGUMENT:
			return true;

		default:
			return false;
	}
}

// Goober5000
bool is_blank_of_op(int op_const)
{
	switch (op_const)
	{
		case OP_ANY_OF:
		case OP_EVERY_OF:
		case OP_NUMBER_OF:
		case OP_RANDOM_OF:
		case OP_RANDOM_MULTIPLE_OF:
		case OP_IN_SEQUENCE:
		case OP_FOR_COUNTER:
			return true;

		default:
			return false;
	}
}

// Goober5000 - added wing capability
int sexp_is_iff(int n)
{
	int i, team;

	// iff value is the first parameter, second is a list of one or more ships/wings to check to see if the
	// iff value matches
	team = iff_lookup(CTEXT(n));

	n = CDR(n);
	for ( ; n != -1; n = CDR(n) )
	{
		object_ship_wing_point_team oswpt;
		sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));

		switch (oswpt.type)
		{
			case OSWPT_TYPE_SHIP:
			{
				// if the team doesn't match the team specified, return false immediately
				if (oswpt.shipp->team != team)
					return SEXP_FALSE;

				break;
			}

			case OSWPT_TYPE_PARSE_OBJECT:
			{
				// if the team doesn't match the team specified, return false immediately
				if (oswpt.p_objp->team != team)
					return SEXP_FALSE;

				break;
			}

			case OSWPT_TYPE_WING:
			case OSWPT_TYPE_WING_NOT_PRESENT:
			{
				for (i = 0; i < oswpt.wingp->current_count; i++)
				{
					// if the team doesn't match the team specified, return false immediately
					if (Ships[oswpt.wingp->ship_index[i]].team != team)
						return SEXP_FALSE;
				}

				break;
			}

			case OSWPT_TYPE_EXITED:
			{
				// see if we can find information about the exited ship (if it is a ship)
				int exited_index = ship_find_exited_ship_by_name(CTEXT(n));
				if (exited_index >= 0)
				{
					// if the team doesn't match the team specified, return false immediately
					if (Ships_exited[exited_index].team != team)
						return SEXP_KNOWN_FALSE;
				}
				else
				{
					// it's probably an exited wing, which we don't store information about
					return SEXP_NAN_FOREVER;
				}
			}

			// we don't handle the other cases
			default:
				return SEXP_NAN;
		}

	}

	// got this far: we must be okay for all ships/wings
	return SEXP_TRUE;
}

// Goober5000
void sexp_ingame_ship_change_iff(ship *shipp, int new_team)
{
	Assert(shipp != NULL);

	shipp->team = new_team;

	// send a network packet if we need to
	if( MULTIPLAYER_MASTER && (Net_player != NULL) && (shipp->objnum >= 0))
		send_change_iff_packet(Objects[shipp->objnum].net_signature, new_team);
}

// Goober5000
void sexp_parse_ship_change_iff(p_object *parse_obj, int new_team)
{
	Assert(parse_obj);

	parse_obj->team = new_team;
}

// Goober5000 - added wing capability
void sexp_change_iff(int n)
{
	int new_team;

	new_team = iff_lookup(CTEXT(n));
	n = CDR(n);

	for ( ; n != -1; n = CDR(n) )
	{
		object_ship_wing_point_team oswpt;
		sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));

		switch (oswpt.type)
		{
			// change ingame ship
			case OSWPT_TYPE_SHIP:
			{
				sexp_ingame_ship_change_iff(oswpt.shipp, new_team);

				break;
			}

			// change ship yet to arrive
			case OSWPT_TYPE_PARSE_OBJECT:
			{
				sexp_parse_ship_change_iff(oswpt.p_objp, new_team);

				break;
			}

			// change wing (we must set the flags for all ships present as well as all ships yet to arrive)
			case OSWPT_TYPE_WING:
			case OSWPT_TYPE_WING_NOT_PRESENT:
			{
				// current ships
				for (int i = 0; i < oswpt.wingp->current_count; i++)
					sexp_ingame_ship_change_iff(&Ships[oswpt.wingp->ship_index[i]], new_team);

				// ships yet to arrive
				for (p_object *p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp))
				{
					if (p_objp->wingnum == WING_INDEX(oswpt.wingp))
						sexp_parse_ship_change_iff(p_objp, new_team);
				}

				break;
			}
		}
	}
}

void sexp_ingame_ship_change_iff_color(ship *shipp, int observer_team, int observed_team, int alternate_iff_color)
{
	Assert(shipp != NULL);

	shipp->ship_iff_color[observer_team][observed_team] = alternate_iff_color;

	// Like the rest of the change_iff_color functions copied with minor alterations from earlier change_iff functions.
	if( MULTIPLAYER_MASTER && (Net_player != NULL) && (shipp->objnum >= 0))
		send_change_iff_color_packet(Objects[shipp->objnum].net_signature, observer_team, observed_team, alternate_iff_color);
}

void sexp_parse_ship_change_iff_color(p_object *parse_obj, int observer_team, int observed_team, int alternate_iff_color)
{
	Assert(parse_obj);

	parse_obj->alt_iff_color[observer_team][observed_team] = alternate_iff_color;
}

 // Wanderer
void sexp_change_iff_color(int n)
{
	int observer_team, observed_team, alternate_iff_color;
	int i;
	int rgb[3];

	// First node
	if(n == -1){
		Warning(LOCATION, "Detected missing observer team parameter in sexp-change_iff_color");
		return;
	}
	observer_team = iff_lookup(CTEXT(n));

	// Second node
	n = CDR(n);
	if(n == -1){
		Warning(LOCATION, "Detected missing observed team parameter in sexp-change_iff_color");
		return;
	}
	observed_team = iff_lookup(CTEXT(n));

	// Three following nodes
	for (i=0;i<3;i++)
	{
		n = CDR(n);
		if(n == -1){
			Warning(LOCATION, "Detected incomplete color parameter list in sexp-change_iff_color\n");
			return;
		}
		rgb[i] = eval_num(n);
		if (rgb[i] > 255) {
			Warning(LOCATION, "Invalid argument for iff color in sexp-change-iff-color. Valid range is 0 to 255.\n");
			rgb[i] = 255;
		}
	}
	alternate_iff_color = iff_init_color(rgb[0],rgb[1],rgb[2]);

	// Rest of the nodes
	n = CDR(n);
	for ( ; n != -1; n = CDR(n) )
	{
		object_ship_wing_point_team oswpt;
		sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));

		switch (oswpt.type)
		{
			// change ingame ship
			case OSWPT_TYPE_SHIP:
			{
				sexp_ingame_ship_change_iff_color(oswpt.shipp, observer_team, observed_team, alternate_iff_color);

				break;
			}

			// change ship yet to arrive
			case OSWPT_TYPE_PARSE_OBJECT:
			{
				sexp_parse_ship_change_iff_color(oswpt.p_objp, observer_team, observed_team, alternate_iff_color);

				break;
			}

			// change wing (we must set the flags for all ships present as well as all ships yet to arrive)
			case OSWPT_TYPE_WING:
			case OSWPT_TYPE_WING_NOT_PRESENT:
			{
				// current ships
				for (i = 0; i < oswpt.wingp->current_count; i++)
					sexp_ingame_ship_change_iff_color(&Ships[oswpt.wingp->ship_index[i]], observer_team, observed_team, alternate_iff_color);

				// ships yet to arrive
				for (p_object *p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp))
				{
					if (p_objp->wingnum == WING_INDEX(oswpt.wingp))
						sexp_parse_ship_change_iff_color(p_objp, observer_team, observed_team, alternate_iff_color);
				}

				break;
			}
		}
	}
}

// Goober5000
int sexp_is_ship_class(int n)
{
	int ship_num, ship_class_num;

	Assert( n >= 0 );

	// get class
	ship_class_num = ship_info_lookup(CTEXT(n));
	n = CDR(n);

	// eval ships
	while (n != -1)
	{
		// get ship
		ship_num = ship_name_lookup(CTEXT(n));

		// we can't do anything with ships that aren't present
		if (ship_num < 0)
			return SEXP_CANT_EVAL;

		// if it doesn't match, return false
		if (Ships[ship_num].ship_info_index != ship_class_num)
			return SEXP_FALSE;

		// increment
		n = CDR(n);
	}

	// we're this far; it must be true
	return SEXP_TRUE;
}

// Goober5000
int sexp_is_ship_type(int n)
{
	int ship_num, ship_type_num;

	Assert( n >= 0 );

	// get type
	ship_type_num = ship_type_name_lookup(CTEXT(n));
	n = CDR(n);

	// eval ships
	while (n != -1)
	{
		// get ship
		ship_num = ship_name_lookup(CTEXT(n));

		// we can't do anything with ships that aren't present
		if (ship_num < 0)
			return SEXP_CANT_EVAL;

		// if it doesn't match, return false
		if(ship_class_query_general_type(Ships[ship_num].ship_info_index) != ship_type_num)
			return SEXP_FALSE;

		// increment
		n = CDR(n);
	}

	// we're this far; it must be true
	return SEXP_TRUE;
}

// Goober5000
// ai class value is the first parameter, second is a ship, rest are subsystems to check
int sexp_is_ai_class(int n)
{
	char *ship_name, *subsystem;
	int i, ship_num, ai_class_to_check;

	Assert ( n >= 0 );

	// find ai class
	ai_class_to_check = -1;
	for (i=0; i<Num_ai_classes; i++)
	{
		if (!stricmp(Ai_class_names[i], CTEXT(n)))
			ai_class_to_check = i;
	}

	Assert(ai_class_to_check >= 0);

	n = CDR(n);
	ship_name = CTEXT(n);
	n = CDR(n);

	// find ship
	ship_num = ship_name_lookup(ship_name);

	// we can't do anything with ships that aren't present
	if (ship_num < 0)
		return SEXP_CANT_EVAL;

	// subsys?
	if (n != -1)
	{
		ship_subsys *ss;

		// loopity-loop
		for ( ; n != -1; n = CDR(n) )
		{
			subsystem = CTEXT(n);

			// find the ship subsystem
			// if it doesn't match, or subsys isn't found, return false immediately
			ss = ship_get_subsys(&Ships[ship_num], subsystem);
			if (ss != NULL)
			{
				if (ss->weapons.ai_class != ai_class_to_check)
					return SEXP_FALSE;
			}
			else
				return SEXP_FALSE;
		}

		// we've come this far; it must all be true
		return SEXP_TRUE;
	}
	// just the ship
	else
	{
		if (Ai_info[Ships[ship_num].ai_index].ai_class == ai_class_to_check)
			return SEXP_TRUE;
		else
			return SEXP_FALSE;
	}
}

// Goober5000
void sexp_change_ai_class(int n)
{
	int i, ship_num, new_ai_class;

	Assert ( n >= 0 );

	// find ai class
	new_ai_class = -1;
	for (i=0; i<Num_ai_classes; i++)
	{
		if (!stricmp(Ai_class_names[i], CTEXT(n)))
			new_ai_class = i;
	}

	Assert(new_ai_class >= 0);

	// find ship
	n = CDR(n);
	ship_num = ship_name_lookup(CTEXT(n));
	n = CDR(n);

	// we can't do anything with ships that aren't present
	if (ship_num < 0)
		return;

	// subsys?
	if (n != -1)
	{
		// loopity-loop
		for ( ; n != -1; n = CDR(n) )
		{
			ship_subsystem_set_new_ai_class(ship_num, CTEXT(n), new_ai_class);

			// send a network packet if we need to
			if( MULTIPLAYER_MASTER && (Net_player != NULL) && (Ships[ship_num].objnum >= 0))
			{
				send_change_ai_class_packet(Objects[Ships[ship_num].objnum].net_signature, CTEXT(n), new_ai_class);
			}
		}
	}
	// just the one ship
	else
	{
		ship_set_new_ai_class(ship_num, new_ai_class);

		// send a network packet if we need to
		if( MULTIPLAYER_MASTER && (Net_player != NULL) && (Ships[ship_num].objnum >= 0))
		{
			send_change_ai_class_packet(Objects[Ships[ship_num].objnum].net_signature, NULL, new_ai_class);
		}
	}
}

// following routine adds an ai goal to a ship structure.  The sexpression index
// passed in should be an ai-goal of the proper form.  The code in MissionGoal should
// check the syntax.

void sexp_add_ship_goal(int n)
{
	int num, sindex;
	char *ship_name;

	Assert ( n >= 0 );
	ship_name = CTEXT(n);
	num = ship_name_lookup(ship_name, 1);	// Goober5000 - including player
	if ( num < 0 )									// ship not around anymore???? then forget it!
		return;

	sindex = CDR(n);
	ai_add_ship_goal_sexp( sindex, AIG_TYPE_EVENT_SHIP, &(Ai_info[Ships[num].ai_index]) );
}

// identical to above, except add a wing
void sexp_add_wing_goal(int n)
{
	int num, sindex;
	char *wing_name;

	Assert ( n >= 0 );
	wing_name = CTEXT(n);
	num = wing_name_lookup(wing_name);
	if ( num < 0 )									// ship not around anymore???? then forget it!
		return;

	sindex = CDR(n);
	ai_add_wing_goal_sexp( sindex, AIG_TYPE_EVENT_WING, num );
}

/**
 * Adds a goal to the specified entry (ships and wings have unique names between the two sets).
 */
void sexp_add_goal(int n)
{
	int num, sindex;
	char *name;

	Assert ( n >= 0 );
	name = CTEXT(n);
	sindex = CDR(n);

	// first, look for ship name -- if found, then add ship goal.  else look for wing name -- if
	// found, add wing goal
	if ( (num = ship_name_lookup(name, 1)) != -1 )	// Goober5000 - include players
		ai_add_ship_goal_sexp( sindex, AIG_TYPE_EVENT_SHIP, &(Ai_info[Ships[num].ai_index]) );
	else if ( (num = wing_name_lookup(name)) != -1 )
		ai_add_wing_goal_sexp( sindex, AIG_TYPE_EVENT_WING, num );
}

// Goober5000
void sexp_remove_goal(int n)
{
	Assert( n >= 0 );
	/* Grab the information that we need about this goal removal action */
	int num, sindex;
	int goalindex;
	char *name;

	name = CTEXT(n);
	sindex = CDR(n);

	// first, look for ship name -- if found, then add ship goal.  else look for wing name -- if
	// found, add wing goal
	if ( (num = ship_name_lookup(name, 1)) != -1 )
	{
		goalindex = ai_remove_goal_sexp_sub( sindex, Ai_info[Ships[num].ai_index].goals );
		if ( goalindex >= 0 )
		{
			if ( Ai_info[Ships[num].ai_index].active_goal == goalindex )
				Ai_info[Ships[num].ai_index].active_goal = AI_GOAL_NONE;
		}
	}
	else if ( (num = wing_name_lookup(name)) != -1 )
	{
		ai_remove_wing_goal_sexp( sindex, num );
	}
	
}

/**
 * Clear out all AI goals for a ship
 */
void sexp_clear_ship_goals(int n)
{
	int num;
	char *ship_name;

	Assert ( n >= 0 );
	ship_name = CTEXT(n);
	if ( (num = ship_name_lookup(ship_name, 1)) != -1) 	// Goober5000 - include players
	{
		ai_clear_ship_goals( &(Ai_info[Ships[num].ai_index]) );
	}
}

/**
 * Clear out AI goals for a wing
 */
void sexp_clear_wing_goals(int n)
{
	int num;
	char *wing_name;

	Assert ( n >= 0 );
	wing_name = CTEXT(n);
	num = wing_name_lookup(wing_name);
	if ( num < 0 )
		return;
	ai_clear_wing_goals( num );
}

/**
 * Clear all AI goals for the given ship or wing
 */
void sexp_clear_goals(int n)
{
	int num;
	char *name;

	Assert ( n >= 0 );
	while ( n != -1 ) {
		name = CTEXT(n);
		if ( (num = ship_name_lookup(name, 1)) != -1 )	// Goober5000 - include players
			ai_clear_ship_goals( &(Ai_info[Ships[num].ai_index]) );
		else if ( (num = wing_name_lookup(name)) != -1 )
			ai_clear_wing_goals( num );

		n = CDR(n);
	}
}

// Goober5000
void sexp_hud_disable(int n)
{
	int disable_hud = eval_num(n);
	hud_set_draw(!disable_hud);

	multi_start_callback();
	multi_send_int(disable_hud);
	multi_end_callback();
}

void multi_sexp_hud_disable()
{
	int disable_hud;

	if (multi_get_int(disable_hud)) {
		hud_set_draw(!disable_hud);
	}
}

// Goober5000
void sexp_hud_disable_except_messages(int n)
{
	int disable_hud = eval_num(n);
	hud_disable_except_messages(disable_hud);

	multi_start_callback();
	multi_send_int(disable_hud);
	multi_end_callback();
}

void multi_sexp_hud_disable_except_messages()
{
	int disable_hud;

	if (multi_get_int(disable_hud)) {
		hud_disable_except_messages(disable_hud);
	}
}

void sexp_hud_set_text_num(int n)
{
	char* gaugename = CTEXT(n);
	char tmp[16] = "";

	HudGauge* cg = hud_get_gauge(gaugename);
	if(cg) {
		sprintf( tmp, "%d", eval_num(CDR(n)) );
		cg->updateCustomGaugeText(tmp);
	}
}

void sexp_hud_set_text(int n)
{
	char* gaugename = CTEXT(n);
	char* text = CTEXT(CDR(n));

	HudGauge* cg = hud_get_gauge(gaugename);
	if(cg) {
		cg->updateCustomGaugeText(text);
	}
}

void sexp_hud_set_message(int n)
{
	char* gaugename = CTEXT(n);
	char* text = CTEXT(CDR(n));
	SCP_string message;

	for (int i = 0; i < Num_messages; i++) {
		if ( !stricmp(text, Messages[i].name) ) {
			message = Messages[i].message;

			sexp_replace_variable_names_with_values(message);

			HudGauge* cg = hud_get_gauge(gaugename);
			if(cg) {
				cg->updateCustomGaugeText(message);
			} else {
				WarningEx(LOCATION, "Could not find a hud gauge named %s\n", gaugename);
			}
			return;
		}
	}

	WarningEx(LOCATION, "sexp_hud_set_message couldn't find a message by the name of %s in the mission\n", text);
}

void sexp_hud_set_directive(int n)
{
	char* gaugename = CTEXT(n);
	char* text = CTEXT(CDR(n));
	char message[MESSAGE_LENGTH];

	message_translate_tokens(message, text);

	if (strlen(message) > MESSAGE_LENGTH) {
		WarningEx(LOCATION, "Message %s is too long for use in a HUD gauge. Please shorten it to %d characters or less.", message, MESSAGE_LENGTH);
		return;
	}

	HudGauge* cg = hud_get_gauge(gaugename);
	if(cg) {
		cg->updateCustomGaugeText(message);
	} else {
		WarningEx(LOCATION, "Could not find a hud gauge named %s\n", gaugename);
	}
}

void sexp_hud_clear_messages()
{
	if(Ship_info[Player_ship->ship_info_index].hud_gauges.size() > 0) {
		size_t num_gauges = Ship_info[Player_ship->ship_info_index].hud_gauges.size();

		for(size_t i = 0; i < num_gauges; i++) {
			if (Ship_info[Player_ship->ship_info_index].hud_gauges[i]->getObjectType() == HUD_OBJECT_MESSAGES) {
				HudGaugeMessages* gauge = static_cast<HudGaugeMessages*>(Ship_info[Player_ship->ship_info_index].hud_gauges[i]);
				gauge->clearMessages();
			}
		}
	} else {
		size_t num_gauges = default_hud_gauges.size();

		for(size_t i = 0; i < num_gauges; i++) {
			if (default_hud_gauges[i]->getObjectType() == HUD_OBJECT_MESSAGES) {
				HudGaugeMessages* gauge = static_cast<HudGaugeMessages*>(default_hud_gauges[i]);
				gauge->clearMessages();
			}
		}
	}
}

void sexp_hud_set_coords(int n)
{
	char* gaugename = CTEXT(n);
	int coord_x = eval_num(CDR(n));
	int coord_y = eval_num(CDR(CDR(n)));

	HudGauge* cg = hud_get_gauge(gaugename);
	if(cg) {
		cg->updateCustomGaugeCoords(coord_x, coord_y);
	}
}

void sexp_hud_set_frame(int n)
{
	char* gaugename = CTEXT(n);
	int frame_num = eval_num(CDR(n));

	HudGauge* cg = hud_get_gauge(gaugename);
	if(cg) {
		cg->updateCustomGaugeFrame(frame_num);
	}
}

void sexp_hud_set_color(int n)
{
	char* gaugename = CTEXT(n);
	ubyte red = (ubyte) eval_num(CDR(n));
	ubyte green = (ubyte) eval_num(CDR(CDR(n)));
	ubyte blue = (ubyte) eval_num(CDR(CDR(CDR(n))));

	HudGauge* cg = hud_get_gauge(gaugename);
	if(cg) {
		cg->sexpLockConfigColor(false);
		cg->updateColor(red, green, blue, (HUD_color_alpha+1)*16);
		cg->sexpLockConfigColor(true);
	}
}


// Goober5000
void sexp_hud_set_max_targeting_range(int n)
{
	Hud_max_targeting_range = eval_num(n);

	if (Hud_max_targeting_range < 0) {
		Hud_max_targeting_range = 0;
}

	multi_start_callback();
	multi_send_int(Hud_max_targeting_range);
	multi_end_callback();

}

void multi_sexp_hud_set_max_targeting_range()
{
	multi_get_int(Hud_max_targeting_range);
}

/* Make sure that the Sexp_hud_display_* get added to the game_state
transitions in freespace.cpp (game_enter_state()). */
int Sexp_hud_display_warpout = 0;

void sexp_hud_display_gauge(int n) {
	int show_for = eval_num(n);
	char* gauge = CTEXT(CDR(n));

	if ( stricmp(SEXP_HUD_GAUGE_WARPOUT, gauge) == 0 ) {
		Sexp_hud_display_warpout = (show_for > 1)? timestamp(show_for) : (show_for);
	} 
}

void sexp_hud_gauge_set_active(int n) {
	HudGauge* hg;
	char* name = CTEXT(n);
	bool active = (is_sexp_true(CDR(n)) != 0);

	hg = hud_get_gauge(name);

	if (hg != NULL) {
		hg->updateActive(active);
	}
}

void sexp_hud_set_custom_gauge_active(int node) {
	HudGauge* hg;
	bool activate = (is_sexp_true(node) > 0);
	node = CDR(node);
	for(; node >= 0; node = CDR(node)) {

		char* name = CTEXT(node);
		hg = hud_get_gauge(name);

		if (hg != NULL) {
			hg->updateActive(activate);
		}

	}

}

int hud_gauge_type_lookup(char* name) {
	for(int i = 0; i < Num_hud_gauge_types; i++) {
		if(!stricmp(name, Hud_gauge_types[i].name))
			return Hud_gauge_types[i].def;
	}
	return -1;
}

void sexp_hud_activate_gauge_type(int n) {
	int config_type = hud_gauge_type_lookup(CTEXT(n));
	bool active = (is_sexp_true(CDR(n)) != 0);
	
	if (config_type != -1) { 
		if(Ship_info[Player_ship->ship_info_index].hud_gauges.size() > 0) {
			size_t num_gauges = Ship_info[Player_ship->ship_info_index].hud_gauges.size();

			for(size_t i = 0; i < num_gauges; i++) {
				if (Ship_info[Player_ship->ship_info_index].hud_gauges[i]->getObjectType() == config_type)
					Ship_info[Player_ship->ship_info_index].hud_gauges[i]->updateSexpOverride(!active);
			}
		} else {
			size_t num_gauges = default_hud_gauges.size();

			for(size_t i = 0; i < num_gauges; i++) {
				if (default_hud_gauges[i]->getObjectType() == config_type)
					default_hud_gauges[i]->updateSexpOverride(!active);
			}
		}
	}
}

void sexp_hud_set_retail_gauge_active(int node) {

	bool activate = (is_sexp_true(node) > 0);
	node = CDR(node);

	for(; node >= 0; node = CDR(node)) {

		int config_type = hud_gauge_type_lookup(CTEXT(node));

		if (config_type != -1) {
			if(Ship_info[Player_ship->ship_info_index].hud_gauges.size() > 0) {
			size_t num_gauges = Ship_info[Player_ship->ship_info_index].hud_gauges.size();

			for(size_t i = 0; i < num_gauges; i++) {
				if (Ship_info[Player_ship->ship_info_index].hud_gauges[i]->getObjectType() == config_type)
					Ship_info[Player_ship->ship_info_index].hud_gauges[i]->updateSexpOverride(!activate);
				}
			} else {
			size_t num_gauges = default_hud_gauges.size();

			for(size_t i = 0; i < num_gauges; i++) {
				if (default_hud_gauges[i]->getObjectType() == config_type)
					default_hud_gauges[i]->updateSexpOverride(!activate);
				}
			}
		}

	}

}

void multi_sexp_hud_display_gauge()
{
	int show_for; 

	if (multi_get_int(show_for)) {
		Sexp_hud_display_warpout = (show_for > 1)? timestamp(show_for) : (show_for);
	}
}

// Goober5000
/**
 * Trigger whether player uses the game AI for stuff
 */
void sexp_player_use_ai(int flag)
{
	Player_use_ai = flag ? 1 : 0;
}

// Karajorma
void sexp_allow_treason (int n) 
{
	n = CDR(n);
	if (n != -1) {
		if ( is_sexp_true(n) ) {
			The_mission.flags |= MISSION_FLAG_NO_TRAITOR;
		} 
		else {
			The_mission.flags &= ~MISSION_FLAG_NO_TRAITOR;
		}
	}
}

void sexp_set_player_orders(int n) 
{
	ship *shipp; 
	int i;
	int allow_order;
	int orders = 0;
	int default_orders; 

	shipp = sexp_get_ship_from_node(n);

	if (shipp == NULL) {
		return;
	}

	// we need to know which orders this ship class can accept.
	default_orders = ship_get_default_orders_accepted(&Ship_info[shipp->ship_info_index]);
	n = CDR(n);
	allow_order = is_sexp_true(n);
	n = CDR(n);
	do {
		for (i = 0 ; i < NUM_COMM_ORDER_ITEMS ; i++) {
			// since it's the cheaper test, test first if the ship will even accept this order first
			if (default_orders & Sexp_comm_orders[i].item) {
				if (!stricmp(CTEXT(n), Sexp_comm_orders[i].name)) {
					orders |= Sexp_comm_orders[i].item;
					break;
				}
			}
		}

		n = CDR(n);
	}while (n >= 0);
		
	// set or unset the orders
	if (allow_order) {
		shipp->orders_accepted |= orders;
	}
	else {
		shipp->orders_accepted &= ~orders;
	}
}

// Goober5000
void sexp_change_soundtrack(int n)
{
	event_sexp_change_soundtrack(CTEXT(n));

	if (MULTIPLAYER_MASTER) {
		multi_start_callback(); 
		multi_send_string(CTEXT(n));
		multi_end_callback(); 
	}
}

void multi_sexp_change_soundtrack()
{
	char new_track[NAME_LENGTH]; 

	if (multi_get_string(new_track)) {
		event_sexp_change_soundtrack(new_track);
	}
}

// Goober5000
void sexp_pause_unpause_music(bool pause)
{
	if ( Sexp_music_handle != -1 ) {
		if ( pause && !audiostream_is_paused(Sexp_music_handle) ) {
			audiostream_pause(Sexp_music_handle, true);
		} else if ( !pause && audiostream_is_paused(Sexp_music_handle) ) {
			audiostream_unpause(Sexp_music_handle, true);
		}
	}
}

// Goober5000
void sexp_stop_music(int fade)
{
	if ( Sexp_music_handle != -1 ) {
		audiostream_close_file(Sexp_music_handle, fade);
		Sexp_music_handle = -1;
	}
}

// Goober5000
void sexp_music_close()
{
	if ( Cmdline_freespace_no_music ) {
		return;
	}

	sexp_stop_music();
}

// Goober5000
void sexp_load_music(char* fname, int type = -1)
{
	if ( Cmdline_freespace_no_music ) {
		return;
	}

	if ( Sexp_music_handle != -1 )
	{
		sexp_stop_music();
	}

	if ( type < 0 )
	{
		type = ASF_MENUMUSIC;
	}

	if ( fname )
	{
		Sexp_music_handle = audiostream_open( fname, type );
	}
}

// Goober5000
void sexp_start_music(int loop)
{
	if ( Sexp_music_handle != -1 ) {
		if ( !audiostream_is_playing(Sexp_music_handle) )
			audiostream_play(Sexp_music_handle, (Master_event_music_volume * aav_music_volume), loop);
	}
	else {
		nprintf(("Warning", "Can not play music. sexp_start_music called when no music file is set for Sexp_music_handle!\n"));
	}
}

int sexp_get_sound_index(int node)
{
	Assert(node >= 0);
	int sound_index = -1;

	// this node is another SEXP operator or a plain number
	if (CAR(node) != -1 || Sexp_nodes[node].subtype == SEXP_ATOM_NUMBER)
	{
		sound_index = gamesnd_get_by_tbl_index(eval_num(node));
	}
	// it's gotta be a name
	else
	{
		const char *sound_name = CTEXT(node);

		// if it's not <none>, try looking it up
		if (stricmp(sound_name, SEXP_NONE_STRING))
		{
			sound_index = gamesnd_get_by_name(sound_name);

			if (sound_index < 0)
				Warning(LOCATION, "unrecognized sound name \"%s\"!", sound_name);
		}
	}

	return sound_index;
}

// Goober5000
void sexp_play_sound_from_table(int n)
{
	vec3d origin;
	int sound_index;

	Assert( n >= 0 );

	// read in data --------------------------------
	origin.xyz.x = (float)eval_num(n);
	n = CDR(n);
	origin.xyz.y = (float)eval_num(n);
	n = CDR(n);
	origin.xyz.z = (float)eval_num(n);
	n = CDR(n);
	sound_index = sexp_get_sound_index(n);


	// play sound effect ---------------------------
	if (sound_index >= 0) {
		game_snd *snd = &Snds[sound_index];
		if (snd->min == 0 && snd->max == 0) {
			// if sound doesn't specify 3d range, don't play in 3d
			snd_play( snd, 0.0f, 1.0f, SND_PRIORITY_MUST_PLAY );
		} else {
			snd_play_3d( snd, &origin, &View_position, 0.0f, NULL, 0, 1.0f, SND_PRIORITY_MUST_PLAY );
		}
	}

	if (MULTIPLAYER_MASTER) {
		multi_start_callback();
		multi_send_float(origin.xyz.x);
		multi_send_float(origin.xyz.y);
		multi_send_float(origin.xyz.z);
		multi_send_int(sound_index);
		multi_end_callback();
	}
}

void multi_sexp_play_sound_from_table()
{
	vec3d origin;
	int sound_index = -1;

	multi_get_float(origin.xyz.x);
	multi_get_float(origin.xyz.y);
	multi_get_float(origin.xyz.z);
	multi_get_int(sound_index);


	// play sound effect ---------------------------
	if (sound_index >= 0) {
		game_snd *snd = &Snds[sound_index];
		if (snd->min == 0 && snd->max == 0) {
			// if sound doesn't specify 3d range, don't play in 3d
			snd_play( snd, 0.0f, 1.0f, SND_PRIORITY_MUST_PLAY );
		} else {
			snd_play_3d( snd, &origin, &View_position, 0.0f, NULL, 0, 1.0f, SND_PRIORITY_MUST_PLAY );
		}
	}
}

// Goober5000
void sexp_close_sound_from_file(int n)
{
	int fade = is_sexp_true(n);
	sexp_stop_music(fade);

	if (MULTIPLAYER_MASTER) {
		multi_start_callback();
		multi_send_bool(fade ? true : false); 
		multi_end_callback();
	}
}

void multi_sexp_close_sound_from_file()
{
	bool fade; 
	if (multi_get_bool(fade)) {
		sexp_stop_music(fade);
	}
}

// Goober5000
void sexp_play_sound_from_file(int n)
{
	int loop = 0;
	int soundfx = 0;
	int type = ASF_MENUMUSIC;

	// third option, but needed when loading music -
	soundfx = CDDR(n);

	if (soundfx >= 0) {
		soundfx = eval_sexp(soundfx);

		if (soundfx > 0) {
			type = ASF_SOUNDFX;
		}
	}

	// load sound file -----------------------------
	sexp_load_music(CTEXT(n), type);
	
	if (MULTIPLAYER_MASTER) {
		multi_start_callback();
		multi_send_string(CTEXT(n));
	}

	n = CDR(n);
	if (n >= 0) {
		loop = eval_sexp(n);
	}

	// play sound file -----------------------------
	sexp_start_music(loop);	

	if (MULTIPLAYER_MASTER) {
		multi_send_bool(loop ? true : false); 
		multi_end_callback();
	}
}

void multi_sexp_play_sound_from_file()
{
	char filename[NAME_LENGTH];
	bool (loop);
	if (!multi_get_string(filename)) {
		return;
	}
	sexp_load_music(filename);

	multi_get_bool(loop);
	sexp_start_music(loop);	
}

// Goober5000
void sexp_pause_sound_from_file(int node)
{
	bool pause = (is_sexp_true(node) != 0);

	if (MULTIPLAYER_MASTER) {
		multi_send_bool(pause); 
		multi_end_callback();
	}

	sexp_pause_unpause_music(pause);
}

void multi_sexp_pause_sound_from_file()
{
	bool pause; 
	if (multi_get_bool(pause)) {
		sexp_pause_unpause_music(pause);
	}
}

int sexp_sound_environment_option_lookup(char *text)
{
	int i;

	Assert(text != NULL);
	if (text == NULL) {
		return -1;
	}
	
	for (i = 0; i < Num_sound_environment_options; i++) {
		if (!strcmp(text, Sound_environment_option[i])) {
			return i;
		}
	}

	return -1;
}

// Taylor
void sexp_set_sound_environment(int node)
{
	int n = node;
	sound_env env;
	int preset_id = -1;

	char *preset = CTEXT(n);
	n = CDR(n);

	if ( preset && !stricmp(preset, SEXP_NONE_STRING) ) {
		sound_env_disable();
		return;
	}

	preset_id = ds_eax_get_preset_id( preset );
	if (preset_id < 0) {
		return;
	}

	// fill in defaults for this preset, in case we don't set everything
	if ( sound_env_get(&env, preset_id) ) {
		return;
	}

	while (n >= 0) {
		int option = sexp_sound_environment_option_lookup(CTEXT(n));
		n = CDR(n);

		// watch out for bogus options
		if (n < 0) {
			break;
		}

		float val = (float)eval_num(n) / 1000.0f;
		n = CDR(n);

		if ( option == SEO_VOLUME ) {
			env.volume = val;
		} else if ( option == SEO_DECAY_TIME ) {
			env.decay = val;
		} else if ( option == SEO_DAMPING ) {
			env.damping = val;
		}
	}
	
	sound_env_set(&env);
}

// Taylor
void sexp_update_sound_environment(int node)
{
	int n = node;

	while (n >= 0) {
		int option = sexp_sound_environment_option_lookup(CTEXT(n));
		n = CDR(n);

		// watch out for bogus options
		if (n < 0) {
			break;
		}

		float val = (float)eval_num(n) / 1000.0f;
		n = CDR(n);

		if ( option == SEO_VOLUME ) {
			ds_eax_set_volume(val);
		} else if ( option == SEO_DECAY_TIME ) {
			ds_eax_set_decay_time(val);
		} else if ( option == SEO_DAMPING ) {
			ds_eax_set_damping(val);
		}
	}
}

//The E
	//From sexp help:
	//{ OP_ADJUST_AUDIO_VOLUME, "adjust-audio-volume\r\n"
	//	"Adjusts the relative volume of one sound type. Takes 2 or 3 arguments....\r\n"
	//	"\t1:\tSound Type to adjust, either Music, Voice or Effects\r\n"
	//	"\t2:\tPercentage of the users' settings to adjust to, 0 will be silence, 100 means the maximum volume as set by the user\r\n"
	//	"\t3:\tFade time (optional), time in milliseconds to adjust the volume"},

int audio_volume_option_lookup(char *text)
{
	int i;

	Assert(text != NULL);
	if (text == NULL) {
		return -1;
	}
	
	for (i = 0; i < Num_adjust_audio_options; i++) {
		if (!strcmp(text, Adjust_audio_options[i])) {
			return i;
		}
	}

	return -1;
}

void sexp_adjust_audio_volume(int node)
{
	int n = node;

	if (n > 0) {
		int option = audio_volume_option_lookup(CTEXT(n));
		if (option >= 0) {
			n = CDR(n);

			float target_volume = 1.0f;
			if (n >= 0) {
				target_volume = (float)eval_num(n) / 100;
				CLAMP(target_volume, 0.0f, 1.0f);
				n = CDR(n);
			}

			int time = 0;
			if (n >= 0)
				time = eval_num(n);

			snd_adjust_audio_volume(option, target_volume, time);
		}
	}
}

int sexp_explosion_option_lookup(char *text)
{
	int i;

	Assert(text != NULL);
	if (text == NULL) {
		return -1;
	}
	
	for (i = 0; i < Num_explosion_options; i++) {
		if (!strcmp(text, Explosion_option[i])) {
			return i;
		}
	}

	return -1;
}

// Goober5000
void sexp_set_explosion_option(int node)
{
	int n = node, ship_num;
	ship *shipp;
	ship_info *sip;
	shockwave_create_info *sci;

	// get ship
	ship_num = ship_name_lookup(CTEXT(n));
	if (ship_num < 0)
		return;

	shipp = &Ships[ship_num];
	sip = &Ship_info[shipp->ship_info_index];
	sci = &sip->shockwave;

	n = CDR(n);

	// if we haven't changed anything yet, create a new special-exp with the same values as a standard exp
	if (!shipp->use_special_explosion)
	{
		shipp->special_exp_damage = fl2i(sci->damage);
		shipp->special_exp_blast = fl2i(sci->blast);
		shipp->special_exp_inner = fl2i(sci->inner_rad);
		shipp->special_exp_outer = fl2i(sci->outer_rad);
		shipp->special_exp_shockwave_speed = fl2i(sci->speed);
		shipp->special_exp_deathroll_time = 0;

		shipp->use_special_explosion = true;
		shipp->use_shockwave = (sci->speed > 0);
	}

	// process all options
	while (n >= 0)
	{
		int option = sexp_explosion_option_lookup(CTEXT(n));
		n = CDR(n);

		// watch out for bogus options
		if (n < 0)
			break;

		int val = eval_num(n);
		Assert(val >= 0);	// should be true due to OPF_POSITIVE
		n = CDR(n);

		if (option == EO_DAMAGE) {
			shipp->special_exp_damage = val;
		} else if (option == EO_BLAST) {
			shipp->special_exp_blast = val;
		} else if (option == EO_INNER_RADIUS) {
			shipp->special_exp_inner = val;
		} else if (option == EO_OUTER_RADIUS) {
			shipp->special_exp_outer = val;
		} else if (option == EO_SHOCKWAVE_SPEED) {
			shipp->special_exp_shockwave_speed = val;
			shipp->use_shockwave = (val > 0);
		} else if (option == EO_DEATH_ROLL_TIME) {
			shipp->special_exp_deathroll_time = val;

			// hmm, it would be cool to modify the explosion in progress
			if (shipp->flags & SF_DYING && val >= 2) {
				shipp->final_death_time = timestamp(val);
			}
		}
	}

	// if all our values are the same as a standard exp, turn off the special exp
	if ((shipp->special_exp_damage == sci->damage) && (shipp->special_exp_blast == sci->blast) && (shipp->special_exp_inner == sci->inner_rad)
		&& (shipp->special_exp_outer == sci->outer_rad) && (shipp->special_exp_shockwave_speed == sci->speed) && (shipp->special_exp_deathroll_time == 0))
	{
		shipp->use_special_explosion = false;
		shipp->use_shockwave = false;

		shipp->special_exp_damage = -1;
		shipp->special_exp_blast = -1;
		shipp->special_exp_inner = -1;
		shipp->special_exp_outer = -1;
		shipp->special_exp_shockwave_speed = -1;
		shipp->special_exp_deathroll_time = 0;
	}
}

// Goober5000
void sexp_explosion_effect(int n)
/* From the SEXP help...
	{ OP_EXPLOSION_EFFECT, "explosion-effect\r\n"
		"\tCauses an explosion at a given origin, with the given parameters.  "
		"Takes 11 or 13 arguments...\r\n"
		"\t1:  Origin X\r\n"
		"\t2:  Origin Y\r\n"
		"\t3:  Origin Z\r\n"
		"\t4:  Damage\r\n"
		"\t5:  Blast force\r\n"
		"\t6:  Size of explosion (if 0, explosion will not be visible)\r\n"
		"\t7:  Inner radius to apply damage (if 0, explosion will not be visible)\r\n"
		"\t8:  Outer radius to apply damage (if 0, explosion will not be visible)\r\n"
		"\t9:  Shockwave speed (if 0, there will be no shockwave)\r\n"
		"\t10: Type (0 = medium, 1 = large1, 2 = large2)\r\n"  (otherwise use the index in fireball.tbl - FUBAR)
		"\t11: Sound (index into sounds.tbl)\r\n"
		"\t12: EMP intensity (optional)\r\n"
		"\t13: EMP duration in seconds (optional)" },
*/
// Basically, this function pretends that there's a ship at the origin that's blowing up, and
// it does stuff accordingly.  In some places, it has to tiptoe around a little because the
// code often expects a parent object when in fact there is none. <.<  >.>
{
	vec3d origin;
	int max_damage, max_blast, explosion_size, inner_radius, outer_radius, shockwave_speed, fireball_type, sound_index;
	int emp_intensity, emp_duration;

	Assert( n >= 0 );

	// read in data --------------------------------
	origin.xyz.x = (float)eval_num(n);
	n = CDR(n);
	origin.xyz.y = (float)eval_num(n);
	n = CDR(n);
	origin.xyz.z = (float)eval_num(n);
	n = CDR(n);

	max_damage = eval_num(n);
	n = CDR(n);
	max_blast = eval_num(n);
	n = CDR(n);

	explosion_size = eval_num(n);
	n = CDR(n);
	inner_radius = eval_num(n);
	n = CDR(n);
	outer_radius = eval_num(n);
	n = CDR(n);

	shockwave_speed = eval_num(n);
	n = CDR(n);

	// fireball type
	if (eval_num(n) == 0)
	{
		fireball_type = FIREBALL_EXPLOSION_MEDIUM;
	}
	else if (eval_num(n) == 1)
	{
		fireball_type = FIREBALL_EXPLOSION_LARGE1;
	}
	else if (eval_num(n) == 2)
	{
		fireball_type = FIREBALL_EXPLOSION_LARGE2;
	}
	else if (eval_num(n) >= Num_fireball_types)	{
		Warning(LOCATION, "explosion-effect type is out of range; quitting the explosion...\n");
		return;
	}
	else {
		fireball_type = eval_num(n);
	}
	n = CDR(n);

	sound_index = sexp_get_sound_index(n);

	n = CDR(n);

	// optional EMP
	emp_intensity = 0;
	emp_duration = 0;
	if (n != -1)
	{
		emp_intensity = eval_num(n);
		n = CDR(n);
	}
	if (n != -1)
	{
		emp_duration = eval_num(n);
		n = CDR(n);
	}


	// play sound effect ---------------------------
	if (sound_index >= 0)
	{
		snd_play_3d( &Snds[sound_index], &origin, &View_position, 0.0f, NULL, 0, 1.0f, SND_PRIORITY_MUST_PLAY  );
	}


	// create the fireball -------------------------
	if (explosion_size && inner_radius && outer_radius)
	{
		if(fireball_type == FIREBALL_EXPLOSION_MEDIUM)
			fireball_create( &origin, fireball_type, FIREBALL_MEDIUM_EXPLOSION, -1, (float)explosion_size );
		else
			fireball_create( &origin, fireball_type, FIREBALL_LARGE_EXPLOSION, -1, (float)explosion_size );
	}

	// apply area affect damage --------------------
	if (max_damage || max_blast)
	{
		if ( shockwave_speed > 0 )
		{
			shockwave_create_info sci;
			shockwave_create_info_init(&sci);

			sci.inner_rad = (float)inner_radius;
			sci.outer_rad = (float)outer_radius;
			sci.blast = (float)max_blast;
			sci.damage = (float)max_damage;
			sci.speed = (float)shockwave_speed;
			sci.rot_angles.p = frand_range(0.0f, 1.99f*PI);
			sci.rot_angles.b = frand_range(0.0f, 1.99f*PI);
			sci.rot_angles.h = frand_range(0.0f, 1.99f*PI);
			shockwave_create(-1, &origin, &sci, SW_SHIP_DEATH);
		}
		else
		{
			object *objp;
			float t_blast = 0.0f;
			float t_damage = 0.0f;
			for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) )
			{
				if ( (objp->type != OBJ_SHIP) && (objp->type != OBJ_ASTEROID) )
				{
					continue;
				}
		
				// don't blast navbuoys
				if ( objp->type == OBJ_SHIP )
				{
					if ( ship_get_SIF(objp->instance) & SIF_NAVBUOY )
					{
						continue;
					}
				}

				if ( ship_explode_area_calc_damage( &origin, &objp->pos, (float)inner_radius, (float)outer_radius, (float)max_damage, (float)max_blast, &t_damage, &t_blast ) == -1 )
				{
					continue;
				}
	
				switch ( objp->type )
				{
					case OBJ_SHIP:
						ship_apply_global_damage( objp, NULL, &origin, t_damage );
						vec3d force, vec_ship_to_impact;
						vm_vec_sub( &vec_ship_to_impact, &objp->pos, &origin );
						if (!IS_VEC_NULL_SQ_SAFE( &vec_ship_to_impact )) {
							vm_vec_copy_normalize( &force, &vec_ship_to_impact );
							vm_vec_scale( &force, (float)max_blast );
							ship_apply_whack( &force, &vec_ship_to_impact, objp );
						}
						break;

					case OBJ_ASTEROID:
						asteroid_hit(objp, NULL, NULL, t_damage);
						break;
	
					default:
						Int3();
						break;
				}
			}	// end for
		}
	}


	// apply emp damage if applicable --------------
	if (emp_intensity && emp_duration)
	{
		emp_apply(&origin, (float)inner_radius, (float)outer_radius, (float)emp_intensity, (float)emp_duration);
	}
}

// Goober5000
void sexp_warp_effect(int n)
/* From the SEXP help...
	{ OP_WARP_EFFECT, "warp-effect\r\n"
		"\tCauses a subspace warp effect at a given origin, facing toward a given location, with the given parameters.  "
		"Takes 12 arguments...\r\n"
		"\t1:  Origin X\r\n"
		"\t2:  Origin Y\r\n"
		"\t3:  Origin Z\r\n"
		"\t4:  Location X\r\n"
		"\t5:  Location Y\r\n"
		"\t6:  Location Z\r\n"
		"\t7:  Radius\r\n"
		"\t8:  Duration in seconds\r\n"
		"\t9:  Warp opening sound (index into sounds.tbl)\r\n"
		"\t10: Warp closing sound (index into sounds.tbl)\r\n"
		"\t11: Type (0 for standard blue [default], 1 for Knossos green)\r\n"
		"\t12: Shape (0 for 2-D [default], 1 for 3-D)" },
*/
{
	vec3d origin, location, v_orient;
	matrix m_orient;
	int radius, duration, warp_open_sound_index, warp_close_sound_index, fireball_type, extra_flags;
	extra_flags = FBF_WARP_VIA_SEXP;

	// read in data --------------------------------
	origin.xyz.x = (float)eval_num(n);
	n = CDR(n);
	origin.xyz.y = (float)eval_num(n);
	n = CDR(n);
	origin.xyz.z = (float)eval_num(n);
	n = CDR(n);

	location.xyz.x = (float)eval_num(n);
	n = CDR(n);
	location.xyz.y = (float)eval_num(n);
	n = CDR(n);
	location.xyz.z = (float)eval_num(n);
	n = CDR(n);

	radius = eval_num(n);
	n = CDR(n);
	duration = eval_num(n);
	if (duration < 4) duration = 4;
	n = CDR(n);

	warp_open_sound_index = sexp_get_sound_index(n);
	n = CDR(n);
	warp_close_sound_index = sexp_get_sound_index(n);
	n = CDR(n);

	// fireball type
	if (eval_num(n) == 0)
	{
		fireball_type = FIREBALL_WARP;
	}
	else if (eval_num(n) == 1)
	{
		fireball_type = FIREBALL_KNOSSOS;
	}
	else
	{
		Warning(LOCATION, "warp-effect type is out of range; quitting the warp...\n");
		return;
	}
	n = CDR(n);

	// shape
	if (eval_num(n) == 0)
	{
		// do nothing; this is standard
	}
	else if (eval_num(n) == 1)
	{
		extra_flags |= FBF_WARP_3D;
	}
	else
	{
		Warning(LOCATION, "warp-effect shape is out of range; quitting the warp...\n");
		return;
	}


	// calculate orientation matrix ----------------

	vm_vec_sub(&v_orient, &location, &origin);

	if (IS_VEC_NULL_SQ_SAFE(&v_orient))
	{
		Warning(LOCATION, "error in warp-effect: warp can't point to itself; quitting the warp...\n");
		return;
	}

	vm_vector_2_matrix(&m_orient, &v_orient, NULL, NULL);

	// create fireball -----------------------------

	fireball_create(&origin, fireball_type, FIREBALL_WARP_EFFECT, -1, (float)radius, 0, NULL, (float)duration, -1, &m_orient, 0, extra_flags, warp_open_sound_index, warp_close_sound_index);
}

// this function get called by send-message or send-message random with the name of the message, sender,
// and priority.
void sexp_send_one_message( char *name, char *who_from, char *priority, int group, int delay )
{
	int ipriority, num, ship_index, source;
	ship *shipp;

	if(physics_paused){
		return;
	}

	Assert( (name != NULL) && (who_from != NULL) && (priority != NULL) );

	// determine the priority of the message
	if ( !stricmp(priority, "low") )
		ipriority = MESSAGE_PRIORITY_LOW;
	else if ( !stricmp(priority, "normal") )
		ipriority = MESSAGE_PRIORITY_NORMAL;
	else if ( !stricmp(priority, "high") )
		ipriority = MESSAGE_PRIORITY_HIGH;
	else {
		Int3();
		ipriority = MESSAGE_PRIORITY_NORMAL;
	}

	// check to see if the 'who_from' string is a ship that had been destroyed or departed.  If so,
	// then don't send the message.  We must look at 'who_from' to determine what to look for.  who_from
	// may be any allied person, any wingman, a wingman from a specific wing, or a specific ship
	ship_index = -1;
	shipp = NULL;
	source = MESSAGE_SOURCE_COMMAND;
	if ( who_from[0] == '#' ) {
		message_send_unique_to_player( name, &(who_from[1]), MESSAGE_SOURCE_SPECIAL, ipriority, group, delay );
		return;
	} else if (!stricmp(who_from, "<any allied>")) {
		return;
	} else if ( (num = wing_name_lookup(who_from)) != -1 ) {
		// message from a wing
		// choose wing leader to speak for wing (hence "1" at end of ship_get_random_ship_in_wing)
		ship_index = ship_get_random_ship_in_wing( num, SHIP_GET_UNSILENCED, 1 );
		if ( ship_index == -1 ) {
			if ( ipriority != MESSAGE_PRIORITY_HIGH )
				return;
		}

	} else if ( mission_log_get_time(LOG_SHIP_DESTROYED, who_from, NULL, NULL) || mission_log_get_time(LOG_SHIP_DEPARTED, who_from, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, who_from, NULL, NULL)
		|| mission_log_get_time(LOG_WING_DESTROYED, who_from, NULL, NULL) || mission_log_get_time(LOG_WING_DEPARTED, who_from, NULL, NULL) ) {
		// getting into this if statement means that the ship or wing (sender) is no longer in the mission
		// if message is high priority, make it come from Terran Command
		if ( ipriority != MESSAGE_PRIORITY_HIGH )
			return;
		
		source = MESSAGE_SOURCE_COMMAND;

	} else if ( !stricmp(who_from, "<any wingman>") || (wing_name_lookup(who_from) != -1) ) {
		source = MESSAGE_SOURCE_WINGMAN;
	} else if ( !stricmp(who_from, "<none>") ) {
		source = MESSAGE_SOURCE_NONE;
	} else {
		// Message from a apecific ship
		source = MESSAGE_SOURCE_SHIP;
		ship_index = ship_name_lookup(who_from);
		if ( ship_index == -1 ) {
			// bail if not high priority, otherwise reroute to command
			if ( ipriority != MESSAGE_PRIORITY_HIGH )
				return;
			source = MESSAGE_SOURCE_COMMAND;
		}
	}

	if ( ship_index == -1 ){
		shipp = NULL;
	} else {
		shipp = &Ships[ship_index];
	}

	message_send_unique_to_player( name, shipp, source, ipriority, group, delay );
}

void sexp_send_message(int n)
{
	char *name, *who_from, *priority, *tmp;

	if(physics_paused){
		return;
	}

	Assert ( n != -1 );
	who_from = CTEXT(n);
	priority = CTEXT(CDR(n));
	name = CTEXT(CDR(CDR(n)));

	// a temporary check to see if the name field matched a priority since I am in the process
	// of reordering the arguments
	if ( !stricmp(name, "low") || !stricmp(name, "normal") || !stricmp(name, "high") ) {
		tmp = name;
		name = priority;
		priority = tmp;
	}

	sexp_send_one_message( name, who_from, priority, 0, 0 );
}

void sexp_send_message_list(int n)
{
	char *name, *who_from, *priority;
	int delay;

	if(physics_paused){
		return;
	}

	// send a bunch of messages
	delay = 0;
	while(n != -1){
		who_from = CTEXT(n);

		// next node
		n = CDR(n);
		if(n == -1){
			Warning(LOCATION, "Detected incomplete parameter list in sexp-send-message-list");
			return;
		}
		priority = CTEXT(n);

		// next node
		n = CDR(n);
		if(n == -1){
			Warning(LOCATION, "Detected incomplete parameter list in sexp-send-message-list");
			return;
		}
		name = CTEXT(n);

		// next node
		n = CDR(n);
		if(n == -1){
			Warning(LOCATION, "Detected incomplete parameter list in sexp-send-message-list");
			return;
		}
		delay += eval_num(n);

		// send the message
		sexp_send_one_message(name, who_from, priority, 1, delay);

		// next node
		n = CDR(n);
	}
}

void sexp_send_random_message(int n)
{
	char *name, *who_from, *priority;
	int temp, num_messages, message_num;

	Assert ( n != -1 );
	who_from = CTEXT(n);
	priority = CTEXT(CDR(n));

	if(physics_paused){
		return;
	}

	// count the number of messages that we have
	n = CDR(CDR(n));
	temp = n;
	num_messages = 0;
	while ( n != -1 ) {
		n = CDR(n);
		num_messages++;
	}
	Assert ( num_messages >= 1 );
	
	// get a random message, and pass the parameters to send_one_message
	message_num = myrand() % num_messages;
	n = temp;
	while ( n != -1 ) {
		if ( message_num == 0 )
			break;
		message_num--;
		n = CDR(n);
	}
	Assert (n != -1);		// should have found the message!!!
	name = CTEXT(n);

	sexp_send_one_message( name, who_from, priority, 0, 0 );
}

void sexp_self_destruct(int node)
{
	int n, ship_num;

	for (n = node; n != -1; n = CDR(n))	{
		// get the ship
		ship_num = ship_name_lookup(CTEXT(n));

		// if it still exists, destroy it
		if (ship_num >= 0) {
			ship_self_destruct(&Objects[Ships[ship_num].objnum]);
		}
	}
}

void sexp_next_mission(int n)
{
	char *mission_name;
	int i;

	mission_name = CTEXT(n);

	if (mission_name == NULL) {
		Error( LOCATION, "Mission name is NULL in campaign file for next-mission command!");
	}

	for (i = 0; i < Campaign.num_missions; i++) {
		if ( !stricmp(Campaign.missions[i].name, mission_name) ) {
			Campaign.next_mission = i;
			return;
		}
	}
	Error(LOCATION, "Mission name %s not found in campaign file for next-mission command", mission_name);
}

/**
 * Deal with the end-of-campaign sexpression. 
 */
void sexp_end_of_campaign(int n)
{
	// this is really a do-nothing sexpression.  It is pretty much a placeholder to allow
	// campaigns to have repeat-mission branches at the end of the campaign.  By not setting
	// anything in this function, the higher level campaign code will see this as end-of-campaign
	// since next_mission isn't set to anything.  (To be safe, we'll set to -1).
	Campaign.next_mission = -1;	
}

// sexpression to end everything.  One parameter is the movie to play when this is over.
// Goober5000 - edited to only to the FS2-specific code when actually ending the FS2 main
// campaign, and otherwise to do the conventional code
void sexp_end_campaign(int n)
{
	int ignore_player_mortality = 1;

	if (!(Game_mode & GM_CAMPAIGN_MODE)) {
		return;
	}

	if (n != -1) {
		ignore_player_mortality = is_sexp_true(n);
	}

	// if the player is dead we may want to let the death screen handle things
	if (!ignore_player_mortality && (Player_ship->flags & SF_DYING)) {
		return;
	}

	// in FS2 our ending is a bit wacky. we'll just flag the mission as having ended the campaign	
	//
	// changed this to check for an active supernova rather than a special campaign since the supernova
	// code needs special time to execute and will post GS_EVENT_END_CAMPAIGN with Game_mode check
	// or show death-popup when it's done - taylor
	if (supernova_active() /*&& !stricmp(Campaign.filename, "freespace2")*/) {
		Campaign_ending_via_supernova = 1;
	} else {
		// post and event to move us to the end-of-campaign state
		gameseq_post_event(GS_EVENT_END_CAMPAIGN);
	}
}

/**
 * Reduces the strength of a subsystem by the given percentage.
 *
 * If it is reduced to below 0%, then the hits of the subsystem are set to 0
 */
void sexp_sabotage_subsystem(int n)
{
	char *shipname, *subsystem;
	int	percentage, shipnum, index, generic_type;
	float sabotage_hits;
	ship	*shipp;
	ship_subsys *ss = NULL, *ss_start;
	bool do_loop = true;

	shipname = CTEXT(n);
	subsystem = CTEXT(CDR(n));
	percentage = eval_num(CDR(CDR(n)));

	shipnum = ship_name_lookup(shipname);
	
	// if no ship, then return immediately.
	if ( shipnum == -1 )
		return;
	shipp = &Ships[shipnum];

	// see if we are dealing with the HULL
	if ( !stricmp( subsystem, SEXP_HULL_STRING) ) {
		float ihs;
		object *objp;

		ihs = shipp->ship_max_hull_strength;
		sabotage_hits = ihs * ((float)percentage / 100.0f);
		objp = &Objects[shipp->objnum];
		objp->hull_strength -= sabotage_hits;

		// self destruct the ship if <= 0.
		if ( objp->hull_strength <= 0.0f )
			ship_self_destruct( objp );
		return;
	}

	// see if we are dealing with the Simulated HULL
	if ( !stricmp( subsystem, SEXP_SIM_HULL_STRING) ) {
		float ihs;
		object *objp;

		ihs = shipp->ship_max_hull_strength;
		sabotage_hits = ihs * ((float)percentage / 100.0f);
		objp = &Objects[shipp->objnum];
		objp->sim_hull_strength -= sabotage_hits;

		return;
	}

	// now find the given subsystem on the ship.  This could be a generic type like <All Engines>
	generic_type = get_generic_subsys(subsystem);
	ss_start = GET_FIRST(&shipp->subsys_list); 

	while (do_loop) {
		if (generic_type) {
			// loop until we find a subsystem of that type
			for ( ; ss_start != END_OF_LIST(&Ships[shipnum].subsys_list); ss_start = GET_NEXT(ss_start)) {
				ss = NULL;
				if (generic_type == ss_start->system_info->type) {
					ss = ss_start;
					ss_start = GET_NEXT(ss_start);
					break;
				}
			}

			// reached the end of the subsystem list 
			if (ss_start == END_OF_LIST(&Ships[shipnum].subsys_list)) {
				// If the last subsystem wasn't of interest we don't need to go any further
				if (ss == NULL) { 
					return;
				}
				do_loop = false;
			}			
		}
		else {
			do_loop = false;
			index = ship_get_subsys_index(shipp, subsystem, 1);	// Bypass any error since we supply one here
			if ( index == -1 ) {
				nprintf(("Warning", "Couldn't find subsystem %s on ship %s for sabotage subsystem\n", subsystem, shipp->ship_name));
				return;
			}
			// get the pointer to the subsystem.  Check it's current hits against it's max hits, and
			// set the strength to the given percentage if current strength is > given percentage
			ss = ship_get_indexed_subsys( shipp, index );
			if (ss == NULL) {
				nprintf(("Warning", "Nonexistent subsystem for index %d on ship %s for sabotage subsystem\n", index, shipp->ship_name));
				return;
			}
		}

		sabotage_hits = ss->max_hits * ((float)percentage / 100.0f);
		ss->current_hits -= sabotage_hits;
		if ( ss->current_hits < 0.0f )
			ss->current_hits = 0.0f;

		// maybe blow up subsys
		if (ss->current_hits <= 0) {
			do_subobj_destroyed_stuff(shipp, ss, NULL);
		}

		ship_recalc_subsys_strength( shipp );
	}
}

/**
 * Adds some percentage of hits to a subsystem.
 * 
 * Anything repaired about 100% is set to max hits
 */
void sexp_repair_subsystem(int n)
{
	char *shipname, *subsystem;
	int	percentage, shipnum, index, do_submodel_repair, generic_type;
	float repair_hits;
	ship *shipp;
	ship_subsys *ss = NULL, *ss_start;
	bool do_loop = true;

	shipname = CTEXT(n);
	subsystem = CTEXT(CDR(n));
	shipnum = ship_name_lookup(shipname);
	
	do_submodel_repair = is_sexp_true(CDDDR(n));
	
	// if no ship, then return immediately.
	if ( shipnum == -1 ) {
		return;
	}
	shipp = &Ships[shipnum];
	
	// get percentage
	percentage = eval_num(CDR(CDR(n)));

	// see if we are dealing with the HULL
	if ( !stricmp( subsystem, SEXP_HULL_STRING) ) {
		float ihs;
		object *objp;

		ihs = shipp->ship_max_hull_strength;
		repair_hits = ihs * ((float)percentage / 100.0f);
		objp = &Objects[shipp->objnum];
		objp->hull_strength += repair_hits;
		if ( objp->hull_strength > ihs )
			objp->hull_strength = ihs;
		return;
	}

	// see if we are dealing with the Simulated HULL
	if ( !stricmp( subsystem, SEXP_SIM_HULL_STRING) ) {
		float ihs;
		object *objp;

		ihs = shipp->ship_max_hull_strength;
		repair_hits = ihs * ((float)percentage / 100.0f);
		objp = &Objects[shipp->objnum];
		objp->hull_strength += repair_hits;
		if ( objp->sim_hull_strength > ihs )
			objp->sim_hull_strength = ihs;
		return;
	}

	// now find the given subsystem on the ship.This could be a generic type like <All Engines>
	generic_type = get_generic_subsys(subsystem);
	ss_start = GET_FIRST(&shipp->subsys_list); 

	while (do_loop) {
		if (generic_type) {
			// loop until we find a subsystem of that type
			for ( ; ss_start != END_OF_LIST(&Ships[shipnum].subsys_list); ss_start = GET_NEXT(ss_start)) {
				ss = NULL;
				if (generic_type == ss_start->system_info->type) {
					ss = ss_start;
					ss_start = GET_NEXT(ss_start);
					break;
				}
			}

			// reached the end of the subsystem list 
			if (ss_start == END_OF_LIST(&Ships[shipnum].subsys_list)) {
				// If the last subsystem wasn't of interest we don't need to go any further
				if (ss == NULL) { 
					return;
				}
				do_loop = false;
			}			
		}
		else {
			do_loop = false;
			index = ship_get_subsys_index(shipp, subsystem, 1);	// Bypass any error since we supply one here
			if ( index == -1 ) {
				nprintf(("Warning", "Couldn't find subsystem %s on ship %s for repair subsystem\n", subsystem, shipp->ship_name));
				return;
			}
			// get the pointer to the subsystem.  Check it's current hits against it's max hits, and
			// set the strength to the given percentage if current strength is < given percentage
			ss = ship_get_indexed_subsys( shipp, index );
			if (ss == NULL) {
				nprintf(("Warning", "Nonexistent subsystem for index %d on ship %s for repair subsystem\n", index, shipp->ship_name));
				return;
			}
		}
	
		repair_hits = ss->max_hits * ((float)percentage / 100.0f);
		ss->current_hits += repair_hits;
		if ( ss->current_hits > ss->max_hits )
			ss->current_hits = ss->max_hits;

		if ((ss->current_hits > 0) && (do_submodel_repair))
		{
			ss->submodel_info_1.blown_off = 0;
			ss->submodel_info_2.blown_off = 0;
		}

		ship_recalc_subsys_strength( shipp );
	}
}

/**
 * Set a subsystem of a ship at a specific percentage
 */
void sexp_set_subsystem_strength(int n)
{
	char *shipname, *subsystem;
	int	percentage, shipnum, index, do_submodel_repair, generic_type;
	ship *shipp;
	ship_subsys *ss = NULL, *ss_start;
	bool do_loop = true;

	shipname = CTEXT(n);
	subsystem = CTEXT(CDR(n));
	percentage = eval_num(CDR(CDR(n)));

	do_submodel_repair = is_sexp_true(CDDDR(n));

	shipnum = ship_name_lookup(shipname);
	
	// if no ship, then return immediately.
	if ( shipnum == -1 )
		return;
	shipp = &Ships[shipnum];

	if ( percentage > 100 ) {
		mprintf(("Percentage for set_subsystem_strength > 100 on ship %s for subsystem '%s'-- setting to 100\n", shipname, subsystem));
		percentage = 100;
	} else if ( percentage < 0 ) {
		mprintf(("Percantage for set_subsystem_strength < 0 on ship %s for subsystem '%s' -- setting to 0\n", shipname, subsystem));
		percentage = 0;
	}

	// see if we are dealing with the HULL
	if ( !stricmp( subsystem, SEXP_HULL_STRING) ) {
		float ihs;
		object *objp;

		objp = &Objects[shipp->objnum];

		// destroy the ship if percentage is 0
		if ( percentage == 0 ) {
			ship_self_destruct( objp );
		} else {
			ihs = shipp->ship_max_hull_strength;
			objp->hull_strength = ihs * ((float)percentage / 100.0f);
		}

		return;
	}

	// see if we are dealing with the Simulated HULL
	if ( !stricmp( subsystem, SEXP_SIM_HULL_STRING) ) {
		float ihs;
		object *objp;

		objp = &Objects[shipp->objnum];
		ihs = shipp->ship_max_hull_strength;
		objp->sim_hull_strength = ihs * ((float)percentage / 100.0f);

		return;
	}

	// now find the given subsystem on the ship.This could be a generic type like <All Engines>
	generic_type = get_generic_subsys(subsystem);
	ss_start = GET_FIRST(&shipp->subsys_list); 

	while (do_loop) {
		if (generic_type) {
			// loop until we find a subsystem of that type
			for ( ; ss_start != END_OF_LIST(&Ships[shipnum].subsys_list); ss_start = GET_NEXT(ss_start)) {
				ss = NULL;
				if (generic_type == ss_start->system_info->type) {
					ss = ss_start;
					ss_start = GET_NEXT(ss_start);
					break;
				}
			}

			// reached the end of the subsystem list 
			if (ss_start == END_OF_LIST(&Ships[shipnum].subsys_list)) {
				// If the last subsystem wasn't of interest we don't need to go any further
				if (ss == NULL) { 
					return;
				}
				do_loop = false;
			}			
		}
		else {
			do_loop = false;
			index = ship_get_subsys_index(shipp, subsystem, 1);	// Bypass any error since we supply one here
			if ( index == -1 ) {
				nprintf(("Warning", "Couldn't find subsystem %s on ship %s for set subsystem strength\n", subsystem, shipp->ship_name));
				return;
			}

			// get the pointer to the subsystem.  Check it's current hits against it's max hits, and
			// set the strength to the given percentage
			ss = ship_get_indexed_subsys( shipp, index );
			if (ss == NULL) {
				nprintf(("Warning", "Nonexistent subsystem for index %d on ship %s for set subsystem strength\n", index, shipp->ship_name));
				return;
			}
		}
		
		// maybe blow up subsys
		if (ss->current_hits > 0) {
			if (percentage < 1) {
				do_subobj_destroyed_stuff(shipp, ss, NULL);
			}
		}

		// set hit points
		ss->current_hits = ss->max_hits * ((float)percentage / 100.0f);

		if ((ss->current_hits > 0) && (do_submodel_repair))
		{
			ss->submodel_info_1.blown_off = 0;
			ss->submodel_info_2.blown_off = 0;
		}

		ship_recalc_subsys_strength( shipp );
	}
}

// destroys a subsystem without explosions
void sexp_destroy_subsys_instantly (int n)
{
	char *subsystem;
	int	shipnum, index, generic_type;
	ship *shipp;
	ship_subsys *ss = NULL;
	
	// if MULTIPLAYER bail
	if (Game_mode & GM_MULTIPLAYER) {
		return;
	}

	shipnum = ship_name_lookup(CTEXT(n));
	// if no ship, then return immediately.
	if ( shipnum == -1 ){
		return;
	}

	shipp = &Ships[shipnum];
	n = CDR(n);
	
	//Process subsystems
	while(n != -1)
	{
		subsystem = CTEXT(n);
		if ( !stricmp( subsystem, SEXP_HULL_STRING) || !stricmp( subsystem, SEXP_SIM_HULL_STRING)){
			n = CDR(n);
			continue;
		}
		// deal with generic subsystems
		generic_type = get_generic_subsys(subsystem);
		if (generic_type) {
			for (ss = GET_FIRST(&shipp->subsys_list); ss != END_OF_LIST(&shipp->subsys_list); ss = GET_NEXT(ss)) {
				if (generic_type == ss->system_info->type) {
					// do destruction stuff
					ss->current_hits = 0;
					ship_recalc_subsys_strength(shipp);
					do_subobj_destroyed_stuff(shipp, ss, NULL, true);
				}
			}
		}
		else
		{
			// normal subsystems
			ss = ship_get_subsys(shipp, subsystem);
			index = ship_get_subsys_index(shipp, subsystem, 1);
			if ( index == -1 ) {
				nprintf(("Warning", "Couldn't find subsystem %s on ship %s for destroy-subsys-instantly\n", subsystem, shipp->ship_name));
				n = CDR(n);
				continue;
			}
			if(ss == NULL) {
				nprintf(("Warning", "Nonexistent subsystem for index %d on ship %s for destroy-subsys-instantly\n", index, shipp->ship_name));
				n = CDR(n);
				continue;
			}
			// do destruction stuff
			ss->current_hits = 0;
			ship_recalc_subsys_strength(shipp);
			do_subobj_destroyed_stuff(shipp, ss, NULL, true);
		}
		// next
		n = CDR(n);
	}
}

/**
 * Changes the validity of a goal.
 * 
 * The flag paramater tells us whether to mark the goals as valid or invalid
 */
void sexp_change_goal_validity( int n, int flag )
{
	char *name;

	while ( n != -1 ) {
		name = CTEXT(n);
		if ( flag )
			mission_goal_mark_valid( name );
		else
			mission_goal_mark_invalid( name );

		n = CDR(n);
	}
}

// Goober5000
// yeesh - be careful of the cargo-no-deplete flag :p
int sexp_is_cargo(int n)
{
	char *cargo, *ship_name, *subsystem;
	int ship_num, cargo_index;

	cargo = CTEXT(n);
	ship_name = CTEXT(CDR(n));
	if (CDR(CDR(n)) != -1)
		subsystem = CTEXT(CDR(CDR(n)));
	else
		subsystem = NULL;

	cargo_index = -1;

	// find ship
	ship_num = ship_name_lookup(ship_name);

	// in-mission?
	if (ship_num != -1)
	{
		if (subsystem)
		{
			// find the ship subsystem
			ship_subsys *ss = ship_get_subsys(&Ships[ship_num], subsystem);
			if (ss != NULL)
			{
				// set cargo
				cargo_index = ss->subsys_cargo_name;
			}
		}
		else
		{
			cargo_index = Ships[ship_num].cargo1;
		}
	}
	else
	{
		// can't check subsys of ships not in mission
		if (subsystem)
		{
			return SEXP_CANT_EVAL;
		}

		// departed?
		int exited_index = ship_find_exited_ship_by_name(ship_name);
		if (exited_index != -1)
		{
			cargo_index = Ships_exited[exited_index].cargo1;
		}
		// not arrived yet
		else
		{
			p_object *p_objp;

			// find cargo for the parse object
			p_objp = mission_parse_get_arrival_ship(ship_name);
			Assert (p_objp);
			cargo_index = (int) p_objp->cargo1;
		}
	}

	// did we get any cargo
	if (cargo_index < 0)
		return SEXP_FALSE;

	// check cargo
	if (!stricmp(Cargo_names[cargo_index & CARGO_INDEX_MASK], cargo))
		return SEXP_TRUE;
	else
		return SEXP_FALSE;
}

// Goober5000
// yeesh - be careful of the cargo-no-deplete flag :p
void sexp_set_cargo(int n)
{
	char *cargo, *ship_name, *subsystem;
	int ship_num, i, cargo_index;

	cargo = CTEXT(n);
	ship_name = CTEXT(CDR(n));
	if (CDR(CDR(n)) != -1)
		subsystem = CTEXT(CDR(CDR(n)));
	else
		subsystem = NULL;

	// check to see if ship destroyed or departed.  In either case, do nothing.
	if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) )
		return;

	cargo_index = -1;
	// find this cargo in the cargo list
	for (i = 0; i < Num_cargo; i++)
	{
		// found it?
		if (!stricmp(cargo, Cargo_names[i]))
		{
			cargo_index = i;
			break;
		}
	}

	// not found
	if (cargo_index == -1)
	{
		// make new entry if possible
		if (Num_cargo + 1 >= MAX_CARGO)
		{
			Warning(LOCATION, "set-cargo: Maximum number of cargo names (%d) reached.  Ignoring new name.\n", MAX_CARGO);
			return;
		}

		Assert(strlen(cargo) <= NAME_LENGTH - 1);

		cargo_index = Num_cargo;
		Num_cargo++;

		strcpy(Cargo_names[cargo_index], cargo);
	}

	// get the ship
	ship_num = ship_name_lookup(ship_name);

	// we can only set subsystems if the ship is in the mission
	if (ship_num != -1)
	{
		if (subsystem)
		{
			ship_subsys *ss = ship_get_subsys(&Ships[ship_num], subsystem);
			if (ss == NULL) {
				Assert (!ship_class_unchanged(ship_num));
				return;
			}

			// set cargo
			ss->subsys_cargo_name = cargo_index | (ss->subsys_cargo_name & CARGO_NO_DEPLETE);
		}
		else
		{
			// simply set the ship cargo
			Ships[ship_num].cargo1 = char(cargo_index | (Ships[ship_num].cargo1 & CARGO_NO_DEPLETE));
		}
	}
	else
	{
		if (!subsystem)
		{
			p_object *p_objp;

			// set cargo for the parse object
			p_objp = mission_parse_get_arrival_ship(ship_name);
			Assert (p_objp);
			p_objp->cargo1 = char(cargo_index | (p_objp->cargo1 & CARGO_NO_DEPLETE));
		}
	}
}

/**
 * Transfer cargo from one ship to another
 */
void sexp_transfer_cargo(int n)
{
	char *shipname1, *shipname2;
	int shipnum1, shipnum2, i;

	shipname1 = CTEXT(n);
	shipname2 = CTEXT(CDR(n));

	// find the ships -- if neither in the mission, the abort
	shipnum1 = ship_name_lookup(shipname1);
	shipnum2 = ship_name_lookup(shipname2);
	if ( (shipnum1 == -1) || (shipnum2 == -1) )
		return;

	// we must be sure that these two objects are indeed docked
	if (!dock_check_find_direct_docked_object(&Objects[Ships[shipnum1].objnum], &Objects[Ships[shipnum2].objnum]))
	{
		return;
	}

	if ( !stricmp(Cargo_names[Ships[shipnum1].cargo1 & CARGO_INDEX_MASK], "nothing") ) {
		return;
	}

	// transfer cargo from ship1 to ship2
#ifndef NDEBUG
	// Don't give warning for large ships (cruiser on up) 
	if (! (Ship_info[Ships[shipnum2].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) ) {
		if ( stricmp(Cargo_names[Ships[shipnum2].cargo1 & CARGO_INDEX_MASK], "nothing") ) {
			Warning(LOCATION, "Transferring cargo to %s which already\nhas cargo %s.\nCargo will be replaced", Ships[shipnum2].ship_name, Cargo_names[Ships[shipnum2].cargo1 & CARGO_INDEX_MASK] );
		}
	}
#endif
	Ships[shipnum2].cargo1 = char((Ships[shipnum1].cargo1 & CARGO_INDEX_MASK) | (Ships[shipnum2].cargo1 & CARGO_NO_DEPLETE));

	if ( !(Ships[shipnum1].cargo1 & CARGO_NO_DEPLETE) ) {
		// need to set ship1's cargo to nothing.  scan the cargo_names array looking for the string nothing.
		// add it if not found
		for (i = 0; i < Num_cargo; i++ ) {
			if ( !stricmp(Cargo_names[i], "nothing") ) {
				Ships[shipnum1].cargo1 = char(i);
				return;
			}
		}
		strcpy(Cargo_names[i], "Nothing");
		Num_cargo++;
	}
}

/**
 * Exchanges cargo between two ships
 */
void sexp_exchange_cargo(int n)
{
	char *shipname1, *shipname2;
	int shipnum1, shipnum2, temp;

	shipname1 = CTEXT(n);
	shipname2 = CTEXT(CDR(n));

	// find the ships -- if neither in the mission, abort
	shipnum1 = ship_name_lookup(shipname1);
	shipnum2 = ship_name_lookup(shipname2);
	if ( (shipnum1 == -1) || (shipnum2 == -1) )
		return;

	// we must be sure that these two objects are indeed docked
	if (!dock_check_find_direct_docked_object(&Objects[Ships[shipnum1].objnum], &Objects[Ships[shipnum2].objnum]))
	{
		Int3();			// you are trying to transfer cargo between two ships not docked
		return;
	}

	temp = (Ships[shipnum1].cargo1 & CARGO_INDEX_MASK);
	Ships[shipnum1].cargo1 = char(Ships[shipnum2].cargo1 & CARGO_INDEX_MASK);
	Ships[shipnum2].cargo1 = char(temp);
}

void sexp_cap_waypoint_speed(int n)
{
	char *shipname;
	int shipnum;
	int speed;

	shipname = CTEXT(n);
	speed = eval_num(CDR(n));

	shipnum = ship_name_lookup(shipname);

	if (shipnum == -1) {
		// trying to set waypoint speed of ship not already in game
		return;
	}

	// cap speed to range (-1, 32767) to store within int
	if (speed < 0) {
		speed = -1;
	}

	if (speed > 32767) {
		speed = 32767;
	}

	Ai_info[Ships[shipnum].ai_index].waypoint_speed_cap = speed;
}

/**
 * Causes a ship to jettison its cargo
 * note that the 2nd arg (jettison delay) is not implemented
 */
void sexp_jettison_cargo(int n)
{
	char *shipname;
	int ship_index;

	// get some data
	shipname = CTEXT(n);

	// lookup the ship
	ship_index = ship_name_lookup(shipname);
	if(ship_index < 0)
		return;
	object *parent_objp = &Objects[Ships[ship_index].objnum];

	// note: skipping over the unimplemented "jettison delay"
	n = CDDR(n);

	// no arguments - jettison all docked objects
	if (n == -1)
	{
		// Goober5000 - as with ai_deathroll_start, we can't simply iterate through the dock list while we're
		// undocking things.  So just repeatedly jettison the first object.
		while (object_is_docked(parent_objp))
		{
			object_jettison_cargo(parent_objp, dock_get_first_docked_object(parent_objp));
		}
	}
	// arguments - jettison only those objects
	else
	{
		for (; n != -1; n = CDR(n))
		{
			// make sure ship exists
			ship_index = ship_name_lookup(CTEXT(n));
			if (ship_index < 0)
				continue;

			// make sure we are docked to it
			if (!dock_check_find_direct_docked_object(parent_objp, &Objects[Ships[ship_index].objnum]))
				continue;

			object_jettison_cargo(parent_objp, &Objects[Ships[ship_index].objnum]);			
		}
	}
}

void sexp_set_docked(int n)
{
	// get some data
	char* docker_ship_name = CTEXT(n);
	n = CDR(n);
	char* docker_point_name = CTEXT(n);
	n = CDR(n);
	char* dockee_ship_name = CTEXT(n);
	n = CDR(n);
	char* dockee_point_name = CTEXT(n);
	n = CDR(n);

	// lookup the ships
	int docker_ship_index = ship_name_lookup(docker_ship_name);
	int dockee_ship_index = ship_name_lookup(dockee_ship_name);
	if(docker_ship_index < 0 || dockee_ship_index < 0)
		return;

	ship* docker_ship = &Ships[docker_ship_index];
	ship* dockee_ship = &Ships[dockee_ship_index];
	object* docker_objp = &Objects[docker_ship->objnum];
	object* dockee_objp = &Objects[dockee_ship->objnum];

	//Get dockpoints by name
	int docker_point_index = model_find_dock_name_index(Ship_info[docker_ship->ship_info_index].model_num, docker_point_name);
	int dockee_point_index = model_find_dock_name_index(Ship_info[dockee_ship->ship_info_index].model_num, dockee_point_name);

	Assertion(docker_point_index >= 0, "Docker point '%s' not found on docker ship '%s'", docker_point_name, docker_ship_name);
	Assertion(dockee_point_index >= 0, "Dockee point '%s' not found on dockee ship '%s'", dockee_point_name, dockee_ship_name);

	//Make sure that the specified dockpoints are all free (if not, do nothing)
	if (dock_find_object_at_dockpoint(docker_objp, docker_point_index) != NULL || 
		dock_find_object_at_dockpoint(dockee_objp, dockee_point_index) != NULL)
	{
		return;
	}

	//Set docked
	dock_orient_and_approach(docker_objp, docker_point_index, dockee_objp, dockee_point_index, DOA_DOCK_STAY);
	ai_do_objects_docked_stuff(docker_objp, docker_point_index, dockee_objp, dockee_point_index, true);
}

void sexp_cargo_no_deplete(int n)
{
	char *shipname;
	int ship_index, no_deplete = 1;

	// get some data
	shipname = CTEXT(n);

	// lookup the ship
	ship_index = ship_name_lookup(shipname);
	if(ship_index < 0){
		return;
	}

	if ( !(Ship_info[Ships[ship_index].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) ) {
		Warning(LOCATION, "Trying to make non BIG or HUGE ship %s with non-depletable cargo.\n", Ships[ship_index].ship_name);
		return;
	}

	if (CDR(n) != -1) {
		no_deplete = eval_num(CDR(n));
		Assert((no_deplete == 0) || (no_deplete == 1));
		if ( (no_deplete != 0) && (no_deplete != 1) ) {
			no_deplete = 1;
		}
	}

	if (no_deplete) {
		Ships[ship_index].cargo1 |= CARGO_NO_DEPLETE;
	} else {
		Ships[ship_index].cargo1 &= (~CARGO_NO_DEPLETE);
	}

}

// Goober5000
void sexp_force_jump()
{
	// Shouldn't be gliding now....
	Player_obj->phys_info.flags &= ~PF_GLIDING;
	Player_obj->phys_info.flags &= ~PF_FORCE_GLIDE;

	if (Game_mode & GM_MULTIPLAYER) {
		multi_handle_end_mission_request(); 
	}
	else {
		// forced warp, taken from training failure code
		gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_START_FORCED );	//	Force player to warp out.
	}

}

void sexp_mission_set_nebula(int n)
{
	stars_set_nebula(eval_num(n) > 0);
}

/* freespace.cpp does not have these availiable externally, and we must call
them so that the main simulation loop does not have to constantly check for
Game_subspace_effect so that it could turn on the subspace sounds.

Because these are in freespace.cpp there are also stubs of these functions
in fred.cpp as it does not deal with the game loop (obviously) but still
links against code.lib. */
extern void game_start_subspace_ambient_sound();
extern void game_stop_subspace_ambient_sound();

void sexp_mission_set_subspace(int n)
{
	if (eval_num(n) > 0) {
		The_mission.flags |= MISSION_FLAG_SUBSPACE;
		Game_subspace_effect = 1;
		game_start_subspace_ambient_sound();
	} else {
		The_mission.flags &= ~MISSION_FLAG_SUBSPACE;
		Game_subspace_effect = 0;
		game_stop_subspace_ambient_sound();
	}
}

void sexp_add_background_bitmap(int n)
{
	int sexp_var;
	int new_number;
	char number_as_str[TOKEN_LENGTH];
	starfield_list_entry sle;

	// filename
	strcpy_s(sle.filename, CTEXT(n));
	n = CDR(n);

	// sanity checking
	if (stars_find_bitmap(sle.filename) < 0)
	{
		Warning(LOCATION, "sexp-add-background-bitmap: Background bitmap %s not found!", sle.filename);
		return;
	}

	// angles
	sle.ang.p = fl_radians(eval_num(n) % 360);
	n = CDR(n);
	sle.ang.b = fl_radians(eval_num(n) % 360);
	n = CDR(n);
	sle.ang.h = fl_radians(eval_num(n) % 360);
	n = CDR(n);

	// scale
	sle.scale_x = eval_num(n) / 100.0f;
	n = CDR(n);
	sle.scale_y = eval_num(n) / 100.0f;
	n = CDR(n);

	// div
	sle.div_x = eval_num(n);
	n = CDR(n);
	sle.div_y = eval_num(n);
	n = CDR(n);

	// restrict parameters
	if (sle.scale_x > 18) sle.scale_x = 18;
	if (sle.scale_x < 0.1f) sle.scale_x = 0.1f;
	if (sle.scale_y > 18) sle.scale_y = 18;
	if (sle.scale_y < 0.1f) sle.scale_y = 0.1f;
	if (sle.div_x > 5) sle.div_x = 5;
	if (sle.div_x < 1) sle.div_x = 1;
	if (sle.div_y > 5) sle.div_y = 5;
	if (sle.div_y < 1) sle.div_y = 1;

	if (n == -1) {
		stars_add_bitmap_entry(&sle);
	} else {
		Assert((n >= 0) && (n < Num_sexp_nodes));

		// ripped from sexp_modify_variable()
		// get sexp_variable index
		Assert(Sexp_nodes[n].first == -1);
		sexp_var = atoi(Sexp_nodes[n].text);
		
		// verify variable set
		Assert(Sexp_variables[sexp_var].type & SEXP_VARIABLE_SET);

		if (Sexp_variables[sexp_var].type & SEXP_VARIABLE_NUMBER)
		{
			new_number = stars_add_bitmap_entry(&sle);
			if (new_number < 0)
			{
				Warning(LOCATION, "Unable to add starfield bitmap: '%s'!", sle.filename);
				new_number = 0;
			}

			sprintf(number_as_str, "%d", new_number);

			// assign to variable
			sexp_modify_variable(number_as_str, sexp_var);
		}
		else
		{
			Error(LOCATION, "sexp-add-background-bitmap: Variable %s must be a number variable!", Sexp_variables[sexp_var].variable_name);
			return;
		}
	}
}

void sexp_remove_background_bitmap(int n)
{
	int slot = eval_num(n);

	if (slot >= 0) {
		int instances = stars_get_num_bitmaps();
		if ( instances > slot ) {
			stars_mark_bitmap_unused( slot );
		} else {
			Warning(LOCATION, "remove-background-bitmap: slot %d does not exist. Slot must be less than %d.",
				slot, instances);
		}
	}
}

void sexp_add_sun_bitmap(int n)
{
	int sexp_var;
	int new_number;
	char number_as_str[TOKEN_LENGTH];
	starfield_list_entry sle;

	// filename
	strcpy_s(sle.filename, CTEXT(n));
	n = CDR(n);

	// sanity checking
	if (stars_find_sun(sle.filename) < 0)
	{
		Warning(LOCATION, "sexp-add-sun-bitmap: Sun %s not found!", sle.filename);
		return;
	}

	// angles
	sle.ang.p = fl_radians(eval_num(n) % 360);
	n = CDR(n);
	sle.ang.b = fl_radians(eval_num(n) % 360);
	n = CDR(n);
	sle.ang.h = fl_radians(eval_num(n) % 360);
	n = CDR(n);

	// scale
	sle.scale_x = eval_num(n) / 100.0f;
	n = CDR(n);
	sle.scale_y = sle.scale_x;

	// div
	sle.div_x = 1;
	sle.div_y = 1;

	// restrict parameters
	if (sle.scale_x > 50) sle.scale_x = 50;
	if (sle.scale_x < 0.1f) sle.scale_x = 0.1f;
	if (sle.scale_y > 50) sle.scale_y = 50;
	if (sle.scale_y < 0.1f) sle.scale_y = 0.1f;
	
	if (n == -1) {
		stars_add_sun_entry(&sle);
	} else {
		Assert((n >= 0) && (n < Num_sexp_nodes));

		// ripped from sexp_modify_variable()
		// get sexp_variable index
		Assert(Sexp_nodes[n].first == -1);
		sexp_var = atoi(Sexp_nodes[n].text);
		
		// verify variable set
		Assert(Sexp_variables[sexp_var].type & SEXP_VARIABLE_SET);

		if (Sexp_variables[sexp_var].type & SEXP_VARIABLE_NUMBER)
		{
			// get new numerical value
			new_number = stars_add_sun_entry(&sle);

			if (new_number < 0)
			{
				Warning(LOCATION, "Unable to add sun: '%s'!", sle.filename);
				new_number = 0;
			}

			sprintf(number_as_str, "%d", new_number);

			// assign to variable
			sexp_modify_variable(number_as_str, sexp_var);
		}
		else
		{
			Error(LOCATION, "sexp-add-sun-bitmap: Variable %s must be a number variable!", Sexp_variables[sexp_var].variable_name);
			return;
		}
	}
}

void sexp_remove_sun_bitmap(int n)
{
	int slot = eval_num(n);

	if (slot >= 0) {
		int instances = stars_get_num_suns();
		if ( instances > slot ) {
			stars_mark_sun_unused( slot );
		} else {
			Warning(LOCATION, "remove-sun-bitmap: slot %d does not exist. Slot must be less than %d.",
				slot, instances);
		}
	}
}

void sexp_nebula_change_storm(int n)
{
	if (!(The_mission.flags & MISSION_FLAG_FULLNEB)) return;
	
	nebl_set_storm(CTEXT(n));
}

void sexp_nebula_toggle_poof(int n)
{
	char *name = CTEXT(n);
	int result = is_sexp_true(CDR(n));
	int i;

	if (name == NULL) return;

	for (i = 0; i < MAX_NEB2_POOFS; i++)
	{
		if (!stricmp(name,Neb2_poof_filenames[i])) break;
	}

	//coulnd't find the poof
	if (i == MAX_NEB2_POOFS) return;

	if (result) Neb2_poof_flags |= (1 << i);
	else Neb2_poof_flags &= ~(1 << i);
	
	neb2_eye_changed();
}

void sexp_nebula_change_pattern(int n)
{
	if (!(The_mission.flags & MISSION_FLAG_FULLNEB)) return;
	
	strcpy_s(Neb2_texture_name,(CTEXT(n)));

	neb2_post_level_init();
}

/**
 * End the mission.
 *
 * Implemented by Sesquipedalian; fixed by EdrickV; enhanced by others
 */
void sexp_end_mission(int n)
{
	int ignore_player_mortality = 1;
	int boot_to_main_hall = 0;
	int from_debrief_to_main_hall = 0;

	if (n != -1) {
		ignore_player_mortality = is_sexp_true(n);
		n = CDR(n);
	}
	if (n != -1) {
		boot_to_main_hall = is_sexp_true(n);
		n = CDR(n);
	}
	if (n != -1) {
		from_debrief_to_main_hall = is_sexp_true(n);
		n = CDR(n);
	}

	// if the player is dead we may want to let the death screen handle things
	if (!ignore_player_mortality && (Player_ship->flags & SF_DYING)) {
		return;
	}

	// ending via debrief and then going to mainhall could maybe work with multiplayer?
	if (from_debrief_to_main_hall) {
		The_mission.flags |= MISSION_FLAG_END_TO_MAINHALL;
	} else {
		The_mission.flags &= ~MISSION_FLAG_END_TO_MAINHALL;
	}

	// if we go straight to the main hall we have to clean up the mission without entering the debriefing
	if (boot_to_main_hall && !(Game_mode & GM_MULTIPLAYER)) {
		gameseq_post_event(GS_EVENT_END_GAME);
	} else {
		send_debrief_event();
	}

	// Karajorma - callback all the clients here. 
	if (MULTIPLAYER_MASTER)
	{
		multi_handle_sudden_mission_end();
		send_force_end_mission_packet();
	}
}

// Goober5000
void sexp_set_debriefing_toggled(int node)
{
	if (is_sexp_true(node))
		The_mission.flags |= MISSION_FLAG_TOGGLE_DEBRIEFING;
	else
		The_mission.flags &= ~MISSION_FLAG_TOGGLE_DEBRIEFING;
}

/**
 * Toggle the status bit for the AI code which tells the AI if it is a good time to rearm.
 *
 * The status being set means good time.  Status not being set (unset), means bad time. Designers must implement this.
 */
void sexp_good_time_to_rearm(int n)
{
	int team, time;

	team = iff_lookup(CTEXT(n));
	time = eval_num(CDR(n));						// this is the time for how long a good rearm is active -- in seconds

	ai_set_rearm_status(team, time);
}

/**
 * Grants promotion to the player
 */
void sexp_grant_promotion()
{
	// short circuit multiplayer for now until we figure out what to do.
	if ( Game_mode & GM_MULTIPLAYER )
		return;

	// set a bit to tell player should get promoted at the end of the mission.  I suppose the other
	// thing that we could do would be to set the players score to at least the amount of
	// points for the next level, but this way is better I think.
	if ( Game_mode & GM_CAMPAIGN_MODE ) {
		Player->flags |= PLAYER_FLAGS_PROMOTED;
	}
}

/**
 * Gives the named medal to the players in the mission
 */
void sexp_grant_medal(int n)
{
	int i;
	char *medal_name;

	// don't give medals in normal gameplay when not in campaign mode
	if ( (Game_mode & GM_NORMAL) && !(Game_mode & GM_CAMPAIGN_MODE) )
		return;

	medal_name = CTEXT(n);
	if (medal_name == NULL)
		return;

	if (Player->stats.m_medal_earned >= 0) {
		Warning(LOCATION, "Cannot grant more than one medal per mission!  New medal '%s' will replace old medal '%s'!", medal_name, Medals[Player->stats.m_medal_earned].name);
	}

	for (i = 0; i < Num_medals; i++ ) {
		if ( !stricmp(medal_name, Medals[i].name) )
			break;
	}

	if ( i < Num_medals ) {
		Player->stats.m_medal_earned = i;

		if ( Game_mode & GM_MULTIPLAYER ) {
			for ( int j = 0; j < MAX_PLAYERS; j++ ) {
				if ( MULTI_CONNECTED(Net_players[j]) ) {
					Net_players[j].m_player->stats.m_medal_earned = i;
				}
			}
		}
	}
}

void sexp_change_player_score(int node)
{
	int sindex;	
	int score;
	int plr_index;

	score = eval_num(node); 
	node = CDR(node);

	if(!(Game_mode & GM_MULTIPLAYER)){
		if ( (sindex = ship_name_lookup(CTEXT(node))) == -1) {
			Warning(LOCATION, "Invalid shipname '%s' passed to sexp_change_player_score!", CTEXT(node));
			return;
		}

		if (Player_ship != &Ships[sindex]) {
			Warning(LOCATION, "Can not award points to '%s'. Ship is not a player!", CTEXT(node));
			return; 	
		}
		Player->stats.m_score += score; 
		if (Player->stats.m_score < 0) {
			Player->stats.m_score = 0; 
		}
	}
	else {
		while (node >= 0) {
			plr_index = multi_find_player_by_ship_name(CTEXT(node), true);
			if (plr_index >= 0) {
				Net_player[plr_index].m_player->stats.m_score += score;
				
				if (Net_player[plr_index].m_player->stats.m_score < 0) {
					Net_player[plr_index].m_player->stats.m_score = 0;
				}
			}			

			node = CDR(node);
		}
	}
}

void sexp_change_team_score(int node)
{
	int i, score, team;

	// since we only have a team score in TvT
	if ( !(MULTI_TEAM) ) {
		return;
	}

	score = eval_num(node); 
	team = eval_num(CDR(node)); 

	if (team == 0) {
		for (i = 0; i < MAX_TVT_TEAMS; i++) {
			Multi_team_score[i] += score;  
		}
	}
	else if (team > 0 && team <= MAX_TVT_TEAMS) {
		Multi_team_score[team - 1] += score;  
	}
	else {
		Warning(LOCATION, "Invalid team number. Team %d does not exist", team);
	}
}



void sexp_tech_add_ship(int node)
{
	int i;
	char *name;

	Assert(node >= 0);
	// this function doesn't mean anything when not in campaign mode
	if ( !(Game_mode & GM_CAMPAIGN_MODE) )
		return;

	while (node >= 0) {
		name = CTEXT(node);
		i = ship_info_lookup(name);
		if (i >= 0)
			Ship_info[i].flags |= SIF_IN_TECH_DATABASE;
		else
			Warning(LOCATION, "In tech-add-ship, ship class \"%s\" invalid", name);

		node = CDR(node);
	}
}

void sexp_tech_add_weapon(int node)
{
	int i;
	char *name;

	Assert(node >= 0);
	// this function doesn't mean anything when not in campaign mode
	if ( !(Game_mode & GM_CAMPAIGN_MODE) )
		return;

	while (node >= 0) {
		name = CTEXT(node);
		i = weapon_info_lookup(name);
		if (i >= 0)
			Weapon_info[i].wi_flags |= WIF_IN_TECH_DATABASE;
		else
			Warning(LOCATION, "In tech-add-weapon, weapon class \"%s\" invalid", name);

		node = CDR(node);
	}
}

// Goober5000
void sexp_tech_add_intel(int node)
{
	int i;
	char *name;

	Assert(node >= 0);
	// this function doesn't mean anything when not in campaign mode
	if ( !(Game_mode & GM_CAMPAIGN_MODE) )
		return;

	while (node >= 0) {
		name = CTEXT(node);
		i = intel_info_lookup(name);
		if (i >= 0)
			Intel_info[i].flags |= IIF_IN_TECH_DATABASE;
		else
			Warning(LOCATION, "In tech-add-intel, intel name \"%s\" invalid", name);

		node = CDR(node);
	}
}


// Goober5000
void sexp_tech_add_intel_xstr(int node)
{
	int i, id, n = node;
	char *name;

	Assert(n >= 0);
	// this function doesn't mean anything when not in campaign mode
	if ( !(Game_mode & GM_CAMPAIGN_MODE) )
		return;

	while (n >= 0)
	{
		// don't use things like CTEXT or eval_num, since we didn't in the preloader
		name = Sexp_nodes[n].text;
		n = CDR(n);
		if (n < 0)
			break;
		id = atoi(Sexp_nodes[n].text);
		n = CDR(n);

		// we already translated this node in the preloader, so just look it up
		i = intel_info_lookup(name);
		if (i >= 0)
			Intel_info[i].flags |= IIF_IN_TECH_DATABASE;
		else
			Warning(LOCATION, "Intel entry XSTR(\"%s\", %d) invalid", name, id);
	}
}

// Goober5000 - reset all the tech entries to their default states
void sexp_tech_reset_to_default()
{
	// this function doesn't mean anything when not in campaign mode
	if ( !(Game_mode & GM_CAMPAIGN_MODE) )
		return;

	tech_reset_to_default();
}

/**
 * Set variables needed to grant a new ship/weapon to the player during the course
 * of a mission
 */
void sexp_allow_ship(int n)
{
	int sindex;
	char *name;

	// this function doesn't mean anything when not in campaign mode
	if ( !(Game_mode & GM_CAMPAIGN_MODE) )
		return;

	// get the name of the ship and lookup up the ship_info index for it
	name = CTEXT(n);
	sindex = ship_info_lookup( name );
	if ( sindex == -1 )
		return;

	// now we have a valid index --
	mission_campaign_save_persistent( CAMPAIGN_PERSISTENT_SHIP, sindex );
}

void sexp_allow_weapon(int n)
{
	int sindex;
	char *name;

	// this function doesn't mean anything when not in campaign mode
	if ( !(Game_mode & GM_CAMPAIGN_MODE) )
		return;

	// get the name of the weapon and lookup up the weapon_info index for it
	name = CTEXT(n);
	sindex = weapon_info_lookup( name );
	if ( sindex == -1 )
		return;

	// now we have a valid index --
	mission_campaign_save_persistent( CAMPAIGN_PERSISTENT_WEAPON, sindex );
}

/**
 * generic function for all those sexps that set flags
 *
 * @note this function has a similar purpose to sexp_alter_ship_flag_helper; make sure you check/update both
 */
void sexp_deal_with_ship_flag(int node, bool process_subsequent_nodes, int object_flag, int object_flag2, int ship_flag, int ship_flag2, int p_object_flag, int p_object_flag2, bool set_it, bool send_multiplayer = false, bool include_players_in_ship_lookup = false)
{
	char *ship_name;
	int ship_index;
	int n = node;

	if (send_multiplayer && MULTIPLAYER_MASTER) {
		multi_start_callback(); 
		multi_send_int(object_flag); 
		/* Uncommenting this will break compatibility with earlier builds but it is pointless to send it until object_flag2
		is actually used by the engine 
		*/
		// multi_send_int(object_flag2); 
		multi_send_int(ship_flag); 
		multi_send_int(ship_flag2); 
		multi_send_int(p_object_flag); 
		multi_send_int(p_object_flag2); 
		multi_send_bool(set_it); 
	}

	// loop for all ships in the sexp
	// NB: if the flag is set, we will continue acting on nodes until we run out of them;
	//     if not, we will only act on the first one
	for (; n >= 0; process_subsequent_nodes ? n = CDR(n) : n = -1)
	{
		// get ship name
		ship_name = CTEXT(n);

		// check to see if ship destroyed or departed.  In either case, do nothing.
		if (mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL))
			continue;

		// see if ship exists in-mission
		ship_index = ship_name_lookup(ship_name, include_players_in_ship_lookup ? 1 : 0);

		// if ship is in-mission
		if (ship_index >= 0)
		{
			// save flags for state change comparisons
			int object_flag_orig = Objects[Ships[ship_index].objnum].flags;

			// see if we have an object flag to set
			if (object_flag)
			{
				// set or clear?
				if (set_it)
					Objects[Ships[ship_index].objnum].flags |= object_flag;
				else
					Objects[Ships[ship_index].objnum].flags &= ~object_flag;
			}

			// handle ETS when modifying shields
			if (object_flag == OF_NO_SHIELDS) {
				if (set_it) {
					zero_one_ets(&Ships[ship_index].shield_recharge_index, &Ships[ship_index].weapon_recharge_index, &Ships[ship_index].engine_recharge_index);
				} else if (object_flag_orig & OF_NO_SHIELDS) {
					set_default_recharge_rates(&Objects[Ships[ship_index].objnum]);
				}
			}

			// see if we have an object flag2 to set
			if (object_flag2)
			{
/*
				// set or clear?
				if (set_it)
					Objects[Ships[ship_index].objnum].flags2 |= object_flag2;
				else
					Objects[Ships[ship_index].objnum].flags2 &= ~object_flag2;
*/
			}

			// see if we have a ship flag to set
			if (ship_flag)
			{
				// set or clear?
				if (set_it)
					Ships[ship_index].flags |= ship_flag;
				else
					Ships[ship_index].flags &= ~ship_flag;
			}

			// see if we have a ship flag2 to set
			if (ship_flag2)
			{
				// set or clear?
				if (set_it)
					Ships[ship_index].flags2 |= ship_flag2;
				else
					Ships[ship_index].flags2 &= ~ship_flag2;
			}

			// the lock afterburner SEXP also needs to set a physics flag
			if (ship_flag2 == SF2_AFTERBURNER_LOCKED) {
				if (set_it) {
					afterburners_stop(&Objects[Ships[ship_index].objnum], 1);
				}
			}

			if (send_multiplayer && MULTIPLAYER_MASTER) {
				multi_send_bool(true); 
				multi_send_ship(ship_index); 
			}
		}
		// if it's not in-mission
		else
		{
			// grab it from the arrival list
			p_object *p_objp = mission_parse_get_arrival_ship(ship_name);
			
			// ships that have had ship-vanish used on them should be skipped
			if (!p_objp) {
				continue;
			}

			// see if we have a p_object flag to set
			if (p_object_flag)
			{
				// set or clear?
				if (set_it)
					p_objp->flags |= p_object_flag;
				else
					p_objp->flags &= ~p_object_flag;
			}

			// see if we have a p_object flag2 to set
			if (p_object_flag2)
			{
				// set or clear?
				if (set_it)
					p_objp->flags2 |= p_object_flag2;
				else
					p_objp->flags2 &= ~p_object_flag2;
			}

			if (send_multiplayer && MULTIPLAYER_MASTER) {
				multi_send_bool(false); 
				multi_send_parse_object(p_objp); 
			}
		}
	}

	if (send_multiplayer && MULTIPLAYER_MASTER) {
		multi_end_callback();
	}
}

void multi_sexp_deal_with_ship_flag() 
{
	int object_flag = 0;
	// int object_flag2 = 0; 
	int ship_flag = 0; 
	int ship_flag2 = 0;
	int p_object_flag = 0;
	int p_object_flag2 = 0;
	bool set_it = false;
	bool ship_arrived = true; 
	ship *shipp = NULL;
	p_object *pobjp = NULL;

	multi_get_int(object_flag); 
	// multi_get_int(object_flag2); 
	multi_get_int(ship_flag); 
	multi_get_int(ship_flag2); 
	multi_get_int(p_object_flag); 
	multi_get_int(p_object_flag2); 
	multi_get_bool(set_it);

	// if any of the above failed so will this loop
	while (multi_get_bool(ship_arrived)) 
	{

		if (ship_arrived) {
			multi_get_ship(shipp);
			if (shipp == NULL) {
				WarningEx(LOCATION, "Null ship pointer in multi_sexp_deal_with_ship_flag(), tell a coder.\n");
				return;
			}

			// save flags for state change comparisons
			int object_flag_orig = Objects[shipp->objnum].flags;

			if (set_it) {
				Objects[shipp->objnum].flags |= object_flag;
				// Objects[shipp->objnum].flags2 |= object_flag2;
				shipp->flags |= ship_flag;
				shipp->flags2 |= ship_flag2;
			}
			else {
				Objects[shipp->objnum].flags &= ~object_flag;
				// Objects[shipp->objnum].flags2 &= ~object_flag2;
				shipp->flags &= ~ship_flag;
				shipp->flags2 &= ~ship_flag2;
			}

			// deal with side effects of these flags
			if (object_flag == OF_NO_SHIELDS) {
				if (set_it) {
					zero_one_ets(&shipp->shield_recharge_index, &shipp->weapon_recharge_index, &shipp->engine_recharge_index);
				} else if (object_flag_orig & OF_NO_SHIELDS) {
					set_default_recharge_rates(&Objects[shipp->objnum]);
				}
			}

			if (ship_flag2 == SF2_AFTERBURNER_LOCKED) {
				if (set_it) {
					afterburners_stop(&Objects[shipp->objnum], 1);
				}
			}

			if ((ship_flag2 == SF2_STEALTH) && !set_it) {
				if (shipp->flags & SF_ESCORT) {
					hud_add_ship_to_escort(shipp->objnum, 1);
				}			
			}
			if ((ship_flag2 == SF2_FRIENDLY_STEALTH_INVIS) && !set_it && (shipp->flags2 & SF2_STEALTH) && (shipp->team == Player_ship->team)) {
				if (shipp->flags & SF_ESCORT) {
					hud_add_ship_to_escort(shipp->objnum, 1);
				}			
			}
			if (ship_flag == SF_HIDDEN_FROM_SENSORS) {
				if (set_it) {
					if (Player_ai->target_objnum == shipp->objnum) {
						hud_cease_targeting(); 
					}
				}
				else {
					if (shipp->flags & SF_ESCORT) {
						hud_add_ship_to_escort(shipp->objnum, 1);
					}		
				}
			}
		}
		else {
			multi_get_parse_object(pobjp); 
			if (pobjp != NULL) {
				if (set_it) {
					pobjp->flags |= p_object_flag;
					pobjp->flags2 |= p_object_flag2;
				}
				else {
					pobjp->flags &= ~p_object_flag;
					pobjp->flags2 &= ~p_object_flag2;
				}
			}
		}
	}
}

/**
 * sets flags on objects from alter-ship-flag
 *
 * @note this function has a similar purpose to sexp_deal_with_ship_flag; make sure you check/update both
 */
void sexp_alter_ship_flag_helper(object_ship_wing_point_team &oswpt, bool future_ships, int object_flag, int object_flag2, int ship_flag, int ship_flag2, int parse_obj_flag, int parse_obj_flag2, int ai_flag, int ai_flag2, bool set_flag)
{
	int i, object_flag_orig;
	ship_obj	*so;
	object_ship_wing_point_team oswpt2;
	p_object *p_objp;

	switch (oswpt.type)
	{			
		case OSWPT_TYPE_NONE:
		case OSWPT_TYPE_EXITED:
			return;

		case OSWPT_TYPE_WHOLE_TEAM:
			Assert (oswpt.team >= 0); 
			oswpt2.clear();
			for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ){
				if (Ships[Objects[so->objnum].instance].team == oswpt.team) {
					object_ship_wing_point_team_set_ship(&oswpt2, so, future_ships); 

					// recurse
					sexp_alter_ship_flag_helper(oswpt2, future_ships, object_flag, object_flag2, ship_flag, ship_flag2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2, set_flag);
				}
			}

			if (future_ships) {
				for (p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp)) {
					if (p_objp->team == oswpt.team) {
						oswpt2.p_objp = p_objp;
						oswpt2.type = OSWPT_TYPE_PARSE_OBJECT;
						sexp_alter_ship_flag_helper(oswpt2, future_ships, object_flag, object_flag2, ship_flag, ship_flag2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2, set_flag);
					}
				}
			}
			break;

		case OSWPT_TYPE_WING:
		case OSWPT_TYPE_WING_NOT_PRESENT:
			// if the wing isn't here, and we're only dealing with ships which are, we're done. 
			if  (!future_ships){
				if (oswpt.type == OSWPT_TYPE_WING_NOT_PRESENT) {
					return; 
				}
			}
			else {
				for (p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp)) {
					if (p_objp->wingnum == WING_INDEX(oswpt.wingp)) {
						oswpt2.p_objp = p_objp;
						oswpt2.type = OSWPT_TYPE_PARSE_OBJECT;
						sexp_alter_ship_flag_helper(oswpt2, future_ships, object_flag, object_flag2, ship_flag, ship_flag2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2, set_flag);
					}
				}
			}

			for (i = 0; i < oswpt.wingp->current_count; i++) {
				object_ship_wing_point_team_set_ship(&oswpt2, &Ships[oswpt.wingp->ship_index[i]], future_ships); 
				sexp_alter_ship_flag_helper(oswpt2, future_ships, object_flag, object_flag2, ship_flag, ship_flag2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2, set_flag);
			}

			break;

		// finally! If we actually have a ship, we can set its flags!
		case OSWPT_TYPE_SHIP:
			// save flags for state change comparisons
			object_flag_orig = oswpt.objp->flags;

			// see if we have an object flag to set
			if (object_flag)
			{
				// set or clear?
				if (set_flag)
					obj_set_flags(oswpt.objp, oswpt.objp->flags | object_flag);
				else
					obj_set_flags(oswpt.objp, oswpt.objp->flags & ~object_flag);
			}

			// handle ETS when modifying shields
			if (object_flag == OF_NO_SHIELDS) {
				if (set_flag) {
					zero_one_ets(&oswpt.shipp->shield_recharge_index, &oswpt.shipp->weapon_recharge_index, &oswpt.shipp->engine_recharge_index);
				} else if (object_flag_orig & OF_NO_SHIELDS) {
					set_default_recharge_rates(oswpt.objp);
				}
			}

			// see if we have an object flag2 to set
			if (object_flag2)
			{
				// Add code here when have flag2 settings
			}

			// see if we have a ship flag to set
			if (ship_flag)
			{
				// set or clear?
				if (set_flag)
					oswpt.shipp->flags |= ship_flag;
				else
					oswpt.shipp->flags &= ~ship_flag;
			}

			// see if we have a ship flag2 to set
			if (ship_flag2)
			{
				// set or clear?
				if (set_flag)
					oswpt.shipp->flags2 |= ship_flag2;
				else
					oswpt.shipp->flags2 &= ~ship_flag2;
			}

			// the lock afterburner SEXP also needs to set a physics flag
			if (ship_flag2 == SF2_AFTERBURNER_LOCKED) {
				if (set_flag) {
					afterburners_stop(oswpt.objp, 1);
				}
			}

			// see if we have an ai flag to set
			if (ai_flag)
			{
				// set or clear?
				if (set_flag)
					Ai_info[oswpt.shipp->ai_index].ai_flags |= ai_flag;
				else
					Ai_info[oswpt.shipp->ai_index].ai_flags &= ~ai_flag;
			}

			// see if we have an object flag2 to set
			if (ai_flag2)
			{
				// Add code here when have flag2 settings
			}

			// no break statement. We want to fall through. 
			
		case OSWPT_TYPE_PARSE_OBJECT:
			if (!future_ships) {
				return;
			}

			// see if we have a p_object flag to set
			if (parse_obj_flag && oswpt.p_objp != NULL)
			{
				// set or clear?
				if (set_flag)
					oswpt.p_objp->flags |= parse_obj_flag;
				else
					oswpt.p_objp->flags &= ~parse_obj_flag;
			}

			// see if we have a p_object flag2 to set
			if (parse_obj_flag2 && oswpt.p_objp != NULL)
			{
				// set or clear?
				if (set_flag)
					oswpt.p_objp->flags2 |= parse_obj_flag2;
				else
					oswpt.p_objp->flags2 &= ~parse_obj_flag2;
			}
			break;


	}

}

void alter_flag_for_all_ships(bool future_ships, int object_flag, int object_flag2, int ship_flag, int ship_flag2, int parse_obj_flag, int parse_obj_flag2, int ai_flag, int ai_flag2, bool set_flag)
{
	ship_obj	*so;
	p_object	*p_objp;
	object_ship_wing_point_team oswpt;

	// set all the ships present in the mission
	for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
		object_ship_wing_point_team_set_ship(&oswpt, so, future_ships); 

		sexp_alter_ship_flag_helper(oswpt, future_ships, object_flag, object_flag2, ship_flag, ship_flag2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2, set_flag);
	}

	// set up all the ships which have yet to arrive
	if (future_ships) {
		oswpt.clear(); 
		for (p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp))
		{
			oswpt.p_objp = p_objp; 
			oswpt.type = OSWPT_TYPE_PARSE_OBJECT;
			sexp_alter_ship_flag_helper(oswpt, future_ships, object_flag, object_flag2, ship_flag, ship_flag2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2, set_flag);
		}
	}
}

bool sexp_check_flag_arrays(char *flag_name, int &object_flag, int &object_flag2, int &ship_flags, int &ship_flags2, int &parse_obj_flag, int &parse_obj_flag2, int &ai_flag, int &ai_flag2)
{
	int i;
	bool send_multi = false;

	for ( i = 0; i < MAX_OBJECT_FLAG_NAMES; i++) {
		if (!stricmp(Object_flag_names[i].flag_name, flag_name)) {
			// make sure the list writes to the correct list of flags!
			if (Object_flag_names[i].flag_list == 1) {
				object_flag = Object_flag_names[i].flag;
			}
			else if (Object_flag_names[i].flag_list == 2) {
				object_flag2 = Object_flag_names[i].flag;
			}
			break;
		}
	}

	for ( i = 0; i < MAX_SHIP_FLAG_NAMES; i++) {
		if (!stricmp(Ship_flag_names[i].flag_name, flag_name)) {
			// make sure the list writes to the correct list of flags!
			if (Ship_flag_names[i].flag_list == 1) {
				ship_flags = Ship_flag_names[i].flag;
			}
			else if (Ship_flag_names[i].flag_list == 2) {
				ship_flags2 = Ship_flag_names[i].flag;
				// only ship flags2 and above need to be sent the game handles the first set of flags elsewhere
				send_multi = true;
			}
			break;
		}
	}

	// parse files already have a list of names in the same order as the flags, so we can do something slightly different here. 
	for ( i = 0; i < MAX_PARSE_OBJECT_FLAGS; i++) {
		if (!stricmp(Parse_object_flags[i], flag_name)) {
			parse_obj_flag = (1 << i);
			break;
		}
	}

	for ( i = 0; i < MAX_PARSE_OBJECT_FLAGS_2; i++) {
		if (!stricmp(Parse_object_flags_2[i], flag_name)) {
			parse_obj_flag2 = (1 << i);
			break;
		}
	}

	for ( i = 0; i < MAX_AI_FLAG_NAMES; i++) {
		if (!stricmp(Ai_flag_names[i].flag_name, flag_name)) {
			// make sure the list writes to the correct list of flags!
			if (Ai_flag_names[i].flag_list == 1) {
				ai_flag = Ai_flag_names[i].flag;
			}
			else if (Ai_flag_names[i].flag_list == 2) {
				ai_flag2 = Ai_flag_names[i].flag;
			}
			break;
		}
	}

	return send_multi;
}

int sexp_are_ship_flags_set(int node)
{
	char *flag_name;
	ship *shipp;
	int object_flag = 0;
	int object_flag2 = 0;
	int ship_flags = 0;
	int ship_flags2 = 0;
	int parse_obj_flag = 0;
	int parse_obj_flag2 = 0;
	int ai_flag = 0;
	int ai_flag2 = 0;

	shipp = sexp_get_ship_from_node(node);

	// return false if the ship doesn't exist
	if (shipp == NULL) {
		return 0;
	}

	node = CDR(node); 

	while (node != -1) {
		flag_name = CTEXT(node); 
		sexp_check_flag_arrays(flag_name, object_flag, object_flag2, ship_flags, ship_flags2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2);

		// now check the flags
		if (object_flag) {
			if (!(Objects[shipp->objnum].flags & object_flag))
				return 0; 
		}
		// if we ever get object flags 2 - they go here.

		if (ship_flags) {
			if (!(shipp->flags & ship_flags))
				return 0; 
		}
		if (ship_flags2) {
			if (!(shipp->flags2 & ship_flags2))
				return 0; 
		}

		// we don't check parse flags

		if (ai_flag) {
			if (!(Ai_info[shipp->ai_index].ai_flags & ai_flag))
				return 0; 
		}

		// no ai flags 2 yet. When we do, they go here.
		node = CDR(node); 
	}

	// if we're still here, all the flags we were looking for were present
	return 1; 
}

void sexp_alter_ship_flag(int node)
{
	char *flag_name;
	int object_flag = 0;
	int object_flag2 = 0;
	int ship_flags = 0;
	int ship_flags2 = 0;
	int parse_obj_flag = 0;
	int parse_obj_flag2 = 0;
	int ai_flag = 0;
	int ai_flag2 = 0;
	bool set_flag = false; 
	bool future_ships = false; 
	object_ship_wing_point_team oswpt;

	flag_name = CTEXT(node); 

	sexp_check_flag_arrays(flag_name, object_flag, object_flag2, ship_flags, ship_flags2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2);

	node = CDR(node); 
	if (is_sexp_true(node)) {
		set_flag = true;
	}

	node = CDR(node);
	if (is_sexp_true(node)) {
		future_ships = true;
	}


	// start the multiplayer packet
	multi_start_callback();
	multi_send_int(object_flag);
	/* Uncommenting this will break compatibility with earlier builds but it is pointless to send it until object_flag2
	is actually used by the engine
	*/
	// multi_send_int(object_flag2);
	multi_send_int(ship_flags);
	multi_send_int(ship_flags2);
	multi_send_int(parse_obj_flag);
	multi_send_int(parse_obj_flag2);
	multi_send_int(ai_flag);
	/* Uncommenting this will break compatibility with earlier builds but it is pointless to send it until ai_flag2
	is actually used by the engine
	*/
	// multi_send_int(ai_flag2);
	multi_send_bool(set_flag);
	multi_send_bool(future_ships);

	node = CDR(node);

	// no 4th argument means do this to every ship in the mission (and if the flag is set, every ship that will be too).
	if (node == -1) {
		// send a message to the clients saying there were no more arguments
		multi_send_bool(false);

		alter_flag_for_all_ships(future_ships, object_flag, object_flag2, ship_flags, ship_flags2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2, set_flag);
	}


	else {
		// send a message to the clients saying there are more arguments
		multi_send_bool(true);

		while (node != -1) {
			sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(node), future_ships); 
			
			// no point in setting these flags at all
			if (oswpt.type == OSWPT_TYPE_NONE || oswpt.type == OSWPT_TYPE_EXITED ) {
				node = CDR(node);
				continue; 
			}

			sexp_alter_ship_flag_helper(oswpt, future_ships, object_flag, object_flag2, ship_flags, ship_flags2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2, set_flag);
			node = CDR(node);

			multi_send_int(oswpt.type);

			switch (oswpt.type) {
				case OSWPT_TYPE_SHIP:
					multi_send_ship(oswpt.shipp);
					break;

				case OSWPT_TYPE_PARSE_OBJECT:
					multi_send_parse_object(oswpt.p_objp);
					break;

				case OSWPT_TYPE_WING_NOT_PRESENT:
				case OSWPT_TYPE_WING:
					multi_send_ushort(oswpt.wingp->net_signature);
					break;

				case OSWPT_TYPE_WHOLE_TEAM:
					multi_send_int(oswpt.team);
					break;
			}
		}
	}
	multi_end_callback();
}



void multi_sexp_alter_ship_flag() 
{
	int i;
	int object_flag = 0;
	int object_flag2 = 0; 
	int ship_flag = 0; 
	int ship_flag2 = 0;
	int parse_obj_flag = 0;
	int parse_obj_flag2 = 0;
	bool set_flag = false;
	bool future_ships = true; 
	bool process_data = false;
	int ai_flag = 0;
	int ai_flag2 = 0;
	int type = -1;
	object_ship_wing_point_team oswpt;
	ushort wing_sig;

	multi_get_int(object_flag); 
	// multi_get_int(object_flag2); 
	multi_get_int(ship_flag); 
	multi_get_int(ship_flag2); 
	multi_get_int(parse_obj_flag); 
	multi_get_int(parse_obj_flag2); 
	multi_get_int(ai_flag); 
	multi_get_bool(set_flag);
	multi_get_bool(future_ships);
 
	// if any of the above failed so will this loop
	if (!multi_get_bool(process_data)) 
	{
		return;
	}

	// no more data means do this to every ship in the mission
	if (!process_data) {
		alter_flag_for_all_ships(future_ships, object_flag, object_flag2, ship_flag, ship_flag2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2, set_flag);
	}
	else {
		while (multi_get_int(type)) {
			oswpt.clear();
			oswpt.type = type; 

			switch (oswpt.type) {
				case OSWPT_TYPE_SHIP:
					if (multi_get_ship(oswpt.shipp)) {
						oswpt.objp = &Objects[oswpt.shipp->objnum];
					} else {
						Warning(LOCATION, "OSWPT had an invalid ship in multi_sexp_alter_ship_flag(), skipping");
						continue;
					}
					break;

				case OSWPT_TYPE_PARSE_OBJECT:
					multi_get_parse_object(oswpt.p_objp);
					break;

				case OSWPT_TYPE_WING_NOT_PRESENT:
				case OSWPT_TYPE_WING:
					multi_get_ushort(wing_sig);
					for (i = 0; i < Num_wings; i++) {
						if (Wings[i].net_signature == wing_sig) {
							oswpt.wingp = &Wings[i];

							// wing leader handling taken from sexp_get_object_ship_wing_point_team
							if ((oswpt.wingp->special_ship >= 0) && (oswpt.wingp->ship_index[oswpt.wingp->special_ship] >= 0)) {
								oswpt.shipp = &Ships[oswpt.wingp->ship_index[oswpt.wingp->special_ship]];
								oswpt.objp = &Objects[oswpt.shipp->objnum];
							} else {
								oswpt.shipp = &Ships[oswpt.wingp->ship_index[0]];
								oswpt.objp = &Objects[oswpt.shipp->objnum];
								Warning(LOCATION, "Substituting ship '%s' at index 0 for nonexistent wing leader at index %d!", oswpt.shipp->ship_name, oswpt.wingp->special_ship);
							}
							break;
						}
					}

					if (oswpt.wingp == NULL) {
						Warning(LOCATION, "Unable to get wing to apply flags to in multi_sexp_alter_ship_flag()"); 
					}
					break;

				case OSWPT_TYPE_WHOLE_TEAM:
					multi_get_int(oswpt.team);
					break;
			}
			sexp_alter_ship_flag_helper(oswpt, future_ships, object_flag, object_flag2, ship_flag, ship_flag2, parse_obj_flag, parse_obj_flag2, ai_flag, ai_flag2, set_flag);
		}
	}
}


// modified by Goober5000; now it should work properly
// function to deal with breaking/fixing the warp engines on ships/wings.
// --repairable is true when we are breaking the warp drive (can be repaired)
// --damage_it is true when we are sabotaging it, one way or the other; false when fixing it
void sexp_deal_with_warp( int n, bool repairable, bool damage_it )
{
	int ship_flag, p_object_flag;

	if (repairable)
	{
		ship_flag = SF_WARP_BROKEN;
		p_object_flag = P_SF_WARP_BROKEN;
	}
	else
	{
		ship_flag = SF_WARP_NEVER;
		p_object_flag = P_SF_WARP_NEVER;
	}

	sexp_deal_with_ship_flag(n, true, 0, 0, ship_flag, 0, p_object_flag, 0, damage_it);
}

// Goober5000
void sexp_set_subspace_drive(int node)
{
	bool set_flag = !is_sexp_true(node);

	sexp_deal_with_ship_flag(CDR(node), true, 0, 0, 0, SF2_NO_SUBSPACE_DRIVE, 0, 0, set_flag);
}

/**
 * Tell the AI when it is okay to fire certain secondary weapons at other ships.
 */
void sexp_good_secondary_time(int n)
{
	char *team_name, *weapon_name, *ship_name;
	int num_weapons, weapon_index, team;

	team_name = CTEXT(n);
	num_weapons = eval_num(CDR(n));
	weapon_name = CTEXT(CDR(CDR(n)));
	ship_name = CTEXT(CDR(CDR(CDR(n))));

	weapon_index = weapon_info_lookup(weapon_name);
	if ( weapon_index == -1 ) {
		nprintf(("Warning", "couldn't find weapon %s for good-secondary-time\n", weapon_name));
		return;
	}

	// get the team type from the team_name
	team = iff_lookup(team_name);

	// see if the ship has departed or has been destroyed.  If so, then we don't need to set up the
	// AI stuff
	if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) )
		return;

	ai_good_secondary_time( team, weapon_index, num_weapons, ship_name );
}

// Karajorma - Turns the built in messages for pilots and command on or off
void sexp_toggle_builtin_messages (int node, bool enable_messages)
{
	char *ship_name;
	int wingnum, shipnum, ship_index;

	// If no arguments were supplied then turn off all messages then bail
	if (node < 0)
	{
		if (enable_messages) 
		{
			The_mission.flags &= ~MISSION_FLAG_NO_BUILTIN_MSGS;	
			return;
		}
		else 
		{
			The_mission.flags |= MISSION_FLAG_NO_BUILTIN_MSGS;
			return;
		}
	}

	// iterate through all the nodes supplied
	while (node >= 0)
	{		
		ship_name = CTEXT(node);

		// check that this isn't a request to silence command. 
		if ((*ship_name == '#') && !stricmp(&ship_name[1], The_mission.command_sender)) 
		{
			// Either disable or enable messages from command
			if (enable_messages) 
			{
				The_mission.flags &= ~MISSION_FLAG_NO_BUILTIN_COMMAND;	
			}
			else 
			{
				The_mission.flags |= MISSION_FLAG_NO_BUILTIN_COMMAND;
			}
		}
		else if (!stricmp(ship_name, "<Any Wingman>"))
		{
			// Since trying to determine whose wingman in a stand alone multiplayer game opens a can of worms
			// Any Wingman silences all ships in wings regardless of whose side they're on. 
			for (wingnum = 0; wingnum < Num_wings; wingnum++ ) {
				for ( shipnum = 0; shipnum < Wings[wingnum].current_count; shipnum++ ) {
					ship_index = Wings[wingnum].ship_index[shipnum];
					Assert( ship_index != -1 );

					if (enable_messages) {
						Ships[ship_index].flags2 &= ~SF2_NO_BUILTIN_MESSAGES;
					}
					else {
						Ships[ship_index].flags2 |= SF2_NO_BUILTIN_MESSAGES;
					}
				}
			}
		}
		// If it isn't command then assume that we're dealing with a ship 
		else 
		{
			sexp_deal_with_ship_flag(node, false, 0, 0, 0, SF2_NO_BUILTIN_MESSAGES, 0, P2_SF2_NO_BUILTIN_MESSAGES, !enable_messages);
		}

		node = CDR(node);
	}
}

void sexp_set_persona (int node) 
{
	int persona_index = -1, sindex, i; 
	char *persona_name; 

	persona_name = CTEXT(node);

	for (i = 0 ; i < Num_personas ; i++) {
		if (!strcmp(persona_name, Personas[i].name) && (Personas[i].flags & PERSONA_FLAG_WINGMAN)) {
			persona_index = i;
			break;
		}
	}

	if (persona_index == -1) {
		Warning(LOCATION, "Unable to change to persona type: '%s'. Persona is not a wingman!", persona_name);
		return; 
	}

	node = CDR(node); 
	Assert (node >=0);

	if (MULTIPLAYER_MASTER) {
		multi_start_callback();
		multi_send_int(persona_index); 
	}

	// now loop through the list of ships
	for ( ; node >= 0; node = CDR(node) ) {
		sindex = ship_name_lookup( CTEXT(node) );

		if (sindex < 0) {
			continue;
		}

		if (Ships[sindex].objnum < 0) {
			continue;
		}

		Ships[sindex].persona_index = persona_index; 

		if (MULTIPLAYER_MASTER) {
			multi_send_ship(sindex); 
		}
	}

	if (MULTIPLAYER_MASTER) {
		multi_end_callback();
	}
}

void multi_sexp_set_persona()
{
	ship *shipp = NULL; 
	int persona_index = -1; 

	if (!multi_get_int(persona_index) ) {
		return; 
	}

	while (multi_get_ship(shipp)) {
		Assert(persona_index != -1);
		if (shipp != NULL) {
			shipp->persona_index = persona_index;
		}
	}
}

void sexp_set_mission_mood (int node)
{
	char *mood; 

	mood = CTEXT(node);
	for (SCP_vector<SCP_string>::iterator iter = Builtin_moods.begin(); iter != Builtin_moods.end(); ++iter) {
		if (!strcmp(iter->c_str(), mood)) {
			Current_mission_mood = iter - Builtin_moods.begin();
			return;
		}
	}

	Warning(LOCATION, "Sexp-mission-mood attempted to set mood %s which does not exist in messages.tbl", mood); 
}

int sexp_weapon_fired_delay(int node, int op_num)
{
	ship *shipp;
	
	int requested_bank; 
	int delay;
	int last_fired = -1; 

	shipp = sexp_get_ship_from_node(node); 
	if (shipp == NULL) {
		return SEXP_FALSE;
	}

	// Get the bank to check
	node = CDR(node);
	requested_bank = eval_num(node);
	if (requested_bank < 0) {
		return SEXP_FALSE;
	}

	// get the delay
	node = CDR(node);
	delay = eval_num(node);
	if (delay <= 0 ) {
		return SEXP_FALSE; 
	}

	switch (op_num) {
		case OP_PRIMARY_FIRED_SINCE: 
			if (requested_bank >= shipp->weapons.num_primary_banks) {
				return SEXP_FALSE;
			}
			last_fired = shipp->weapons.last_primary_fire_stamp[requested_bank];
			break; 

		case OP_SECONDARY_FIRED_SINCE: 
			if (requested_bank >= shipp->weapons.num_secondary_banks) {
				return SEXP_FALSE;
			}
			last_fired = shipp->weapons.last_secondary_fire_stamp[requested_bank];
			break; 
	}

	if (last_fired < 0) {
		// weapon was never fired
		return SEXP_FALSE;
	}

	if (timestamp() - delay < last_fired) {
		return SEXP_TRUE; 
	}

	return SEXP_FALSE;
}

int sexp_has_weapon(int node, int op_num)
{
	ship *shipp;
	int i;
	int requested_bank;
	int weapon_index;
	int num_weapon_banks = 0;
	int *weapon_banks = NULL;

	shipp = sexp_get_ship_from_node(node); 
	if (shipp == NULL) {
		return SEXP_FALSE;
	}

	// Get the bank to check
	node = CDR(node);
	if (!strcmp(CTEXT(node), SEXP_ALL_BANKS_STRING)) {
		requested_bank = -1;
	}
	else {
		requested_bank = eval_num(node);
	}	
	node = CDR(node);
 
	switch (op_num) {
		case OP_HAS_PRIMARY_WEAPON:
			weapon_banks = shipp->weapons.primary_bank_weapons;
			num_weapon_banks = shipp->weapons.num_primary_banks;
			break;

		case OP_HAS_SECONDARY_WEAPON:
			weapon_banks = shipp->weapons.secondary_bank_weapons;
			num_weapon_banks = shipp->weapons.num_secondary_banks;
			break;

		default:
			Warning(LOCATION, "Unrecognised bank type used in has-x-weapon. Returning false");
			return SEXP_FALSE;
	}
	

	//loop through the weapons and test them
	while (node > -1) {
		weapon_index = weapon_info_lookup(CTEXT(node));
		Assertion (weapon_index >= 0, "Weapon name %s is unknown.", CTEXT(node));

		// if we're checking every bank
		if (requested_bank == -1) {
			for (i = 0; i < num_weapon_banks; i++) {
				if (weapon_index == weapon_banks[i]) {
					return SEXP_TRUE;
				}
			}
		}

		// if we're only checking one bank
		else {
			if (weapon_index == weapon_banks[requested_bank]) {
				return SEXP_TRUE;
			}
		}
	
		node = CDR(node);
	}

	return SEXP_FALSE;
}

/**
 * Gets status of goals for previous missions (in the current campaign).
 *
 * @param n Sexp node number
 * @param status tell this function if we are looking for a goal_satisfied, goal_failed, or goal incomplete event
 */
int sexp_previous_goal_status( int n, int status )
{
	int rval = 0;
	char *goal_name, *mission_name;
	int i, mission_num, default_value = 0, use_defaults = 1;

	mission_name = CTEXT(n);
	goal_name = CTEXT(CDR(n));

	// check for possible next optional argument
	n = CDR(CDR(n));
	if ( n != -1 ) {
		default_value = is_sexp_true(n);
	}

	// try to find the given mission name in the current list of missions in the campaign.
	if ( Game_mode & GM_CAMPAIGN_MODE ) {
		i = mission_campaign_find_mission( mission_name );

		if ( i == -1 ) {
			// if mission not found, assume that goal was false (so previous-goal-false returns true)
			nprintf(("General", "Couldn't find mission name \"%s\" in current campaign's list of missions.\nReturning %s for goal-status function.", mission_name, (status==GOAL_COMPLETE)?"false":"true"));
			if ( status == GOAL_COMPLETE )
				rval = SEXP_KNOWN_FALSE;
			else
				rval = SEXP_KNOWN_TRUE;

			use_defaults = 0;
		} else if (Campaign.missions[i].flags & CMISSION_FLAG_SKIPPED) {
			use_defaults = 1;
		} else {
			// now try and find the goal this mission
			mission_num = i;
			for (i = 0; i < Campaign.missions[mission_num].num_goals; i++) {
				if ( !stricmp(Campaign.missions[mission_num].goals[i].name, goal_name) )
					break;
			}

			if ( i == Campaign.missions[mission_num].num_goals ) {
				Warning(LOCATION, "Couldn't find goal name \"%s\" in mission %s.\nReturning %s for goal-true function.", goal_name, mission_name, (status==GOAL_COMPLETE)?"false":"true");
				if ( status == GOAL_COMPLETE )
					rval = SEXP_KNOWN_FALSE;
				else
					rval = SEXP_KNOWN_TRUE;

			} else {
				// now return KNOWN_TRUE or KNOWN_FALSE based on the status field in the goal structure
				if ( Campaign.missions[mission_num].goals[i].status == status )
					rval = SEXP_KNOWN_TRUE;
				else
					rval = SEXP_KNOWN_FALSE;
			}

			use_defaults = 0;
		}
	}

	if (use_defaults) {
		// when not in campaign mode, always return KNOWN_TRUE when looking for goal complete, and KNOWN_FALSE
		// otherwise
		if ( n != -1 ) {
			if ( default_value )
				rval = SEXP_KNOWN_TRUE;
			else
				rval = SEXP_KNOWN_FALSE;
		} else {
			if ( status == GOAL_COMPLETE )
				rval = SEXP_KNOWN_TRUE;
			else
				rval = SEXP_KNOWN_FALSE;
		}
	}

	return rval;
}

// sexpression which gets the status of an event from a previous mission.  Like the above function but
// dealing with events instead of goals.  Again, the status parameter tells the code if we are looking
// for an event_true, event_false, or event_incomplete status
int sexp_previous_event_status( int n, int status )
{
	int rval = 0;
	char *name, *mission_name;
	int i, mission_num, default_value = 0, use_defaults = 1;

	mission_name = CTEXT(n);
	name = CTEXT(CDR(n));

	// check for possible optional parameter
	n = CDR(CDR(n));
	if ( n != -1 ){
		default_value = is_sexp_true(n);
	}

	if ( Game_mode & GM_CAMPAIGN_MODE ) {
		// following function returns -1 when mission isn't found.
		i = mission_campaign_find_mission( mission_name );

		// if the mission name wasn't found -- make this return FALSE for the event status.
		if ( i == -1 ) {
			nprintf(("General", "Couldn't find mission name \"%s\" in current campaign's list of missions.\nReturning %s for event-status function.", mission_name, (status==EVENT_SATISFIED)?"false":"true"));
			if ( status == EVENT_SATISFIED ) {
				rval = SEXP_KNOWN_FALSE;
			} else {
				rval = SEXP_KNOWN_TRUE;
			}

			use_defaults = 0;
		} else if (Campaign.missions[i].flags & CMISSION_FLAG_SKIPPED) {
			use_defaults = 1;
		} else {
			// now try and find the goal this mission
			mission_num = i;
			for (i = 0; i < Campaign.missions[mission_num].num_events; i++) {
				if ( !stricmp(Campaign.missions[mission_num].events[i].name, name) )
					break;
			}

			if ( i == Campaign.missions[mission_num].num_events ) {
				Warning(LOCATION, "Couldn't find event name \"%s\" in mission %s.\nReturning %s for event_status function.", name, mission_name, (status==EVENT_SATISFIED)?"false":"true");
				if ( status == EVENT_SATISFIED )
					rval = SEXP_KNOWN_FALSE;
				else
					rval = SEXP_KNOWN_TRUE;

			} else {
				// now return KNOWN_TRUE or KNOWN_FALSE based on the status field in the goal structure
				if ( Campaign.missions[mission_num].events[i].status == status )
					rval = SEXP_KNOWN_TRUE;
				else
					rval = SEXP_KNOWN_FALSE;
			}

			use_defaults = 0;
		}
	} 

	if (use_defaults) {
		if ( n != -1 ) {
			if ( default_value )
				rval = SEXP_KNOWN_TRUE;
			else
				rval = SEXP_KNOWN_FALSE;
		} else {
			if ( status == EVENT_SATISFIED )
				rval = SEXP_KNOWN_TRUE;
			else
				rval = SEXP_KNOWN_FALSE;
		}
	}

	return rval;
}

/**
 * Return the status of an event in the current mission.  
 *
 * @param n Sexp node number
 * @param want_true indicates if we are checking whether the event is true or the event is false.
 */
int sexp_event_status( int n, int want_true )
{
	char *name;
	int i, result;

	name = CTEXT(n);

	if (name == NULL) {
		Int3();
		return SEXP_FALSE;
	}

	for (i = 0; i < Num_mission_events; i++ ) {
		// look for the event name, check it's status.  If formula is gone, we know the state won't ever change.
		if ( !stricmp(Mission_events[i].name, name) ) {
			result = Mission_events[i].result;
			if (Mission_events[i].formula < 0) {
				if ( (want_true && result) || (!want_true && !result) )
					return SEXP_KNOWN_TRUE;
				else
					return SEXP_KNOWN_FALSE;

			} else {
				if ( (want_true && result) || (!want_true && !result) )
					return SEXP_TRUE;
				else
					return SEXP_FALSE;
			}
		}
	}

	return SEXP_FALSE;
}

/**
 * Return the status of an event N seconds after the event is true or false.
 *
 * Similar to above function but waits N seconds before returning true
 */
int sexp_event_delay_status( int n, int want_true, bool use_msecs = false)
{
	char *name;
	int i, result;
	fix delay;
	int rval = SEXP_FALSE;
	int use_as_directive = 0;

	name = CTEXT(n);

	if (name == NULL) {
		Int3();
		return SEXP_FALSE;
	}

	uint64_t tempDelay = eval_num(CDR(n));

	if (use_msecs) {
		tempDelay = tempDelay << 16;
		tempDelay = tempDelay / 1000;

		delay = (fix) tempDelay;
	} else {
		delay = i2f(tempDelay);
	}

	for (i = 0; i < Num_mission_events; i++ ) {
		// look for the event name, check it's status.  If formula is gone, we know the state won't ever change.
		if ( !stricmp(Mission_events[i].name, name) ) {
			if ( (fix) Mission_events[i].timestamp + delay >= Missiontime ) {
				rval = SEXP_FALSE;
				break;
			}

			result = Mission_events[i].result;
			if (Mission_events[i].formula < 0) {
				if ( (want_true && result) || (!want_true && !result) ) {
					rval = SEXP_KNOWN_TRUE;
					break;
				} else {
					rval = SEXP_KNOWN_FALSE;
					break;
				}
			} else {
				if ( want_true && result ) {  //) || (!want_true && !result) )
					rval = SEXP_TRUE;
					break;
				} else {
					rval = SEXP_FALSE;
					break;
				}
			}
		}
	}

	// check for possible optional parameter
	n = CDDR(n);
	if (n != -1)
		use_as_directive = is_sexp_true(n);

	// zero out Sexp_useful_number if it's not true and we don't want this for specific directive use
	if ( !use_as_directive && (rval != SEXP_TRUE) && (rval != SEXP_KNOWN_TRUE) )
		Sexp_useful_number = 0;  // indicate sexp isn't current yet

	return rval;
}

/**
 * Returns true if the given event is still incomplete
 */
int sexp_event_incomplete(int n)
{
	char *name;
	int i;

	name = CTEXT(n);

	if (name == NULL) {
		Int3();
		return SEXP_FALSE;
	}
	
	for (i = 0; i < Num_mission_events; i++ ) {
		if ( !stricmp(Mission_events[i].name, name ) ) {
			// if the formula is still >= 0 (meaning it is still getting eval'ed), then
			// the event is incomplete
			if ( Mission_events[i].formula != -1 )
				return SEXP_TRUE;
			else
				return SEXP_KNOWN_FALSE;
		}
	}

	return SEXP_FALSE;
}

/**
 * Return the status of an goal N seconds after the goal is true or false.
 *
 * Similar to above function but operates on goals instead of events
 */
int sexp_goal_delay_status( int n, int want_true )
{
	char *name;
	fix delay, time;

	name = CTEXT(n);
	delay = i2f(eval_num(CDR(n)));
	
	if ( want_true ) {
		// if we are looking for a goal true entry and we find a false, then return known false here
		if ( mission_log_get_time(LOG_GOAL_FAILED, name, NULL, NULL) )
			return SEXP_KNOWN_FALSE;
		else if ( mission_log_get_time(LOG_GOAL_SATISFIED, name, NULL, &time) ) {
			if ( (Missiontime - time) >= delay )
				return SEXP_KNOWN_TRUE;
		}
	} else {
		// if we are looking for a goal false entry and we find a true, then return known false here
		if ( mission_log_get_time(LOG_GOAL_SATISFIED, name, NULL, NULL) )
			return SEXP_KNOWN_FALSE;
		else if ( mission_log_get_time(LOG_GOAL_FAILED, name, NULL, &time) ) {
			if ( (Missiontime - time) >= delay )
				return SEXP_KNOWN_TRUE;
		}
	}

	return SEXP_FALSE;
}

/**
 * Returns true if the given goal is still incomplete
 */
int sexp_goal_incomplete(int n)
{
	char *name;

	name = CTEXT(n);

	if ( mission_log_get_time( LOG_GOAL_SATISFIED, name, NULL, NULL) || mission_log_get_time( LOG_GOAL_FAILED, name, NULL, NULL) )
		return SEXP_KNOWN_FALSE;
	else
		return SEXP_TRUE;
}

/**
 * Protects/unprotects a ship.
 *
 * @param n Sexp node number
 * @param flag Whether or not the protect bit should be set (flag==true) or cleared (flag==false)
 */
void sexp_protect_ships(int n, bool flag)
{
	sexp_deal_with_ship_flag(n, true, OF_PROTECTED, 0, 0, 0, P_OF_PROTECTED, 0, flag);
}

/**
 * Protects/unprotects a ship from beams.
 *
 * @param n Sexp node number
 * @param flag Whether or not the protect bit should be set (flag==true) or cleared (flag==false)
 */
void sexp_beam_protect_ships(int n, bool flag)
{
	sexp_deal_with_ship_flag(n, true, OF_BEAM_PROTECTED, 0, 0, 0, P_OF_BEAM_PROTECTED, 0, flag);
}

/**
 * Protects/unprotects a ship from various turrets.
 *
 * @param n Sexp node number
 * @param flag Whether or not the protect bit should be set (flag==true) or cleared (flag==false)
 */
void sexp_turret_protect_ships(int n, bool flag)
{
	char *turret_type = CTEXT(n);
	n = CDR(n);

	if (!stricmp(turret_type, "beam"))
		sexp_deal_with_ship_flag(n, true, OF_BEAM_PROTECTED, 0, 0, 0, P_OF_BEAM_PROTECTED, 0, flag);
	else if (!stricmp(turret_type, "flak"))
		sexp_deal_with_ship_flag(n, true, OF_FLAK_PROTECTED, 0, 0, 0, P_OF_FLAK_PROTECTED, 0, flag);
	else if (!stricmp(turret_type, "laser"))
		sexp_deal_with_ship_flag(n, true, OF_LASER_PROTECTED, 0, 0, 0, P_OF_LASER_PROTECTED, 0, flag);
	else if (!stricmp(turret_type, "missile"))
		sexp_deal_with_ship_flag(n, true, OF_MISSILE_PROTECTED, 0, 0, 0, P_OF_MISSILE_PROTECTED, 0, flag);
	else
		Warning(LOCATION, "Invalid turret type '%s'!", turret_type);
}

// Goober5000 - sets the "don't collide invisible" flag on a list of ships
void sexp_dont_collide_invisible(int n, bool dont_collide)
{
	sexp_deal_with_ship_flag(n, true, 0, 0, 0, SF2_DONT_COLLIDE_INVIS, 0, P_SF2_DONT_COLLIDE_INVIS, dont_collide);
}

// Goober5000 - sets the "immobile" flag on a list of ships
void sexp_set_immobile(int n, bool immobile)
{
	sexp_deal_with_ship_flag(n, true, OF_IMMOBILE, 0, 0, 0, 0, P2_OF_IMMOBILE, immobile);
}

// Goober5000 - sets the "no-ets" flag on a list of ships
void sexp_disable_ets(int n, bool disable)
{
	sexp_deal_with_ship_flag(n, true, 0, 0, 0, SF2_NO_ETS, 0, P2_SF2_NO_ETS, disable);
}

// Goober5000 - sets the vaporize flag on a list of ships
void sexp_ships_vaporize(int n, bool vaporize)
{
	sexp_deal_with_ship_flag(n, true, 0, 0, SF_VAPORIZE, 0, P_SF_VAPORIZE, 0, vaporize);
}

/**
 * Make ships "visible" and "invisible" to sensors.
 *
 * @param n Sexp node number
 * @param visible Is true when making ships visible, false otherwise
 */
void sexp_ships_visible(int n, bool visible)
{
	sexp_deal_with_ship_flag(n, true, 0, 0, SF_HIDDEN_FROM_SENSORS, 0, P_SF_HIDDEN_FROM_SENSORS, 0, !visible, true);

	// we also have to add any escort ships that were made visible
	for (; n >= 0; n = CDR(n))
	{
		int shipnum = ship_name_lookup(CTEXT(n));
		if (shipnum < 0)
			continue;

		if (!visible && Player_ai->target_objnum == Ships[shipnum].objnum) {
			hud_cease_targeting(); 
		}
		else if (visible && (Ships[shipnum].flags & SF_ESCORT)) {
			hud_add_ship_to_escort(Ships[shipnum].objnum, 1);
		}		
	}
}

// Goober5000
void sexp_ships_stealthy(int n, bool stealthy)
{
	sexp_deal_with_ship_flag(n, true, 0, 0, 0, SF2_STEALTH, 0, P_SF2_STEALTH, stealthy, true);

	// we also have to add any escort ships that were made visible
	if (!stealthy)
	{
		for (; n >= 0; n = CDR(n))
		{
			int shipnum = ship_name_lookup(CTEXT(n));
			if (shipnum < 0)
				continue;

			if (Ships[shipnum].flags & SF_ESCORT)
				hud_add_ship_to_escort(Ships[shipnum].objnum, 1);
		}
	}
}

// Goober5000
void sexp_friendly_stealth_invisible(int n, bool invisible)
{
	sexp_deal_with_ship_flag(n, true, 0, 0, 0, SF2_FRIENDLY_STEALTH_INVIS, 0, P_SF2_FRIENDLY_STEALTH_INVIS, invisible, true);

	// we also have to add any escort ships that were made visible
	if (!invisible)
	{
		for (; n >= 0; n = CDR(n))
		{
			int shipnum = ship_name_lookup(CTEXT(n));
			if (shipnum < 0)
				continue;

			if (Ships[shipnum].flags2 & SF2_STEALTH && Player_ship->team == Ships[shipnum].team)
			{
				if (Ships[shipnum].flags & SF_ESCORT)
					hud_add_ship_to_escort(Ships[shipnum].objnum, 1);
			}
		}
	}
}

//FUBAR
//generic function to deal with subsystem flag sexps.
//setit only passed for backward compatibility with older sexps.
void sexp_ship_deal_with_subsystem_flag(int node, int ss_flag, bool sendit = false, bool setit = false)
{	
	ship *shipp = NULL;
	ship_subsys *ss = NULL;	
	
	// get ship
	shipp = sexp_get_ship_from_node(node); 
	if (shipp == NULL) {
		return;
	}

	//replace or not
	// OP_SHIP_SUBSYS_TARGETABLE/UNTARGETABLE, OP_SHIP_SUBSYS_TARGETABLE and OP_TURRET_SUBSYS_TARGET_ENABLE/DISABLE 
	// will have already passed us this data we don't need to set it for them. 
	// backward compatibility hack for older sexps
	if (!((ss_flag == SSF_UNTARGETABLE) || (ss_flag == SSF_NO_SS_TARGETING)))
	{
		node = CDR(node);
		setit = (is_sexp_true(node) ? true : false);
	}
	
	//multiplayer packet start
	if (sendit)
	{
		multi_start_callback(); 
		multi_send_ship(shipp);
		multi_send_bool(setit);
	}

	//Process subsystems
	while(node != -1)
	{
		// deal with generic subsystem names
		int generic_type = get_generic_subsys(CTEXT(node));
		if (generic_type) {
			for (ss = GET_FIRST(&shipp->subsys_list); ss != END_OF_LIST(&shipp->subsys_list); ss = GET_NEXT(ss)) {
				if (generic_type == ss->system_info->type) {
					if (setit)
						ss->flags |= ss_flag;
					else
						ss->flags &= ~ss_flag;
				}
			}
		}
		else
		{
			// get the subsystem
			ss = ship_get_subsys(shipp, CTEXT(node));
			if(ss == NULL)
			{
				node = CDR(node);
				continue;
			}
 
			// set the flag
			if(setit)
				ss->flags |= ss_flag;
			else
				ss->flags &= ~ss_flag;
		}

		// multiplayer send subsystem name
		if (sendit)
			multi_send_string(CTEXT(node));

		// next
		node = CDR(node);
	}

	// mulitplayer end of packet
	if (sendit)
		multi_end_callback();
}
void multi_sexp_deal_with_subsys_flag(int ss_flag)
{
	bool setit = false;
	ship_subsys *ss = NULL;
    ship *shipp = NULL;
	char ss_name[MAX_NAME_LEN];

	multi_get_ship(shipp);
	multi_get_bool(setit);
 
	while (multi_get_string(ss_name)) 
	{
		// deal with generic subsystem names
		int generic_type = get_generic_subsys(ss_name);
		if (generic_type) {
			for (ss = GET_FIRST(&shipp->subsys_list); ss != END_OF_LIST(&shipp->subsys_list); ss = GET_NEXT(ss)) {
				if (generic_type == ss->system_info->type) {
					if (setit)
						ss->flags |= ss_flag;
					else
						ss->flags &= ~ss_flag;
				}
			}
		}
		else
		{
			ss = ship_get_subsys(shipp, ss_name);
			if(ss != NULL)
			{	
				// set the flag
				if(setit)
					ss->flags |= ss_flag;
				else
					ss->flags &= ~ss_flag;
			}
		}
	}
}
// Goober5000
void sexp_ship_tag( int n, int tag )
{
	int ship_num, tag_level, tag_time, ssm_index(0);
    int ssm_team = 0;

	// check to see if ship destroyed or departed.  In either case, do nothing.
	if ( mission_log_get_time(LOG_SHIP_DEPARTED, CTEXT(n), NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, CTEXT(n), NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, CTEXT(n), NULL, NULL) )
		return;

	// get the ship num
	ship_num = ship_name_lookup(CTEXT(n));
	if ( ship_num < 0 )
		return;

	// if untag, then unset everything and leave
	if (!tag)
	{
		Ships[ship_num].tag_left = -1.0f;
		Ships[ship_num].level2_tag_left = -1.0f;
		return;
	}

	// get the tag level and time
	n = CDR(n);
	tag_level = eval_num(n);
	n = CDR(n);
	tag_time = eval_num(n);

	// get SSM info if needed
	vec3d start;
	if (tag_level == 3)
	{
		n = CDR(n);
		if (n < 0)
			return;
		ssm_index = ssm_info_lookup(CTEXT(n));
		if (ssm_index < 0)
			return;

		n = CDR(n);
		if (n < 0)
			return;
		start.xyz.x = (float)eval_num(n);

		n = CDR(n);
		if (n < 0)
			return;
		start.xyz.y = (float)eval_num(n);

		n = CDR(n);
		if (n < 0)
			return;
		start.xyz.z = (float)eval_num(n);

        n = CDR(n);

        if (n < 0)
        {
            ssm_team = 0;
        }
        else
        {
            ssm_team = iff_lookup(CTEXT(n));
        }
	}

	ship_apply_tag(ship_num, tag_level, (float)tag_time, &Objects[Ships[ship_num].objnum], &start, ssm_index, ssm_team);
}

// sexpression to toggle invulnerability flag of ships.
void sexp_ships_invulnerable( int n, bool invulnerable )
{
	sexp_deal_with_ship_flag(n, true, OF_INVULNERABLE, 0, 0, 0, P_OF_INVULNERABLE, 0, invulnerable);
}

void sexp_ships_bomb_targetable(int n, bool targetable)
{
	sexp_deal_with_ship_flag(n, true, OF_TARGETABLE_AS_BOMB, 0, 0, 0, 0, P2_OF_TARGETABLE_AS_BOMB, targetable, true);
}

// Goober5000
void sexp_ship_guardian_threshold(int node)
{
	char *ship_name;
	int ship_num, threshold;
	int n = -1;

	threshold = eval_num(node);

	n = CDR(node);

	// for all ships
	for ( ; n != -1; n = CDR(n) ) {
		// check to see if ship destroyed or departed.  In either case, do nothing.
		ship_name = CTEXT(n);

		if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) ) {
			continue;
		}

		// get the ship num.  If we get a -1 for the number here, ship has yet to arrive.
		ship_num = ship_name_lookup(ship_name);

		if (ship_num != -1) {
			Ships[ship_num].ship_guardian_threshold = threshold;
		}
	}
}

// Goober5000
void sexp_ship_subsys_guardian_threshold(int num)
{
	char *ship_name, *hull_name;
	int ship_num, threshold;
	ship_subsys *ss;
	int n = -1;

	threshold = eval_num(num);

	n = CDR(num);

	// check to see if ship destroyed or departed.  In either case, do nothing.
	ship_name = CTEXT(n);

	if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) ) {
		return;
	}

	// get the ship num.  If we get a -1 for the number here, ship has yet to arrive.
	ship_num = ship_name_lookup(ship_name);

	if (ship_num == -1) {
		return;
	}

	n = CDR(n);

	// for all subsystems
	for ( ; n != -1; n = CDR(n) ) {
		// check for HULL
		hull_name = CTEXT(n);

		if (hull_name != NULL) {
			int generic_type = get_generic_subsys(hull_name);
			if ( !strcmp(hull_name, SEXP_HULL_STRING) ) {
				Ships[ship_num].ship_guardian_threshold = threshold;
			}
			else if (generic_type) {
				// search through all subsystems
				for (ss = GET_FIRST(&Ships[ship_num].subsys_list); ss != END_OF_LIST(&Ships[ship_num].subsys_list); ss = GET_NEXT(ss)) {
					if (generic_type == ss->system_info->type) {
						ss->subsys_guardian_threshold = threshold;
					}
				}
			}				
			else {
				ss = ship_get_subsys(&Ships[ship_num], hull_name);
				if ( ss == NULL ) {
					if (ship_class_unchanged(ship_num)) {
						Warning(LOCATION, "Invalid subsystem passed to ship-subsys-guardian-threshold: %s does not have a %s subsystem", ship_name, hull_name);
					}
				} 
				else {
					ss->subsys_guardian_threshold = threshold;
				}
			}
		}
	}
}

// sexpression to toggle KEEP ALIVE flag of ship object
void sexp_ships_guardian( int n, int guardian )
{
	char *ship_name;
	int num;

	for ( ; n != -1; n = CDR(n) )
	{
		ship_name = CTEXT(n);

		// check to see if ship destroyed or departed.  In either case, do nothing.
		if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) )
			continue;

		// get the ship num.  If we get a -1 for the number here, ship has yet to arrive.  Store this ship
		// in a list until created
		num = ship_name_lookup(ship_name);
		if ( num != -1 ) {
			Ships[num].ship_guardian_threshold = guardian ? SHIP_GUARDIAN_THRESHOLD_DEFAULT : 0;
		} else {
			p_object *p_objp = mission_parse_get_arrival_ship(ship_name);
			if (p_objp)
			{
				if ( guardian )
					p_objp->flags |= P_SF_GUARDIAN;
				else
					p_objp->flags &= ~P_SF_GUARDIAN;
			}
		}
	}
}

void sexp_ship_create(int n)
{
	int new_ship_class = -1;
	char *new_ship_name;
	vec3d new_ship_pos = vmd_zero_vector;
	angles new_ship_ang = {0.0f, 0.0f, 0.0f};
	matrix new_ship_ori = vmd_identity_matrix;
	bool change_angles = false;

	Assert( n >= 0 );

	// get ship name - none means don't specify it
	// if ship with this name already exists, ship_create will respond appropriately
	if (!stricmp(CTEXT(n), SEXP_NONE_STRING))
	{
		new_ship_name = NULL;
	}
	else
	{
		new_ship_name = CTEXT(n);
	}
	
	//Get ship class
	n = CDR(n);
	new_ship_class = ship_info_lookup(CTEXT(n));

	if(new_ship_class == -1) {
		Warning(LOCATION, "Invalid ship class passed to ship-create; ship type '%s' does not exist", CTEXT(n));
		return;
	}

	n = CDR(n);
	new_ship_pos.xyz.x = (float) eval_num(n);
	n = CDR(n);
	new_ship_pos.xyz.y = (float) eval_num(n);
	n = CDR(n);
	new_ship_pos.xyz.z = (float) eval_num(n);

	n = CDR(n);
	if(n != -1) {
		new_ship_ang.p = fl_radians(eval_num(n) % 360);
		change_angles = true;
	}

	n = CDR(n);
	if(n != -1) {
		new_ship_ang.b = fl_radians(eval_num(n) % 360);
		change_angles = true;
	}

	n = CDR(n);
	if(n != -1) {
		new_ship_ang.h = fl_radians(eval_num(n) % 360);
		change_angles = true;
	}

	//This is a costly function, so only do it if needed
	if(change_angles) {
		vm_angles_2_matrix(&new_ship_ori, &new_ship_ang);
	}

	ship_create(&new_ship_ori, &new_ship_pos, new_ship_class, new_ship_name);
}

// Goober5000
void sexp_weapon_create(int n)
{
	int weapon_class, parent_objnum, target_objnum, weapon_objnum;
	ship_subsys *targeted_ss;

	vec3d weapon_pos = vmd_zero_vector;
	angles weapon_angles = {0.0f, 0.0f, 0.0f};
	matrix weapon_orient = vmd_identity_matrix;
	int is_locked;
	bool change_angles = false;

	Assert( n >= 0 );

	parent_objnum = -1;
	if (stricmp(CTEXT(n), SEXP_NONE_STRING))
	{
		int parent_ship = ship_name_lookup(CTEXT(n));

		if (parent_ship >= 0)
			parent_objnum = Ships[parent_ship].objnum;
	}
	n = CDR(n);
	
	weapon_class = weapon_info_lookup(CTEXT(n));
	n = CDR(n);
	if (weapon_class < 0)
	{
		Warning(LOCATION, "Invalid weapon class passed to weapon-create; weapon type '%s' does not exist", CTEXT(n));
		return;
	}

	weapon_pos.xyz.x = (float) eval_num(n);
	n = CDR(n);
	weapon_pos.xyz.y = (float) eval_num(n);
	n = CDR(n);
	weapon_pos.xyz.z = (float) eval_num(n);
	n = CDR(n);

	if (n >= 0)
	{
		weapon_angles.p = fl_radians(eval_num(n) % 360);
		n = CDR(n);
		change_angles = true;
	}

	if (n >= 0)
	{
		weapon_angles.b = fl_radians(eval_num(n) % 360);
		n = CDR(n);
		change_angles = true;
	}

	if (n >= 0)
	{
		weapon_angles.h = fl_radians(eval_num(n) % 360);
		n = CDR(n);
		change_angles = true;
	}

	// This is a costly function, so only do it if needed
	if (change_angles)
	{
		vm_angles_2_matrix(&weapon_orient, &weapon_angles);
	}

	target_objnum = -1;
	if (n >= 0)
	{
		int target_ship = ship_name_lookup(CTEXT(n));

		if (target_ship >= 0)
			target_objnum = Ships[target_ship].objnum;

		n = CDR(n);
	}

	targeted_ss = NULL;
	if (n >= 0)
	{
		if (target_objnum >= 0)
			targeted_ss = ship_get_subsys(&Ships[Objects[target_objnum].instance], CTEXT(n));

		n = CDR(n);
	}

	is_locked = (target_objnum >= 0) ? 1 : 0;	// assume full lock; this lets lasers track if people want them to

	// create the weapon
	weapon_objnum = weapon_create(&weapon_pos, &weapon_orient, weapon_class, parent_objnum, -1, is_locked);

	// maybe make the weapon track its target
	if (is_locked)
		weapon_set_tracking_info(weapon_objnum, parent_objnum, target_objnum, is_locked, targeted_ss);
}

// make ship vanish without a trace (and what its docked to)
void sexp_ship_vanish(int n)
{
	char *ship_name;
	int num;

	// if MULTIPLAYER bail
	if (Game_mode & GM_MULTIPLAYER) {
		return;
	}

	for ( ; n != -1; n = CDR(n) ) {
		ship_name = CTEXT(n);

		// check to see if ship destroyed or departed.  In either case, do nothing.
		if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) )
			continue;

		// get the ship num.  If we get a -1 for the number here, ship has yet to arrive
		num = ship_name_lookup(ship_name);
		if ( num != -1 )
			ship_actually_depart(num, SHIP_VANISHED);
	}
}

void sexp_destroy_instantly(int n)
{
	char *ship_name;
	int ship_num;
	object *ship_obj_p;

	// if MULTIPLAYER bail
	if (Game_mode & GM_MULTIPLAYER) {
		return;
	}

	for ( ; n != -1; n = CDR(n) ) {
		ship_name = CTEXT(n);

		// check to see if ship destroyed or departed.  In either case, do nothing.
		if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) )
			continue;
		ship_num = ship_name_lookup(ship_name);

		// if it still exists, destroy it
		if (ship_num >= 0) {
			ship_obj_p = &Objects[Ships[ship_num].objnum];

			//if its the player don't destroy
			if (ship_obj_p == Player_obj)
				continue;
			ship_destroy_instantly(ship_obj_p,ship_num);
		}
	}
}

void sexp_shields_off(int n, bool shields_off ) //-Sesquipedalian
{
	sexp_deal_with_ship_flag(n, true, OF_NO_SHIELDS, 0, 0, 0, P_OF_NO_SHIELDS, 0, shields_off, true);
}

// Goober5000
void sexp_ingame_ship_kamikaze(ship *shipp, int kdamage)
{
	Assert(shipp);

	ai_info *aip = &Ai_info[shipp->ai_index];

	if (kdamage > 0)
	{
		aip->ai_flags |= AIF_KAMIKAZE;
		aip->kamikaze_damage = kdamage;
	}
	else
	{
		aip->ai_flags &= ~AIF_KAMIKAZE;
		aip->kamikaze_damage = 0;
	}
}

// Goober5000
void sexp_parse_ship_kamikaze(p_object *parse_obj, int kdamage)
{
	Assert(parse_obj);

	if (kdamage > 0)
	{
		parse_obj->flags |= P_AIF_KAMIKAZE;
		parse_obj->kamikaze_damage = kdamage;
	}
	else
	{
		parse_obj->flags &= ~P_AIF_KAMIKAZE;
		parse_obj->kamikaze_damage = 0;
	}
}

// Goober5000 - redone, added wing stuff
void sexp_kamikaze(int n, int kamikaze)
{
	int kdamage;

	kdamage = 0;
	if (kamikaze)
	{
		kdamage = eval_num(n);
		n = CDR(n);
	}

	for ( ; n != -1; n = CDR(n) )
	{
		object_ship_wing_point_team oswpt;
		sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));

		switch (oswpt.type)
		{
			// change ingame ship
			case OSWPT_TYPE_SHIP:
			{
				sexp_ingame_ship_kamikaze(oswpt.shipp, kdamage);

				break;
			}

			// change ship yet to arrive
			case OSWPT_TYPE_PARSE_OBJECT:
			{
				sexp_parse_ship_kamikaze(oswpt.p_objp, kdamage);

				break;
			}

			// change wing (we must set the flags for all ships present as well as all ships yet to arrive)
			case OSWPT_TYPE_WING:
			case OSWPT_TYPE_WING_NOT_PRESENT:
			{
				// current ships
				for (int i = 0; i < oswpt.wingp->current_count; i++)
					sexp_ingame_ship_kamikaze(&Ships[oswpt.wingp->ship_index[i]], kdamage);

				// ships yet to arrive
				for (p_object *p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp))
				{
					if (p_objp->wingnum == WING_INDEX(oswpt.wingp))
						sexp_parse_ship_kamikaze(p_objp, kdamage);
				}
			}
		}
	}
}

// Goober5000
void sexp_ingame_ship_alt_name(ship *shipp, int alt_index)
{
	Assert((shipp != NULL) && (alt_index < Mission_alt_type_count));

	// we might be clearing it
	if (alt_index < 0)
	{
		shipp->alt_type_index = -1;
		return;
	}

	// see if this is actually the ship class
	if (!stricmp(Ship_info[shipp->ship_info_index].name, Mission_alt_types[alt_index]))
	{
		shipp->alt_type_index = -1;
		return;
	}

	shipp->alt_type_index = alt_index;
}

// Goober5000
void sexp_parse_ship_alt_name(p_object *parse_obj, int alt_index)
{
	Assert((parse_obj != NULL) && (alt_index < Mission_alt_type_count));

	// we might be clearing it
	if (alt_index < 0)
	{
		parse_obj->alt_type_index = -1;
		return;
	}

	// see if this is actually the ship class
	if (!stricmp(Ship_class_names[parse_obj->ship_class], Mission_alt_types[alt_index]))
	{
		parse_obj->alt_type_index = -1;
		return;
	}

	parse_obj->alt_type_index = alt_index;
}

// Goober5000
void sexp_ship_change_alt_name(int node)
{
	int n = node, new_alt_index;
	char *new_alt_name;

	// get the alt-name
	new_alt_name = CTEXT(n);
	n = CDR(n);

	// and its index
	if (!*new_alt_name || !stricmp(new_alt_name, SEXP_ANY_STRING))
	{
		new_alt_index = -1;
	}
	else
	{
		new_alt_index = mission_parse_lookup_alt(new_alt_name);
		if (new_alt_index < 0)
			new_alt_index = mission_parse_add_alt(new_alt_name);
	}

	for ( ; n != -1; n = CDR(n) )
	{
		object_ship_wing_point_team oswpt;
		sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));

		switch (oswpt.type)
		{
			// change ingame ship
			case OSWPT_TYPE_SHIP:
			{
				sexp_ingame_ship_alt_name(oswpt.shipp, new_alt_index);
				break;
			}

			// change ship yet to arrive
			case OSWPT_TYPE_PARSE_OBJECT:
			{
				sexp_parse_ship_alt_name(oswpt.p_objp, new_alt_index);
				break;
			}

			// change wing (we must set the flags for all ships present as well as all ships yet to arrive)
			case OSWPT_TYPE_WING:
			case OSWPT_TYPE_WING_NOT_PRESENT:
			{		
				// current ships
				for (int i = 0; i < oswpt.wingp->current_count; i++)
					sexp_ingame_ship_alt_name(&Ships[oswpt.wingp->ship_index[i]], new_alt_index);
	
				// ships yet to arrive
				for (p_object *p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp))
				{
					if (p_objp->wingnum == WING_INDEX(oswpt.wingp))
						sexp_parse_ship_alt_name(p_objp, new_alt_index);
				}
				break;
			}
		}
	}
}

// FUBAR
void sexp_ship_change_callsign(int node)
{
	char *new_callsign;
	int sindex, cindex;
	ship *shipp = NULL;

	// get the callsign
	new_callsign = CTEXT(node);
	node = CDR(node);

	// and its index
	if (!*new_callsign || !stricmp(new_callsign, SEXP_ANY_STRING))
	{
		cindex = -1;
	}
	else
	{
		cindex = mission_parse_lookup_callsign(new_callsign);
		if (cindex < 0)
			cindex = mission_parse_add_callsign(new_callsign);
	}

	// packets for multi
	multi_start_callback();
	multi_send_string(new_callsign); 

	while ( node >= 0 )
	{
		sindex = ship_name_lookup(CTEXT(node));
		if (sindex >= 0) 
		{
			shipp = &Ships[sindex];
			shipp->callsign_index = cindex;
			multi_send_ship(shipp);
		}
		node = CDR(node);
	}

	multi_end_callback();
}

void multi_sexp_ship_change_callsign()
{
	char new_callsign[TOKEN_LENGTH];
	int cindex;
	ship *shipp = NULL;

	multi_get_string(new_callsign);
	if (!new_callsign[0] || !stricmp(new_callsign, SEXP_ANY_STRING))
	{
		cindex = -1;
	}
	else
	{
		cindex = mission_parse_lookup_callsign(new_callsign);
		if (cindex < 0) 
		{
			cindex = mission_parse_add_callsign(new_callsign);
		}
	}

	while (multi_get_ship(shipp)) 
	{
		if (shipp != NULL) 
		{
			shipp->callsign_index = cindex;
		}
	}
}

// Goober5000
void sexp_set_death_message(int n)
{
	int i;

	// we'll suppose it's the string for now
	Player->death_message = CTEXT(n);

	// but use an actual message if one exists
	for (i=0; i<Num_messages; i++)
	{
		if (!stricmp(Messages[i].name, Player->death_message.c_str()))
		{
			Player->death_message = Messages[i].message;
			break;
		}
	}

	// apply localization
	lcl_replace_stuff(Player->death_message);

	sexp_replace_variable_names_with_values(Player->death_message);
}

int sexp_key_pressed(int node)
{
	int z, t;

	Assert(node != -1);
	z = translate_key_to_index(CTEXT(node), false);
	if (z < 0){
		return SEXP_FALSE;
	}

	if (!Control_config[z].used){
		return SEXP_FALSE;
	}

	if (CDR(node) < 0){
		return SEXP_TRUE;
	}

	t = eval_num(CDR(node));
	return timestamp_has_time_elapsed(Control_config[z].used, t * 1000);
}

void sexp_key_reset(int node)
{
	int n, z;

	for (n = node; n != -1; n = CDR(n))
	{
		z = translate_key_to_index(CTEXT(n), false);
		if (z >= 0)
			Control_config[z].used = 0;
	}
}
				
void sexp_ignore_key(int node)
{
	int ignore_count;
	int ignored_key;


	ignore_count = eval_num(node);

	multi_start_callback();
	multi_send_int(ignore_count);

	node = CDR(node);
	while (node > -1) {
		// get the key
		ignored_key = translate_key_to_index(CTEXT(node), false);

		if (ignored_key > -1) {
			Ignored_keys[ignored_key] = ignore_count;
		}

		multi_send_int(ignored_key);

		node = CDR(node);
	}

	multi_end_callback();
}

void multi_sexp_ignore_key()
{
	int ignored_key, ignore_count;

	multi_get_int(ignore_count);
	
	while (multi_get_int(ignored_key)) {
		Ignored_keys[ignored_key] = ignore_count;
	}
}

int sexp_targeted(int node)
{
	int z;
	ship_subsys *ptr;

	z = ship_query_state(CTEXT(node));
	if (z == 1){
		return SEXP_KNOWN_FALSE;  // ship isn't around, nor will it ever be
	} else if (z == -1) {
		return SEXP_CANT_EVAL;
	}

	z = ship_name_lookup(CTEXT(node), 1);
	if ((z < 0) || !Player_ai || (Ships[z].objnum != Player_ai->target_objnum)){
		return SEXP_FALSE;
	}

	if (CDR(node) >= 0) {
		z = eval_num(CDR(node)) * 1000;
		if (!timestamp_has_time_elapsed(Players_target_timestamp, z)){
			return SEXP_FALSE;
		}

		if (CDR(CDR(node)) >= 0) {
			ptr = Player_ai->targeted_subsys;
			if (!ptr || subsystem_stricmp(ptr->system_info->subobj_name, CTEXT(CDR(CDR(node))))){
				return SEXP_FALSE;
			}
		}
	}

	return SEXP_TRUE;
}

int sexp_node_targeted(int node)
{
	int z;

	CJumpNode *jnp = jumpnode_get_by_name(CTEXT(node));

	if (jnp==NULL || !Player_ai || (jnp->GetSCPObjectNumber() != Player_ai->target_objnum)){
		return SEXP_FALSE;
	}

	if (CDR(node) >= 0) {
		z = eval_num(CDR(node)) * 1000;
		if (!timestamp_has_time_elapsed(Players_target_timestamp, z)){
			return SEXP_FALSE;
		}
	}

	return SEXP_TRUE;
}

int sexp_speed(int node)
{
	if (Training_context & TRAINING_CONTEXT_SPEED) {
		if (Training_context_speed_set){
			if (timestamp_has_time_elapsed(Training_context_speed_timestamp, eval_num(node) * 1000)){
				return SEXP_KNOWN_TRUE;
			}
		}
	}

	return SEXP_FALSE;
}

int sexp_get_throttle_speed(int node)
{
	player *the_player; 

	the_player = get_player_from_ship_node(node); 

	if (the_player != NULL) {
		float max_speed = Ship_info[Ships[Objects[the_player->objnum].instance].ship_info_index].max_speed;
		return (int)(the_player->ci.forward_cruise_percent / 100.0f * max_speed);
	}

	return 0;
}

// CommanderDJ
void sexp_set_player_throttle_speed(int node)
{
	//get and sanity check the player first
	player *the_player;
	the_player = get_player_from_ship_node(node); 

	if(the_player != NULL)
	{
		//now the throttle percentage
		node = CDR(node);
		int throttle_percent = eval_num(node);
		CLAMP(throttle_percent, 0, 100);
		
		//now actually set the throttle
		the_player->ci.forward_cruise_percent = (float) throttle_percent;
	}
}

// Goober5000
int sexp_primaries_depleted(int node)
{
	int sindex, num_banks, num_depleted_banks;
	ship *shipp;

	// get ship
	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0) {
		return SEXP_FALSE;
	}

	shipp = &Ships[sindex];
	if (shipp->objnum < 0) {
		return SEXP_FALSE;
	}

	// see if ship has ballistic primary weapons   
	if (!(Ship_info[shipp->ship_info_index].flags & SIF_BALLISTIC_PRIMARIES))   
		return SEXP_FALSE; 

	// get num primary banks
	num_banks = shipp->weapons.num_primary_banks;
	num_depleted_banks = 0;

	// get number of depleted banks
	for (int idx=0; idx<num_banks; idx++)
	{
		// is this a ballistic bank?
		if (Weapon_info[shipp->weapons.primary_bank_weapons[idx]].wi_flags2 & WIF2_BALLISTIC)
		{
			// is this bank out of ammo?
			if (shipp->weapons.primary_bank_ammo[idx] == 0)
			{
				num_depleted_banks++;
			}
		}
	}

	// are they all depleted?
	return (num_depleted_banks == num_banks);
}

int sexp_secondaries_depleted(int node)
{
	int sindex, num_banks, num_depleted_banks;
	ship *shipp;

	// get ship
	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0) {
		return SEXP_FALSE;
	}

	shipp = &Ships[sindex];
	if (shipp->objnum < 0) {
		return SEXP_FALSE;
	}

	// get num secondary banks
	num_banks = shipp->weapons.num_secondary_banks;
	num_depleted_banks = 0;

	// get number of depleted banks
	for (int idx=0; idx<num_banks; idx++) {
		if (shipp->weapons.secondary_bank_ammo[idx] == 0) {
			num_depleted_banks++;
		}
	}

	// are they all depleted?
	return (num_depleted_banks == num_banks);
}

int sexp_facing(int node)
{
	float a1, a2;
	vec3d v1, v2;

	if (!Player_obj) {
		return SEXP_FALSE;
	}

	ship *target_shipp = sexp_get_ship_from_node(node);
	if (target_shipp == NULL) {
		// hasn't arrived yet
		if (mission_parse_get_arrival_ship(CTEXT(node)) != NULL) {
			return SEXP_CANT_EVAL;
		}
		// not found and won't arrive: invalid
		return SEXP_KNOWN_FALSE;
	}
	double angle = atof(CTEXT(CDR(node)));

	v1 = Player_obj->orient.vec.fvec;
	vm_vec_normalize(&v1);

	vm_vec_sub(&v2, &Objects[target_shipp->objnum].pos, &Player_obj->pos);
	vm_vec_normalize(&v2);

	a1 = vm_vec_dot(&v1, &v2);
	a2 = (float) cos(ANG_TO_RAD(angle));
	if (a1 >= a2){
		return SEXP_TRUE;
	}

	return SEXP_FALSE;
}

int sexp_is_facing(int node)
{
	object *origin_objp, *target_objp;
	float a1, a2;
	vec3d v1, v2;
	
	ship *origin_shipp = sexp_get_ship_from_node(node);
	if (origin_shipp == NULL) {
		// hasn't arrived yet
		if (mission_parse_get_arrival_ship(CTEXT(node)) != NULL) {
			return SEXP_CANT_EVAL;
		}
		// not found and won't arrive: invalid
		return SEXP_KNOWN_FALSE;
	}
	node = CDR(node);

	object_ship_wing_point_team oswpt;
	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(node));

	if (oswpt.type == OSWPT_TYPE_SHIP && sexp_get_ship_from_node(node) == NULL) {
		return SEXP_KNOWN_FALSE;
	}

	// only true if ship has departed or not yet arrived
	if (oswpt.type == OSWPT_TYPE_EXITED || oswpt.type == OSWPT_TYPE_PARSE_OBJECT) {
		return SEXP_CANT_EVAL;
	}

	if (oswpt.type == OSWPT_TYPE_NONE)
		return SEXP_CANT_EVAL;

	origin_objp = &Objects[origin_shipp->objnum];
	target_objp = oswpt.objp;

	node = CDR(node);

	double angle = atof(CTEXT(node));
	node = CDR(node);

	// check optional distance argument
	if (node > 0 && (sexp_distance3(origin_objp, target_objp) > eval_num(node))) {
		return SEXP_FALSE;
	}

	v1 = origin_objp->orient.vec.fvec;	
	vm_vec_normalize(&v1);

	vm_vec_sub(&v2, &target_objp->pos, &origin_objp->pos);
	vm_vec_normalize(&v2);

	a1 = vm_vec_dot(&v1, &v2);
	a2 = (float) cos(ANG_TO_RAD(angle));
	if (a1 >= a2){
		return SEXP_TRUE;
	}

	return SEXP_FALSE;
}

// is ship facing first waypoint in waypoint path
int sexp_facing2(int node)
{
	float a1, a2;
	vec3d v1, v2;

	// bail if Player_obj is not good
	if (!Player_obj) {
		return SEXP_CANT_EVAL;
	}

	// get player fvec
	v1 = Player_obj->orient.vec.fvec;
	vm_vec_normalize(&v1);

	// get waypoint name
	char *waypoint_name = CTEXT(node);

	// get position of first waypoint
	waypoint_list *wp_list = find_matching_waypoint_list(waypoint_name);

	if (wp_list == NULL) {
		return SEXP_CANT_EVAL;
	}

	vm_vec_sub(&v2, wp_list->get_waypoints().front().get_pos(), &Player_obj->pos);
	vm_vec_normalize(&v2);
	a1 = vm_vec_dot(&v1, &v2);
	a2 = (float) cos(ANG_TO_RAD(atof(CTEXT(CDR(node)))));
	if (a1 >= a2){
		return SEXP_TRUE;
	}

	return SEXP_FALSE;
}

int sexp_order(int n)
{
	char *order_to = CTEXT(n);
	char *order = CTEXT(CDR(n));
	char *target = NULL;

	//target
	n = CDDR(n); 
	if (n != -1)
		target = CTEXT(n);
	
	return hud_query_order_issued(order_to, order, target);
}

int sexp_query_orders (int n)
{
	char *order_to = CTEXT(n);
	char *order = CTEXT(CDR(n));
	char *target = NULL;
	char *order_from = NULL;
	char *special = NULL;
	int timestamp = 0;

	// delay
	n = CDDR(n); 
	if (n != -1) {
		timestamp = eval_sexp(n); 
		n = CDR(n); 
	}
	
	//target
	if (n != -1) {
		target = CTEXT(n);
		n = CDR(n); 
	}

	// player order comes from
	if (n != -1) {
		order_from = CTEXT(n);
		n = CDR(n); 
	}

	// optional special argument
	if (n != -1)
		special = CTEXT(n);

	return hud_query_order_issued(order_to, order, target, timestamp, order_from, special);
}

// Karajorma
void sexp_reset_orders (int n)
{
	Squadmsg_history.clear();
}

int sexp_waypoint_missed()
{
	if (Training_context & TRAINING_CONTEXT_FLY_PATH) {
		if (Training_context_at_waypoint > Training_context_goal_waypoint){
			return SEXP_TRUE;
		}
	}

	return SEXP_FALSE;
}

int sexp_waypoint_twice()
{
	if (Training_context & TRAINING_CONTEXT_FLY_PATH) {
		if (Training_context_at_waypoint < Training_context_goal_waypoint - 1){
			return SEXP_TRUE;
		}
	}

	return SEXP_FALSE;
}

int sexp_path_flown()
{
	if (Training_context & TRAINING_CONTEXT_FLY_PATH) {
		if ((uint) Training_context_goal_waypoint == Training_context_path->get_waypoints().size()){
			return SEXP_TRUE;
		}
	}

	return SEXP_FALSE;
}

void sexp_send_training_message(int node)
{
	int t = -1, delay = 0;

	if(physics_paused){
		return;
	}

	Assert(node >= 0);
	Assert(Event_index >= 0);

	if ((CDR(node) >= 0) && (CDR(CDR(node)) >= 0)) {
		delay = eval_num(CDR(CDR(node))) * 1000;
		t = CDR(CDR(CDR(node)));
		if (t >= 0){
			t = eval_num(t);
		}
	}

	multi_start_callback();
	multi_send_int(t);
	multi_send_int(delay);

	if ((Mission_events[Event_index].repeat_count > 1) || (CDR(node) < 0)){
		message_training_queue(CTEXT(node), timestamp(delay), t);
		multi_send_string(CTEXT(node));
	} else {
		message_training_queue(CTEXT(CDR(node)), timestamp(delay), t);
		multi_send_string(CTEXT(CDR(node)));
	}
	multi_end_callback();
}

void multi_sexp_send_training_message()
{	
	int t, delay;
	char message[TOKEN_LENGTH];

	multi_get_int(t);
	multi_get_int(delay);
	if (multi_get_string(message)) {
		message_training_queue(message, timestamp(delay), t); 
	}
	
}

int sexp_shield_recharge_pct(int node)
{
	int sindex;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return 0;
	}
	if(Ships[sindex].objnum < 0){
		return 0;
	}

	// shield recharge pct
	return (int)(100.0f * Energy_levels[Ships[sindex].shield_recharge_index]);
}

int sexp_engine_recharge_pct(int node)
{
	int sindex;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return 0;
	}
	if(Ships[sindex].objnum < 0){
		return 0;
	}

	// shield recharge pct
	return (int)(100.0f * Energy_levels[Ships[sindex].engine_recharge_index]);
}

int sexp_weapon_recharge_pct(int node)
{
	int sindex;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return 0;
	}
	if(Ships[sindex].objnum < 0){
		return 0;
	}

	// shield recharge pct
	return (int)(100.0f * Energy_levels[Ships[sindex].weapon_recharge_index]);
}

/**
 * retrieve one ETS index from a ship
 */
int sexp_get_ets_value(int node)
{
	int sindex;
	SCP_string ets_type;

	ets_type = CTEXT(node);
	node = CDR(node);

	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0) {
		return SEXP_FALSE;
	}
	if (Ships[sindex].objnum < 0) {
		return SEXP_FALSE;
	}

	if (!stricmp(ets_type.c_str(), "engine")) {
		return Ships[sindex].engine_recharge_index;
	} else if (!stricmp(ets_type.c_str(), "shield")) {
		return Ships[sindex].shield_recharge_index;
	} else if (!stricmp(ets_type.c_str(), "weapon")) {
		return Ships[sindex].weapon_recharge_index;
	} else {
		return SEXP_FALSE;
	}
}

/**
 * set all ETS indexes for one or more ships
 */
void sexp_set_ets_values(int node)
{
	int sindex;
	int ets_idx[num_retail_ets_gauges];

	ets_idx[ENGINES] = eval_num(node);
	node = CDR(node);
	ets_idx[SHIELDS] = eval_num(node);
	node = CDR(node);
	ets_idx[WEAPONS] = eval_num(node);
	node = CDR(node);

	// sanity check inputs
	sanity_check_ets_inputs(ets_idx);

	multi_start_callback();

	// apply ETS settings to specified ships
	for ( ; node != -1; node = CDR(node)) {
		sindex = ship_name_lookup(CTEXT(node));

		if (sindex >= 0 && validate_ship_ets_indxes(sindex, ets_idx)) {
			Ships[sindex].engine_recharge_index = ets_idx[ENGINES];
			Ships[sindex].shield_recharge_index = ets_idx[SHIELDS];
			Ships[sindex].weapon_recharge_index = ets_idx[WEAPONS];

			multi_send_ship(sindex);
			multi_send_int(ets_idx[ENGINES]);
			multi_send_int(ets_idx[SHIELDS]);
			multi_send_int(ets_idx[WEAPONS]);
		}
	}
	multi_end_callback();
}

void multi_sexp_set_ets_values()
{
	int sindex;
	int ets_idx[num_retail_ets_gauges];

	while (multi_get_ship(sindex)) {
		multi_get_int(ets_idx[ENGINES]);
		multi_get_int(ets_idx[SHIELDS]);
		multi_get_int(ets_idx[WEAPONS]);

		Ships[sindex].engine_recharge_index = ets_idx[ENGINES];
		Ships[sindex].shield_recharge_index = ets_idx[SHIELDS];
		Ships[sindex].weapon_recharge_index = ets_idx[WEAPONS];
	}
}

int sexp_shield_quad_low(int node)
{
	int sindex, idx;	
	float max_quad, check;
	ship_info *sip;
	object *objp;

	// get the ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return SEXP_FALSE;
	}
	if((Ships[sindex].objnum < 0) || (Ships[sindex].objnum >= MAX_OBJECTS)){
		return SEXP_FALSE;
	}
	if((Ships[sindex].ship_info_index < 0) || (Ships[sindex].ship_info_index >= static_cast<int>(Ship_info.size()))){
		return SEXP_FALSE;
	}
	objp = &Objects[Ships[sindex].objnum];
	sip = &Ship_info[Ships[sindex].ship_info_index];
	if(!(sip->flags & SIF_SMALL_SHIP)){
		return SEXP_FALSE;
	}
	max_quad = get_max_shield_quad(objp);	

	// shield pct
	check = (float)eval_num(CDR(node));

	// check his quadrants
	for(idx=0; idx<objp->n_quadrants; idx++){
		if( ((objp->shield_quadrant[idx] / max_quad) * 100.0f) <= check ){
			return SEXP_TRUE;
		}
	}

	// all good
	return SEXP_FALSE;	
}

// Goober5000
int sexp_primary_ammo_pct(int node)
{
	ship *shipp;
	int sindex;
	int check, idx;
	int ret_sum[MAX_SHIP_PRIMARY_BANKS];
	int ret = 0;

	// get the ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0)
	{
		return 0;
	}
	if((Ships[sindex].objnum < 0) || (Ships[sindex].objnum >= MAX_OBJECTS))
	{
		return 0;
	}
	shipp = &Ships[sindex];
	
	// bank to check
	check = eval_num(CDR(node));

	// bogus check?
	if(check < 0){
		return 0;
	}

	// cumulative sum?
	if(check >= shipp->weapons.num_primary_banks)
	{
		for(idx=0; idx<shipp->weapons.num_primary_banks; idx++)
		{
			// ballistic
			if (Weapon_info[shipp->weapons.primary_bank_weapons[idx]].wi_flags2 & WIF2_BALLISTIC)
			{
				ret_sum[idx] = (int)(((float)shipp->weapons.primary_bank_ammo[idx] / (float)shipp->weapons.primary_bank_start_ammo[idx]) * 100.0f);
			}
			// non-ballistic
			else
			{
				ret_sum[idx] = 100;
			}
		}

		// add it up
		ret = 0;
		for(idx=0; idx<shipp->weapons.num_primary_banks; idx++)
		{
			ret += ret_sum[idx];
		}
		ret = (int)((float)ret / (float)shipp->weapons.num_primary_banks);
	}
	else
	{
		// ballistic
		if (Weapon_info[shipp->weapons.primary_bank_weapons[check]].wi_flags2 & WIF2_BALLISTIC)
		{
			ret = (int)(((float)shipp->weapons.primary_bank_ammo[check] / (float)shipp->weapons.primary_bank_start_ammo[check]) * 100.0f);
		}
		// non-ballistic
		else
		{
			ret = 100;
		}
	}	

	// return
	return ret;
}

int sexp_secondary_ammo_pct(int node)
{
	ship *shipp;
	int sindex;
	int check, idx;
	int ret_sum[MAX_SHIP_SECONDARY_BANKS];
	int ret = 0;

	// get the ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return 0;
	}
	if((Ships[sindex].objnum < 0) || (Ships[sindex].objnum >= MAX_OBJECTS)){
		return 0;
	}
	shipp = &Ships[sindex];
	
	// bank to check
	check = eval_num(CDR(node));

	// bogus check?
	if(check < 0){
		return 0;
	}

	// cumulative sum?
	if(check >= shipp->weapons.num_secondary_banks){
		for(idx=0; idx<shipp->weapons.num_secondary_banks; idx++){
			ret_sum[idx] = (int)(((float)shipp->weapons.secondary_bank_ammo[idx] / (float)shipp->weapons.secondary_bank_start_ammo[idx]) * 100.0f);
		}

		// add it up
		ret = 0;
		for(idx=0; idx<shipp->weapons.num_secondary_banks; idx++){
			ret += ret_sum[idx];
		}
		ret = (int)((float)ret / (float)shipp->weapons.num_secondary_banks);
	} else {
		ret = (int)(((float)shipp->weapons.secondary_bank_ammo[check] / (float)shipp->weapons.secondary_bank_start_ammo[check]) * 100.0f);
	}	

	// return
	return ret;
}


// Karajorma - returns the number of bullets left in an ballistic ammo bank. Unlike primary_ammo_pct
// it does this as a numerical value rather than as a percentage of the maximum
int sexp_get_primary_ammo(int node)
{
	ship *shipp;
	int ammo_left = 0;
	int sindex;
	int check;

	// get the ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0)
	{
		return 0;
	}
	if((Ships[sindex].objnum < 0) || (Ships[sindex].objnum >= MAX_OBJECTS))
	{
		return 0;
	}
	shipp = &Ships[sindex];
	
	// bank to check
	check = eval_num(CDR(node));

	// bogus check?
	if(check < 0){
		return 0;
	}

	// cumulative sum?
	if(check >= shipp->weapons.num_primary_banks)
	{
		for(int bank=0; bank<shipp->weapons.num_primary_banks; bank++)
		{
			// Only ballistic weapons need to be counted
			if (Weapon_info[shipp->weapons.primary_bank_weapons[bank]].wi_flags2 & WIF2_BALLISTIC)
			{
				ammo_left += shipp->weapons.primary_bank_ammo[bank] ;
			}
		}
	}
	else
	{
		// Again only ballistic weapons need to be counted
		if (Weapon_info[shipp->weapons.primary_bank_weapons[check]].wi_flags2 & WIF2_BALLISTIC)
		{
			ammo_left = shipp->weapons.primary_bank_ammo[check] ;
		}
	}	

	// return
	return ammo_left;
}


// Karajorma - sets the amount of ammo in a certain ballistic weapon bank to the specified value
void sexp_set_primary_ammo (int node) 
{
	int sindex;
	int requested_bank ;
	int requested_weapons ;
	int rearm_limit = 0;

	// Check that a ship has been supplied
	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0) 
	{
		return ;
	}

	// Get the bank to set the number on
	requested_bank = eval_num(CDR(node));
	if (requested_bank < 0)
	{
		return ;
	}

	//  Get the number of weapons requested
	node = CDR(node);
	requested_weapons = eval_num(CDR(node)); 
	if (requested_weapons < 0)
	{
		return ;
	}
	
	node = CDDR(node);	

	// If a rearm limit hasn't been specified simply change the ammo.Otherwise read in the rearm limit
	if (node < 0) {
		set_primary_ammo (sindex, requested_bank, requested_weapons);
	}
	else {
		rearm_limit = eval_num(node); 
		set_primary_ammo (sindex, requested_bank, requested_weapons, rearm_limit);
	}
}

//Karajorma - Helper function for the set-primary-ammo and weapon functions
void set_primary_ammo (int ship_index, int requested_bank, int requested_ammo, int rearm_limit, bool update)
{
	ship *shipp;
	int maximum_allowed ;

	// Check that it's valid
	if((Ships[ship_index].objnum < 0) || (Ships[ship_index].objnum >= MAX_OBJECTS)){
		return ;
	}
	shipp = &Ships[ship_index];
	
	// Can only set one bank at a time. Check that someone hasn't asked for the contents of all 
	// the banks or a non-existant bank
	if ((requested_bank > shipp->weapons.num_primary_banks) || requested_bank < 0)
	{
		return ;
	}

	// Check that this isn't a non-ballistic bank as it's pointless to set the amount of ammo for those
	if (!(Weapon_info[shipp->weapons.primary_bank_weapons[requested_bank]].wi_flags2 & WIF2_BALLISTIC))
	{
		return ;
	}

	//Check that a valid number of weapons have been specified. 
	if (requested_ammo < 0) 
	{
		return ;
	}

	// Is the number requested larger than the maximum allowed for that particular bank? 
	maximum_allowed = fl2i((Ship_info[shipp->ship_info_index].primary_bank_ammo_capacity[requested_bank] 
		/ Weapon_info[shipp->weapons.primary_bank_weapons[requested_bank]].cargo_size)+0.5);
	if (maximum_allowed < requested_ammo) 
	{
		requested_ammo = maximum_allowed ;
	}

	// Set the number of weapons
	shipp->weapons.primary_bank_ammo[requested_bank] = requested_ammo ;

	// If a rearm limit has been specified set it.
	if (rearm_limit >= 0)
	{
		// Don't allow more weapons than the bank can actually hold.
		if (rearm_limit > maximum_allowed) 
		{
			rearm_limit = maximum_allowed;
		}

		shipp->weapons.primary_bank_start_ammo[requested_bank] = rearm_limit;
	}

	// The change needs to be passed on if this is a multiplayer game
	if (MULTIPLAYER_MASTER & update)
	{
		send_weapon_or_ammo_changed_packet(ship_index, 0, requested_bank, requested_ammo, rearm_limit, -1);
	}
}

// Karajorma - returns the number of missiles left in an ammo bank. Unlike secondary_ammo_pct
// it does this as a numerical value rather than as a percentage of the maximum
int sexp_get_secondary_ammo (int node)
{
	int ammo_left = 0 ;
	ship *shipp ;
	int sindex ; 
	int check ;

	// Get the ship
	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0) 
	{
		return 0;
	}
	if((Ships[sindex].objnum < 0) || (Ships[sindex].objnum >= MAX_OBJECTS)){
		return 0;
	}
	shipp = &Ships[sindex];
	
	// bank to check
	check = eval_num(CDR(node));

	// bogus check?
	if(check < 0){
		return 0;
	}

	// Are we looking at the number of secondaries in all banks? 
	if(check > shipp->weapons.num_secondary_banks)
	{
		for(int bank=0; bank<shipp->weapons.num_secondary_banks; bank++)
		{
			ammo_left += shipp->weapons.secondary_bank_ammo[bank] ;
		}
	}
	// If not return the value for the bank requested.
	else 
	{
		ammo_left = shipp->weapons.secondary_bank_ammo[check] ; 
	}

	return ammo_left ;
}

// Karajorma - sets the amount of ammo in a certain weapon bank to the specified value
void sexp_set_secondary_ammo (int node) 
{
	int sindex;
	int requested_bank;
	int requested_weapons;
	int rearm_limit;

	// Check that a ship has been supplied
	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0) 
	{
		return ;
	}
	
	// Get the bank to set the number on
	requested_bank = eval_num(CDR(node));
	if (requested_bank < 0)
	{
		return ;
	}

	//  Get the number of weapons requested	
	node = CDR(node);
	requested_weapons = eval_num(CDR(node)); 
	if (requested_weapons < 0)
	{
		return ;
	}

	node = CDDR(node);	

	// If a rearm limit hasn't been specified simply change the ammo.Otherwise read in the rearm limit
	if (node < 0) {
		set_secondary_ammo(sindex, requested_bank, requested_weapons);
	}
	else {
		rearm_limit = eval_num(node); 
		set_secondary_ammo(sindex, requested_bank, requested_weapons, rearm_limit);
	}
}

//Karajorma - Helper function for the set-secondary-ammo and weapon functions
void set_secondary_ammo (int ship_index, int requested_bank, int requested_ammo, int rearm_limit, bool update)
{
	ship *shipp;
	int maximum_allowed;
	// Check that it's valid
	if((Ships[ship_index].objnum < 0) || (Ships[ship_index].objnum >= MAX_OBJECTS)){
		return ;
	}
	shipp = &Ships[ship_index];

	// Can only set one bank at a time. Check that someone hasn't asked for the contents of all 
	// the banks or a non-existant bank
	if ((requested_bank > shipp->weapons.num_secondary_banks) || requested_bank < 0)
	{
		return ;
	}
	
	if (requested_ammo < 0)
	{
		return ;
	}

	// Is the number requested larger than the maximum allowed for that particular bank? 
	maximum_allowed = fl2i(shipp->weapons.secondary_bank_capacity[requested_bank] 
		/ Weapon_info[shipp->weapons.secondary_bank_weapons[requested_bank]].cargo_size);
	if (maximum_allowed < requested_ammo) 
	{
		requested_ammo = maximum_allowed ;
	}

	// Set the number of weapons
	shipp->weapons.secondary_bank_ammo[requested_bank] = requested_ammo ;

	// If a rearm limit has been specified set it.
	if (rearm_limit >= 0)
	{
		// Don't allow more weapons than the bank can actually hold.
		if (rearm_limit > maximum_allowed) 
		{
			rearm_limit = maximum_allowed;
		}

		shipp->weapons.secondary_bank_start_ammo[requested_bank] = rearm_limit;
	}

	// The change needs to be passed on if this is a multiplayer game and we're not already updating the weapon
	if (MULTIPLAYER_MASTER && update)
	{
		send_weapon_or_ammo_changed_packet(ship_index, 1, requested_bank, requested_ammo, rearm_limit, -1);
	}
}

// Karajorma - Changes the weapon in the requested bank to the one supplied. Optionally sets the ammo and 
// rearm limit too. 
void sexp_set_weapon (int node, bool primary)
{
	ship *shipp;	
	int sindex, requested_bank, windex, requested_ammo=-1, rearm_limit=-1;

	Assert (node != -1);

	// Check that a ship has been supplied
	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0) 
	{
		return ;
	}

	// Check that it's valid
	if((Ships[sindex].objnum < 0) || (Ships[sindex].objnum >= MAX_OBJECTS)){
		return ;
	}
	shipp = &Ships[sindex];

	// Get the bank to change the weapon of
	requested_bank = eval_num(CDR(node));

	// Skip to the node holding the weapon name
	node = CDDR(node);

	windex = weapon_info_lookup(CTEXT(node));
	if (windex < 0)
	{
		return;
	}

	if (primary)
	{
		// Change the weapon
		shipp->weapons.primary_bank_weapons[requested_bank] = windex ; 
	}
	else 
	{
		// Change the weapon
		shipp->weapons.secondary_bank_weapons[requested_bank] = windex ;
	}

	
	// Check to see if the optional ammo and rearm_limit settings were supplied
	node = CDR(node);
	if (node >= 0) {
		requested_ammo = eval_num(node); 
		
		if (requested_ammo < 0) {
			requested_ammo = 0; 
		}
		node = CDR(node);
		
		// If nothing was supplied then set the rearm limit to a negative value so that it is ignored
		if (node < 0) {
			rearm_limit = -1;
		}
		else {
			rearm_limit = eval_num(node); 
		}

		// Set the ammo but do not send an ammo changed update packet as we'll do that later from here
		if (primary) {
			set_primary_ammo (sindex, requested_bank, requested_ammo, rearm_limit, false);
		}
		else {
			set_secondary_ammo (sindex, requested_bank, requested_ammo, rearm_limit, false);
		}
	}
	else {
		// read the data 
		if (primary) {
			requested_ammo = shipp->weapons.primary_bank_ammo[requested_bank];
			rearm_limit = shipp->weapons.primary_bank_start_ammo[requested_bank];
		}
		else {
			requested_ammo = shipp->weapons.secondary_bank_ammo[requested_bank];
			rearm_limit = shipp->weapons.secondary_bank_start_ammo[requested_bank];
		}
	}

	// Now pass this info on to clients if need be.
	if (MULTIPLAYER_MASTER)
	{
		if (primary) {
			send_weapon_or_ammo_changed_packet(sindex, 0, requested_bank, requested_ammo, rearm_limit, windex);
		}
		else {
			send_weapon_or_ammo_changed_packet(sindex, 1, requested_bank, requested_ammo, rearm_limit, windex);
		}
	}
}

int sexp_get_countermeasures(int node) 
{
	ship *shipp;

	shipp = sexp_get_ship_from_node(node);

	if (shipp !=NULL) {
		return shipp->cmeasure_count;
	}
	else {
		return SEXP_NAN;
	}
}

void sexp_set_countermeasures(int node)
{
	ship *shipp;
	int num_cmeasures;

	shipp = sexp_get_ship_from_node(node);

	if (shipp == NULL) {
		return;
	}
	node = CDR(node);
	num_cmeasures = eval_num(node);
	if (num_cmeasures < 0) {
		num_cmeasures = 0;
	}
	else if (num_cmeasures > Ship_info[shipp->ship_info_index].cmeasure_max) {
		num_cmeasures = Ship_info[shipp->ship_info_index].cmeasure_max;
	}

	shipp->cmeasure_count = num_cmeasures;

	multi_start_callback();
	multi_send_ship(shipp);
	multi_send_int(num_cmeasures);
	multi_end_callback();
}

void multi_sexp_set_countermeasures()
{	
	int num_cmeasures = 0;
	ship *shipp; 

	multi_get_ship(shipp);
	if (shipp == NULL) {
		return;
	}
	if (multi_get_int(num_cmeasures)) {
		shipp->cmeasure_count = num_cmeasures;
	}
}

// KeldorKatarn - Locks or unlocks the afterburner on the requested ship
void sexp_deal_with_afterburner_lock (int node, bool lock)
{
	Assert (node != -1);
	sexp_deal_with_ship_flag(node, true, 0, 0, 0, SF2_AFTERBURNER_LOCKED, 0, 0, (lock ? 1:0), true);
}

// Karajorma - locks or unlocks primary weapons on the requested ship
void sexp_deal_with_primary_lock (int node, bool lock)
{
	Assert (node != -1);	
	sexp_deal_with_ship_flag(node, true, 0, 0, 0, SF2_PRIMARIES_LOCKED, 0, P2_SF2_PRIMARIES_LOCKED, (lock ? 1:0), true);

}

void sexp_deal_with_secondary_lock (int node, bool lock)
{
	Assert (node != -1);	
	sexp_deal_with_ship_flag(node, true, 0, 0, 0, SF2_SECONDARIES_LOCKED, 0, P2_SF2_SECONDARIES_LOCKED, (lock ? 1:0), true);

}

//Karajorma - Changes the subsystem name displayed on the HUD.  
void sexp_change_subsystem_name(int node) 
{
	ship *shipp;
	int ship_index;
	char *new_name;
	ship_subsys *subsystem_to_rename;

	Assert (node != -1);

	// Check that a ship has been supplied
	ship_index = ship_name_lookup(CTEXT(node));
	if (ship_index < 0) {
		return;
	}

	shipp = &Ships[ship_index];
	node = CDR(node);

	if (node < 0) {
		return;
	}

	new_name = CTEXT(node);
	node = CDR(node);
	
	if (MULTIPLAYER_MASTER) {
		multi_start_callback();
		multi_send_ship(shipp); 
		multi_send_string(new_name); 
	}

	// loop through all the subsystems the SEXP has provided
	while (node >= 0) {

		//Get the new subsystem name
		subsystem_to_rename = ship_get_subsys(&Ships[ship_index], CTEXT(node));
		if (subsystem_to_rename != NULL) {
			ship_subsys_set_name(subsystem_to_rename, new_name); 
	
			if (MULTIPLAYER_MASTER) {
				multi_send_string(CTEXT(node)); 
			}
		}

		node = CDR(node);
	}
	
	if (MULTIPLAYER_MASTER) {
		multi_end_callback();
	}
}

void multi_sexp_change_subsystem_name()
{
	ship *shipp = NULL;
	char new_name[TOKEN_LENGTH];
	char subsys_name[MAX_NAME_LEN];
	ship_subsys *subsystem_to_rename;

	multi_get_ship(shipp);
	multi_get_string(new_name);
	while (multi_get_string(subsys_name)) {
		subsystem_to_rename = ship_get_subsys(shipp, subsys_name);
		if (subsystem_to_rename != NULL) {
			ship_subsys_set_name(subsystem_to_rename, new_name);
		}
	}
}

// Goober5000
void sexp_change_ship_class(int n)
{
	int ship_num, class_num = ship_info_lookup(CTEXT(n));
	Assert(class_num != -1);

	n = CDR(n);

	if (MULTIPLAYER_MASTER) {
		multi_start_callback();
		multi_send_int(class_num);
	}

	// all ships in the sexp
	for ( ; n != -1; n = CDR(n))
	{
		ship_num = ship_name_lookup(CTEXT(n), 1);

		// If the ship hasn't arrived we still want the ability to change its class.
		if (ship_num == -1)
		{
			// Get the name of the ship that we are interested in
			char* ship_name = CTEXT(n); 
			p_object *pobj ;
			bool match_found = false;
			

			// Search the Ship_arrival_list to see if the ship is waiting to arrive
			for (pobj = GET_FIRST(&Ship_arrival_list); pobj != END_OF_LIST(&Ship_arrival_list); pobj = GET_NEXT(pobj))
			{
				if (!(strcmp(pobj->name, ship_name)))
				{
					match_found = true;
					break;
				}
			}

			if (match_found)
			{
				swap_parse_object(pobj, class_num);

				if (MULTIPLAYER_MASTER) {
					multi_send_bool(false); 
					multi_send_parse_object(pobj); 
				}
			}
		}
		// If the ship is already in the mission
		else 
		{
			// don't mess with a ship that's occupied
			if (!(Ships[ship_num].flags & (SF_DYING | SF_ARRIVING | SF_DEPARTING)))
			{
				change_ship_type(ship_num, class_num, 1);
				if (&Ships[ship_num] == Player_ship) {
					set_current_hud();
				}

				if (MULTIPLAYER_MASTER) {
					multi_send_bool(true); 
					multi_send_ship(ship_num); 
				}
			}
		}
	}

	if (MULTIPLAYER_MASTER) {
		multi_end_callback();
	}
}

void multi_sexp_change_ship_class()
{
	int class_num = -1;
	int ship_num = -1;
	bool ship_arrived;
	p_object *pobjp = NULL;

	multi_get_int(class_num);
	while (multi_get_bool(ship_arrived)) {
		if (ship_arrived) {
			multi_get_ship(ship_num);
			if ((class_num >= 0) && (ship_num >= 0)) {
				change_ship_type(ship_num, class_num, 1);
				if (&Ships[ship_num] == Player_ship) {
					set_current_hud();
				}
			}
		}
		else {
			multi_get_parse_object(pobjp); 
			if ((class_num >= 0) && (pobjp != NULL)) {
				swap_parse_object(pobjp, class_num);
			}
		}
	}
}

// Goober5000
void ship_copy_damage(ship *target_shipp, ship *source_shipp)
{
	int i;
	object *target_objp = &Objects[target_shipp->objnum];
	object *source_objp = &Objects[source_shipp->objnum];
	ship_subsys *source_ss;
	ship_subsys *target_ss;

	if (target_shipp->ship_info_index != source_shipp->ship_info_index)
	{
		nprintf(("SEXP", "Copying damage of ship %s to ship %s which has a different ship class.  Strange results might occur.\n", source_shipp->ship_name, target_shipp->ship_name));
	}


	// copy hull...
	target_shipp->special_hitpoints = source_shipp->special_hitpoints;
	target_shipp->ship_max_hull_strength = source_shipp->ship_max_hull_strength;
	target_objp->hull_strength = source_objp->hull_strength;

	// ...and shields
	target_shipp->ship_max_shield_strength = source_shipp->ship_max_shield_strength;
	for (i = 0; i < MIN(target_objp->n_quadrants, source_objp->n_quadrants); i++)
		target_objp->shield_quadrant[i] = source_objp->shield_quadrant[i];


	// search through all subsystems on source ship and map them onto target ship
	for (source_ss = GET_FIRST(&source_shipp->subsys_list); source_ss != GET_LAST(&source_shipp->subsys_list); source_ss = GET_NEXT(source_ss))
	{
		// find subsystem to configure
		target_ss = ship_get_subsys(target_shipp, source_ss->system_info->subobj_name);
		if (target_ss == NULL)
			continue;

		// copy
		target_ss->max_hits = source_ss->max_hits;
		target_ss->current_hits = source_ss->current_hits;
		target_ss->submodel_info_1.blown_off = source_ss->submodel_info_1.blown_off;
		target_ss->submodel_info_2.blown_off = source_ss->submodel_info_2.blown_off;
	}
}

extern int insert_subsys_status(p_object *pobjp);

// Goober5000
void parse_copy_damage(p_object *target_pobjp, ship *source_shipp)
{
	object *source_objp = &Objects[source_shipp->objnum];
	ship_subsys *source_ss;
	subsys_status *target_sssp;

	if (target_pobjp->ship_class != source_shipp->ship_info_index)
	{
		nprintf(("SEXP", "Copying damage of ship %s to ship %s which has a different ship class.  Strange results might occur.\n", source_shipp->ship_name, target_pobjp->name));
	}

	// copy hull...
	target_pobjp->special_hitpoints = source_shipp->special_hitpoints;
	target_pobjp->ship_max_hull_strength = source_shipp->ship_max_hull_strength;
	target_pobjp->initial_hull = fl2i(get_hull_pct(source_objp) * 100.0f);

	// ...and shields
	target_pobjp->ship_max_shield_strength = source_shipp->ship_max_shield_strength;
	target_pobjp->initial_shields = fl2i(get_shield_pct(source_objp) * 100.0f);
	target_pobjp->max_shield_recharge = source_shipp->max_shield_recharge;


	// search through all subsystems on source ship and map them onto target ship
	for (source_ss = GET_FIRST(&source_shipp->subsys_list); source_ss != GET_LAST(&source_shipp->subsys_list); source_ss = GET_NEXT(source_ss))
	{
		// find subsystem to configure
		target_sssp = parse_get_subsys_status(target_pobjp, source_ss->system_info->subobj_name);

		// gak... none allocated; we need to allocate one!
		if (target_sssp == NULL)
		{
			// jam in the new subsystem at the end of the existing list for this parse object
			int new_idx = insert_subsys_status(target_pobjp);
			target_sssp = &Subsys_status[new_idx];

			strcpy_s(target_sssp->name, source_ss->system_info->subobj_name);
		}

		// copy
		if (source_ss->max_hits == 0.0f)
		{
			Warning(LOCATION, "Why does %s's subsystem %s have a maximum strength of 0?", source_shipp->ship_name, source_ss->system_info->subobj_name);
			target_sssp->percent = 100.0f;
		}
		else
		{
			target_sssp->percent = 100.0f - (source_ss->current_hits / source_ss->max_hits) * 100.0f;
		}
	}
}

// Goober5000
void sexp_ship_copy_damage(int node)
{
	int n, source_shipnum, target_shipnum;
	p_object *target_pobjp;

	// source ship must be present
	source_shipnum = ship_name_lookup(CTEXT(node));
	if (source_shipnum < 0)
		return;

	// loop through all subsequent arguments
	for (n = CDR(node); n != -1; n = CDR(n))
	{
		// maybe it's present in-mission
		target_shipnum = ship_name_lookup(CTEXT(n));
		if (target_shipnum >= 0)
		{
			ship_copy_damage(&Ships[target_shipnum], &Ships[source_shipnum]);
			continue;
		}

		// maybe it's on the arrival list
		target_pobjp = mission_parse_get_arrival_ship(CTEXT(n));
		if (target_pobjp != NULL)
		{
			parse_copy_damage(target_pobjp, &Ships[source_shipnum]);
			continue;
		}

		// must have departed or not even existed... do nothing
	}
}


//-Bobboau
void sexp_activate_deactivate_glow_points(int n, bool activate)
{
	int sindex;
	size_t i;

	for ( ; n != -1; n = CDR(n))
	{
		sindex = ship_name_lookup(CTEXT(n), 1);
		if (sindex >= 0)
		{
			for (i = 0; i < Ships[sindex].glow_point_bank_active.size(); i++)
				Ships[sindex].glow_point_bank_active[i] = activate;
		}
	}
}

//-Bobboau
void sexp_activate_deactivate_glow_point_bank(int n, bool activate)
{
	int sindex, num;

	sindex = ship_name_lookup(CTEXT(n), 1);
	if (sindex >= 0)
	{
		for ( n = CDR(n); n != -1; n = CDR(n))
		{
			num = eval_num(n);
			if (num >= 0 && num < (int)Ships[sindex].glow_point_bank_active.size())
			{
				Ships[sindex].glow_point_bank_active[num] = activate;
			}
		}
	}
}

//-Bobboau
void sexp_activate_deactivate_glow_maps(int n, int activate)
{
	int sindex;
	ship *shipp;

	for ( ; n != -1; n = CDR(n))
	{
		sindex = ship_name_lookup(CTEXT(n), 1);
		if (sindex >= 0)
		{
			shipp = &Ships[sindex];

			if (activate)
				shipp->flags2 &= ~SF2_GLOWMAPS_DISABLED;
			else
				shipp->flags2 |= SF2_GLOWMAPS_DISABLED;
		}
	}
}

void sexp_set_ambient_light(int node)
{
	int red, green, blue; 
	int level = 0;

	Assert(node > -1);
	red = eval_num(node); 
	if (red < 0 || red > 255) {
		red = 0;
	}

	node = CDR(node); 
	Assert(node > -1);
	green = eval_num(node); 
	if (green < 0 || green > 255) {
		green = 0;
	}

	node = CDR(node); 
	Assert(node > -1);
	blue = eval_num(node); 
	if (blue < 0 || blue > 255) {
		blue = 0;
	}

	level |= red; 
	level |= green << 8;
	level |= blue << 16;

	// setting the ambient light level for the mission won't actually do anything as it is parsed at mission 
	// start but it should be updated in case someone changes that later
	The_mission.ambient_light_level = level; 

	// call the graphics function to actually set the level
	gr_set_ambient_light(red, green, blue);

	// do the multiplayer callback
	if (MULTIPLAYER_MASTER) {
		multi_start_callback();
		multi_send_int(level);
		multi_end_callback();
	}
}

void multi_sexp_set_ambient_light()
{
	int level = 0;
	if (multi_get_int(level)) {
		The_mission.ambient_light_level = level;
		gr_set_ambient_light((level & 0xff),((level >> 8) & 0xff), ((level >> 16) & 0xff));
	}
}

void sexp_set_post_effect(int node)
{
	char *name = CTEXT(node);

	if (name == NULL) {
		return;
	}

	int amount = eval_num(CDR(node));

	if (amount < 0 || amount > 100)
		amount = 0;

	gr_post_process_set_effect(name, amount);
}

// Goober5000
void sexp_set_skybox_orientation(int n)
{
	matrix m;
	angles a;

	a.p = fl_radians(eval_num(n) % 360);
	n = CDR(n);

	a.b = fl_radians(eval_num(n) % 360);
	n = CDR(n);

	a.h = fl_radians(eval_num(n) % 360);
	n = CDR(n);

	vm_angles_2_matrix(&m, &a);
	stars_set_background_orientation(&m);
}

// taylor - load and set a skybox model
void sexp_set_skybox_model(int n)
{
	char new_skybox_model[TOKEN_LENGTH+1]; //max input is TOKEN_LENGTH, +1 for NUL
	strcpy_s(new_skybox_model, CTEXT(n));
	int new_skybox_model_flags = DEFAULT_NMODEL_FLAGS;

	// check if we need to reset the animated texture timestamp
	n = CDR(n);
	if (n == -1 || is_sexp_true(n)) {
		Skybox_timestamp = game_get_overall_frametime();
	}

	if (n != -1) n = CDR(n);

	// gather any flags
	while (n != -1) {
		// this should check all entries in Skybox_flags
		if ( !stricmp("add-lighting", CTEXT(n) )) {
			new_skybox_model_flags &= ~MR_NO_LIGHTING;
		}
		else if ( !stricmp("no-transparency", CTEXT(n) )) {
			new_skybox_model_flags &= ~MR_ALL_XPARENT;
		}
		else if ( !stricmp("add-zbuffer", CTEXT(n) )) {
			new_skybox_model_flags &= ~MR_NO_ZBUFFER;
		}
		else if ( !stricmp("add-culling", CTEXT(n) )) {
			new_skybox_model_flags &= ~MR_NO_CULL;
		}
		else if ( !stricmp("no-glowmaps", CTEXT(n) )) {
			new_skybox_model_flags |= MR_NO_GLOWMAPS;
		}
		else if ( !stricmp("force-clamp", CTEXT(n) )) {
			new_skybox_model_flags |= MR_FORCE_CLAMP;
		}
		else {
			Warning(LOCATION, "Invalid flag passed to set-skybox-model: %s\n", CTEXT(n));
		}
		n = CDR(n);
	}
	if ( !stricmp("default", new_skybox_model )) {
		stars_set_background_model( The_mission.skybox_model, NULL, new_skybox_model_flags );
	} else {
		// stars_level_init() will set the actual mission skybox after this gets
		// evaluated during parse. by setting it now we get everything loaded so
		// there is less slowdown when it actually swaps out - taylor
		stars_set_background_model( new_skybox_model, NULL, new_skybox_model_flags );
	}
}

// taylor - preload a skybox model.  this doesn't set anything as viewable, just loads it into memory
void sexp_set_skybox_model_preload(char *name)
{
	int i;

	if ( !stricmp("default", name) ) {
		// if there isn't a mission skybox model then don't load one
		if ( strlen(The_mission.skybox_model) ) {
			i = model_load( The_mission.skybox_model, 0, NULL );
			model_page_in_textures( i );
		}
	} else {
		i = model_load( name, 0, NULL );
		model_page_in_textures( i );
	}
}

void sexp_beam_fire(int node, bool at_coords)
{
	int sindex, n = node;
	beam_fire_info fire_info;		
	int idx;

	// zero stuff out
	memset(&fire_info, 0, sizeof(beam_fire_info));
	fire_info.accuracy = 0.000001f;							// this will guarantee a hit

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(n));
	n = CDR(n);
	if (sindex < 0) {
		return;
	}
	if (Ships[sindex].objnum < 0) {
		return;
	}
	fire_info.shooter = &Objects[Ships[sindex].objnum];

	// get the subsystem
	fire_info.turret = ship_get_subsys(&Ships[sindex], CTEXT(n));
	n = CDR(n);
	if (fire_info.turret == NULL) {
		return;
	}

	if (at_coords) {
		// get the target coordinates
		fire_info.target_pos1.xyz.x = fire_info.target_pos2.xyz.x = static_cast<float>(eval_num(n));
		n = CDR(n);
		fire_info.target_pos1.xyz.y = fire_info.target_pos2.xyz.y = static_cast<float>(eval_num(n));
		n = CDR(n);
		fire_info.target_pos1.xyz.z = fire_info.target_pos2.xyz.z = static_cast<float>(eval_num(n));
		n = CDR(n);
		fire_info.bfi_flags |= BFIF_TARGETING_COORDS;
		fire_info.target = NULL;
		fire_info.target_subsys = NULL;
	} else {
		// get the target
		sindex = ship_name_lookup(CTEXT(n));
		n = CDR(n);
		if (sindex < 0) {
			return;
		}
		if (Ships[sindex].objnum < 0) {
			return;
		}
		fire_info.target = &Objects[Ships[sindex].objnum];

		// see if the optional subsystem can be found	
		fire_info.target_subsys = NULL;
		if (n >= 0) {
			fire_info.target_subsys = ship_get_subsys(&Ships[sindex], CTEXT(n));
			n = CDR(n);
		}
	}

	// optionally force firing
	if (n >= 0 && is_sexp_true(n)) {
		fire_info.bfi_flags |= BFIF_FORCE_FIRING;
		n = CDR(n);
	}

	// get the second set of coordinates
	if (at_coords) {
		if (n >= 0) {
			fire_info.target_pos2.xyz.x = static_cast<float>(eval_num(n));
			n = CDR(n);
		}
		if (n >= 0) {
			fire_info.target_pos2.xyz.y = static_cast<float>(eval_num(n));
			n = CDR(n);
		}
		if (n >= 0) {
			fire_info.target_pos2.xyz.z = static_cast<float>(eval_num(n));
			n = CDR(n);
		}
	}

	// --- done getting arguments ---

	// if it has no primary weapons
	if (fire_info.turret->weapons.num_primary_banks <= 0) {
		Warning(LOCATION, "Couldn't fire turret on ship %s; subsystem %s has no primary weapons", CTEXT(node), CTEXT(CDR(node)));
		return;
	}

	// if the turret is destroyed
	if (!(fire_info.bfi_flags & BFIF_FORCE_FIRING) && fire_info.turret->current_hits <= 0.0f) {
		return;
	}

	// hmm, this could be wacky. Let's just simply select the first beam weapon in the turret
	fire_info.beam_info_index = -1;	
	for (idx=0; idx<fire_info.turret->weapons.num_primary_banks; idx++) {
		Assertion(fire_info.turret->weapons.primary_bank_weapons[idx] >= 0 && fire_info.turret->weapons.primary_bank_weapons[idx] < MAX_WEAPON_TYPES,
				"sexp_beam_fire: found invalid weapon index (%i), get a coder\n!", fire_info.turret->weapons.primary_bank_weapons[idx]);
		// store the weapon info index
		if (Weapon_info[fire_info.turret->weapons.primary_bank_weapons[idx]].wi_flags & WIF_BEAM) {
			fire_info.beam_info_index = fire_info.turret->weapons.primary_bank_weapons[idx];
		}
	}

	// fire the beam
	if (fire_info.beam_info_index != -1) {
		beam_fire(&fire_info);
	} else {
		// it would appear the turret doesn't have any beam weapons
		Warning(LOCATION, "Couldn't fire turret on ship %s; subsystem %s has no beam weapons", CTEXT(node), CTEXT(CDR(node)));
	}
}	

void sexp_beam_floating_fire(int n)
{
	int sindex;
	beam_fire_info fire_info;
	memset(&fire_info, 0, sizeof(beam_fire_info));
	fire_info.accuracy = 0.000001f;							// this will guarantee a hit
	fire_info.bfi_flags |= BFIF_FLOATING_BEAM;
	fire_info.turret = NULL;		// A free-floating beam isn't fired from a subsystem.

	fire_info.beam_info_index = weapon_info_lookup(CTEXT(n));
	n = CDR(n);
	if (fire_info.beam_info_index < 0)
	{
		Warning(LOCATION, "Invalid weapon class passed to beam-create; weapon type '%s' does not exist!\n", CTEXT(n));
		return;
	}
	if (!(Weapon_info[fire_info.beam_info_index].wi_flags & WIF_BEAM)) {
		Warning(LOCATION, "Invalid weapon class passed to beam-create; weapon type '%s' is not a beam!\n", CTEXT(n));
		return;
	}

	fire_info.shooter = NULL;
	if (stricmp(CTEXT(n), SEXP_NONE_STRING))
	{
		sindex = ship_name_lookup(CTEXT(n));

		if (sindex >= 0)
			fire_info.shooter = &Objects[Ships[sindex].objnum];
	}
	n = CDR(n);

	fire_info.team = static_cast<char>(iff_lookup(CTEXT(n)));
	n = CDR(n);

	fire_info.starting_pos.xyz.x = static_cast<float>(eval_num(n));
	n = CDR(n);
	fire_info.starting_pos.xyz.y = static_cast<float>(eval_num(n));
	n = CDR(n);
	fire_info.starting_pos.xyz.z = static_cast<float>(eval_num(n));
	n = CDR(n);

	fire_info.target = NULL;
	fire_info.target_subsys = NULL;

	sindex = -1;
	if (stricmp(CTEXT(n), SEXP_NONE_STRING))
	{
		sindex = ship_name_lookup(CTEXT(n));

		if (sindex >= 0)
			fire_info.target = &Objects[Ships[sindex].objnum];
	} else {
		fire_info.bfi_flags |= BFIF_TARGETING_COORDS;
	}
	n = CDR(n);

	if (n >= 0)
	{
		if (stricmp(CTEXT(n), SEXP_NONE_STRING)) {
			if (sindex >= 0)
				fire_info.target_subsys = ship_get_subsys(&Ships[sindex], CTEXT(n));
		}

		n = CDR(n);
	}

	if (n >= 0) {
		fire_info.target_pos1.xyz.x = fire_info.target_pos2.xyz.x = static_cast<float>(eval_num(n));
		n = CDR(n);
	}
	if (n >= 0) {
		fire_info.target_pos1.xyz.y = fire_info.target_pos2.xyz.y = static_cast<float>(eval_num(n));
		n = CDR(n);
	}
	if (n >= 0) {
		fire_info.target_pos1.xyz.z = fire_info.target_pos2.xyz.z = static_cast<float>(eval_num(n));
		n = CDR(n);
	}

	if (n >= 0) {
		fire_info.target_pos2.xyz.x = static_cast<float>(eval_num(n));
		n = CDR(n);
	}
	if (n >= 0) {
		fire_info.target_pos2.xyz.y = static_cast<float>(eval_num(n));
		n = CDR(n);
	}
	if (n >= 0) {
		fire_info.target_pos2.xyz.z = static_cast<float>(eval_num(n));
		n = CDR(n);
	}

	beam_fire(&fire_info);
}

void sexp_beam_free(int node)
{
	int sindex;
	ship_subsys *turret = NULL;	

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	node = CDR(node);
	for ( ; node >= 0; node = CDR(node) ) {
		// get the subsystem
		turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
		if(turret == NULL){
			continue;
		}

		// flag it as beam free :)
		if (!(turret->weapons.flags & SW_FLAG_BEAM_FREE))
		{
			turret->weapons.flags |= SW_FLAG_BEAM_FREE;
			turret->turret_next_fire_stamp = timestamp((int) frand_range(50.0f, 4000.0f));
		}
	}
}

void sexp_set_thrusters(int node) 
{
	bool activate = is_sexp_true(node) > 0;
	node = CDR(node);

	for(; node >= 0; node = CDR(node)) {
		int sindex = ship_name_lookup(CTEXT(node));
		
		if (sindex < 0) {
			continue;
		}

		if (Ships[sindex].objnum < 0) {
			continue;
		}

		if (activate)
			Ships[sindex].flags2 &= ~SF2_NO_THRUSTERS;
		else
			Ships[sindex].flags2 |= SF2_NO_THRUSTERS;
	}
}

void sexp_beam_free_all(int node)
{
	ship_subsys *subsys;
	int sindex;

	for (int n = node; n >= 0; n = CDR(n)) {
		// get the firing ship
		sindex = ship_name_lookup( CTEXT(n) );

		if (sindex < 0) {
			continue;
		}

		if (Ships[sindex].objnum < 0) {
			continue;
		}

		// free all beam weapons
		subsys = GET_FIRST(&Ships[sindex].subsys_list);

		while ( subsys != END_OF_LIST(&Ships[sindex].subsys_list) ) {
			// just mark all turrets as beam free
			if ((subsys->system_info->type == SUBSYSTEM_TURRET) && (!(subsys->weapons.flags & SW_FLAG_BEAM_FREE)))
			{
				subsys->weapons.flags |= SW_FLAG_BEAM_FREE;
				subsys->turret_next_fire_stamp = timestamp((int) frand_range(50.0f, 4000.0f));
			}

			// next item
			subsys = GET_NEXT(subsys);
		}
	}
}

void sexp_beam_lock(int node)
{	
	int sindex;
	ship_subsys *turret = NULL;	

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	node = CDR(node);
	for ( ; node >= 0; node = CDR(node) ) {
		// get the subsystem
		turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
		if(turret == NULL){
			continue;
		}

		// flag it as not beam free
		turret->weapons.flags &= ~(SW_FLAG_BEAM_FREE);
	}
}

void sexp_beam_lock_all(int node)
{
	ship_subsys *subsys;
	int sindex;

	for (int n = node; n >= 0; n = CDR(n)) {
		// get the firing ship
		sindex = ship_name_lookup( CTEXT(n) );

		if (sindex < 0) {
			continue;
		}

		if (Ships[sindex].objnum < 0) {
			continue;
		}

		// lock all beam weapons
		subsys = GET_FIRST(&Ships[sindex].subsys_list);

		while ( subsys != END_OF_LIST(&Ships[sindex].subsys_list) ) {
			// just mark all turrets as not beam free
			if (subsys->system_info->type == SUBSYSTEM_TURRET) {
				subsys->weapons.flags &= ~(SW_FLAG_BEAM_FREE);
			}

			// next item
			subsys = GET_NEXT(subsys);
		}
	}
}

void sexp_turret_free(int node)
{
	int sindex;
	ship_subsys *turret = NULL;	

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	node = CDR(node);
	for ( ; node >= 0; node = CDR(node) ) {
		// get the subsystem
		turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
		if(turret == NULL){
			continue;
		}

		// flag turret as no longer locked :)
		if (turret->weapons.flags & SW_FLAG_TURRET_LOCK) 
		{
			turret->weapons.flags &= (~SW_FLAG_TURRET_LOCK);
			turret->turret_next_fire_stamp = timestamp((int) frand_range(50.0f, 4000.0f));
		}
	}
}

void sexp_turret_free_all(int node)
{
	ship_subsys *subsys;
	int sindex;

	for (int n = node; n >= 0; n = CDR(n)) {
		// get the firing ship
		sindex = ship_name_lookup( CTEXT(n) );

		if (sindex < 0) {
			continue;
		}

		if (Ships[sindex].objnum < 0) {
			continue;
		}

		// free all turrets
		subsys = GET_FIRST(&Ships[sindex].subsys_list);

		while ( subsys != END_OF_LIST(&Ships[sindex].subsys_list) ) {
			// just mark all turrets as free
			if ((subsys->system_info->type == SUBSYSTEM_TURRET) && (subsys->weapons.flags & SW_FLAG_TURRET_LOCK)) {
				subsys->weapons.flags &= (~SW_FLAG_TURRET_LOCK);
				subsys->turret_next_fire_stamp = timestamp((int) frand_range(50.0f, 4000.0f));
			}

			// next item
			subsys = GET_NEXT(subsys);
		}
	}
}

void sexp_turret_lock(int node)
{	
	int sindex;
	ship_subsys *turret = NULL;	

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	node = CDR(node);
	for ( ; node >= 0; node = CDR(node) ) {
		// get the subsystem
		turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
		if(turret == NULL){
			continue;
		}

		// flag turret as locked
		turret->weapons.flags |= SW_FLAG_TURRET_LOCK;
	}
}

void sexp_turret_lock_all(int node)
{
	ship_subsys *subsys;
	int sindex;

	for (int n = node; n >= 0; n = CDR(n)) {
		// get the firing ship
		sindex = ship_name_lookup( CTEXT(n) );

		if (sindex < 0) {
			continue;
		}

		if (Ships[sindex].objnum < 0) {
			continue;
		}

		// lock all turrets
		subsys = GET_FIRST(&Ships[sindex].subsys_list);

		while ( subsys != END_OF_LIST(&Ships[sindex].subsys_list) ) {
			// just mark all turrets as locked
			if (subsys->system_info->type == SUBSYSTEM_TURRET) {
				subsys->weapons.flags |= SW_FLAG_TURRET_LOCK;
			}

			// next item
			subsys = GET_NEXT(subsys);
		}
	}
}

void sexp_turret_tagged_only_all(int node)
{
	ship_subsys *subsys;
	int sindex;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	// mark all turrets to only target tagged ships
	subsys = GET_FIRST(&Ships[sindex].subsys_list);
	while(subsys != END_OF_LIST(&Ships[sindex].subsys_list)){
		// just mark all turrets as locked
		if(subsys->system_info->type == SUBSYSTEM_TURRET){
			subsys->weapons.flags |= SW_FLAG_TAGGED_ONLY;
		}

		// next item
		subsys = GET_NEXT(subsys);
	}
}

void sexp_turret_tagged_clear_all(int node)
{
	ship_subsys *subsys;
	int sindex;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	// mark all turrets so not restricted to only tagged ships
	subsys = GET_FIRST(&Ships[sindex].subsys_list);
	while(subsys != END_OF_LIST(&Ships[sindex].subsys_list)){
		// just mark all turrets as locked
		if(subsys->system_info->type == SUBSYSTEM_TURRET){
			subsys->weapons.flags &= (~SW_FLAG_TAGGED_ONLY);
		}

		// next item
		subsys = GET_NEXT(subsys);
	}
}

void sexp_turret_change_weapon(int node)
{	
	int sindex;
	int windex;	//hehe
	ship_subsys *turret = NULL;	
	ship_weapon *swp = NULL;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0 || Ships[sindex].objnum < 0){
		return;
	}

	//Get subsystem
	node = CDR(node);
	turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
	if(turret == NULL){
		return;
	}
	swp = &turret->weapons;

	node = CDR(node);
	windex = weapon_info_lookup(CTEXT(node));
	if(windex < 0) {
		return;
	}

	//Get the slot
	float capacity, size;
	int prim_slot = 0;
	int sec_slot = 0;

	node = CDR(node);
	prim_slot = eval_num(node);

	node = CDR(node);
	sec_slot = eval_num(node);

	if(prim_slot)
	{
		if(prim_slot > MAX_SHIP_PRIMARY_BANKS) {
			return;
		}

		if(prim_slot > swp->num_primary_banks) {
			swp->num_primary_banks++;
			prim_slot = swp->num_primary_banks;
		}

		//Get an index
		prim_slot--;

		//Get the max capacity
		capacity = (float) swp->primary_bank_capacity[prim_slot];
		size = (float) Weapon_info[windex].cargo_size;

		//Set various vars
		swp->primary_bank_start_ammo[prim_slot] = (int) (capacity / size);
		swp->primary_bank_ammo[prim_slot] = swp->primary_bank_start_ammo[prim_slot];
		swp->primary_bank_weapons[prim_slot] = windex;
		swp->primary_bank_rearm_time[prim_slot] = timestamp(0);
		swp->primary_bank_fof_cooldown[prim_slot] = 0.0f;
	}
	else if(sec_slot)
	{
		if(sec_slot > MAX_SHIP_PRIMARY_BANKS) {
			return;
		}

		if(sec_slot > swp->num_secondary_banks) {
			swp->num_secondary_banks++;
			sec_slot = swp->num_secondary_banks;
		}

		//Get an index
		sec_slot--;

		//Get the max capacity
		capacity = (float) swp->secondary_bank_capacity[sec_slot];
		size = (float) Weapon_info[windex].cargo_size;

		//Set various vars
		swp->secondary_bank_start_ammo[sec_slot] = (int) (capacity / size);
		swp->secondary_bank_ammo[sec_slot] = swp->secondary_bank_start_ammo[sec_slot];
		swp->secondary_bank_weapons[sec_slot] = windex;
		swp->secondary_bank_rearm_time[sec_slot] = timestamp(0);
	}
}

void sexp_set_armor_type(int node)
{	
	int sindex;
	int armor, rset;
	ship_subsys *ss = NULL;
	ship *shipp = NULL;
	ship_info *sip = NULL;

	// get ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0) {
		return;
	}
	if(Ships[sindex].objnum < 0) {
		return;
	}
	shipp = &Ships[sindex];
	sip = &Ship_info[shipp->ship_info_index];

	// set or reset
	node = CDR(node);
	rset = is_sexp_true(node);

	// get armor
	node = CDR(node);
	if (!stricmp(SEXP_NONE_STRING, CTEXT(node))) {
		armor = -1;
	} else {
		armor = armor_type_get_idx(CTEXT(node));
	}
	
	//Set armor
	while(node != -1)
	{
		if (!stricmp(SEXP_HULL_STRING, CTEXT(node)))
		{
			// we are setting the ship itself
			if (!rset)
				shipp->armor_type_idx = sip->armor_type_idx;
			else
				shipp->armor_type_idx = armor;
		}
		else if (!stricmp(SEXP_SHIELD_STRING, CTEXT(node)))
		{
			// we are setting the ships shields
			if (!rset)
				shipp->shield_armor_type_idx = sip->shield_armor_type_idx;
			else
				shipp->shield_armor_type_idx = armor;
		}
		else 
		{
			// get the subsystem
			ss = ship_get_subsys(&Ships[sindex], CTEXT(node));
			if(ss == NULL){
				node = CDR(node);
				continue;
			}
		
			// set the range
			if (!rset)
				ss->armor_type_idx = ss->system_info->armor_type_idx;
			else
				ss->armor_type_idx = armor;
		}
		// next
		node = CDR(node);
	}
}

void sexp_weapon_set_damage_type(int node)
{	
	int windex, damage, swave, rset;
	size_t t;

	// weapon or shockwave
	swave = is_sexp_true(node);

	// get damage type
	node = CDR(node);
	if (!stricmp(SEXP_NONE_STRING, CTEXT(node)))
		damage = -1;
	else 
	{
		for(t = 0; t < Damage_types.size(); t++) 
		{
			if ( !stricmp(Damage_types[t].name, CTEXT(node)))  
				break;
		}
		if (t == Damage_types.size()) 
			return;
		damage = (int)t;
	}

	//Set or reset to defualt
	node = CDR(node);
	rset = is_sexp_true(node);
	
	//Set Damage
	node = CDR(node);
	while(node != -1)
	{
		// get the weapon
		windex = weapon_info_lookup(CTEXT(node));
		if(windex >= 0) 
		{
			// set the damage type
			if (swave)
				if (!rset)
					Weapon_info[windex].damage_type_idx = Weapon_info[windex].damage_type_idx_sav;
				else
					Weapon_info[windex].damage_type_idx = damage;
			else
				if (!rset)
					Weapon_info[windex].shockwave.damage_type_idx = Weapon_info[windex].shockwave.damage_type_idx_sav;
				else
					Weapon_info[windex].shockwave.damage_type_idx = damage;
		// next
		}
		node = CDR(node);
	}
}

void sexp_ship_set_damage_type(int node)
{	
	int sindex, damage, debris, rset;
	size_t t;
	ship *shipp = NULL;

	// collision or debris
	debris = is_sexp_true(node);

	// get damage type
	node = CDR(node);
	if (!stricmp(SEXP_NONE_STRING, CTEXT(node)))
		damage = -1;
	else 
	{
		for(t = 0; t < Damage_types.size(); t++) 
		{
			if ( !stricmp(Damage_types[t].name, CTEXT(node)))  
				break;
		}
		if (t == Damage_types.size()) 
			return;
		damage = (int)t;
	}

	//Set or reset to defualt
	node = CDR(node);
	rset = is_sexp_true(node);
	
	//Set Damage
	node = CDR(node);
	while(node != -1)
	{
		// get the ship
		sindex = ship_name_lookup(CTEXT(node));
		if(sindex >= 0) 
		{
			shipp = &Ships[sindex];
			// set the damage type
			if (debris)
			{
				if (!rset)
					shipp->collision_damage_type_idx = Ship_info[shipp->ship_info_index].collision_damage_type_idx;
				else
					shipp->collision_damage_type_idx = damage;
			}
			else 
			{
				if (!rset)
					shipp->debris_damage_type_idx = Ship_info[shipp->ship_info_index].debris_damage_type_idx;
				else
					shipp->debris_damage_type_idx = damage;
			}
			// next
		}
		node = CDR(node);
	}
}
void sexp_ship_shockwave_set_damage_type(int node)
{	
	int sindex, damage, rset;
	size_t t;

	// get damage type
	if (!stricmp(SEXP_NONE_STRING, CTEXT(node)))
		damage = -1;
	else 
	{
		for(t = 0; t < Damage_types.size(); t++) 
		{
			if ( !stricmp(Damage_types[t].name, CTEXT(node)))  
				break;
		}
		if (t == Damage_types.size()) 
			return;
		damage = (int)t;
	}

	//Set or reset to defualt
	node = CDR(node);
	rset = is_sexp_true(node);
	
	//Set Damage
	node = CDR(node);
	while(node != -1)
	{
		// get the ship
		sindex = ship_info_lookup(CTEXT(node));
		if(sindex >= 0) 
		{
			// set the damage type
			if (!rset)
				Ship_info[sindex].shockwave.damage_type_idx = Ship_info[sindex].shockwave.damage_type_idx_sav;
			else
				Ship_info[sindex].shockwave.damage_type_idx = damage;
			// next
		}
		node = CDR(node);
	}
}
void sexp_field_set_damage_type(int node)
{	
	int damage, rset;
	size_t t;

	// get damage type
	if (!stricmp(SEXP_NONE_STRING, CTEXT(node)))
		damage = -1;
	else 
	{
		for(t = 0; t < Damage_types.size(); t++) 
		{
			if ( !stricmp(Damage_types[t].name, CTEXT(node)))  
				break;
		}
		if (t == Damage_types.size()) 
			return;
		damage = (int)t;
	}

	//Set or reset to defualt
	node = CDR(node);
	rset = is_sexp_true(node);
	
	//Set Damage
	node = CDR(node);
	for(t = 0; t < Asteroid_info.size(); t++) 
	if (!rset)
		Asteroid_info[t].damage_type_idx = Asteroid_info[t].damage_type_idx_sav;
	else
		Asteroid_info[t].damage_type_idx = damage;
}
void sexp_turret_set_target_order(int node)
{	
	int sindex;
	ship_subsys *turret = NULL;	
	int oindex;
	int i;

	// get ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	//Get turret subsys
	node = CDR(node);
	turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
	if(turret == NULL){
		return;
	}

	//Reset order
	for(i = 0; i < NUM_TURRET_ORDER_TYPES; i++) {
		turret->turret_targeting_order[i] = -1;
	}
	
	oindex = 0;
	node = CDR(node);
	while(node != -1)
	{
		if(oindex >= NUM_TURRET_ORDER_TYPES) {
			break;
		}

		for(i = 0; i < NUM_TURRET_ORDER_TYPES; i++) {
			if(!stricmp(Turret_target_order_names[i], CTEXT(node))) {
				turret->turret_targeting_order[oindex] = i;
			}
		}

		oindex++;
		node = CDR(node);
	}
}
void sexp_turret_set_direction_preference(int node)
{	
	int sindex;
	ship_subsys *turret = NULL;	
	
	// get ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	//store direction preference
	node = CDR(node);
	int dirpref = eval_num(node);
	node = CDR(node);

	//Set range
	while(node != -1){
		// get the subsystem
		turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
		if(turret == NULL){
			node = CDR(node);
			continue;
		}

		// set the range
		if(dirpref < 0)
			turret->optimum_range = turret->system_info->optimum_range;
		else
			if (dirpref == 0) {
				turret->favor_current_facing = 0.0f;
			} else {
				CAP(dirpref, 1, 100);
				turret->favor_current_facing = 1.0f + (((float) (100 - dirpref)) / 10.0f);
			}
		
		// next
		node = CDR(node);
	}
}

void sexp_turret_set_rate_of_fire(int node)
{	
	int sindex;
	ship_subsys *turret = NULL;	
	
	// get ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	//store rof
	node = CDR(node);
	float rof = (float)eval_num(node);
	node = CDR(node);

	//Set rof
	while(node != -1){
		// get the subsystem
		turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
		if(turret == NULL){
			node = CDR(node);
			continue;
		}

		// set the range
		if(rof < 0)
			turret->rof_scaler = turret->system_info->turret_rof_scaler ;
		else
			turret->rof_scaler = rof/100;
		
		// next
		node = CDR(node);
	}
}

void sexp_turret_set_optimum_range(int node)
{	
	int sindex;
	ship_subsys *turret = NULL;	
	
	// get ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	//store range
	node = CDR(node);
	float range = (float)eval_num(node);
	node = CDR(node);

	//Set range
	while(node != -1){
		// get the subsystem
		turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
		if(turret == NULL){
			node = CDR(node);
			continue;
		}

		// set the range
		if(range < 0)
			turret->optimum_range = turret->system_info->optimum_range;
		else
			turret->optimum_range = range;
		
		// next
		node = CDR(node);
	}
}

void sexp_turret_set_target_priorities(int node)
{	
	int sindex;
	ship_subsys *turret = NULL;	
	int i;
	int j;

	// get ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	//Get turret subsys
	node = CDR(node);
	turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
	if(turret == NULL){
		return;
	}

	//Reset or new list
	node = CDR(node);   
	if(!(is_sexp_true(node))) {	//Reset
		turret->num_target_priorities = turret->system_info->num_target_priorities;
		for (j = 0; j < 32; j++) {
			turret->target_priority[j] = turret->system_info->target_priority[j];
		}
	}
	else {					//New List
		node = CDR(node);
		//clear the list
		turret->num_target_priorities = 0;
		for (i = 0; i < 32; i++) {
			turret->target_priority[i] = -1;
		}
		int num_groups = Ai_tp_list.size();
		// set the target priorities
		while(node != -1){
			if(turret->num_target_priorities < 32){
				for(j = 0; j < num_groups; j++) {
					if ( !stricmp(Ai_tp_list[j].name, CTEXT(node)))  {
							turret->target_priority[turret->num_target_priorities] = j;
							turret->num_target_priorities++;
					}
				}
			}
		// next
		node = CDR(node);
		}
	}
}

void sexp_ship_turret_target_order(int node)
{	
	int sindex;
	ship_subsys *turret = NULL;	
	int oindex;
	int i;
	int new_target_order[NUM_TURRET_ORDER_TYPES];

	// get ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}
	
	//Reset order
	for(i = 0; i < NUM_TURRET_ORDER_TYPES; i++) {
		new_target_order[i] = -1;
	}

	oindex = 0;
	node = CDR(node);
	while(node != -1)
	{
		if(oindex >= NUM_TURRET_ORDER_TYPES) {
			break;
		}

		for(i = 0; i < NUM_TURRET_ORDER_TYPES; i++) {
			if(!stricmp(Turret_target_order_names[i], CTEXT(node))) {
				new_target_order[oindex] = i;
			}
		}

		oindex++;
		node = CDR(node);
	}

	turret = GET_FIRST(&Ships[sindex].subsys_list);
	while(turret != END_OF_LIST(&Ships[sindex].subsys_list))
	{
		memcpy(turret->turret_targeting_order, new_target_order, NUM_TURRET_ORDER_TYPES*sizeof(int));

		// next item
		turret = GET_NEXT(turret);
	}
}

// DahBlount
int sexp_get_turret_primary_ammo(int node)
{
	int sindex;
	ship_subsys *turret = NULL;
	ship_weapon *swp;
	int bank, check, ammo_left = 0;

	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0) {
		return 0;
	}
	if (Ships[sindex].objnum < 0) {
		return 0;
	}

	node = CDR(node);

	turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
	if (turret == NULL) {
		return 0;
	}
	if (!(turret->system_info->flags2 & MSS_FLAG2_TURRET_USE_AMMO)) {
		return 0;
	}

	swp = &turret->weapons;

	node = CDR(node);

	check = eval_num(node);
	if (check < 0) {
		return 0;
	}

	if (check >= swp->num_primary_banks)
	{
		for (bank = 0; bank < swp->num_primary_banks; bank++)
		{
			// Only ballistic weapons need to be counted
			if (Weapon_info[swp->primary_bank_weapons[bank]].wi_flags2 & WIF2_BALLISTIC)
			{
				ammo_left += swp->primary_bank_ammo[bank];
			}
		}
	} else {
		// Again only ballistic weapons need to be counted
		if (Weapon_info[swp->primary_bank_weapons[check]].wi_flags2 & WIF2_BALLISTIC)
		{
			ammo_left = swp->primary_bank_ammo[check];
		}
	}

	return ammo_left;
}

// DahBlount - Sets a turrets primary ammo capacity
void sexp_set_turret_primary_ammo(int node)
{
	int sindex;
	ship_subsys *turret = NULL;
	int requested_bank;
	int requested_weapons;

	// Check that a ship has been supplied
	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0)
	{
		return;
	}

	node = CDR(node);

	// Get the turret
	char *subsys = CTEXT(node);
	turret = ship_get_subsys(&Ships[sindex], subsys);
	if (turret == NULL) {
		return;
	}

	node = CDR(node);

	// Get the bank to set the number on
	requested_bank = eval_num(node);
	if (requested_bank < 0)
	{
		return;
	}

	//  Get the number of weapons requested	
	node = CDR(node);
	requested_weapons = eval_num(node);
	if (requested_weapons < 0)
	{
		return;
	}

	set_turret_primary_ammo(turret, requested_bank, requested_weapons);

	// Multiplayer call back
	multi_start_callback();
	multi_send_int(sindex);
	multi_send_string(subsys);
	multi_send_int(requested_bank);
	multi_send_int(requested_weapons);
	multi_end_callback();
}

void multi_sexp_set_turret_primary_ammo()
{
	int sindex, requested_bank, requested_weapons;
	char subsys[TOKEN_LENGTH];
	multi_get_int(sindex);
	multi_get_string(subsys);
	multi_get_int(requested_bank);
	multi_get_int(requested_weapons);

	ship_subsys *turret = ship_get_subsys(&Ships[sindex], subsys);

	set_turret_primary_ammo(turret, requested_bank, requested_weapons);
}

// DahBlount - Helper function for setting turret primary ammo
void set_turret_primary_ammo(ship_subsys *turret, int requested_bank, int requested_ammo, bool update)
{
	// Can only set one bank at a time. Check that someone hasn't asked for the contents of all 
	// the banks or a non-existant bank
	if ((requested_bank > turret->weapons.num_primary_banks) || requested_bank < 0)
	{
		return;
	}

	// Check that this isn't a non-ballistic bank as it's pointless to set the amount of ammo for those
	if (!(Weapon_info[turret->weapons.primary_bank_weapons[requested_bank]].wi_flags2 & WIF2_BALLISTIC))
	{
		return;
	}

	if (requested_ammo < 0)
	{
		return;
	}

	// Is the number requested larger than the maximum allowed for that particular bank? 
	int maximum_allowed = fl2i(turret->weapons.primary_bank_capacity[requested_bank]
		/ Weapon_info[turret->weapons.primary_bank_weapons[requested_bank]].cargo_size);
	if (maximum_allowed < requested_ammo)
	{
		requested_ammo = maximum_allowed;
	}

	// Set the number of weapons
	turret->weapons.primary_bank_ammo[requested_bank] = requested_ammo;
}

// DahBlount - Gets a turrets secondary ammo capacity
int sexp_get_turret_secondary_ammo(int node)
{
	int sindex;
	ship_subsys *turret = NULL;
	ship_weapon *swp;
	int bank, check, ammo_left = 0;

	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0) {
		return 0;
	}
	if (Ships[sindex].objnum < 0) {
		return 0;
	}

	node = CDR(node);

	turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
	if (turret == NULL) {
		return 0;
	}
	if (!(turret->system_info->flags2 & MSS_FLAG2_TURRET_USE_AMMO)) {
		return 0;
	}

	swp = &turret->weapons;

	node = CDR(node);

	check = eval_num(node);
	if (check < 0) {
		return 0;
	}

	if (check >= swp->num_secondary_banks)
	{
		for (bank = 0; bank < swp->num_secondary_banks; bank++)
		{
			ammo_left += swp->secondary_bank_ammo[bank];
		}
	} else {
		ammo_left = swp->primary_bank_ammo[check];
	}

	return ammo_left;
}

// DahBlount - Sets a turrets secondary ammo capacity
void sexp_set_turret_secondary_ammo(int node)
{
	int sindex;
	ship_subsys *turret = NULL;
	int requested_bank;
	int requested_weapons;

	// Check that a ship has been supplied
	sindex = ship_name_lookup(CTEXT(node));
	if (sindex < 0)
	{
		return;
	}

	node = CDR(node);

	// Get the turret
	char *subsys = CTEXT(node);
	turret = ship_get_subsys(&Ships[sindex], subsys);
	if (turret == NULL) {
		return;
	}

	node = CDR(node);

	// Get the bank to set the number on
	requested_bank = eval_num(node);
	if (requested_bank < 0)
	{
		return;
	}

	//  Get the number of weapons requested

	node = CDR(node);

	requested_weapons = eval_num(node);
	if (requested_weapons < 0)
	{
		return;
	}

	set_turret_secondary_ammo(turret, requested_bank, requested_weapons);

	// Multiplayer call back
	multi_start_callback();
	multi_send_int(sindex);
	multi_send_string(subsys);
	multi_send_int(requested_bank);
	multi_send_int(requested_weapons);
	multi_end_callback();
}

void multi_sexp_set_turret_secondary_ammo()
{
	int sindex, requested_bank, requested_weapons;
	char subsys[TOKEN_LENGTH];
	multi_get_int(sindex);
	multi_get_string(subsys);
	multi_get_int(requested_bank);
	multi_get_int(requested_weapons);

	ship_subsys *turret = ship_get_subsys(&Ships[sindex], subsys);

	set_turret_secondary_ammo(turret, requested_bank, requested_weapons);
}

// DahBlount - Helper function for setting turret secondary ammo
void set_turret_secondary_ammo(ship_subsys *turret, int requested_bank, int requested_ammo, bool update)
{
	// Can only set one bank at a time. Check that someone hasn't asked for the contents of all 
	// the banks or a non-existant bank
	if ((requested_bank > turret->weapons.num_secondary_banks) || requested_bank < 0)
	{
		return;
	}

	if (requested_ammo < 0)
	{
		return;
	}

	// Is the number requested larger than the maximum allowed for that particular bank? 
	int maximum_allowed = fl2i(turret->weapons.secondary_bank_capacity[requested_bank]
		/ Weapon_info[turret->weapons.secondary_bank_weapons[requested_bank]].cargo_size);
	if (maximum_allowed < requested_ammo)
	{
		requested_ammo = maximum_allowed;
	}

	// Set the number of weapons
	turret->weapons.secondary_bank_ammo[requested_bank] = requested_ammo;
}

// Goober5000
void sexp_set_subsys_rotation_lock_free(int node, int locked)
{
	int ship_num;		
	ship_subsys *rotate;

	// get the ship
	ship_num = ship_name_lookup(CTEXT(node));
	if (ship_num < 0)
		return;
	
	if (Ships[ship_num].objnum < 0)
		return;

	node = CDR(node);

	// loop for all specified subsystems
	for ( ; node >= 0; node = CDR(node) )
	{
		// get the rotating subsystem
		rotate = ship_get_subsys(&Ships[ship_num], CTEXT(node));
		if (rotate == NULL)
			continue;

		// set rotate or not, depending on flag
		if (locked)
		{
			rotate->flags &= ~SSF_ROTATES;
			if (rotate->subsys_snd_flags & SSSF_ROTATE)
			{
				obj_snd_delete_type(Ships[ship_num].objnum, rotate->system_info->rotation_snd, rotate);
				rotate->subsys_snd_flags &= ~SSSF_ROTATE;
			}
		}
		else
		{
			rotate->flags |= SSF_ROTATES;
			if (rotate->system_info->rotation_snd >= 0)
			{
				obj_snd_assign(Ships[ship_num].objnum, rotate->system_info->rotation_snd, &rotate->system_info->pnt, 0, OS_SUBSYS_ROTATION, rotate);
				rotate->subsys_snd_flags |= SSSF_ROTATE;
			}
		}
	}
}

// Goober5000
void sexp_reverse_rotating_subsystem(int node)
{
	int ship_num;
	ship_subsys *rotate;

	// get the ship
	ship_num = ship_name_lookup(CTEXT(node));
	if (ship_num < 0)
		return;
	
	if (Ships[ship_num].objnum < 0)
		return;

	node = CDR(node);

	// loop for all specified subsystems
	for ( ; node >= 0; node = CDR(node) )
	{
		// get the rotating subsystem
		rotate = ship_get_subsys(&Ships[ship_num], CTEXT(node));
		if (rotate == NULL)
			continue;

		// switch direction of rotation
		rotate->turn_rate *= -1.0f;
		rotate->submodel_info_1.cur_turn_rate *= -1.0f;
		rotate->submodel_info_1.desired_turn_rate *= -1.0f;
	}
}

// Goober5000
void sexp_rotating_subsys_set_turn_time(int node)
{
	int ship_num, n = node;
	float turn_time, turn_accel;
	ship_subsys *rotate;

	// get the ship
	ship_num = ship_name_lookup(CTEXT(n));
	if (ship_num < 0)
		return;
	if (Ships[ship_num].objnum < 0)
		return;
	n = CDR(n);

	// get the rotating subsystem
	rotate = ship_get_subsys(&Ships[ship_num], CTEXT(n));
	if (rotate == NULL)
		return;
	n = CDR(n);

	// get and set the turn time
	turn_time = eval_num(n) / 1000.0f;
	rotate->submodel_info_1.desired_turn_rate = PI2 / turn_time;
	n = CDR(n);

	// maybe get and set the turn accel
	if (n != -1)
	{
		turn_accel = eval_num(n) / 1000.0f;
		rotate->submodel_info_1.turn_accel = PI2 / turn_accel;
	}
	else
		rotate->submodel_info_1.cur_turn_rate = PI2 / turn_time;
}

void sexp_trigger_submodel_animation(int node)
{
	int ship_num, animation_type, animation_subtype, direction, n = node;
	bool instant;

	// get the ship
	ship_num = ship_name_lookup(CTEXT(n));
	if (ship_num < 0)
		return;
	if (Ships[ship_num].objnum < 0)
		return;
	n = CDR(n);

	// get the type
	animation_type = model_anim_match_type(CTEXT(n));
	if (animation_type == TRIGGER_TYPE_NONE)
	{
		Warning(LOCATION, "Unable to match animation type \"%s\"!", CTEXT(n));
		return;
	}
	n = CDR(n);

	// get the subtype
	animation_subtype = eval_num(n);
	n = CDR(n);

	// get the direction, 1 or -1
	direction = eval_num(n);
	if (direction != 1 && direction != -1)
	{
		Warning(LOCATION, "Direction is %d; it must be 1 or -1!", direction);
		return;
	}
	n = CDR(n);

	// instant or not
	if (n >= 0)
	{
		instant = (is_sexp_true(n) != 0);
		n = CDR(n);
	}
	else
		instant = false;

	// do we narrow it to a specific subsystem?
	if (n >= 0)
	{
		ship_subsys *ss = ship_get_subsys(&Ships[ship_num], CTEXT(n));
		if (ss == NULL)
		{
			Warning(LOCATION, "Subsystem \"%s\" not found on ship \"%s\"!", CTEXT(n), CTEXT(node));
			return;
		}
		model_anim_start_type(ss, animation_type, animation_subtype, direction, instant);
	}
	else
	{
		model_anim_start_type(&Ships[ship_num], animation_type, animation_subtype, direction, instant);
	}
}

void sexp_turret_tagged_specific(int node)
{
	ship_subsys *subsys;
	int sindex;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	node = CDR(node);
	for ( ; node >= 0; node = CDR(node) ) {
		// get the subsystem
		subsys = ship_get_subsys(&Ships[sindex], CTEXT(node));
		if(subsys == NULL){
			continue;
		}

		// flag turret as slaved to tag
		subsys->weapons.flags |= SW_FLAG_TAGGED_ONLY;
	}
}

void sexp_turret_tagged_clear_specific(int node)
{
	ship_subsys *subsys;
	int sindex;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	node = CDR(node);
	for ( ; node >= 0; node = CDR(node) ) {
		// get the subsystem
		subsys = ship_get_subsys(&Ships[sindex], CTEXT(node));
		if(subsys == NULL){
			continue;
		}

		// flag turret as slaved to tag
		subsys->weapons.flags &= (~SW_FLAG_TAGGED_ONLY);
	}
}

void sexp_add_remove_escort(int node)
{
	int sindex;
	int flag;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}

	// determine whether to add or remove it
	flag = eval_num(CDR(node));

	// add/remove
	if(flag){
		Ships[sindex].escort_priority = flag ;	
		hud_add_ship_to_escort(Ships[sindex].objnum, 1);
	} else {
		hud_remove_ship_from_escort(Ships[sindex].objnum);
	}

	multi_start_callback();
	multi_send_int(sindex);
	multi_send_int(flag); 
	multi_end_callback();
}

void multi_sexp_add_remove_escort()
{
	int sindex;
	int flag;

	multi_get_int(sindex); 
	if (!(multi_get_int(flag))) {
		return;
	}

	// add/remove
	if(flag){
		Ships[sindex].escort_priority = flag ;	
		hud_add_ship_to_escort(Ships[sindex].objnum, 1);
	} else {
		hud_remove_ship_from_escort(Ships[sindex].objnum);
	}
}

//given: two escort priorities and a list of ships
//do:    sets the most damaged one to the first priority and the rest to the second.
void sexp_damage_escort_list(int node)
{
	int n;
	int priority1;		//escort priority to set the most damaged ship
	int priority2;		//""         ""   to set the other ships

	ship* shipp;
	float smallest_hull_pct=1;		//smallest hull pct found
	int small_shipnum=-1;		//index in Ships[] of the above
	float current_hull_pct;			//hull pct of current ship we are evaluating
	int shipnum=-1;				//index in Ships[] of the above

	priority1=eval_num(node);
	priority2=eval_num(CDR(node));

	//go to start of ship list
	n=CDR(CDR(node));
	
	//loop through the ships
	for ( ; n != -1; n = CDR(n) )
	{
		// check to see if ship destroyed or departed.  In either case, do nothing.
		if ( mission_log_get_time(LOG_SHIP_DEPARTED, CTEXT(n), NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, CTEXT(n), NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, CTEXT(n), NULL, NULL) )
			continue;

		shipnum=ship_name_lookup(CTEXT(n));
		
		//it may be dead
		if (shipnum < 0)
			continue;

		if (Ships[shipnum].objnum < 0)
			continue;

		shipp=&Ships[shipnum];

		//calc hull integrity and compare
		current_hull_pct = get_hull_pct(&Objects[Ships[shipnum].objnum]);

		if (current_hull_pct < smallest_hull_pct)
		{
			if (small_shipnum != -1) // avoid negative array index during 1st loop iteration
			{
				Ships[small_shipnum].escort_priority=priority2;		//give the previous smallest the lower priority
			}
			
			smallest_hull_pct=current_hull_pct;
			small_shipnum=shipnum;
	
			shipp->escort_priority=priority1;					//give the new smallest the higher priority
			hud_add_ship_to_escort(Ships[shipnum].objnum,1);
		}
		else														//if its bigger to begin with give it lower priority
		{
			shipp->escort_priority=priority2;
			hud_add_ship_to_escort(Ships[shipnum].objnum,1);
		}
	}
}

// Goober5000 - set stuff for mission support ship
void sexp_set_support_ship(int n)
{
	int i, temp_val;

	// get arrival location
	temp_val = -1;
	for (i=0; i<MAX_ARRIVAL_NAMES; i++)
	{
		if (!stricmp(CTEXT(n), Arrival_location_names[i]))
			temp_val = i;
	}
	if (temp_val < 0)
	{
		Warning(LOCATION, "Support ship arrival location '%s' not found.\n", CTEXT(n));
		return;
	}
	The_mission.support_ships.arrival_location = temp_val;

	// get arrival anchor
	n = CDR(n);
	if (!stricmp(CTEXT(n), "<no anchor>"))
	{
		// if no anchor, set arrival location to hyperspace
		The_mission.support_ships.arrival_location = 0;
	}
	else
	{
		// anchor must exist - look for it
		temp_val = -1;
		for (i=0; i<Num_parse_names; i++)
		{
			if (!stricmp(CTEXT(n), Parse_names[i]))
				temp_val = i;
		}
		// if not found, make a new entry
		if (temp_val < 0)
		{
			strcpy_s(Parse_names[Num_parse_names], CTEXT(n));
			temp_val = Num_parse_names;
			Num_parse_names++;
		}
		The_mission.support_ships.arrival_anchor = temp_val;
	}

	// get departure location
	n = CDR(n);
	temp_val = -1;
	for (i=0; i<MAX_DEPARTURE_NAMES; i++)
	{
		if (!stricmp(CTEXT(n), Departure_location_names[i]))
			temp_val = i;
	}
	if (temp_val < 0)
	{
		Warning(LOCATION, "Support ship departure location '%s' not found.\n", CTEXT(n));
		return;
	}
	The_mission.support_ships.departure_location = temp_val;

	// get departure anchor
	n = CDR(n);
	if (!stricmp(CTEXT(n), "<no anchor>"))
	{
		// if no anchor, set departure location to hyperspace
		The_mission.support_ships.departure_location = 0;
	}
	else
	{
		// anchor must exist - look for it
		temp_val = -1;
		for (i=0; i<Num_parse_names; i++)
		{
			if (!stricmp(CTEXT(n), Parse_names[i]))
				temp_val = i;
		}
		// if not found, make a new entry
		if (temp_val < 0)
		{
			strcpy_s(Parse_names[Num_parse_names], CTEXT(n));
			temp_val = Num_parse_names;
			Num_parse_names++;
		}
		The_mission.support_ships.departure_anchor = temp_val;
	}

	// get ship class
	n = CDR(n);
	temp_val = ship_info_lookup(CTEXT(n));
	if ((temp_val < 0) && ((stricmp(CTEXT(n), "<species support ship class>")) && (stricmp(CTEXT(n), "<any support ship class>"))) )
	{
		Warning(LOCATION, "Support ship class '%s' not found.\n", CTEXT(n));
		return;
	}
	if ((temp_val >= 0) && !(Ship_info[temp_val].flags & SIF_SUPPORT))
	{
		Warning(LOCATION, "Ship %s is not a support ship!", Ship_info[temp_val].name);
		return;
	}
	The_mission.support_ships.ship_class = temp_val;

	// get max number of ships allowed
	n = CDR(n);
	The_mission.support_ships.max_support_ships = eval_num(n);

	// get the number of concurrent ships allowed
	n = CDR(n);
	if ( n == -1 ) {
		// 7th arg not specified, set default
		The_mission.support_ships.max_concurrent_ships = 1;
	} else {
		The_mission.support_ships.max_concurrent_ships = eval_num(n);
	}
}

// Goober5000 - set stuff for arriving ships or wings
void sexp_set_arrival_info(int node)
{
	int i, arrival_location, arrival_anchor, arrival_mask, arrival_distance, arrival_delay, n = node;
	bool show_warp;
	object_ship_wing_point_team oswpt;

	// get ship or wing
	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));
	n = CDR(n);

	// get arrival location
	arrival_location = -1;
	for (i=0; i<MAX_ARRIVAL_NAMES; i++)
	{
		if (!stricmp(CTEXT(n), Arrival_location_names[i]))
			arrival_location = i;
	}
	if (arrival_location < 0)
	{
		Warning(LOCATION, "Arrival location '%s' not found.\n", CTEXT(n));
		return;
	}
	n = CDR(n);

	// get arrival anchor
	arrival_anchor = -1;
	if ((n < 0) || !stricmp(CTEXT(n), "<no anchor>"))
	{
		// if no anchor, set arrival location to hyperspace
		arrival_location = 0;
	}
	else
	{
		// anchor must exist - look for it
		for (i=0; i<Num_parse_names; i++)
		{
			if (!stricmp(CTEXT(n), Parse_names[i]))
				arrival_anchor = i;
		}
		// if not found, make a new entry
		if (arrival_anchor < 0)
		{
			strcpy_s(Parse_names[Num_parse_names], CTEXT(n));
			arrival_anchor = Num_parse_names;
			Num_parse_names++;
		}
	}
	n = CDR(n);

	// get arrival path mask
	arrival_mask = 0;
	if (n >= 0)
		arrival_mask = eval_num(n);
	n = CDR(n);

	// get arrival distance
	arrival_distance = 0;
	if (n >= 0)
		arrival_distance = eval_num(n);
	n = CDR(n);

	// get arrival delay
	arrival_delay = 0;
	if (n >= 0)
		arrival_delay = eval_num(n);
	n = CDR(n);

	// get warp effect
	show_warp = true;
	if (n >= 0)
		show_warp = (is_sexp_true(n) != 0);

	// now set all that information depending on the first argument
	if (oswpt.type == OSWPT_TYPE_SHIP)
	{
		oswpt.shipp->arrival_location = arrival_location;
		oswpt.shipp->arrival_anchor = arrival_anchor;
		oswpt.shipp->arrival_path_mask = arrival_mask;
		oswpt.shipp->arrival_distance = arrival_distance;
		oswpt.shipp->arrival_delay = arrival_delay;

		if (show_warp)
			oswpt.shipp->flags &= ~SF_NO_ARRIVAL_WARP;
		else
			oswpt.shipp->flags |= SF_NO_ARRIVAL_WARP;
	}
	else if (oswpt.type == OSWPT_TYPE_WING || oswpt.type == OSWPT_TYPE_WING_NOT_PRESENT)
	{
		oswpt.wingp->arrival_location = arrival_location;
		oswpt.wingp->arrival_anchor = arrival_anchor;
		oswpt.wingp->arrival_path_mask = arrival_mask;
		oswpt.wingp->arrival_distance = arrival_distance;
		oswpt.wingp->arrival_delay = arrival_delay;

		if (show_warp)
			oswpt.wingp->flags &= ~WF_NO_ARRIVAL_WARP;
		else
			oswpt.wingp->flags |= WF_NO_ARRIVAL_WARP;
	}
	else if (oswpt.type == OSWPT_TYPE_PARSE_OBJECT)
	{
		oswpt.p_objp->arrival_location = arrival_location;
		oswpt.p_objp->arrival_anchor = arrival_anchor;
		oswpt.p_objp->arrival_path_mask = arrival_mask;
		oswpt.p_objp->arrival_distance = arrival_distance;
		oswpt.p_objp->arrival_delay = arrival_delay;

		if (show_warp)
			oswpt.p_objp->flags &= ~P_SF_NO_ARRIVAL_WARP;
		else
			oswpt.p_objp->flags |= P_SF_NO_ARRIVAL_WARP;
	}
}

// Goober5000 - set stuff for departing ships or wings
void sexp_set_departure_info(int node)
{
	int i, departure_location, departure_anchor, departure_mask, departure_delay, n = node;
	bool show_warp;
	object_ship_wing_point_team oswpt;

	// get ship or wing
	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));
	n = CDR(n);

	// get departure location
	departure_location = -1;
	for (i=0; i<MAX_DEPARTURE_NAMES; i++)
	{
		if (!stricmp(CTEXT(n), Departure_location_names[i]))
			departure_location = i;
	}
	if (departure_location < 0)
	{
		Warning(LOCATION, "Departure location '%s' not found.\n", CTEXT(n));
		return;
	}
	n = CDR(n);

	// get departure anchor
	departure_anchor = -1;
	if ((n < 0) || !stricmp(CTEXT(n), "<no anchor>"))
	{
		// if no anchor, set departure location to hyperspace
		departure_location = 0;
	}
	else
	{
		// anchor must exist - look for it
		for (i=0; i<Num_parse_names; i++)
		{
			if (!stricmp(CTEXT(n), Parse_names[i]))
				departure_anchor = i;
		}
		// if not found, make a new entry
		if (departure_anchor < 0)
		{
			strcpy_s(Parse_names[Num_parse_names], CTEXT(n));
			departure_anchor = Num_parse_names;
			Num_parse_names++;
		}
	}
	n = CDR(n);

	// get departure path mask
	departure_mask = 0;
	if (n >= 0)
		departure_mask = eval_num(n);
	n = CDR(n);

	// get departure delay
	departure_delay = 0;
	if (n >= 0)
		departure_delay = eval_num(n);
	n = CDR(n);

	// get warp effect
	show_warp = true;
	if (n >= 0)
		show_warp = (is_sexp_true(n) != 0);

	// now set all that information depending on the first argument
	if (oswpt.type == OSWPT_TYPE_SHIP)
	{
		oswpt.shipp->departure_location = departure_location;
		oswpt.shipp->departure_anchor = departure_anchor;
		oswpt.shipp->departure_path_mask = departure_mask;
		oswpt.shipp->departure_delay = departure_delay;

		if (show_warp)
			oswpt.shipp->flags &= ~SF_NO_DEPARTURE_WARP;
		else
			oswpt.shipp->flags |= SF_NO_DEPARTURE_WARP;
	}
	else if (oswpt.type == OSWPT_TYPE_WING || oswpt.type == OSWPT_TYPE_WING_NOT_PRESENT)
	{
		oswpt.wingp->departure_location = departure_location;
		oswpt.wingp->departure_anchor = departure_anchor;
		oswpt.wingp->departure_path_mask = departure_mask;
		oswpt.wingp->departure_delay = departure_delay;

		if (show_warp)
			oswpt.wingp->flags &= ~WF_NO_DEPARTURE_WARP;
		else
			oswpt.wingp->flags |= WF_NO_DEPARTURE_WARP;
	}
	else if (oswpt.type == OSWPT_TYPE_PARSE_OBJECT)
	{
		oswpt.p_objp->departure_location = departure_location;
		oswpt.p_objp->departure_anchor = departure_anchor;
		oswpt.p_objp->departure_path_mask = departure_mask;
		oswpt.p_objp->departure_delay = departure_delay;

		if (show_warp)
			oswpt.p_objp->flags &= ~P_SF_NO_DEPARTURE_WARP;
		else
			oswpt.p_objp->flags |= P_SF_NO_DEPARTURE_WARP;
	}
}

// Goober5000
// set *all* the escort priorities of ships in escort list as follows: most damaged ship gets
// first priority in the argument list, next damaged gets next priority, etc.; if there are more
// ships than priorities, all remaining ships get the final priority on the list
// -- As indicated in the argument specification, there must be at least one argument but no more
// than MAX_COMPLETE_ESCORT_LIST arguments
void sexp_damage_escort_list_all(int n)
{
	typedef struct
	{
		int index;
		float hull;
	} my_escort_ship;

	int priority[MAX_COMPLETE_ESCORT_LIST];
	my_escort_ship escort_ship[MAX_COMPLETE_ESCORT_LIST];
	int i, j, num_escort_ships, num_priorities, temp_i;
	float temp_f;
	ship *shipp;

	// build list of priorities
	num_priorities = 0;
	for ( ; n != -1; n = CDR(n) )
	{
		priority[num_priorities] = eval_num(n);
		num_priorities++;
	}

	// build custom list of escort ships
	num_escort_ships = 0;
	for (i = 0; i < MAX_SHIPS; i++)
	{
		shipp = &Ships[i];

		// make sure it exists
		if ( shipp->objnum < 0 )
			continue;

		// make sure it's on the escort list
		if ( !(shipp->flags & SF_ESCORT) )
			continue;

		// set index
		escort_ship[num_escort_ships].index = i;

		// calc and set hull integrity
		escort_ship[num_escort_ships].hull = get_hull_pct(&Objects[shipp->objnum]);

		num_escort_ships++;
	}

	// sort it bubbly, lowest hull to highest hull
	for (i = 0; i < num_escort_ships; i++)
	{
		for (j = 0; j < i; j++)
		{
			if (escort_ship[i].hull < escort_ship[j].hull)
			{
				// swap
				temp_i = escort_ship[i].index;
				temp_f = escort_ship[i].hull;
				escort_ship[i].index = escort_ship[j].index;
				escort_ship[i].hull = escort_ship[j].hull;
				escort_ship[j].index = temp_i;
				escort_ship[j].hull = temp_f;
			}
		}
	}

	// loop through and assign priorities
	for (i = 0; i < num_escort_ships; i++)
	{
		if (i >= num_priorities)
			Ships[escort_ship[i].index].escort_priority = priority[num_priorities - 1];
		else
			Ships[escort_ship[i].index].escort_priority = priority[i];
	}

	// redo the escort list
	hud_setup_escort_list();
}

void sexp_awacs_set_radius(int node)
{
	int sindex;		
	ship_subsys *awacs;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}	

	// get the awacs subsystem
	awacs = ship_get_subsys(&Ships[sindex], CTEXT(CDR(node)));
	if(awacs == NULL){
		return;
	}

	if (!(awacs->system_info->flags & MSS_FLAG_AWACS))
		return;

	// set the new awacs radius
	awacs->awacs_radius = (float)eval_num(CDR(CDR(node)));
}

// Goober5000
void sexp_primitive_sensors_set_range(int n)
{
	char *ship_name = CTEXT(n);
	int ship_num, range = eval_num(CDR(n));

	// check to see if ship destroyed or departed.  In either case, do nothing.
	if ( mission_log_get_time(LOG_SHIP_DEPARTED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, ship_name, NULL, NULL) )
		return;

	// get the ship
	ship_num = ship_name_lookup(ship_name);

	// ship not yet in mission? do nothing
	if (ship_num < 0)
		return;

	// set the new range
	Ships[ship_num].primitive_sensor_range = range;
}


//*************************************************************************************************
// Kazan
// AutoNav/AutoPilot system SEXPS

//text: set-nav-carry
//args: 1+, Ship/Wing name
void set_nav_carry_status(int node)
{
	int n=node, i;
	char *name;
	bool skip;

	while (n != -1)
	{
		name = CTEXT(n);
		skip = false;

		for (i = 0; i < MAX_WINGS; i++)
		{
			if (!stricmp(Wings[i].name, name))
			{
				Wings[i].flags |= WF_NAV_CARRY;
				skip = true;
				break;
			}
		}

		if (!skip)
		{
			for (i = 0; i < MAX_SHIPS; i++)
			{
				if (Ships[i].objnum != -1 && !stricmp(Ships[i].ship_name, name))
				{
					Ships[i].flags2 |= SF2_NAVPOINT_CARRY;
					break;
				}
			}
		}
		
		// move to next ship/wing in list
		n = CDR(n);
	}
}

//text: unset-nav-carry
//args: 1+, Ship/Wing name
void unset_nav_carry_status(int node)
{
	int n=node, i;
	char *name;
	bool skip;


	while (n != -1)
	{
		name = CTEXT(n);
		skip = false;

		for (i = 0; i < MAX_WINGS; i++)
		{
			if (!stricmp(Wings[i].name, name))
			{
				Wings[i].flags &= ~WF_NAV_CARRY;
				skip = true;
				break;

			}
		}

		if (!skip)
		{
			for (i = 0; i < MAX_SHIPS; i++)
			{
				if (Ships[i].objnum != -1 && !stricmp(Ships[i].ship_name, name))
				{
					Ships[i].flags2 &= ~SF2_NAVPOINT_CARRY;
					break;
				}
			}
		}
		
		// move to next ship/wing in list
		n = CDR(n);
	}
}


//text: set-nav-needslink
//args: 1+, Ship/Wing name
void set_nav_needslink(int node)
{
	int n=node, i;
	char *name;

	while (n != -1)
	{
		name = CTEXT(n);

		for (i = 0; i < MAX_SHIPS; i++)
		{
			if (Ships[i].objnum != -1 && !stricmp(Ships[i].ship_name, name))
			{
				Ships[i].flags2 &= ~SF2_NAVPOINT_CARRY;
				Ships[i].flags2 |= SF2_NAVPOINT_NEEDSLINK;
				break;
			}
		}
		// move to next ship/wing in list
		n = CDR(n);
	}
}

//text: unset-nav-needslink
//args: 1+, Ship/Wing name
void unset_nav_needslink(int node)
{
	int n=node, i;
	char *name;

	while (n != -1)
	{
		name = CTEXT(n);


		for (i = 0; i < MAX_SHIPS; i++)
		{
			if (Ships[i].objnum != -1 && !stricmp(Ships[i].ship_name, name))
			{
				Ships[i].flags2 &= ~SF2_NAVPOINT_NEEDSLINK;
				break;
			}
		}

		
		// move to next ship/wing in list
		n = CDR(n);
	}
}

void add_nav_waypoint(char *nav, char *WP_path, int vert, char *oswpt_name)
{	
	int i;
	object_ship_wing_point_team oswpt;
	bool add_for_this_player = true; 

	if (oswpt_name != NULL) {
		sexp_get_object_ship_wing_point_team(&oswpt, oswpt_name); 

		// we can't assume this nav should be visible to the player any more
		add_for_this_player = false;

		switch (oswpt.type)
		{
			case OSWPT_TYPE_WHOLE_TEAM:
				if (oswpt.team == Player_ship->team) {
					add_for_this_player = true; 
				}
				break;

			case OSWPT_TYPE_SHIP:
				if (oswpt.shipp == Player_ship) {
					add_for_this_player = true; 
				}
				break;
			case OSWPT_TYPE_WING:
				for ( i = 0; i < oswpt.wingp->current_count; i++) {
					if (Ships[oswpt.wingp->ship_index[i]].objnum == Player_ship->objnum) {
						add_for_this_player = true; 
					}
				}


			// for all other oswpt types we simply ignore this
			default:
				break;
		}
	}
	
	AddNav_Waypoint(nav, WP_path, vert, add_for_this_player ? 0 : NP_HIDDEN);
}


//text: add-nav-waypoint
//args: 4, Nav Name, Waypoint Path Name, Waypoint Path point, ShipWingTeam
void add_nav_waypoint(int node)
{
	char *nav_name = CTEXT(node);
	char *way_name = CTEXT(CDR(node));
	int  vert = eval_num(CDR(CDR(node)));	
	char *oswpt_name;

	node = CDR(CDR(CDR(node)));
	if (node >=0) {
		oswpt_name = CTEXT(node); 
	}
	else {
		oswpt_name = NULL;
	}

	add_nav_waypoint(nav_name, way_name, vert, oswpt_name);

	multi_start_callback();
	multi_send_string(nav_name);
	multi_send_string(way_name);
	multi_send_int(vert);

	if (oswpt_name != NULL) {
		multi_send_string(oswpt_name);
	}

	multi_end_callback();
}

void multi_sexp_add_nav_waypoint()
{
	char nav_name[TOKEN_LENGTH];
	char way_name[TOKEN_LENGTH];
	char oswpt_name[TOKEN_LENGTH];
	int vert;

	if (!multi_get_string(nav_name)) {
		return; 
	}
	
	if (!multi_get_string(way_name)) {
		return;
	}

	if (!multi_get_int(vert)) {
		return;
	}

	if (!multi_get_string(oswpt_name)) {
		add_nav_waypoint(nav_name, way_name, vert, NULL);		
	}
	else {
		add_nav_waypoint(nav_name, way_name, vert, oswpt_name);
	}

	AddNav_Waypoint(nav_name, way_name, vert, 0);
}


//text: add-nav-ship
//args: 2, Nav Name, Ship Name
void add_nav_ship(int node)
{
	char *nav_name = CTEXT(node);
	char *ship_name = CTEXT(CDR(node));
	AddNav_Ship(nav_name, ship_name, 0);

	multi_start_callback();
	multi_send_string(nav_name);
	multi_send_string(ship_name);
	multi_end_callback();
}

void multi_add_nav_ship()
{
	char nav_name[TOKEN_LENGTH];
	char ship_name[TOKEN_LENGTH];

	if (!multi_get_string(nav_name)) {
		return; 
	}
	
	if (!multi_get_string(ship_name)) {
		return;
	}

	AddNav_Ship(nav_name, ship_name, 0);
}


//text: del-nav
//args: 1, Nav Name
void del_nav(int node)
{
	char *nav_name = CTEXT(node);
	DelNavPoint(nav_name);

	multi_start_callback();
	multi_send_string(nav_name);
	multi_end_callback();

}

void multi_del_nav()
{
	char nav_name[TOKEN_LENGTH];

	if (!multi_get_string(nav_name)) {
		return; 
	}
	
	DelNavPoint(nav_name);
}

//text: use-nav-cinematics
//args: 1, boolean enable/disable
void set_use_ap_cinematics(int node)
{
	if (is_sexp_true(node))
	{
		The_mission.flags |= MISSION_FLAG_USE_AP_CINEMATICS;
	}
	else
	{
		The_mission.flags &= ~MISSION_FLAG_USE_AP_CINEMATICS;
	}
}

//text: use-autopilot
//args: 1, boolean enable/disable
void set_use_ap(int node)
{
	if (is_sexp_true(node))
	{
		The_mission.flags &= ~MISSION_FLAG_DEACTIVATE_AP;
	}
	else
	{
		The_mission.flags |= MISSION_FLAG_DEACTIVATE_AP;
	}
}

//text: hide-nav
//args: 1, Nav Name
void hide_nav(int node)
{
	char *nav_name = CTEXT(node);
	Nav_Set_Hidden(nav_name);
}

//text: restrict-nav
//args: 1, nav name
void restrict_nav(int node)
{
	char *nav_name = CTEXT(node);
	Nav_Set_NoAccess(nav_name);
}

//text: unhide-nav
//args: 1, Nav name
void unhide_nav(int node)
{
	char *nav_name = CTEXT(node);
	Nav_UnSet_Hidden(nav_name);
}

//text: unrestrict-nav
//args: 1, nav name
void unrestrict_nav(int node)
{
	char *nav_name = CTEXT(node);
	Nav_UnSet_NoAccess(nav_name);

}

//text: set-nav-visited
//args: 1, Nav Name
void set_nav_visited(int node)
{
	char *nav_name = CTEXT(node);
	Nav_Set_Visited(nav_name);
}

//text: unset-nav-visited
//args: 1, Nav Name
void unset_nav_visited(int node)
{
	char *nav_name = CTEXT(node);
	Nav_UnSet_Visited(nav_name);
}


//text: is-nav-visited
//args: 1, Nav Name
//rets: true/false
int is_nav_visited(int node)
{
	char *nav_name = CTEXT(node);
	return IsVisited(nav_name);
}


//text: is-nav_linked
//args: 1, Ship name
//rets: true/false
int is_nav_linked(int node)
{
	char *ship_name = CTEXT(node);
	for (int i = 0; i < MAX_SHIPS; i++)
	{
		if (Ships[i].objnum != -1 && !stricmp(Ships[i].ship_name, ship_name))
		{
			return (Ships[i].flags2 & SF2_NAVPOINT_CARRY) != 0;
		}
	}
	return 0;
}

//text: distance-to-nav
//args: 1, Nav Name
//rets: distance to nav
int distance_to_nav(int node)
{
	char *nav_name = CTEXT(node);
	return DistanceTo(nav_name);
}

void select_nav(int node)
{
	char *nav_name = CTEXT(node);
	SelectNav(nav_name);
}

void unselect_nav()
{
	DeselectNav();
}


//*************************************************************************************************


int sexp_is_tagged(int node)
{
	int sindex;

	// get the firing ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return SEXP_FALSE;
	}
	if(Ships[sindex].objnum < 0){
		return SEXP_FALSE;
	}
	object *caller = &Objects[Ships[sindex].objnum];
	if(ship_is_tagged(caller)) { // This line and the one above were added.
		return SEXP_TRUE;
	}

	// not tagged
	return SEXP_FALSE;
}

// Joint effort of Sesquipedalian and Goober5000.  Sesq found the code, mucked around making
// sexps with it and learned things, Goober taught Sesq and made the sexp work properly. =D
// Returns true so long as the player has held a missile lock for the specified time.
// If the optional ship and/or ship's subsystem are specified, returns true when that
// has been locked onto, but otherwise returns as long as anything has been locked onto.
int sexp_missile_locked(int node)
{
	int z;

	// if we aren't targeting anything, it's false
	if ((Players_target == -1) || (Players_target == UNINITIALIZED))
		return SEXP_FALSE;

	// if we aren't locked on to anything, it's false
	if (!Players_mlocked)
		return SEXP_FALSE;

	// do we have a specific ship?
	if (CDR(node) != -1)
	{
		// if we're not targeting the specific ship, it's false
		if (stricmp(Ships[Objects[Players_target].instance].ship_name, CTEXT(CDR(node))))
			return SEXP_FALSE;

		// do we have a specific subsystem?
		if (CDR(CDR(node)) != -1)
		{
			// if we aren't targeting a subsystem at all, it's false
			if (!Player_ai->targeted_subsys)
				return SEXP_FALSE;

			// if we're not targeting the specific subsystem, it's false
			if (subsystem_stricmp(Player_ai->targeted_subsys->system_info->subobj_name, CTEXT(CDR(CDR(node)))))
				return SEXP_FALSE;
		}
	}

	// if we've gotten this far, we must have satisfied whatever conditions the sexp imposed
	// finally, test if we've locked for a certain period of time
	z = eval_num(node) * 1000;
	if (timestamp_has_time_elapsed(Players_mlocked_timestamp, z))
	{
		return SEXP_TRUE;
	}

	return SEXP_FALSE;
}

int sexp_is_player (int node) 
{
	int sindex, np_index;
	p_object *p_objp;

	int standard_check = is_sexp_true(node);

	if (!(Game_mode & GM_MULTIPLAYER)){	
		sindex = ship_name_lookup(CTEXT(CDR(node)));

		// There can only be one player ship in singleplayer so if more than one ship is specifed the sexp is false
		if (CDDR(node) < 0 ) {
			return SEXP_FALSE;
		}

		if(sindex >= 0){
			if(Player_obj == &Objects[Ships[sindex].objnum]){
				if (standard_check) {
					if (Player_use_ai) {
						return SEXP_FALSE;
					}
				}
				return SEXP_TRUE;
			}
		}
		return SEXP_FALSE;
	}

	// For multiplayer we need to decide what to do about respawning players
	else {		
		node = CDR(node);
		while (node >= 0) {
			// reset the netplayer index
			np_index = -1; 

			sindex = ship_name_lookup(CTEXT(node));
			if(sindex >= 0){
				if(Ships[sindex].objnum >= 0) {
					// try and find the player
					np_index = multi_find_player_by_object(&Objects[Ships[sindex].objnum]);
				}
			}
			
			if (standard_check && np_index < 0) {
				// Respawning ships don't have an objnum so we need to take a different approach 
				p_objp = mission_parse_get_arrival_ship(CTEXT(node));
				if (p_objp != NULL) {
					np_index = multi_find_player_by_parse_object(p_objp);
				}
			}
			
			// if we couldn't find a valid netplayer index then the ship isn't a player
			if((np_index < 0) || (np_index >= MAX_PLAYERS)){
				return SEXP_FALSE;
			}
			
			node = CDR(node);
		}

		// if we reached this far they all checked out
		return SEXP_TRUE;
	}
}

void sexp_set_respawns(int node)
{
	int num_respawns; 
	p_object *p_objp;

	// we're wasting our time if you can't respawn
	if (!(Game_mode & GM_MULTIPLAYER)) {
		return;
	}

	num_respawns = eval_num(node);

	node = CDR(node);

	// send the information to clients
	multi_start_callback();
	multi_send_int(num_respawns); 

	while (node != -1) {
		// get the parse object for the ship
		p_objp = mission_parse_get_arrival_ship(CTEXT(node));
		if (p_objp != NULL) {
			p_objp->respawn_count = num_respawns;
		}

		multi_send_string(CTEXT(node)); 

		node = CDR(node);
	}
	
	multi_end_callback();
}

void multi_sexp_set_respawns()
{
	p_object *p_objp;
	int num_respawns;
	char parse_name[NAME_LENGTH];

	multi_get_int(num_respawns); 
	while (multi_get_string(parse_name)) {
		// get the parse object for the ship
		p_objp = mission_parse_get_arrival_ship(parse_name);
		if (p_objp != NULL) {
			p_objp->respawn_count = num_respawns;
		}
	}
}

// helper function for the remove-weapons SEXP
void actually_remove_weapons(int weapon_info_index)
{
	int i; 

	for (i = 0; i<MAX_WEAPONS; i++) {
		// weapon doesn't match the optional weapon 
		if ((weapon_info_index > -1) && (Weapons[i].weapon_info_index != weapon_info_index)) {
			continue;
		}

		if (Weapons[i].objnum >= 0) {
			Objects[Weapons[i].objnum].flags |= OF_SHOULD_BE_DEAD;
		}		
	}
}

void sexp_remove_weapons(int node)
{ 
	int weapon_info_index = -1;

	// if we have the optional argument, read it in
	if (node >= 0) {
		weapon_info_index = weapon_info_lookup(CTEXT(node));
		if (weapon_info_index == -1) {
			char *buf = CTEXT(node); 
			mprintf(("Remove-weapons attempted to remove %s. Weapon not found. Remove-weapons will remove all weapons currently in the mission\n", buf)); 
		}
	}

	actually_remove_weapons(weapon_info_index); 
	
	// send the information to clients
	multi_start_callback();
	multi_send_int(weapon_info_index); 
	multi_end_callback();
}

void multi_sexp_remove_weapons()
{
	int weapon_info_index = -1; 

	multi_get_int(weapon_info_index);
	
	actually_remove_weapons(weapon_info_index); 
}


int sexp_return_player_data(int node, int type)
{
	int sindex, np_index = -1;
	player *p = NULL;
	p_object *p_objp;

	sindex = ship_name_lookup(CTEXT(node));

	if(Game_mode & GM_MULTIPLAYER){			
		if(sindex >= 0){
			if(Ships[sindex].objnum >= 0) {
				// try and find the player
				np_index = multi_find_player_by_object(&Objects[Ships[sindex].objnum]);
			}
		}
		
		if (np_index < 0) {
			// Respawning ships don't have an objnum so we need to take a different approach 
			p_objp = mission_parse_get_arrival_ship(CTEXT(node));
			np_index = multi_find_player_by_parse_object(p_objp);
		}
		
		if((np_index >= 0) && (np_index < MAX_PLAYERS)){
			p = Net_players[np_index].m_player;
		}
	}
	// if we're in single player, we're only concerned with ourself
	else {
		if(sindex < 0){
			return 0;
		}
		if(Ships[sindex].objnum < 0){
			return 0;
		}
		
		if(Player_obj == &Objects[Ships[sindex].objnum]){
			p = Player;
		}
	}

	// now, if we have a valid player, return his kills
	if(p != NULL) {
		switch (type) {
			case OP_NUM_KILLS:
				return p->stats.m_kill_count_ok;

			case OP_NUM_ASSISTS:
				return p->stats.m_assists;

			case OP_SHIP_SCORE: 
				return p->stats.m_score;

			case OP_SHIP_DEATHS: 
				return p->stats.m_player_deaths;

			case OP_RESPAWNS_LEFT:
				// Dogfight missions have no respawn limit
				if (MULTI_NOT_DOGFIGHT) {
					if ( Net_players[np_index].flags & NETINFO_FLAG_RESPAWNING) {						
						// since the player hasn't actually respawned yet he hasn't used up a number or spawns equal to his deaths
						// so add an extra life back. 
						return Netgame.respawn - p->stats.m_player_deaths + 1;
					}
					else {
						return Netgame.respawn - p->stats.m_player_deaths;
					}
				}
				break;

			default:
				Int3();
		}
	}	
	// AI ships also have a respawn count so we can return valid data for that at least
	else if ( (Game_mode & GM_MULTIPLAYER) && (type == OP_SHIP_DEATHS || type == OP_RESPAWNS_LEFT ) ) {
		p_objp = mission_parse_get_arrival_ship(CTEXT(node));
		if (p_objp == NULL) {
			return 0;
		}

		if (p_objp->flags & P_OF_PLAYER_START) { 
			switch (type) {				
				case OP_SHIP_DEATHS: 
					// when an AI ship is finally killed its respawn count won't be updated so get the number of deaths 
					// from the log instead
					return mission_log_get_count(LOG_SHIP_DESTROYED, CTEXT(node), NULL) + mission_log_get_count(LOG_SELF_DESTRUCTED, CTEXT(node), NULL);
					
				case OP_RESPAWNS_LEFT:
					return Netgame.respawn - p_objp->respawn_count; 

				default: 
					Int3();
			}
		}
	}

	// AI ships 
	return 0;
}

int sexp_num_type_kills(int node)
{
	int sindex, st_index;
	int idx, total;
	player *p = NULL;

	// get the ship we're interested in
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return 0;
	}
	if(Ships[sindex].objnum < 0){
		return 0;
	}
	
	int np_index;

	// in multiplayer, search through all players
	if(Game_mode & GM_MULTIPLAYER){
		// try and find the player
		np_index = multi_find_player_by_object(&Objects[Ships[sindex].objnum]);
		if((np_index >= 0) && (np_index < MAX_PLAYERS)){
			p = Net_players[np_index].m_player;
		}
	}
	// if we're in single player, we're only concerned with ourself
	else {
		// me
		if(Player_obj == &Objects[Ships[sindex].objnum]){
			p = Player;
		}
	}

	// bad
	if(p == NULL){
		return 0;
	}

	// lookup ship type name
	st_index = ship_type_name_lookup(CTEXT(CDR(node)));
	if(st_index < 0){
		return 0;
	}

	// look stuff up	
	total = 0;
	for(idx = 0; idx < static_cast<int>(Ship_info.size()); idx++) {
		if((p->stats.m_okKills[idx] > 0) && ship_class_query_general_type(idx)==st_index){
			total += p->stats.m_okKills[idx];
		}
	}

	// total
	return total;
}

int sexp_num_class_kills(int node)
{
	int sindex, si_index;
	player *p = NULL;

	// get the ship we're interested in
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return 0;
	}
	if(Ships[sindex].objnum < 0){
		return 0;
	}
	
	int np_index;

	// in multiplayer, search through all players
	if(Game_mode & GM_MULTIPLAYER){
		// try and find the player
		np_index = multi_find_player_by_object(&Objects[Ships[sindex].objnum]);
		if((np_index >= 0) && (np_index < MAX_PLAYERS)){
			p = Net_players[np_index].m_player;
		}
	}
	// if we're in single player, we're only concerned with ourself
	else {
		// me
		if(Player_obj == &Objects[Ships[sindex].objnum]){
			p = Player;
		}
	}

	// bad
	if(p == NULL){
		return 0;
	}

	// get the ship type we're looking for
	si_index = ship_info_lookup(CTEXT(CDR(node)));
	if((si_index < 0) || (si_index >= static_cast<int>(Ship_info.size()))){
		return 0;
	}

	// return the count	
	return p->stats.m_okKills[si_index];
}

void sexp_subsys_set_random(int node)
{
	int sindex, low, high, n, idx, rand, exclusion_list[MAX_MODEL_SUBSYSTEMS];		
	ship_subsys *subsys;
	ship *shipp;

	// get ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return;
	}
	if(Ships[sindex].objnum < 0){
		return;
	}
	shipp = &Ships[sindex];

	// get low
	low = eval_num(CDR(node));
	if (low < 0) {
		low = 0;
	}

	// get high
	high = eval_num(CDR(CDR(node)));
	if (high > 100) {
		high = 100;
	}

	if (low > high) {
		Int3();
		return;
	}

	n = CDR(CDR(CDR(node)));

	// init exclusion list
	memset(exclusion_list, 0, sizeof(int) * Ship_info[shipp->ship_info_index].n_subsystems);

	// get exclusion list
	while( n != -1) {
		int exclude_index = ship_get_subsys_index(shipp, CTEXT(n), 0);
		if (exclude_index >= 0) {
			exclusion_list[exclude_index] = 1;
		}

		n = CDR(n);
	}

	// apply to all others
	for (idx=0; idx<Ship_info[shipp->ship_info_index].n_subsystems; idx++) {
		if ( exclusion_list[idx] == 0 ) {
			// get non excluded subsystem
			subsys = ship_get_indexed_subsys(shipp, idx, NULL);
			if (subsys == NULL) {
				nprintf(("Warning", "Nonexistent subsystem for index %d on ship %s for sabotage subsystem\n", idx, shipp->ship_name));
				continue;
			}

			// randomize its hit points
			rand = rand_internal(low, high);
			subsys->current_hits = 0.01f * rand * subsys->max_hits;
		}
	}
}

void sexp_supernova_start(int node)
{
	supernova_start(eval_num(node));
}

void sexp_supernova_stop(int node)
{
	supernova_stop();
}

int sexp_is_secondary_selected(int node)
{
	int sindex;
	int bank;
	ship *shipp;

	// lookup ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return SEXP_FALSE;
	}
	if(Ships[sindex].objnum < 0){
		return SEXP_FALSE;
	}
	shipp = &Ships[sindex];

	// bogus value?
	bank = eval_num(CDR(node));
	if(bank >= shipp->weapons.num_secondary_banks){
		return SEXP_FALSE;
	}

	// is this the bank currently selected
	if( bank == shipp->weapons.current_secondary_bank ){
		return SEXP_TRUE;
	}

	// nope
	return SEXP_FALSE;
}

int sexp_is_primary_selected(int node)
{
	int sindex;
	int bank;
	ship *shipp;

	// lookup ship
	sindex = ship_name_lookup(CTEXT(node));
	if(sindex < 0){
		return SEXP_FALSE;
	}
	if(Ships[sindex].objnum < 0){
		return SEXP_FALSE;
	}
	shipp = &Ships[sindex];

	// bogus value?
	bank = eval_num(CDR(node));
	if(bank >= shipp->weapons.num_primary_banks){
		return SEXP_FALSE;
	}

	// is this the bank currently selected
	if( (bank == shipp->weapons.current_primary_bank) || (shipp->flags & SF_PRIMARY_LINKED) ){
		return SEXP_TRUE;
	}

	// nope
	return SEXP_FALSE;
}

//	Return SEXP_TRUE if quadrant quadnum is near max.
int shield_quad_near_max(int quadnum)
{
	if (quadnum >= Player_obj->n_quadrants)
		return SEXP_FALSE;

	float	remaining = 0.0f;
	for (int i=0; i<Player_obj->n_quadrants; i++) {
		if (i == quadnum){
			continue;
		}
		remaining += Player_obj->shield_quadrant[i];
	}

	if ((remaining < 2.0f) || (Player_obj->shield_quadrant[quadnum] > get_max_shield_quad(Player_obj) - 5.0f)) {
		return SEXP_TRUE;
	} else {
		return SEXP_FALSE;
	}
}

//	Return truth value for special SEXP.
//	Used in training#5, perhaps in other missions.
int process_special_sexps(int index)
{
	switch (index) {
	case 0:	//	Ship "Freighter 1" is aspect locked by player.
		if (Player_ai->target_objnum != -1) {
			if (!(stricmp(Ships[Objects[Player_ai->target_objnum].instance].ship_name, "Freighter 1"))) {
				if (Player_ai->current_target_is_locked)
					return SEXP_TRUE;
			}
		}
		return SEXP_FALSE;

	case 1:	//	Fired Interceptors
		object	*objp;
		for (objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp)) {
			if (objp->type == OBJ_WEAPON) {
				if (!stricmp(Weapon_info[Weapons[objp->instance].weapon_info_index].name, "Interceptor#weak")) {
					int target = Weapons[objp->instance].target_num;
					if (target != -1) {
						if (Objects[target].type == OBJ_SHIP) {
							if (!(stricmp(Ships[Objects[target].instance].ship_name, "Freighter 1")))
								return SEXP_TRUE;
						}
					}
				}
			}
		}
		return SEXP_FALSE;

	case 2:	//	Ship "Freighter 1", subsystem "Weapons" is aspect locked by player.
		if (Player_ai->target_objnum != -1) {
			if (!(stricmp(Ships[Objects[Player_ai->target_objnum].instance].ship_name, "Freighter 1"))) {
				if (!(subsystem_stricmp(Player_ai->targeted_subsys->system_info->name, "Weapons"))) {
					if (Player_ai->current_target_is_locked){
						return SEXP_TRUE;
					}
				}
			}
		}
		return SEXP_FALSE;

	case 3:	//	Player ship suffering shield damage on front.
		if (!(Ship_info[Player_ship->ship_info_index].flags2 & SIF2_MODEL_POINT_SHIELDS)) {
			apply_damage_to_shield(Player_obj, FRONT_QUAD, 10.0f);
			hud_shield_quadrant_hit(Player_obj, FRONT_QUAD);
			return SEXP_TRUE;
		} else {
			nprintf(("Warning", "Shield-related Special-check SEXPs do not work on ship %s because it uses model point shields.\n", Player_ship->ship_name));
			return SEXP_FALSE;
		}
		break;

	case 4:	//	Player ship suffering much damage.
		if (!(Ship_info[Player_ship->ship_info_index].flags2 & SIF2_MODEL_POINT_SHIELDS)) {
			nprintf(("AI", "Frame %i\n", Framecount));
			apply_damage_to_shield(Player_obj, FRONT_QUAD, 10.0f);
			hud_shield_quadrant_hit(Player_obj, FRONT_QUAD);
			if (Player_obj->shield_quadrant[FRONT_QUAD] < 2.0f)
				return SEXP_TRUE;
			else
				return SEXP_FALSE;
		} else {
			nprintf(("Warning", "Shield-related Special-check SEXPs do not work on ship %s because it uses model point shields.\n", Player_ship->ship_name));
			return SEXP_FALSE;
		}
		break;

	case 5:	//	Player's shield is quick repaired
		if (!(Ship_info[Player_ship->ship_info_index].flags2 & SIF2_MODEL_POINT_SHIELDS)) {
			nprintf(("AI", "Frame %i, recharged to %7.3f\n", Framecount, Player_obj->shield_quadrant[FRONT_QUAD]));

			apply_damage_to_shield(Player_obj, FRONT_QUAD, -flFrametime*200.0f);

			if (Player_obj->shield_quadrant[FRONT_QUAD] > get_max_shield_quad(Player_obj))
			Player_obj->shield_quadrant[FRONT_QUAD] = get_max_shield_quad(Player_obj);

			if (Player_obj->shield_quadrant[FRONT_QUAD] > Player_obj->shield_quadrant[(FRONT_QUAD+1)%DEFAULT_SHIELD_SECTIONS] - 2.0f)
				return SEXP_TRUE;
			else
				return SEXP_FALSE;
		} else {
			nprintf(("Warning", "Shield-related Special-check SEXPs do not work on ship %s because it uses model point shields.\n", Player_ship->ship_name));
			return SEXP_FALSE;
		}
		break;

	case 6:	//	3 of player's shield quadrants are reduced to 0.
		if (!(Ship_info[Player_ship->ship_info_index].flags2 & SIF2_MODEL_POINT_SHIELDS)) {
			Player_obj->shield_quadrant[1] = 1.0f;
			Player_obj->shield_quadrant[2] = 1.0f;
			Player_obj->shield_quadrant[3] = 1.0f;
			hud_shield_quadrant_hit(Player_obj, FRONT_QUAD);
		} else {
			nprintf(("Warning", "Shield-related Special-check SEXPs do not work on ship %s because it uses model point shields.\n", Player_ship->ship_name));
			return SEXP_FALSE;
		}
		return SEXP_TRUE;

	case 7:	//	Make sure front quadrant has been maximized, or close to it.
		if (!(Ship_info[Player_ship->ship_info_index].flags2 & SIF2_MODEL_POINT_SHIELDS)) {
			if (shield_quad_near_max(FRONT_QUAD)) return SEXP_TRUE; else return SEXP_FALSE;
		} else {
			nprintf(("Warning", "Shield-related Special-check SEXPs do not work on ship %s because it uses model point shields.\n", Player_ship->ship_name));
			return SEXP_FALSE;
		}
		break;

	case 8:	//	Make sure rear quadrant has been maximized, or close to it.
		if (!(Ship_info[Player_ship->ship_info_index].flags2 & SIF2_MODEL_POINT_SHIELDS)) {
			if (shield_quad_near_max(REAR_QUAD)) return SEXP_TRUE; else return SEXP_FALSE;
		} else {
			nprintf(("Warning", "Shield-related Special-check SEXPs do not work on ship %s because it uses model point shields.\n", Player_ship->ship_name));
			return SEXP_FALSE;
		}
		break;
	
	case 9:	//	Zero left and right quadrants in preparation for maximizing rear quadrant.
		if (!(Ship_info[Player_ship->ship_info_index].flags2 & SIF2_MODEL_POINT_SHIELDS)) {
			Player_obj->shield_quadrant[LEFT_QUAD] = 0.0f;
			Player_obj->shield_quadrant[RIGHT_QUAD] = 0.0f;
			hud_shield_quadrant_hit(Player_obj, LEFT_QUAD);
			return SEXP_TRUE;
		} else {
			nprintf(("Warning", "Shield-related Special-check SEXPs do not work on ship %s because it uses model point shields.\n", Player_ship->ship_name));
			return SEXP_FALSE;
		}
		break;

	case 10:	//	Return true if player is low on Interceptors.
		if (Player_ship->weapons.secondary_bank_ammo[0] + Player_ship->weapons.secondary_bank_ammo[1] < 8)
			return SEXP_TRUE;
		else
			return SEXP_FALSE;
		break;

	case 11:	//	Return true if player has plenty of Interceptors.
		if (Player_ship->weapons.secondary_bank_ammo[0] + Player_ship->weapons.secondary_bank_ammo[1] >= 8)
			return SEXP_TRUE;
		else
			return SEXP_FALSE;
		break;

	case 12:	//	Return true if player is low on Interceptors.
		if (Player_ship->weapons.secondary_bank_ammo[0] + Player_ship->weapons.secondary_bank_ammo[1] < 4)
			return SEXP_TRUE;
		else
			return SEXP_FALSE;
		break;

	case 13:	// Zero front shield quadrant.  Added for Jim Boone on August 26, 1999 by MK.
		if (!(Ship_info[Player_ship->ship_info_index].flags2 & SIF2_MODEL_POINT_SHIELDS)) {
			Player_obj->shield_quadrant[FRONT_QUAD] = 0.0f;
			hud_shield_quadrant_hit(Player_obj, FRONT_QUAD);
			return SEXP_TRUE;
		} else {
			nprintf(("Warning", "Shield-related Special-check SEXPs do not work on ship %s because it uses model point shields.\n", Player_ship->ship_name));
			return SEXP_FALSE;
		}
		break;

	case 100:	//	Return true if player is out of countermeasures.
		if (Player_ship->cmeasure_count <= 0)
			return SEXP_TRUE;
		else
			return SEXP_FALSE;

	default:
		Int3();	//	Unsupported node type.
	}

	return SEXP_FALSE;
}

// Karajorma / Goober5000
int sexp_string_to_int(int n)
{
	bool first_ch = true;
	char *ch, *buf_ch, buf[TOKEN_LENGTH];
	Assert (n != -1);

	// copy all numeric characters to buf
	// also, copy a sign symbol if we haven't copied numbers yet
	buf_ch = buf;
	for (ch = CTEXT(n); *ch != 0; ch++)
	{
		if ((first_ch && (*ch == '-' || *ch == '+')) || strchr("0123456789", *ch))
		{
			*buf_ch = *ch;
			buf_ch++;

			first_ch = false;
		}

		// don't save the fractional parts of decimal numbers
		if (*ch == '.')
			break;
	}

	// terminate string
	*buf_ch = '\0';

	return atoi(buf);
}

// Goober5000
void sexp_int_to_string(int n)
{
	int i, sexp_variable_index;
	char new_text[TOKEN_LENGTH];

	// Only do single player or multi host
	if ( MULTIPLAYER_CLIENT )
		return;

	i = eval_num(n);
	n = CDR(n);

	// get sexp_variable index
	Assert(Sexp_nodes[n].first == -1);
	sexp_variable_index = atoi(Sexp_nodes[n].text);

	// verify variable set
	Assert(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_SET);

	// check variable type
	if (!(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_STRING))
	{
		Warning(LOCATION, "Cannot assign a string to a non-string variable!");
		return;
	}

	// write string
	sprintf(new_text, "%d", i);

	// assign to variable
	sexp_modify_variable(new_text, sexp_variable_index);
}

// Goober5000
void sexp_string_concatenate(int n)
{
	int sexp_variable_index;
	char new_text[TOKEN_LENGTH * 2];

	// Only do single player or multi host
	if ( MULTIPLAYER_CLIENT )
		return;

	char *str1 = CTEXT(n);
	n = CDR(n);
	char *str2 = CTEXT(n);
	n = CDR(n);

	// get sexp_variable index
	Assert(Sexp_nodes[n].first == -1);
	sexp_variable_index = atoi(Sexp_nodes[n].text);

	// verify variable set
	Assert(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_SET);

	// check variable type
	if (!(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_STRING))
	{
		Warning(LOCATION, "Cannot assign a string to a non-string variable!");
		return;
	}

	// concatenate strings
	strcpy_s(new_text, str1);
	strcat_s(new_text, str2);

	// check length
	if (strlen(new_text) >= TOKEN_LENGTH)
	{
		Warning(LOCATION, "Concatenated string is too long and will be truncated.");
		new_text[TOKEN_LENGTH] = 0;
	}

	// assign to variable
	sexp_modify_variable(new_text, sexp_variable_index);
}

// Goober5000
int sexp_string_get_length(int node)
{
	return strlen(CTEXT(node));
}

// Goober5000
void sexp_string_get_substring(int node)
{
	int n = node;
	int sexp_variable_index;
	char new_text[TOKEN_LENGTH];

	// Only do single player or multi host
	if ( MULTIPLAYER_CLIENT )
		return;

	char *parent = CTEXT(n);
	n = CDR(n);
	int pos = eval_num(n);
	n = CDR(n);
	int len = eval_num(n);
	n = CDR(n);

	// get sexp_variable index
	Assert(Sexp_nodes[n].first == -1);
	sexp_variable_index = atoi(Sexp_nodes[n].text);

	// verify variable set
	Assert(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_SET);

	// check variable type
	if (!(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_STRING))
	{
		Warning(LOCATION, "Cannot assign a string to a non-string variable!");
		return;
	}

	int parent_len = strlen(parent);

	// sanity
	if (pos >= parent_len)
	{
		Warning(LOCATION, "( string-get-substring %s %d %d ) failed: starting position is larger than the string length!", parent, pos, len);
		return;
	}

	// sanity
	if (pos + len > parent_len)
		len = parent_len - pos;

	// copy substring
	memset(new_text, 0, TOKEN_LENGTH);
	strncpy(new_text, &parent[pos], len);

	// assign to variable
	sexp_modify_variable(new_text, sexp_variable_index);
}

// Goober5000
void sexp_string_set_substring(int node)
{
	int n = node;
	int sexp_variable_index;
	char new_text[TOKEN_LENGTH * 2];

	// Only do single player or multi host
	if ( MULTIPLAYER_CLIENT )
		return;

	char *parent = CTEXT(n);
	n = CDR(n);
	int pos = eval_num(n);
	n = CDR(n);
	int len = eval_num(n);
	n = CDR(n);
	char *new_substring = CTEXT(n);
	n = CDR(n);

	// get sexp_variable index
	Assert(Sexp_nodes[n].first == -1);
	sexp_variable_index = atoi(Sexp_nodes[n].text);

	// verify variable set
	Assert(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_SET);

	// check variable type
	if (!(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_STRING))
	{
		Warning(LOCATION, "Cannot assign a string to a non-string variable!");
		return;
	}

	int parent_len = strlen(parent);
	int new_len = strlen(new_substring);

	// sanity
	if (pos >= parent_len)
	{
		Warning(LOCATION, "( string-set-substring %s %d %d %s ) failed: starting position is larger than the string length!", parent, pos, len, new_substring);
		return;
	}

	// make the common case fast
	if (len == 1 && new_len == 1)
	{
		strcpy_s(new_text, parent);
		new_text[pos] = new_substring[0];
	}
	else
	{
		// sanity
		if (pos + len > parent_len)
			len = parent_len - pos;

		// copy parent string up to the substring pos
		strncpy(new_text, parent, pos);

		// add new substring
		strcpy(&new_text[pos], new_substring);

		// add rest of parent string
		strcat_s(new_text, &parent[pos + len]);

		// check length
		if (strlen(new_text) >= TOKEN_LENGTH)
		{
			Warning(LOCATION, "Concatenated string is too long and will be truncated.");
			new_text[TOKEN_LENGTH] = 0;
		}
	}

	// assign to variable
	sexp_modify_variable(new_text, sexp_variable_index);
}

// breaks into the code or sends a warning
void sexp_debug(int node)
{
	int i;
	char *id;
	char temp_buf[MESSAGE_LENGTH] = {""};

	#ifdef NDEBUG
	int no_release_message;
	no_release_message = is_sexp_true(node); 
	#endif

	node = CDR(node); 
	Assertion (node >= 0, "No message defined in debug SEXP"); 
	id = CTEXT(node);

	for (i=0; i<Num_messages; i++) {
		// find the message
		if ( !stricmp(id, Messages[i].name) ) {
			//replace variables if necessary
			strcpy_s(temp_buf, Messages[i].message);
			sexp_replace_variable_names_with_values(temp_buf, MESSAGE_LENGTH); 
			break;
		}
	}

	//send the message
	#ifndef NDEBUG
		Warning(LOCATION, "%s", temp_buf);
    #else	
	if (!no_release_message) {	
		ReleaseWarning(LOCATION, "%s", temp_buf);
	}
	#endif
}

// custom sexp operator for handling misc training stuff
int sexp_special_training_check(int node)
{
	int num, rtn;

	num = eval_num(node);
	if (num == SPECIAL_CHECK_TRAINING_FAILURE)
		return Training_failure ? SEXP_TRUE : SEXP_FALSE;

	// To MK: do whatever you want with this number here.
	rtn = process_special_sexps(eval_num(node));

	return rtn;
}

// sexpression to flash a hud gauge.  gauge name is text valud of node
void sexp_flash_hud_gauge( int node )
{
	char *name;
	int i;

	name = CTEXT(node);
	for (i = 0; i < NUM_HUD_GAUGES; i++ ) {
		if ( !stricmp(HUD_gauge_text[i], name) ) {
			hud_gauge_start_flash(i);	// call HUD function to flash gauge

			multi_start_callback();
			multi_send_int(i);
			multi_end_callback();

			break;
		}
	}
}

void multi_sexp_flash_hud_gauge()
{
	int i; 

	if (multi_get_int(i)) {
		hud_gauge_start_flash(i);
	}
}

void sexp_set_training_context_fly_path(int node)
{
	waypoint_list *wp_list = find_matching_waypoint_list(CTEXT(node));
	if (wp_list == NULL)
		return;

	Training_context |= TRAINING_CONTEXT_FLY_PATH;
	Training_context_path = wp_list;
	Training_context_distance = (float) atof(CTEXT(CDR(node)));
	Training_context_goal_waypoint = 0;
	Training_context_at_waypoint = -1;
}

void sexp_set_training_context_speed(int node)
{
	Training_context |= TRAINING_CONTEXT_SPEED;
	Training_context_speed_min = eval_num(node);
	Training_context_speed_max = eval_num(CDR(node));
	Training_context_speed_set = 0;
}

void sexp_scramble_messages(int node, bool scramble)
{
	if (node < 0)
	{
		// scramble messages on player ship... this isn't multi compatible, but neither was the old version of the sexp
		if (scramble)
			Player_ship->flags2 |= SF2_SCRAMBLE_MESSAGES;
		else
			Player_ship->flags2 &= ~SF2_SCRAMBLE_MESSAGES;
		return;
	}

	sexp_deal_with_ship_flag(node, true, 0, 0, 0, SF2_SCRAMBLE_MESSAGES, 0, P2_SF2_SCRAMBLE_MESSAGES, scramble, false, true);
}

void toggle_cutscene_bars(float delta_speed, int set) 
{
	//Do we want the bars?
	if (set) {
		Cutscene_bar_flags |= CUB_CUTSCENE;
	}
	else {
		Cutscene_bar_flags &= ~CUB_CUTSCENE;
	}

	if(delta_speed > 0.0f) {
		Cutscene_bars_progress = 0.0f;
		Cutscene_bar_flags |= CUB_GRADUAL;
		Cutscene_delta_time = delta_speed;
	}
	else {
		Cutscene_bar_flags &= ~CUB_GRADUAL;
	}
}

void sexp_toggle_cutscene_bars(int node, int set)
{
	float delta_speed = 0.0f;

	if(node != -1)
		delta_speed = eval_num(node)/1000.0f;

	toggle_cutscene_bars(delta_speed, set);

	multi_start_callback();
	multi_send_float(delta_speed);
	multi_end_callback();
}

void multi_sexp_toggle_cutscene_bars(int set)
{
	float delta_speed;

	if(multi_get_float(delta_speed) ) {
		toggle_cutscene_bars(delta_speed, set);
	}
}

void sexp_fade(bool fade_in, int duration, ubyte R, ubyte G, ubyte B)
{
	if (duration > 0)
	{
		Fade_start_timestamp = timestamp();
		Fade_end_timestamp = timestamp(duration);
		Fade_type = fade_in ? FI_FADEIN : FI_FADEOUT;
		gr_create_shader(&Viewer_shader, R, G, B, Viewer_shader.c);
	}
	else
	{
		Fade_type = FI_NONE;
		gr_create_shader(&Viewer_shader, R, G, B, fade_in ? 0 : 255);
	}
}

static int Fade_out_r = -1;
static int Fade_out_g = -1;
static int Fade_out_b = -1;

void sexp_fade(int n, bool fade_in)
{
	int duration = 0;
	int R = -1;
	int G = -1;
	int B = -1;

	if (n != -1)
	{
		duration = eval_num(n);
		n = CDR(n);

		if (n != -1)
		{
			R = eval_num(n);
			if (R < 0 || R > 255) R = -1;
			n = CDR(n);

			if (n != -1)
			{
				G = eval_num(n);
				if (G < 0 || G > 255) G = -1;
				n = CDR(n);

				if (n != -1)
				{
					B = eval_num(n);
					if (B < 0 || B > 255) B = -1;
					n = CDR(n);
				}
			}
		}
	}

	// select legacy (or default) fade color
	if (R < 0 || G < 0 || B < 0)
	{
		// fade white
		if (R == 1)
		{
			R = G = B = 255;
		}
		// fade red
		else if (R == 2)
		{
			R = 255;
			G = B = 0;
		}
		// default: fade black
		else
		{
			// Mantis #2944: if we're fading in, and we previously faded out to some specific color, use that same color to fade in
			if (fade_in && (Fade_out_r >= 0) && (Fade_out_g >= 0) && (Fade_out_b >= 0))
			{
				R = Fade_out_r;
				G = Fade_out_g;
				B = Fade_out_b;
			}
			else
			{
				R = G = B = 0;
			}
		}
	}

	// Mantis #2944, if we're fading out to some specific color, save that color
	if (!fade_in && ((R > 0) || (G > 0) || (B > 0)))
	{
		Fade_out_r = R;
		Fade_out_g = G;
		Fade_out_b = B;
	}

	sexp_fade(fade_in, duration, (ubyte) R, (ubyte) G, (ubyte) B);

	multi_start_callback();
	multi_send_int(duration);
	multi_send_int(R);
	multi_send_int(G);
	multi_send_int(B);
	multi_end_callback();
}

void multi_sexp_fade(bool fade_in)
{
	int duration = 0;
	int R = 0;
	int G = 0;
	int B = 0;

	if (multi_get_int(duration))
		if (multi_get_int(R))
			if (multi_get_int(G))
				multi_get_int(B);

	sexp_fade(fade_in, duration, (ubyte) R, (ubyte) G, (ubyte) B);
}

camera* sexp_get_set_camera(bool reset = false)
{
	static camid sexp_camera;
	if(!reset)
	{
		if(Viewer_mode & VM_FREECAMERA)
		{
			camera *cam = cam_get_current().getCamera();
			if(cam != NULL)
				return cam;
		}
	}
	if(!sexp_camera.isValid())
	{
		sexp_camera = cam_create("SEXP camera");
	}

	cam_set_camera(sexp_camera);

	return sexp_camera.getCamera();
}

void sexp_set_camera(int node)
{
	if(node == -1)
	{
		sexp_get_set_camera(true);
		return;
	}

	char *cam_name = CTEXT(node);
	camid cid = cam_lookup(cam_name);
	if(!cid.isValid())
	{
		cid = cam_create(cam_name);
	}
	cam_set_camera(cid);
}

void sexp_set_camera_position(int n)
{
	camera *cam = sexp_get_set_camera();
	
	if(cam == NULL)
		return;

	vec3d camera_vec;
	float camera_time = 0.0f;
	float camera_acc_time = 0.0f;
	float camera_dec_time = 0.0f;

	camera_vec.xyz.x = i2fl(eval_num(n));
	n = CDR(n);
	camera_vec.xyz.y = i2fl(eval_num(n));
	n = CDR(n);
	camera_vec.xyz.z = i2fl(eval_num(n));
	n = CDR(n);

	if(n != -1)
	{
		camera_time = eval_num(n) / 1000.0f;
		n = CDR(n);
		if(n != -1)
		{
			camera_dec_time = camera_acc_time = eval_num(n) / 1000.0f;
			n = CDR(n);
			if(n != -1)
			{
				camera_dec_time = eval_num(n) / 1000.0f;
			}
		}
	}

	cam->set_position(&camera_vec, camera_time, camera_acc_time, camera_dec_time);

	//multiplayer callback
	multi_start_callback();
	multi_send_float(camera_vec.xyz.x);
	multi_send_float(camera_vec.xyz.y);
	multi_send_float(camera_vec.xyz.z);
	multi_send_float(camera_time);
	multi_send_float(camera_acc_time);
	multi_send_float(camera_dec_time);
	multi_end_callback();
}

//CommanderDJ
void multi_sexp_set_camera_position()
{
	camera *cam = sexp_get_set_camera();
	
	if(cam == NULL) {
		Int3();
		return;
	}

	vec3d camera_vec;
	float camera_time = 0.0f;
	float camera_acc_time = 0.0f;
	float camera_dec_time = 0.0f;

	multi_get_float(camera_vec.xyz.x);
	multi_get_float(camera_vec.xyz.y);
	multi_get_float(camera_vec.xyz.z);
	multi_get_float(camera_time);
	multi_get_float(camera_acc_time);
	multi_get_float(camera_dec_time);

	cam->set_position(&camera_vec, camera_time, camera_acc_time, camera_dec_time);
}

void sexp_set_camera_rotation(int n)
{
	camera *cam = sexp_get_set_camera();
	if(cam == NULL)
		return;

	angles rot_angles;
	float rot_time = 0.0f;
	float rot_acc_time = 0.0f;
	float rot_dec_time = 0.0f;

	//Angles are in degrees
	rot_angles.p = fl_radians(eval_num(n) % 360);
	n = CDR(n);
	rot_angles.b = fl_radians(eval_num(n) % 360);
	n = CDR(n);
	rot_angles.h = fl_radians(eval_num(n) % 360);
	n = CDR(n);
	if(n != -1)
	{
		rot_time = eval_num(n) / 1000.0f;
		n = CDR(n);
		if(n != -1)
		{
			rot_dec_time = rot_acc_time = eval_num(n) / 1000.0f;
			n = CDR(n);
			if(n != -1)
			{
				rot_dec_time = eval_num(n) / 1000.0f;
			}
		}
	}

	cam->set_rotation(&rot_angles, rot_time, rot_acc_time, rot_dec_time);

	multi_start_callback();
	multi_send_float(rot_angles.b);
	multi_send_float(rot_angles.h);
	multi_send_float(rot_angles.p);
	multi_send_float(rot_time);
	multi_send_float(rot_acc_time);
	multi_send_float(rot_dec_time);
	multi_end_callback();
}

void multi_sexp_set_camera_rotation()
{
	camera *cam = sexp_get_set_camera();
	if(cam == NULL)
		return;

	angles rot_angles;
	float rot_time = 0.0f;
	float rot_acc_time = 0.0f;
	float rot_dec_time = 0.0f;

	multi_get_float(rot_angles.b);
	multi_get_float(rot_angles.h);
	multi_get_float(rot_angles.p);
	multi_get_float(rot_time);
	multi_get_float(rot_acc_time);
	multi_get_float(rot_dec_time);

	cam->set_rotation(&rot_angles, rot_time, rot_acc_time, rot_dec_time);
}

void sexp_set_camera_facing(int n)
{
	camera *cam = sexp_get_set_camera();
	if(cam == NULL)
		return;

	vec3d location;
	float rot_time = 0.0f;
	float rot_acc_time = 0.0f;
	float rot_dec_time = 0.0f;

	location.xyz.x = i2fl(eval_num(n));
	n = CDR(n);
	location.xyz.y = i2fl(eval_num(n));
	n = CDR(n);
	location.xyz.z = i2fl(eval_num(n));
	n = CDR(n);
	if(n != -1)
	{
		rot_time = eval_num(n) / 1000.0f;
		n = CDR(n);
		if(n != -1)
		{
			rot_dec_time = rot_acc_time = eval_num(n) / 1000.0f;
			n = CDR(n);
			if(n != -1)
			{
				rot_dec_time = eval_num(n) / 1000.0f;
			}
		}
	}

	cam->set_rotation_facing(&location, rot_time, rot_acc_time, rot_dec_time);

	//multiplayer callback
	multi_start_callback();
	multi_send_float(location.xyz.x);
	multi_send_float(location.xyz.y);
	multi_send_float(location.xyz.z);
	multi_send_float(rot_time);
	multi_send_float(rot_acc_time);
	multi_send_float(rot_dec_time);
	multi_end_callback();
}

void multi_sexp_set_camera_facing()
{
	camera *cam = sexp_get_set_camera();
	if(cam == NULL)
		return;

	vec3d location;
	float rot_time = 0.0f;
	float rot_acc_time = 0.0f;
	float rot_dec_time = 0.0f;

	multi_get_float(location.xyz.x);
	multi_get_float(location.xyz.y);
	multi_get_float(location.xyz.z);
	multi_get_float(rot_time);
	multi_get_float(rot_acc_time);
	multi_get_float(rot_dec_time);
 
	cam->set_rotation_facing(&location, rot_time, rot_acc_time, rot_dec_time);
}

//CommanderDJ
/**
 * Helper function for set_camera_facing_object
 */
void actually_set_camera_facing_object(char *object_name, float rot_time, float rot_acc_time, float rot_dec_time)
{
	object_ship_wing_point_team oswpt;
	sexp_get_object_ship_wing_point_team(&oswpt, object_name);

	switch (oswpt.type)
	{
		case OSWPT_TYPE_EXITED:
		{
			Warning(LOCATION, "Camera tried to face destroyed/departed object %s", object_name);
			return;
		}

		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WING:
		case OSWPT_TYPE_WAYPOINT:
		{
			camera *cam = sexp_get_set_camera();
			if(cam == NULL)
				return;
			cam->set_rotation_facing(&oswpt.objp->pos, rot_time, rot_acc_time, rot_dec_time);
			return;
		}
	}
}

void sexp_set_camera_facing_object(int n)
{
	char *object_name = CTEXT(n);
	float rot_time = 0.0f;
	float rot_acc_time = 0.0f;
	float rot_dec_time = 0.0f;

	//Now get the rotation time values
	n = CDR(n);
	if(n != -1)
	{
		rot_time = eval_num(n) / 1000.0f;
		n = CDR(n);
		if(n != -1)
		{
			rot_dec_time = rot_acc_time = eval_num(n) / 1000.0f;
			n = CDR(n);
			if(n != -1)
			{
				rot_dec_time = eval_num(n) / 1000.0f;
			}
		}
	}
	actually_set_camera_facing_object(object_name, rot_time, rot_acc_time, rot_dec_time);

	//multiplayer callback
	multi_start_callback();
	multi_send_string(object_name);
	multi_send_float(rot_time);
	multi_send_float(rot_acc_time);
	multi_send_float(rot_dec_time);
	multi_end_callback();
}

//CommanderDJ
void multi_sexp_set_camera_facing_object()
{
	char object_name[TOKEN_LENGTH];
	float rot_time = 0.0f;
	float rot_acc_time = 0.0f;
	float rot_dec_time = 0.0f;
	
	multi_get_string(object_name);
	multi_get_float(rot_time);
	multi_get_float(rot_acc_time);
	multi_get_float(rot_dec_time);
	
	actually_set_camera_facing_object(object_name, rot_time, rot_acc_time, rot_dec_time);
}

extern float VIEWER_ZOOM_DEFAULT;
void sexp_set_camera_fov(int n)
{
	camera *cam = sexp_get_set_camera();
	
	if(cam == NULL)
		return;

	float camera_time = 0.0f;
	float camera_acc_time = 0.0f;
	float camera_dec_time = 0.0f;

	float camera_fov = fl_radians(eval_num(n) % 360);
	n = CDR(n);

	if(n != -1)
	{
		camera_time = eval_num(n) / 1000.0f;
		n = CDR(n);
		if(n != -1)
		{
			camera_dec_time = camera_acc_time = eval_num(n) / 1000.0f;
			n = CDR(n);
			if(n != -1)
			{
				camera_dec_time = eval_num(n) / 1000.0f;
			}
		}
	}

	cam->set_fov(camera_fov, camera_time, camera_acc_time, camera_dec_time);


	multi_start_callback();
	multi_send_float(camera_fov);
	multi_send_float(camera_time);
	multi_send_float(camera_acc_time);
	multi_send_float(camera_dec_time);
	multi_end_callback();
}

//CommanderDJ
void multi_sexp_set_camera_fov()
{
	camera *cam = sexp_get_set_camera();
	
	if(cam == NULL)
		return;

	float camera_fov = VIEWER_ZOOM_DEFAULT;
	float camera_time = 0.0f;
	float camera_acc_time = 0.0f;
	float camera_dec_time = 0.0f;

	multi_get_float(camera_fov);
	multi_get_float(camera_time);
	multi_get_float(camera_acc_time);
	multi_get_float(camera_dec_time);

	cam->set_fov(camera_fov, camera_time, camera_acc_time, camera_dec_time);
}

//Internal helper function for set-target and set-host
object *sexp_camera_get_objsub(int node, int *o_submodel)
{
	//Get arguments
	int n = node;
	char *obj_name = NULL;
	char *sub_name = NULL;
	
	obj_name = CTEXT(n);
	n = CDR(n);
	if(n != -1)
		sub_name = CTEXT(n);
	
	//Important variables
	object *objp = NULL;
	int submodel = -1;
	
	//*****Process obj_name
	object_ship_wing_point_team oswpt;
	sexp_get_object_ship_wing_point_team(&oswpt, obj_name);
	
	switch (oswpt.type)
	{
		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WING:
		case OSWPT_TYPE_WAYPOINT:
			objp = oswpt.objp;
			break;

		default:
			objp = NULL;
	}

	//*****Process submodel
	if(objp != NULL && sub_name != NULL && oswpt.type == OSWPT_TYPE_SHIP)
	{
		if(stricmp(sub_name, SEXP_NONE_STRING))
		{
			ship_subsys *ss = ship_get_subsys(&Ships[objp->instance], sub_name);
			if (ss != NULL)
			{
				submodel = ss->system_info->subobj_num;
			}
		}
	}
	
	if(o_submodel != NULL)
		*o_submodel = submodel;
	
	return objp;
}

void sexp_set_camera_host(int node)
{
	//Try to get current camera
	camera *cam = sexp_get_set_camera();
	
	if(cam == NULL)
		return;
	
	//*****Get variables
	int submodel = -1;
	object *objp = sexp_camera_get_objsub(node, &submodel);
	
	//*****Set
	cam->set_object_host(objp, submodel);
}

void sexp_set_camera_target(int node)
{
	//Try to get current camera
	camera *cam = sexp_get_set_camera();
	
	if(cam == NULL)
		return;
	
	//*****Get variables
	int submodel = -1;
	object *objp = sexp_camera_get_objsub(node, &submodel);
	
	//*****Set
	cam->set_object_target(objp, submodel);

	multi_start_callback();
	multi_send_object(objp);
	multi_send_int(submodel);
	multi_end_callback();
}

void multi_sexp_set_camera_target()
{
	int submodel;
	object *objp;
	
	//Try to get current camera
	camera *cam = sexp_get_set_camera();
	
	if(cam == NULL)
		return;

	multi_get_object(objp);
	multi_get_int(submodel);
	
	cam->set_object_target(objp, submodel);
}

void sexp_set_fov(int n)
{
	camera *cam = Main_camera.getCamera();
	if(cam == NULL) {
		game_render_frame_setup();
		cam = Main_camera.getCamera();
	}

	//Cap FOV to something reasonable.
	float new_fov = (float)(eval_num(n) % 360);
	Sexp_fov = fl_radians(new_fov);

	multi_start_callback();
	multi_send_float(new_fov);
	multi_end_callback();
}

void multi_sexp_set_fov()
{
	float new_fov;

	camera *cam = Main_camera.getCamera();
	if(cam == NULL) {
		game_render_frame_setup();
		cam = Main_camera.getCamera();
	}

	multi_get_float(new_fov);
	Sexp_fov = fl_radians(new_fov);
}

int sexp_get_fov()
{
	camera *cam = Main_camera.getCamera();
	if(cam == NULL)
		return -1;
	else if(Sexp_fov > 0.0f)
		// SEXP override has been set
		return (int) fl_degrees(Sexp_fov);
	else	
		return (int) fl_degrees(cam->get_fov());
}

/**
 * @todo Check VIEWER_ZOOM_DEFAULT
 */
void sexp_reset_fov()
{
	camera *cam = Main_camera.getCamera();
	if(cam == NULL)
		return;

	Sexp_fov = 0.0;
	//cam->set_fov(VIEWER_ZOOM_DEFAULT);

	multi_do_callback();
}

void multi_sexp_reset_fov()
{
	camera *cam = Main_camera.getCamera();
	if(cam == NULL)
		return;

	Sexp_fov = 0.0;
}

void sexp_reset_camera(int node)
{
	bool cam_reset = false; 
	camera *cam = cam_get_current().getCamera();
	if(cam != NULL)
	{
		if(is_sexp_true(node))
		{
			cam->reset();
			cam_reset = true;
		}
	}
	cam_reset_camera();
	multi_start_callback();
	multi_send_bool(cam_reset);
	multi_end_callback();
}

void multi_sexp_reset_camera()
{
	camera *cam = cam_get_current().getCamera();
	bool cam_reset = false;

	multi_get_bool(cam_reset);
	if((cam != NULL) && cam_reset) {
		cam->reset();
	}
	cam_reset_camera();
}

void sexp_show_subtitle(int node)
{
	//These should be set to the default if not required to be explicitly defined
	int x_pos, y_pos, width=0;
	char *text, *imageanim=NULL;
	float display_time, fade_time=0.0f;
	int r=255, g=255, b=255;
	bool center_x=false, center_y=false;
	int n = -1;
	bool post_shaded = false;

	x_pos = eval_num(node);
	if (gr_screen.center_w != 1024)
		x_pos = (int) ((x_pos / 1024.0f) * gr_screen.center_w);

	n = CDR(node);
	y_pos = eval_num(n);
	if (gr_screen.center_h != 768)
		y_pos = (int) ((y_pos / 768.0f) * gr_screen.center_h);

	n = CDR(n);
	text = CTEXT(n);

	n = CDR(n);
	display_time = eval_num(n)/1000.0f;	//is in ms

	n = CDR(n);
	if(n != -1)
	{
		imageanim = CTEXT(n);

		n = CDR(n);
		if(n != -1)
		{
			fade_time = eval_num(n)/1000.0f; //also in ms

			n = CDR(n);
			if(n != -1)
			{
				center_x = is_sexp_true(n) != 0;

				n = CDR(n);
				if(n != -1)
				{
					center_y = is_sexp_true(n) != 0;
						
					n = CDR(n);
					if(n != -1)
					{
						width = eval_num(n);

						n = CDR(n);
						if(n != -1)
						{
							r = eval_num(n);

							n = CDR(n);
							if(n != -1)
							{
								g = eval_num(n);

								n = CDR(n);
								if(n != -1)
								{
									b = eval_num(n);

									n = CDR(n);
									if ( n !=-1 )
									{
										post_shaded = is_sexp_true(n) != 0;
									}
								}
							}
						}
					}
				}
			}
		}
	}

	if(r > 255)
		r = 255;
	if(g > 255)
		g = 255;
	if(b > 255)
		b = 255;

	//FINALLY !!
	color new_color;
	gr_init_alphacolor(&new_color, r, g, b, 255);

	subtitle new_subtitle(x_pos, y_pos, text, imageanim, display_time, fade_time, &new_color, -1, center_x, center_y, width, 0, post_shaded);
	Subtitles.push_back(new_subtitle);
}

void sexp_clear_subtitles() 
{
	Subtitles.clear();

	multi_do_callback();
}

void multi_sexp_clear_subtitles() 
{
	Subtitles.clear();
}

void sexp_show_subtitle_text(int node)
{
	int i, n = node, message_index = -1;
	char text[MESSAGE_LENGTH];

	// we'll suppose it's the string for now
	char *ctext = CTEXT(n);

	// but use an actual message if one exists
	for (i=0; i<Num_messages; i++)
	{
		if (!stricmp(Messages[i].name, ctext))
		{
			ctext = Messages[i].message;
			message_index = i;
			break;
		}
	}

	// translate things like keypresses, e.g. $T$ for targeting key
	// (we don't need to do variable replacements because the subtitle code already does that)
	message_translate_tokens(text, ctext);

	n = CDR(n);

	int x_pct = eval_num(n);
	n = CDR(n);

	int y_pct = eval_num(n);
	n = CDR(n);

	bool center_x = is_sexp_true(n) != 0;
	n = CDR(n);

	bool center_y = is_sexp_true(n) != 0;
	n = CDR(n);

	float display_time = eval_num(n) / 1000.0f;
	n = CDR(n);

	float fade_time = 0.0f;
	if (n >= 0)
	{
		fade_time = eval_num(n) / 1000.0f;
		n = CDR(n);
	}

	int width_pct = 0;
	if (n >= 0)
	{
		width_pct = eval_num(n);
		n = CDR(n);
	}

	int red = 255;
	if (n >= 0)
	{
		red = eval_num(n);
		n = CDR(n);
	}

	int green = 255;
	if (n >= 0)
	{
		green = eval_num(n);
		n = CDR(n);
	}

	int blue = 255;
	if (n >= 0)
	{
		blue = eval_num(n);
		n = CDR(n);
	}

	int fontnum = -1;
	if (n >= 0)
	{
		char *font_name = CTEXT(n);
		n = CDR(n);

		// perform font lookup
		for (int j = 0; j < Num_fonts; j++)
		{
			if (!stricmp(font_name, Fonts[j].filename))
			{
				fontnum = j;
				break;
			}
		}
	}

	bool post_shaded = false;
	if (n >= 0)
	{
		post_shaded = is_sexp_true(n) != 0;
		n = CDR(n);
	}

	// check bounds
	if (x_pct < -100)
		x_pct = -100;
	if (x_pct > 100)
		x_pct = 100;
	if (y_pct < -100)
		y_pct = -100;
	if (y_pct > 100)
		y_pct = 100;
	if (width_pct > 100)
		width_pct = 100;
	if (red > 255)
		red = 255;
	if (green > 255)
		green = 255;
	if (blue > 255)
		blue = 255;

	color new_color;
	gr_init_alphacolor(&new_color, red, green, blue, 255);

	// calculate pixel positions
	int x_pos = (int) (gr_screen.center_w * (x_pct / 100.0f));
	int y_pos = (int) (gr_screen.center_h * (y_pct / 100.0f));
	int width = (int) (gr_screen.center_w * (width_pct / 100.0f));

	// add the subtitle
	subtitle new_subtitle(x_pos, y_pos, text, NULL, display_time, fade_time, &new_color, fontnum, center_x, center_y, width, 0, post_shaded);
	Subtitles.push_back(new_subtitle);

	multi_start_callback();
	multi_send_int(x_pct);
	multi_send_int(y_pct);
	multi_send_int (message_index);
	// only send the text if it is not a message. If it is a message, we've already sent the index anyway. 
	if (message_index == -1) {
		multi_send_string(text);
	}
	multi_send_float(display_time);
	multi_send_float(fade_time);
	multi_send_int(red);
	multi_send_int(green);
	multi_send_int(blue);
	multi_send_int(fontnum);
	multi_send_bool(center_x);
	multi_send_bool(center_y);
	multi_send_int(width_pct);
	multi_send_bool(post_shaded);
	multi_end_callback();
}

void multi_sexp_show_subtitle_text()
{
	int x_pct, y_pct, width_pct, fontnum, message_index = -1;
	char text[MESSAGE_LENGTH];
	float display_time, fade_time=0.0f;
	int red=255, green=255, blue=255;
	bool center_x=false, center_y=false;
	bool post_shaded = false;
	color new_color;

	multi_get_int(x_pct);
	multi_get_int(y_pct);
	multi_get_int(message_index); 
	if (message_index == -1) {
		multi_get_string(text);
	}
	else {
		char *ctext = Messages[message_index].message;
		message_translate_tokens(text, ctext);
	}
	multi_get_float(display_time);
	multi_get_float(fade_time);
	multi_get_int(red);
	multi_get_int(green);
	multi_get_int(blue);
	multi_get_int(fontnum);
	multi_get_bool(center_x);
	multi_get_bool(center_y);
	multi_get_int(width_pct);
	multi_get_bool(post_shaded);

	gr_init_alphacolor(&new_color, red, green, blue, 255);

	// calculate pixel positions
	int x_pos = (int)(gr_screen.center_w * (x_pct / 100.0f));
	int y_pos = (int)(gr_screen.center_h * (y_pct / 100.0f));
	int width = (int)(gr_screen.center_w * (width_pct / 100.0f));

	// add the subtitle
	subtitle new_subtitle(x_pos, y_pos, text, NULL, display_time, fade_time, &new_color, fontnum, center_x, center_y, width, 0, post_shaded);
	Subtitles.push_back(new_subtitle);	

}

void sexp_show_subtitle_image(int node)
{
	int n = node;

	char *image = CTEXT(n);
	n = CDR(n);

	int x_pct = eval_num(n);
	n = CDR(n);

	int y_pct = eval_num(n);
	n = CDR(n);

	bool center_x = is_sexp_true(n) != 0;
	n = CDR(n);

	bool center_y = is_sexp_true(n) != 0;
	n = CDR(n);

	int width_pct = eval_num(n);
	n = CDR(n);

	int height_pct = eval_num(n);
	n = CDR(n);

	float display_time = eval_num(n) / 1000.0f;
	n = CDR(n);

	float fade_time = 0.0f;
	if (n >= 0)
	{
		fade_time = eval_num(n) / 1000.0f;
		n = CDR(n);
	}

	bool post_shaded = false;
	if (n >= 0)
	{
		post_shaded = is_sexp_true(n) != 0;
		n = CDR(n);
	}

	// check bounds
	if (x_pct < -100)
		x_pct = -100;
	if (x_pct > 100)
		x_pct = 100;
	if (y_pct < -100)
		y_pct = -100;
	if (y_pct > 100)
		y_pct = 100;
	if (width_pct < 0)
		width_pct = 0;
	if (width_pct > 100)
		width_pct = 100;
	if (height_pct < 0)
		height_pct = 0;
	if (height_pct > 100)
		height_pct = 100;

	// calculate pixel positions
	int x_pos = (int)(gr_screen.center_w * (x_pct / 100.0f));
	int y_pos = (int)(gr_screen.center_h * (y_pct / 100.0f));
	int width = (int)(gr_screen.center_w * (width_pct / 100.0f));
	int height = (int)(gr_screen.center_h * (height_pct / 100.0f));

	// add the subtitle
	subtitle new_subtitle(x_pos, y_pos, NULL, image, display_time, fade_time, NULL, -1, center_x, center_y, width, height, post_shaded);
	Subtitles.push_back(new_subtitle);

	multi_start_callback();
	multi_send_int(x_pos);
	multi_send_int(y_pos);
	multi_send_string(image);
	multi_send_float(display_time);
	multi_send_float(fade_time);
	multi_send_bool(center_x);
	multi_send_bool(center_y);
	multi_send_int(width);
	multi_send_int(height);
	multi_send_bool(post_shaded);
	multi_end_callback();
}

void multi_sexp_show_subtitle_image()
{
	int x_pos, y_pos, width=0, height=0;
	char image[TOKEN_LENGTH];
	float display_time, fade_time=0.0f;
	bool center_x=false, center_y=false;
	bool post_shaded = false;

	multi_get_int(x_pos);
	multi_get_int(y_pos);
	multi_get_string(image);
	multi_get_float(display_time);
	multi_get_float(fade_time);
	multi_get_bool(center_x);
	multi_get_bool(center_y);
	multi_get_int(width);
	multi_get_int(height);
	multi_get_bool(post_shaded);

	// add the subtitle
	subtitle new_subtitle(x_pos, y_pos, NULL, image, display_time, fade_time, NULL, -1, center_x, center_y, width, height, post_shaded);
	Subtitles.push_back(new_subtitle);	

}

void sexp_set_time_compression(int n)
{
	float new_multiplier = 0.0f;
	float new_change_time = 0.0f;
	float current_multiplier = 0.0f;

	multi_start_callback();

	new_multiplier = eval_num(n)/100.0f;			//percent->decimal
	multi_send_float(new_multiplier);


	//Time to change
	n = CDR(n);
	if(n != -1) {
		new_change_time = eval_num(n)/1000.0f;			//ms->seconds
		multi_send_float(new_change_time);
	}

	//Override current time compression with this value
	n = CDR(n);
	if(n != -1) {
		current_multiplier = eval_num(n)/100.0f;
		set_time_compression(current_multiplier);
		multi_send_float(current_multiplier);
	}

	multi_end_callback();

	set_time_compression(new_multiplier, new_change_time);
	lock_time_compression(true);
}

void multi_sexp_set_time_compression()
{
	float new_change_time = 0.0f;
	float new_multiplier = 0.0f;
	float current_multiplier = 0.0f;

	multi_get_float(new_multiplier);
	multi_get_float(new_change_time);
	if (multi_get_float(current_multiplier)) {
		set_time_compression(current_multiplier);
	}

	set_time_compression(new_multiplier, new_change_time);
	lock_time_compression(true);
}

void sexp_reset_time_compression()
{
	set_time_compression(1);
	lock_time_compression(false);

	multi_start_callback();
	multi_end_callback();
}

void multi_sexp_reset_time_compression() 
{
	set_time_compression(1);
	lock_time_compression(false);
}

extern bool Perspective_locked;

void sexp_force_perspective(int n)
{
	Perspective_locked = (is_sexp_true(n) != 0);
	n=CDR(n);

	if(n != -1)
	{
		n = eval_num(n);
		switch(n)
		{
			case 0:
				Viewer_mode = 0;
				break;
			case 1:
				Viewer_mode = VM_CHASE;
				break;
			case 2:
				Viewer_mode = VM_EXTERNAL;
				break;
			case 3:
				Viewer_mode = VM_TOPDOWN;
				break;
		}
	}
}

void sexp_set_camera_shudder(int n)
{
	int time = eval_num(n); 
	float intensity = (float) eval_num(CDR(n)) * 0.01f; 

	game_shudder_apply(time, intensity);

	multi_start_callback();
	multi_send_int(time);
	multi_send_float(intensity); 
	multi_end_callback();
}

void multi_sexp_set_camera_shudder()
{
	int time;
	float intensity;

	multi_get_int(time);
	if (multi_get_float(intensity)) {
		game_shudder_apply(time, intensity);
	}
}

void sexp_set_jumpnode_name(int n) //CommanderDJ
{
	char *old_name = CTEXT(n); //for multi

	CJumpNode *jnp = jumpnode_get_by_name(old_name);

	if(jnp==NULL) {
		return;
	}

	n=CDR(n);
	char *new_name = CTEXT(n); //for multi
	jnp->SetName(new_name);

	//multiplayer callback
	multi_start_callback();
	multi_send_string(old_name);
	multi_send_string(new_name);
	multi_end_callback();
}

void multi_sexp_set_jumpnode_name() //CommanderDJ
{
	char old_name[TOKEN_LENGTH];
	char new_name[TOKEN_LENGTH];
	
	multi_get_string(old_name);
	multi_get_string(new_name);

	CJumpNode *jnp = jumpnode_get_by_name(old_name);

	if(jnp==NULL) 
		return;

	jnp->SetName(new_name);
}

void sexp_set_jumpnode_color(int n)
{
	CJumpNode *jnp = jumpnode_get_by_name(CTEXT(n));

	if(jnp==NULL)
		return;

	char* jumpnode_name = CTEXT(n); //for multi

	n=CDR(n);

	int red = eval_num(n);
	int green = eval_num(CDR(n));
	int blue = eval_num(CDR(CDR(n)));
	int alpha = eval_num(CDR(CDR(CDR(n))));

	jnp->SetAlphaColor(red, green, blue, alpha);

	multi_start_callback();
	multi_send_string(jumpnode_name);
	multi_send_int(red);
	multi_send_int(green);
	multi_send_int(blue);
	multi_send_int(alpha);
	multi_end_callback();
}

//CommanderDJ
void multi_sexp_set_jumpnode_color()
{
	char jumpnode_name[TOKEN_LENGTH];
	int red, blue, green, alpha;

	multi_get_string(jumpnode_name);
	CJumpNode *jnp = jumpnode_get_by_name(jumpnode_name);

	if(jnp==NULL) {
		multi_discard_remaining_callback_data();
		return;
	}

	multi_get_int(red);
	multi_get_int(green);
	multi_get_int(blue);
	multi_get_int(alpha);

	jnp->SetAlphaColor(red, green, blue, alpha);
}

void sexp_set_jumpnode_model(int n)
{
	char* jumpnode_name = CTEXT(n);
	CJumpNode *jnp = jumpnode_get_by_name(jumpnode_name);

	if(jnp==NULL)
		return;

	n=CDR(n);
	char* model_name = CTEXT(n);
	n=CDR(n);
	bool show_polys = (is_sexp_true(n) != 0);

	jnp->SetModel(model_name, show_polys);

	multi_start_callback();
	multi_send_string(jumpnode_name);
	multi_send_string(model_name);
	multi_send_bool(show_polys);
	multi_end_callback();
}

void multi_sexp_set_jumpnode_model()
{
	char jumpnode_name[TOKEN_LENGTH];
	char model_name[TOKEN_LENGTH];
	bool show_polys;

	multi_get_string(jumpnode_name);
	multi_get_string(model_name);

	CJumpNode *jnp = jumpnode_get_by_name(jumpnode_name);

	if(jnp==NULL) {
		multi_discard_remaining_callback_data();		
		return;
	}

	show_polys = multi_get_bool(show_polys);

	jnp->SetModel(model_name, show_polys);
}

void sexp_show_hide_jumpnode(int node, bool show)
{
	multi_start_callback();

	for (int n = node; n >= 0; n = CDR(n))
	{
		CJumpNode *jnp = jumpnode_get_by_name(CTEXT(n));
		if (jnp != NULL)
		{
			jnp->SetVisibility(show);
			multi_send_string(CTEXT(n));
		}
	}

	multi_end_callback();
}

void multi_sexp_show_hide_jumpnode(bool show)
{
	char jumpnode_name[TOKEN_LENGTH];

	while (multi_get_string(jumpnode_name))
	{
		CJumpNode *jnp = jumpnode_get_by_name(jumpnode_name);
		if (jnp != NULL)
			jnp->SetVisibility(show);
	}
}

//WMC - This is a bit of a hack, however, it's easier than
//coding in a whole new Script_system function.
int sexp_script_eval(int node, int return_type, bool concat_args = false)
{
	int n = node;

	switch(return_type)
	{
		case OPR_NUMBER:
			{
				char* s = CTEXT(n);
				int r = -1;
				bool success = Script_system.EvalString(CTEXT(n), "|i", &r);

				if(!success)
					Warning(LOCATION, "sexp-script-eval failed to evaluate string \"%s\"; check your syntax", s);

				return r;
			}
		case OPR_STRING:
			{
				char* ret = NULL;
				char* s = CTEXT(n);

				bool success = Script_system.EvalString(s, "|s", &ret);
				n = CDR(n);

				if(!success)
					Warning(LOCATION, "sexp-script-eval failed to evaluate string \"%s\"; check your syntax", s);

				if (n != -1 && success)
				{
					Assert(Sexp_nodes[n].first == -1);
					int variable_index = atoi(Sexp_nodes[n].text);

					// verify variable set
					Assert(Sexp_variables[variable_index].type & SEXP_VARIABLE_SET);

					if (!(Sexp_variables[variable_index].type & SEXP_VARIABLE_STRING))
					{
						Warning(LOCATION, "Variable for script-eval has to be a string variable!");
					}
					else if (ret != NULL)
					{
						// assign to variable
						sexp_modify_variable(ret, variable_index);
					}

					n = CDR(n);
				}
			}
			break;
		case OPR_NULL:
			{
				SCP_string script_cmd;
				while (n != -1)
				{
					char* s = CTEXT(n);

					if (concat_args)
					{
						script_cmd.append(CTEXT(n));
					}
					else
					{
						bool success = Script_system.EvalString(s, NULL, NULL);

						if (!success)
							Warning(LOCATION, "sexp-script-eval failed to evaluate string \"%s\"; check your syntax", s);
					}

					n = CDR(n);
				}

				if (concat_args)
				{
					bool success = Script_system.EvalString(script_cmd.c_str(), NULL, NULL);

					if (!success)
						Warning(LOCATION, "sexp-script-eval failed to evaluate string \"%s\"; check your syntax", script_cmd.c_str());
				}
			}
			break;
		default:
			Error(LOCATION, "Bad type passed to sexp_script_eval - get a coder");
			break;
	}

	return -1;
}

void sexp_script_eval_multi(int node)
{
	char s[TOKEN_LENGTH];
	bool success = true;
	int execute_on_server;
	int sindex;
	player *p;

	strcpy_s(s, CTEXT(node));

	node = CDR(node);

	execute_on_server = is_sexp_true(node);

	node = CDR(node);

	multi_start_callback();
	multi_send_string(s);
	// evalutate on all clients
	if (node == -1) {
		multi_send_bool(true);			
		execute_on_server = 1;
	}
	// we have to send to all clients but we need to send a list of ships so that they know if they evaluate or not
	else {
		multi_send_bool(false);

		do {
			p = get_player_from_ship_node(node, true);

			// not a player ship so skip it
			if (p == NULL ){
				node = CDR(node);
				continue;
			}
			else {
				// if this is me, flag that we should execute the script
				if (p == Player) {					
					execute_on_server = 1;
				}
				// otherwise notify the clients
				else {
					sindex = ship_name_lookup(CTEXT(node));
					multi_send_ship(sindex);
				}
			}

			node = CDR(node);
		} while (node != -1); 
	}

	multi_end_callback();

	if (execute_on_server) {		
		success = Script_system.EvalString(s, NULL, NULL, s);
	}

	if(!success) {
		Warning(LOCATION, "sexp-script-eval failed to evaluate string \"%s\"; check your syntax", s);
	}
}

void multi_sexp_script_eval_multi()
{
	int sindex;
	char s[TOKEN_LENGTH];
	bool sent_to_all = false;
	bool success = true;

	multi_get_string(s);
	multi_get_bool(sent_to_all);

	if (sent_to_all) {
		success = Script_system.EvalString(s, NULL, NULL, s);
	}
	// go through all the ships that were sent and see if any of them match this client.
	else {
		while (multi_get_ship(sindex)) {
			Assertion(sindex >= 0, "Illegal value for the ship index sent in multi_sexp_script_eval_multi()! Ship %d does not exist!", sindex); 
			if (Player->objnum == Ships[sindex].objnum) {
				success = Script_system.EvalString(s, NULL, NULL, s);
			}
		}
	}

	if(!success) {
		Warning(LOCATION, "sexp-script-eval failed to evaluate string \"%s\"; check your syntax", s);
	}
}


void sexp_force_glide(int node)
{
	ship *shipp;
	int sindex;

	// get ship
	sindex = ship_name_lookup(CTEXT(node));

	if (sindex < 0) {
		return;
	}

	shipp = &Ships[sindex];
	if (shipp->objnum < 0) {
		return;
	}

	//Can this ship glide?
	if (!Ship_info[shipp->ship_info_index].can_glide)
		return;

	int glide = is_sexp_true(CDR(node));

	object_set_gliding(&Objects[shipp->objnum], (glide > 0), true);

	return;
}

bool test_point_within_box(vec3d *test_point, vec3d *box_corner_1, vec3d *box_corner_2, object *reference_ship_obj)
{
	vec3d tempv, test_point_buf;

	// If reference_ship is specified, rotate test_point into its reference frame
	if (reference_ship_obj != NULL) 
	{
		vm_vec_sub(&tempv, test_point, &reference_ship_obj->pos);
		vm_vec_rotate(&test_point_buf, &tempv, &reference_ship_obj->orient);

		test_point = &test_point_buf;
	}

	// Check to see if the test point is within the specified box as defined by two extreme corners
	return ((test_point->xyz.x >= box_corner_1->xyz.x && test_point->xyz.x <= box_corner_2->xyz.x) &&
			(test_point->xyz.y >= box_corner_1->xyz.y && test_point->xyz.y <= box_corner_2->xyz.y) &&
			(test_point->xyz.z >= box_corner_1->xyz.z && test_point->xyz.z <= box_corner_2->xyz.z));
}

int sexp_is_in_box(int n)
{
	int i;
	Assert(n >= 0);

	object_ship_wing_point_team oswpt;
	sexp_get_object_ship_wing_point_team(&oswpt, CTEXT(n));
	n = CDR(n);

	// Get box corners
	float x1 = (float) eval_num(n);
	n = CDR(n);
	float x2 = (float) eval_num(n);
	n = CDR(n);
	float y1 = (float) eval_num(n);
	n = CDR(n);
	float y2 = (float) eval_num(n);
	n = CDR(n);
	float z1 = (float) eval_num(n);
	n = CDR(n);
	float z2 = (float) eval_num(n);
	n = CDR(n);	
	vec3d box_corner_1;
	box_corner_1.xyz.x = MIN(x1, x2);
	box_corner_1.xyz.y = MIN(y1, y2);
	box_corner_1.xyz.z = MIN(z1, z2);
	vec3d box_corner_2;
	box_corner_2.xyz.x = MAX(x1, x2);
	box_corner_2.xyz.y = MAX(y1, y2);
	box_corner_2.xyz.z = MAX(z1, z2);

	// Ship to define reference frame is optional
	object* reference_ship_obj = NULL;
	if (n != -1)
	{
		int sindex = ship_name_lookup(CTEXT(n));

		if (sindex < 0 || Ships[sindex].objnum < 0)
			return SEXP_FALSE;

		reference_ship_obj = &Objects[Ships[sindex].objnum];
	}

	// Check position of object
	switch (oswpt.type)
	{
		case OSWPT_TYPE_EXITED:
			return SEXP_KNOWN_FALSE;

		case OSWPT_TYPE_WING:
			for (i = 0; i < oswpt.wingp->current_count; i++)
				if (!test_point_within_box(&Objects[Ships[oswpt.wingp->ship_index[i]].objnum].pos, &box_corner_1, &box_corner_2, reference_ship_obj))
		return SEXP_FALSE;
			return SEXP_TRUE;

		case OSWPT_TYPE_SHIP:
		case OSWPT_TYPE_WAYPOINT:
			return test_point_within_box(&oswpt.objp->pos, &box_corner_1, &box_corner_2, reference_ship_obj);

		default:
		return SEXP_FALSE;
	}
}

int sexp_is_in_mission(int node)
{
	for (int n = node; n != -1; n = CDR(n))
		if (ship_name_lookup(CTEXT(n)) < 0)
			return SEXP_FALSE;

	return SEXP_TRUE;
}

void sexp_manipulate_colgroup(int node, bool add_to_group) {
	object* objp;
	ship* shipp;
	int colgroup_id;

	shipp = sexp_get_ship_from_node(node);

	if (shipp == NULL)
		return;

	objp = &Objects[shipp->objnum];
	colgroup_id = objp->collision_group_id;

	node = CDR(node);

	while (node != -1) {

		int group = eval_num(node);
		
		if (group < 0 || group > 31) {
			WarningEx(LOCATION, "Invalid collision group id %d specified for object %s. Valid IDs range from 0 to 31.\n", group, shipp->ship_name); 
		} else {
			if (add_to_group) {
				colgroup_id |= (1<<group);
			} else {
				colgroup_id &= !(1<<group);
			}
		}

		node = CDR(node);
	}

	objp->collision_group_id = colgroup_id;
}

int sexp_get_colgroup(int node) {
	ship* shipp;

	shipp = sexp_get_ship_from_node(CDR(node));

	return Objects[shipp->objnum].collision_group_id;
}

int get_effect_from_name(char* name) {
	int i = 0;
	for (SCP_vector<ship_effect>::iterator sei = Ship_effects.begin(); sei != Ship_effects.end(); ++sei) {
		if (!stricmp(name, sei->name))
			return i;
		i++;
	}
	return -1;
}

void sexp_ship_effect(int n)
{
	char	*name;
	int ship_index, wing_index;
	
	Assert ( n != -1 );
	
	int effect_num = get_effect_from_name(CTEXT(n));
	if (effect_num == -1) {
		WarningEx(LOCATION, "Invalid effect name passed to ship-effect\n");
		return;
	}
	n = CDR(n);
	int effect_duration = eval_num(n);
	n = CDR(n);

	ship_index = -1;
	wing_index = -1;
	while (n != -1) {
		name = CTEXT(n);

		// check to see if this ship/wing has arrived yet.
		if (sexp_query_has_yet_to_arrive(name)) {
			n = CDR(n);
			continue;
		}

		// check to see if this ship/wing has departed.
		if ( mission_log_get_time (LOG_SHIP_DEPARTED, name, NULL, NULL) || mission_log_get_time (LOG_WING_DEPARTED, name, NULL, NULL) ) {
			n = CDR(n);
			continue;
		}

		// check to see if this ship/wing has been destroyed.
		if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, NULL) || mission_log_get_time(LOG_WING_DESTROYED, name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, name, NULL, NULL)) {
			n = CDR(n);
			continue;
		}

		ship *sp;
		if((wing_index = wing_name_lookup(name)) >= 0)
		{
			wing *wp = &Wings[wing_index];
			for(int i = 0; i < wp->current_count; i++)
			{
				if(wp->ship_index[i] >= 0)
				{
					sp = &Ships[wp->ship_index[i]];
					sp->shader_effect_active = true;
					sp->shader_effect_num = effect_num;
					sp->shader_effect_duration = effect_duration;
					sp->shader_effect_start_time = timer_get_milliseconds();
				}
			}
		}
		else
		{
			if((ship_index = ship_name_lookup(name)) >= 0)
			{
				sp = &Ships[ship_index];
				sp->shader_effect_active = true;
				sp->shader_effect_num = effect_num;
				sp->shader_effect_duration = effect_duration;
				sp->shader_effect_start_time = timer_get_milliseconds();
			}
			else
				mprintf(("Invalid Shipname in SEXP ship-effect\n"));
		}

		// move to next ship/wing in list
		n = CDR(n);
	}
}

void sexp_change_team_color(int n) {
	SCP_string new_color = CTEXT(n);
	SCP_vector<ship*> shippointers;
	n = CDR(n);
	int fade_time = eval_num(n);

	n = CDR(n);

	while (n != -1) {
		ship* shipp = sexp_get_ship_from_node(n);

		if (shipp != NULL) {
			shippointers.push_back(shipp);
		}

		n = CDR(n);
	}

	multi_start_callback();
	multi_send_string(new_color);
	multi_send_int(fade_time);
	multi_send_int(shippointers.size());

	for (SCP_vector<ship*>::iterator shipp = shippointers.begin(); shipp != shippointers.end(); ++shipp) {
		ship* shp = *shipp;
		multi_send_ship(shp);
		if (fade_time == 0) {
			shp->team_name = new_color;
		} else {
			shp->secondary_team_name = new_color;
			shp->team_change_time = fade_time;
			shp->team_change_timestamp = Missiontime;
		}
	}

	multi_end_callback();
}

void multi_sexp_change_team_color() {
	SCP_string new_color = "<none>";
	int fade_time = 0;
	int n_ships = 0;
	
	multi_get_string(new_color);
	multi_get_int(fade_time);
	multi_get_int(n_ships);

	for (int i = 0; i < n_ships; ++i) {
		ship* shipp;
		multi_get_ship(shipp);
		if (fade_time == 0) {
			shipp->team_name = new_color;
		} else {
			shipp->secondary_team_name = new_color;
			shipp->team_change_time = fade_time;
			shipp->team_change_timestamp = Missiontime;
		}
	}
}

void sexp_call_ssm_strike(int node) {
	int ssm_index = ssm_info_lookup(CTEXT(node));
	node = CDR(node);
	int calling_team = iff_lookup(CTEXT(node));
	if (ssm_index < 0 || calling_team < 0)
		return;

	for (int n = node; n != -1; n = CDR(n)) {
		int ship_num = ship_name_lookup(CTEXT(n));
		// don't do anything if the ship isn't there
		if (ship_num >= 0) {
			int obj_num = Ships[ship_num].objnum;
			object *target_ship = &Objects[obj_num];
			vec3d start = target_ship->pos;

			vm_vec_scale_add(&start, &start, &target_ship->orient.vec.fvec, -1);

			ssm_create(target_ship, &start, ssm_index, NULL, calling_team);
		}
	}
}

extern int Cheats_enabled;
int sexp_player_is_cheating_bastard() {
	if (Cheats_enabled) {
		return SEXP_KNOWN_TRUE;	
	}

	return SEXP_FALSE;
}

void sexp_set_motion_debris(int node) {
	Motion_debris_override = is_sexp_true(node) != 0;
}

/**
 * Returns the subsystem type if the name of a subsystem is actually a generic type (e.g \<all engines\> or \<all turrets\>
 */
int get_generic_subsys(char *subsys_name) 
{
	if (!strcmp(subsys_name, SEXP_ALL_ENGINES_STRING)) {
		return SUBSYSTEM_ENGINE;
	} else if (!strcmp(subsys_name, SEXP_ALL_TURRETS_STRING)) {
		return SUBSYSTEM_TURRET;
	}

	Assert(SUBSYSTEM_NONE == 0);
	return SUBSYSTEM_NONE;
}

// Karajorma - returns false if the ship class has changed since the mission was parsed in
// Changes can be from use of the change-ship-class SEXP, loadout or any future method
bool ship_class_unchanged(int ship_index) 
{	
	p_object *p_objp;

	ship *shipp = &Ships[ship_index];	
	p_objp = mission_parse_get_parse_object(shipp->ship_name);

	if ((p_objp != NULL) && (p_objp->ship_class == shipp->ship_info_index)) {
		return true;
	}

	return false;
}

// Goober5000 - needed because any nonzero integer value is "true"
int is_sexp_true(int cur_node, int referenced_node)
{
	int result = eval_sexp(cur_node, referenced_node);

	return (result == SEXP_TRUE); // note: any SEXP_KNOWN_TRUE result will return SEXP_TRUE
}


/**
* 
*/
int generate_event_log_flags_mask(int result)
{
	int matches = 0; 
	mission_event *current_event = &Mission_events[Event_index];

	switch (result) {
		case SEXP_TRUE:
			matches |= MLF_SEXP_TRUE; 
			break; 

		case SEXP_FALSE:
			matches |= MLF_SEXP_FALSE; 
			break;

		default:
			Error(LOCATION, "SEXP has a value which isn't true or false.");	
	}

	if (( result == SEXP_TRUE ) || (result == SEXP_KNOWN_TRUE)) {
		// now deal with the flags depending on repeat and trigger counts
		switch (current_event->mission_log_flags) {
			case MLF_FIRST_REPEAT_ONLY: 
				if (current_event->repeat_count > 1) {			
					matches |= MLF_FIRST_REPEAT_ONLY; 
				}
				break;

			case MLF_LAST_REPEAT_ONLY: 
				if (current_event->repeat_count == 1) {			
					matches |= MLF_LAST_REPEAT_ONLY; 
				}
				break;

			case MLF_FIRST_TRIGGER_ONLY: 
				if (current_event->trigger_count > 1) {			
					matches |= MLF_FIRST_TRIGGER_ONLY; 
				}
				break;

			case MLF_LAST_TRIGGER_ONLY: 
				if ((current_event->trigger_count == 1) && (current_event->flags & MEF_USING_TRIGGER_COUNT)) {			
					matches |= MLF_LAST_TRIGGER_ONLY; 
				}
				break;
		}
	}

	return matches;
}

void current_log_to_backup_log_buffer()
{
	Mission_events[Event_index].backup_log_buffer.clear();
	if (!(Mission_events[Event_index].mission_log_flags & MLF_STATE_CHANGE)){
		return;
	}

	for (int i = 0; i < (int)Current_event_log_buffer->size(); i++) {
		Mission_events[Event_index].backup_log_buffer.push_back(Current_event_log_buffer->at(i));
	}
}

void maybe_write_previous_event_to_log(int result) 
{
	mission_event *this_event = &Mission_events[Event_index];

	// if the old log is empty, all we do is record the result for the next evaluation
	// the old log should only be empty at mission start
	if (this_event->backup_log_buffer.empty()) {
		this_event->previous_result = result;
		return;
	}

	// if there's no change in state, we don't write the previous state to the log
	if ((this_event->mission_log_flags & MLF_STATE_CHANGE) && (result == this_event->previous_result)) {
		current_log_to_backup_log_buffer();
		return;
	}

	log_string(LOGFILE_EVENT_LOG, "Event has changed state. Old state");
	while (!this_event->backup_log_buffer.empty()) {
		log_string(LOGFILE_EVENT_LOG, this_event->backup_log_buffer.back().c_str());
		this_event->backup_log_buffer.pop_back();
	}
	log_string(LOGFILE_EVENT_LOG, "New state");

	// backup the current buffer as this may be a repeating event
	current_log_to_backup_log_buffer();
}

/**
* Checks the mission logs flags for this event and writes to the log if this has been asked for
*/
void maybe_write_to_event_log(int result)
{
	char buffer [256]; 

	int mask = generate_event_log_flags_mask(result); 
	sprintf(buffer, "Event: %s at mission time %d seconds (%d milliseconds)", Mission_events[Event_index].name, f2i(Missiontime), f2i((longlong)Missiontime * 1000));
	Current_event_log_buffer->push_back(buffer);
		
	if (!Snapshot_all_events && (!(mask &=  Mission_events[Event_index].mission_log_flags))) {
		current_log_to_backup_log_buffer();
		Current_event_log_buffer->clear();
		return;
	}

	// remove some of the flags	
	if (mask & (MLF_FIRST_REPEAT_ONLY | MLF_FIRST_TRIGGER_ONLY)) {
		Mission_events[Event_index].mission_log_flags &= ~(MLF_FIRST_REPEAT_ONLY | MLF_FIRST_TRIGGER_ONLY) ; 
	}

	if (Mission_events[Event_index].mission_log_flags & MLF_STATE_CHANGE) {
		maybe_write_previous_event_to_log(result);
	}

	while (!Current_event_log_buffer->empty()) {
		log_string(LOGFILE_EVENT_LOG, Current_event_log_buffer->back().c_str());
		Current_event_log_buffer->pop_back();
	}
	log_string(LOGFILE_EVENT_LOG, "");

}

/**
* Returns the constant used as a SEXP's result as text for printing to the event log
*/
char *sexp_get_result_as_text(int result)
{
	switch (result) {
		case SEXP_TRUE:
			return "TRUE";

		case SEXP_FALSE:
			return "FALSE";

		case SEXP_KNOWN_FALSE:
			return "ALWAYS FALSE";

		case SEXP_KNOWN_TRUE:
			return "ALWAYS TRUE";

		case SEXP_UNKNOWN:	
			return "UNKNOWN";
				
		case SEXP_NAN:	
			return "NOT A NUMBER";

		case SEXP_NAN_FOREVER:
			return "CAN NEVER BE A NUMBER";

		case SEXP_CANT_EVAL:
			return "CAN'T EVALUATE";

		default:
			return NULL;
	}
}

/**
* Checks the mission logs flags for this event and writes to the log if this has been asked for
*/
void add_to_event_log_buffer(int op_num, int result)
{
	Assertion ((Current_event_log_buffer != NULL) &&
				(Current_event_log_variable_buffer != NULL)&& 
				(Current_event_log_argument_buffer != NULL), "Attempting to write to a non-existent log buffer");

	if (op_num == -1) {
		nprintf(("SEXP", "ERROR: op_num function returned %i, this should not happen. Contact a coder.\n", op_num));
		return; //How does this happen?
	}

	char buffer[TOKEN_LENGTH];
	SCP_string tmp; 
	tmp.append(Operators[op_num].text);
	tmp.append(" returned ");

	if ((Operators[op_num].type & (SEXP_INTEGER_OPERATOR|SEXP_ARITHMETIC_OPERATOR)) || (sexp_get_result_as_text(result) == NULL)) {
		sprintf(buffer, "%d", result);
		tmp.append(buffer);
	}
	else {
		tmp.append(sexp_get_result_as_text(result));
	}

	if (True_loop_argument_sexps && !Sexp_replacement_arguments.empty()) {
		tmp.append(" for argument ");
		tmp.append(Sexp_replacement_arguments.back());
	}
	
	if (!Current_event_log_argument_buffer->empty()) {
		tmp.append(" for the following arguments");
		while (!Current_event_log_argument_buffer->empty()) {
			tmp.append("\n");
			tmp.append(Current_event_log_argument_buffer->back().c_str());
			Current_event_log_argument_buffer->pop_back();
		}
	}

	if (!Current_event_log_variable_buffer->empty()) {
		tmp.append("\nVariables:\n");
		while (!Current_event_log_variable_buffer->empty()) {
			tmp.append(Current_event_log_variable_buffer->back().c_str()); 
			Current_event_log_variable_buffer->pop_back();
			tmp.append("[");
			tmp.append(Current_event_log_variable_buffer->back().c_str()); 
			Current_event_log_variable_buffer->pop_back();
			tmp.append("]");
		}
	}

	Current_event_log_buffer->push_back(tmp);
}

/**
 * High-level sexpression evaluator
 */
int eval_sexp(int cur_node, int referenced_node)
{
	int node, type, sexp_val = UNINITIALIZED;
	if (cur_node == -1)  // empty list, i.e. sexp: ( )
		return SEXP_FALSE;

	Assert(cur_node >= 0);			// we have special sexp nodes <= -1!!!  MWA
									// which should be intercepted before we get here.  HOFFOSS
	type = SEXP_NODE_TYPE(cur_node);
	Assert( (type == SEXP_LIST) || (type == SEXP_ATOM) );

	// trap known true and known false sexpressions.  We don't trap on SEXP_NAN sexpressions since
	// they may yet evaluate to true or false.

	if (Sexp_nodes[cur_node].value == SEXP_KNOWN_TRUE) {
		if (Log_event) {
			add_to_event_log_buffer(get_operator_index(cur_node), SEXP_KNOWN_TRUE);
		}
		return SEXP_TRUE;
	}
	else if (Sexp_nodes[cur_node].value == SEXP_KNOWN_FALSE) {
		if (Log_event) {
			add_to_event_log_buffer(get_operator_index(cur_node), SEXP_KNOWN_FALSE);
		}
		return SEXP_FALSE;
	}
	else if (Sexp_nodes[cur_node].value == SEXP_NAN_FOREVER) {
		if (Log_event) {
			add_to_event_log_buffer(get_operator_index(cur_node), SEXP_NAN_FOREVER);
		}
		return SEXP_FALSE;
	}

	if (Sexp_nodes[cur_node].first != -1) {
		node = CAR(cur_node);
		sexp_val = eval_sexp(node);
		Sexp_nodes[cur_node].value = Sexp_nodes[node].value;	// higher level node gets node value
		return sexp_val;

	} else {
		int op_num;

		node = CDR(cur_node);		// makes reading the next bit of code a little easier.

		op_num = get_operator_const(cur_node);
		// add the op_num to the stack if it is an actual operator rather than a number
		if (op_num) {
			Current_sexp_operator.push_back(op_num); 
		}
		switch ( op_num ) {
		// arithmetic operators will always return just their value
			case OP_PLUS:
				sexp_val = add_sexps(node);
				break;

			case OP_MINUS:
				sexp_val = sub_sexps(node);
				break;

			case OP_MUL:
				sexp_val = mul_sexps(node);
				break;

			case OP_MOD:
				sexp_val = mod_sexps(node);
				break;

			case OP_DIV:
				sexp_val = div_sexps(node);
				break;

			case OP_RAND:
			case OP_RAND_MULTIPLE:
				sexp_val = rand_sexp( node, (op_num == OP_RAND_MULTIPLE) );
				break;

			case OP_ABS:
				sexp_val = abs_sexp(node);
				break;

			case OP_MIN:
				sexp_val = min_sexp(node);
				break;

			case OP_MAX:
				sexp_val = max_sexp(node);
				break;

			case OP_AVG:
				sexp_val = avg_sexp(node);
				break;

			case OP_POW:
				sexp_val = pow_sexp(node);
				break;

			case OP_SIGNUM:
				sexp_val = signum_sexp(node);
				break;

			case OP_SET_BIT:
			case OP_UNSET_BIT:
				sexp_val = sexp_set_bit(node, op_num == OP_SET_BIT);
				break;

			case OP_IS_BIT_SET:
				sexp_val = sexp_is_bit_set(node);
				break;

			case OP_BITWISE_AND:
				sexp_val = sexp_bitwise_and(node);
				break;

			case OP_BITWISE_OR:
				sexp_val = sexp_bitwise_or(node);
				break;

			case OP_BITWISE_NOT:
				sexp_val = sexp_bitwise_not(node);
				break;

			case OP_BITWISE_XOR:
				sexp_val = sexp_bitwise_xor(node);
				break;

			// boolean operators can have one of the special sexp values (known true, known false, unknown)
			case OP_TRUE:
				sexp_val = SEXP_KNOWN_TRUE;
				break;

			case OP_FALSE:
				sexp_val = SEXP_KNOWN_FALSE;
				break;

			case OP_OR:
				sexp_val = sexp_or(node);
				break;

			case OP_AND:
				sexp_val = sexp_and(node);
				break;

			case OP_AND_IN_SEQUENCE:
				sexp_val = sexp_and_in_sequence(node);
				break;

			case OP_XOR:
				sexp_val = sexp_xor(node);
				break;

			case OP_EQUALS:
			case OP_GREATER_THAN:
			case OP_LESS_THAN:
			case OP_NOT_EQUAL:
			case OP_GREATER_OR_EQUAL:
			case OP_LESS_OR_EQUAL:
				sexp_val = sexp_number_compare( node, op_num );
				break;

			case OP_STRING_GREATER_THAN:
			case OP_STRING_LESS_THAN:
			case OP_STRING_EQUALS:
				sexp_val = sexp_string_compare( node, op_num );
				break;

			case OP_IS_IFF:
				sexp_val = sexp_is_iff(node);
				break;

			case OP_NOT:
				sexp_val = sexp_not(node);
				break;

			case OP_PREVIOUS_GOAL_TRUE:
				sexp_val = sexp_previous_goal_status( node, GOAL_COMPLETE );
				break;

			case OP_PREVIOUS_GOAL_FALSE:
				sexp_val = sexp_previous_goal_status( node, GOAL_FAILED );
				break;

			case OP_PREVIOUS_GOAL_INCOMPLETE:
				sexp_val = sexp_previous_goal_status( node, GOAL_INCOMPLETE );
				break;

			case OP_PREVIOUS_EVENT_TRUE:
				sexp_val = sexp_previous_event_status( node, EVENT_SATISFIED );
				break;

			case OP_PREVIOUS_EVENT_FALSE:
				sexp_val = sexp_previous_event_status( node, EVENT_FAILED );
				break;

			case OP_PREVIOUS_EVENT_INCOMPLETE:
				sexp_val = sexp_previous_event_status( node, EVENT_INCOMPLETE );
				break;

			case OP_EVENT_TRUE:
			case OP_EVENT_FALSE:
				sexp_val = sexp_event_status( node, (op_num == OP_EVENT_TRUE?1:0) );
				if ((sexp_val != SEXP_TRUE) && (sexp_val != SEXP_KNOWN_TRUE))
					Sexp_useful_number = 0;  // indicate sexp isn't current yet
				break;

			case OP_EVENT_TRUE_DELAY:
			case OP_EVENT_FALSE_DELAY:
				sexp_val = sexp_event_delay_status( node, (op_num == OP_EVENT_TRUE_DELAY?1:0) );
				break;

			case OP_EVENT_TRUE_MSECS_DELAY:
			case OP_EVENT_FALSE_MSECS_DELAY:
				sexp_val = sexp_event_delay_status( node, (op_num == OP_EVENT_TRUE_MSECS_DELAY?1:0), true );
				break;

			case OP_GOAL_TRUE_DELAY:
			case OP_GOAL_FALSE_DELAY:
				sexp_val = sexp_goal_delay_status( node, (op_num == OP_GOAL_TRUE_DELAY?1:0) );
				break;

			case OP_EVENT_INCOMPLETE:
				sexp_val = sexp_event_incomplete(node);
				if ((sexp_val != SEXP_TRUE) && (sexp_val != SEXP_KNOWN_TRUE))
					Sexp_useful_number = 0;  // indicate sexp isn't current yet
				break;

			case OP_GOAL_INCOMPLETE:
				sexp_val = sexp_goal_incomplete(node);
				break;

			// destroy type sexpressions
			case OP_IS_DESTROYED:
				sexp_val = sexp_is_destroyed( node, NULL );
				break;

			case OP_WAS_DESTROYED_BY_DELAY:
				sexp_val = sexp_was_destroyed_by_delay(node);
				break;

			case OP_IS_SUBSYSTEM_DESTROYED:
				sexp_val = sexp_is_subsystem_destroyed(node);
				break;

			case OP_HAS_ARRIVED:
				sexp_val = sexp_has_arrived( node, NULL );
				break;

			case OP_HAS_DEPARTED:
				sexp_val = sexp_has_departed( node, NULL );
				break;

			case OP_IS_DISABLED:
				sexp_val = sexp_is_disabled( node, NULL );
				break;

			case OP_IS_DISARMED:
				sexp_val = sexp_is_disarmed( node, NULL );
				break;

			case OP_WAYPOINTS_DONE:
				sexp_val = sexp_are_waypoints_done(node);
				break;

			// objective operators that use a delay
			case OP_IS_DESTROYED_DELAY:
				sexp_val = sexp_is_destroyed_delay(node);
				break;

			case OP_IS_SUBSYSTEM_DESTROYED_DELAY:
				sexp_val = sexp_is_subsystem_destroyed_delay(node);
				break;

			case OP_HAS_DOCKED:
			case OP_HAS_UNDOCKED:
			case OP_HAS_DOCKED_DELAY:
			case OP_HAS_UNDOCKED_DELAY:
				sexp_val = sexp_has_docked_or_undocked(node, op_num);
				break;

			case OP_HAS_ARRIVED_DELAY:
				sexp_val = sexp_has_arrived_delay(node);
				break;

			case OP_HAS_DEPARTED_DELAY:
				sexp_val = sexp_has_departed_delay(node);
				break;

			case OP_IS_DISABLED_DELAY:
				sexp_val = sexp_is_disabled_delay(node);
				break;

			case OP_IS_DISARMED_DELAY:
				sexp_val = sexp_is_disarmed_delay(node);
				break;

			case OP_WAYPOINTS_DONE_DELAY:
				sexp_val = sexp_are_waypoints_done_delay(node);
				break;

			case OP_SHIP_TYPE_DESTROYED:
				sexp_val = sexp_ship_type_destroyed(node);
				break;

			// time based sexpressions
			case OP_HAS_TIME_ELAPSED:
				sexp_val = sexp_has_time_elapsed(node);
				break;

			case OP_MODIFY_VARIABLE:
				sexp_modify_variable(node);
				sexp_val = SEXP_TRUE;	// SEXP_TRUE means only do once.
				break;

			case OP_GET_VARIABLE_BY_INDEX:
				sexp_val = sexp_get_variable_by_index(node);
				break;

			case OP_SET_VARIABLE_BY_INDEX:
				sexp_set_variable_by_index(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_COPY_VARIABLE_FROM_INDEX:
				sexp_copy_variable_from_index(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_COPY_VARIABLE_BETWEEN_INDEXES:
				sexp_copy_variable_between_indexes(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_TIME_SHIP_DESTROYED:
				sexp_val = sexp_time_destroyed(node);
				break;
			
			case OP_TIME_WING_DESTROYED:
				sexp_val = sexp_time_wing_destroyed(node);
				break;
			
			case OP_TIME_SHIP_ARRIVED:
				sexp_val = sexp_time_ship_arrived(node);
				break;
			
			case OP_TIME_WING_ARRIVED:
				sexp_val = sexp_time_wing_arrived(node);
				break;
			
			case OP_TIME_SHIP_DEPARTED:
				sexp_val = sexp_time_ship_departed(node);
				break;
			
			case OP_TIME_WING_DEPARTED:
				sexp_val = sexp_time_wing_departed(node);
				break;

			case OP_MISSION_TIME:
				sexp_val = sexp_mission_time();
				break;

			case OP_MISSION_TIME_MSECS:
				sexp_val = sexp_mission_time_msecs();
				break;

			case OP_TIME_DOCKED:
				sexp_val = sexp_time_docked(node);
				break;

			case OP_TIME_UNDOCKED:
				sexp_val = sexp_time_undocked(node);
				break;

			case OP_AFTERBURNER_LEFT:
				sexp_val = sexp_get_energy_pct(node, op_num);
				break;

			case OP_WEAPON_ENERGY_LEFT:
				sexp_val = sexp_get_energy_pct(node, op_num);
				break;

			case OP_SHIELDS_LEFT:
				sexp_val = sexp_shields_left(node);
				break;

			case OP_HITS_LEFT:
				sexp_val = sexp_hits_left(node);
				break;

			case OP_HITS_LEFT_SUBSYSTEM:
				sexp_val = sexp_hits_left_subsystem(node);
				break;

			case OP_HITS_LEFT_SUBSYSTEM_GENERIC:
				sexp_val = sexp_hits_left_subsystem_generic(node);
				break;

			case OP_HITS_LEFT_SUBSYSTEM_SPECIFIC:
				sexp_val = sexp_hits_left_subsystem_specific(node);
				break;

			case OP_SIM_HITS_LEFT:
				sexp_val = sexp_sim_hits_left(node);
				break;

			case OP_SPECIAL_WARP_DISTANCE:
				sexp_val = sexp_special_warp_dist(node);
				break;

			case OP_DISTANCE:
				sexp_val = sexp_distance(node);
				break;

			case OP_DISTANCE_SUBSYSTEM:
				sexp_val = sexp_distance_subsystem(node);
				break;

			case OP_NUM_WITHIN_BOX:
				sexp_val = sexp_num_within_box(node);
				break;

			case OP_IS_IN_BOX:
				sexp_val = sexp_is_in_box(node);
				break;

			case OP_IS_IN_MISSION:
				sexp_val = sexp_is_in_mission(node);
				break;

			case OP_IS_SHIP_VISIBLE:
				sexp_val = sexp_is_ship_visible(node);
				break;

			case OP_IS_SHIP_STEALTHY:
				sexp_val = sexp_is_ship_stealthy(node);
				break;

			case OP_IS_FRIENDLY_STEALTH_VISIBLE:
				sexp_val = sexp_is_friendly_stealth_visible(node);
				break;

			case OP_TEAM_SCORE:
				sexp_val = sexp_team_score(node);
				break;

			case OP_LAST_ORDER_TIME:
				sexp_val = sexp_last_order_time(node);
				break;

			case OP_NUM_PLAYERS:
				sexp_val = sexp_num_players();
				break;

			case OP_SKILL_LEVEL_AT_LEAST:
				sexp_val = sexp_skill_level_at_least(node);
				break;

			case OP_IS_CARGO_KNOWN:
			case OP_CARGO_KNOWN_DELAY:
				sexp_val = sexp_is_cargo_known( node, (op_num==OP_IS_CARGO_KNOWN)?0:1 );
				break;

			case OP_HAS_BEEN_TAGGED_DELAY:
				sexp_val = sexp_has_been_tagged_delay(node);
				break;

			case OP_ARE_SHIP_FLAGS_SET:
				sexp_val = sexp_are_ship_flags_set(node);
				break;

			case OP_CAP_SUBSYS_CARGO_KNOWN_DELAY:
				sexp_val = sexp_cap_subsys_cargo_known_delay(node);
				break;

			case OP_WAS_PROMOTION_GRANTED:
				sexp_val = sexp_was_promotion_granted(node);
				break;

			case OP_WAS_MEDAL_GRANTED:
				sexp_val = sexp_was_medal_granted(node);
				break;

			case OP_GET_DAMAGE_CAUSED:
				sexp_val = sexp_get_damage_caused(node);
				break;

			case OP_PERCENT_SHIPS_ARRIVED:
			case OP_PERCENT_SHIPS_DEPARTED:
			case OP_PERCENT_SHIPS_DESTROYED:
			case OP_PERCENT_SHIPS_DISARMED:
			case OP_PERCENT_SHIPS_DISABLED:
				sexp_val = sexp_percent_ships_arrive_depart_destroy_disarm_disable(node, op_num);
				break;

			case OP_DEPART_NODE_DELAY:
				sexp_val = sexp_depart_node_delay(node);
				break;

			case OP_DESTROYED_DEPARTED_DELAY:
				sexp_val = sexp_destroyed_departed_delay(node);
				break;

			// conditional sexpressions
			case OP_WHEN:
			case OP_WHEN_ARGUMENT:
			case OP_IF_THEN_ELSE:
				sexp_val = eval_when( node, op_num );
				break;

			case OP_PERFORM_ACTIONS:
				sexp_val = eval_perform_actions( node );
				break;

			case OP_COND:
				sexp_val = eval_cond(node);
				break;

			// Goober5000: special case; evaluate like when, but flush the sexp tree
			// and return SEXP_NAN so this will always be re-evaluated
			case OP_EVERY_TIME:
			case OP_EVERY_TIME_ARGUMENT:
				eval_when( node, op_num );
				flush_sexp_tree(node);
				sexp_val = SEXP_NAN;
				break;

			// Goober5000
			case OP_ANY_OF:
				sexp_val = eval_any_of( cur_node, referenced_node );
				break;

			// Goober5000
			case OP_EVERY_OF:
				sexp_val = eval_every_of( cur_node, referenced_node );
				break;

			// Goober5000 and Karajorma
			case OP_RANDOM_OF:
			case OP_RANDOM_MULTIPLE_OF:
				sexp_val = eval_random_of( cur_node, referenced_node, (op_num == OP_RANDOM_MULTIPLE_OF) );
				break;

			// Goober5000
			case OP_NUMBER_OF:
				sexp_val = eval_number_of( cur_node, referenced_node );
				break;

			// Karajorma
			case OP_IN_SEQUENCE:
				sexp_val = eval_in_sequence( cur_node, referenced_node );
				break;

			// Goober5000
			case OP_FOR_COUNTER:
				sexp_val = eval_for_counter( cur_node, referenced_node );
				break;

			// Karajorma
			case OP_INVALIDATE_ALL_ARGUMENTS:
			case OP_VALIDATE_ALL_ARGUMENTS:
				sexp_change_all_argument_validity(cur_node, (op_num == OP_INVALIDATE_ALL_ARGUMENTS));
				sexp_val = SEXP_TRUE;
			break;

			// Goober5000
			case OP_INVALIDATE_ARGUMENT:
			case OP_VALIDATE_ARGUMENT:
				sexp_change_argument_validity(node, (op_num == OP_INVALIDATE_ARGUMENT));
				sexp_val = SEXP_TRUE;
				break;

			case OP_DO_FOR_VALID_ARGUMENTS:
				// do-for-valid-arguments should only ever be called within eval_when()
				Int3();
				break;

			case OP_NUM_VALID_ARGUMENTS:
				sexp_val = sexp_num_valid_arguments( cur_node );
				break;

			// sexpressions with side effects
			case OP_CHANGE_IFF:
				sexp_change_iff(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_ADD_SHIP_GOAL:
				sexp_add_ship_goal(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_ADD_WING_GOAL:
				sexp_add_wing_goal(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_ADD_GOAL:
				sexp_add_goal(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_REMOVE_GOAL:
				sexp_remove_goal(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_CLEAR_SHIP_GOALS:
				sexp_clear_ship_goals(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_CLEAR_WING_GOALS:
				sexp_clear_wing_goals(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_CLEAR_GOALS:
				sexp_clear_goals(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_PROTECT_SHIP:
			case OP_UNPROTECT_SHIP:
				sexp_protect_ships(node, (op_num == OP_PROTECT_SHIP));
				sexp_val = SEXP_TRUE;
				break;

			case OP_BEAM_PROTECT_SHIP:
			case OP_BEAM_UNPROTECT_SHIP:
				sexp_beam_protect_ships(node, (op_num == OP_BEAM_PROTECT_SHIP));
				sexp_val = SEXP_TRUE;
				break;

			case OP_TURRET_PROTECT_SHIP:
			case OP_TURRET_UNPROTECT_SHIP:
				sexp_turret_protect_ships(node, (op_num == OP_TURRET_PROTECT_SHIP));
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_STEALTHY:
			case OP_SHIP_UNSTEALTHY:
				sexp_ships_stealthy(node, (op_num == OP_SHIP_STEALTHY));
				sexp_val = SEXP_TRUE;
				break;

			case OP_FRIENDLY_STEALTH_INVISIBLE:
			case OP_FRIENDLY_STEALTH_VISIBLE:
				sexp_friendly_stealth_invisible(node, (op_num == OP_FRIENDLY_STEALTH_INVISIBLE));
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_INVISIBLE:
			case OP_SHIP_VISIBLE:
				sexp_ships_visible(node, (op_num == OP_SHIP_VISIBLE));
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_SHIP_TAG:
			case OP_SHIP_UNTAG:
				sexp_ship_tag(node, (op_num == OP_SHIP_TAG));
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_CHANGE_ALT_NAME:
				sexp_ship_change_alt_name(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_CHANGE_CALLSIGN:
				sexp_ship_change_callsign(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_DEATH_MESSAGE:
				sexp_set_death_message(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_ALTER_SHIP_FLAG:
				sexp_alter_ship_flag(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_VULNERABLE:
			case OP_SHIP_INVULNERABLE:
				sexp_ships_invulnerable(node, (op_num == OP_SHIP_INVULNERABLE));
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_BOMB_TARGETABLE:
			case OP_SHIP_BOMB_UNTARGETABLE:
				sexp_ships_bomb_targetable(node, (op_num == OP_SHIP_BOMB_TARGETABLE));
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_GUARDIAN:
			case OP_SHIP_NO_GUARDIAN:
				sexp_ships_guardian(node, (op_num == OP_SHIP_GUARDIAN));
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_GUARDIAN_THRESHOLD:
				sexp_ship_guardian_threshold(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_SUBSYS_GUARDIAN_THRESHOLD:
				sexp_ship_subsys_guardian_threshold(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_SUBSYS_TARGETABLE:
				sexp_ship_deal_with_subsystem_flag(node, SSF_UNTARGETABLE, true, false);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_SUBSYS_UNTARGETABLE:
				sexp_ship_deal_with_subsystem_flag(node, SSF_UNTARGETABLE, true, true);
				sexp_val = SEXP_TRUE;
				break;

			case OP_TURRET_SUBSYS_TARGET_DISABLE:
				sexp_val = SEXP_TRUE;
				sexp_ship_deal_with_subsystem_flag(node, SSF_NO_SS_TARGETING, false, true);
				break;

			case OP_TURRET_SUBSYS_TARGET_ENABLE:
				sexp_val = SEXP_TRUE;
				sexp_ship_deal_with_subsystem_flag(node, SSF_NO_SS_TARGETING, false, false);
				break;

			case OP_SHIP_SUBSYS_NO_REPLACE:
				sexp_ship_deal_with_subsystem_flag(node, SSF_NO_REPLACE, true);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_SUBSYS_NO_LIVE_DEBRIS:
				sexp_ship_deal_with_subsystem_flag(node, SSF_NO_LIVE_DEBRIS, true);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_SUBSYS_VANISHED:
				sexp_ship_deal_with_subsystem_flag(node, SSF_VANISHED, true);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_SUBSYS_IGNORE_IF_DEAD:
				sexp_ship_deal_with_subsystem_flag(node, SSF_MISSILES_IGNORE_IF_DEAD, false);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_CREATE:
				sexp_ship_create(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_WEAPON_CREATE:
				sexp_weapon_create(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_VANISH:
				sexp_ship_vanish(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_DESTROY_INSTANTLY:
				sexp_destroy_instantly(node);
				sexp_val = SEXP_TRUE;
				break;

			//-Sesquipedalian
			case OP_SHIELDS_ON: 
			case OP_SHIELDS_OFF:
				sexp_shields_off(node, (op_num == OP_SHIELDS_OFF));
				sexp_val = SEXP_TRUE;
				break;

			//-Sesquipedalian
			case OP_KAMIKAZE: 
				sexp_kamikaze(node, (op_num == OP_KAMIKAZE));
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_CARGO:
				sexp_set_cargo(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_IS_CARGO:
				sexp_val = sexp_is_cargo(node);
				break;

			case OP_CHANGE_AI_CLASS:
				sexp_change_ai_class(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_IS_AI_CLASS:
				sexp_val = sexp_is_ai_class(node);
				break;
				
			case OP_IS_SHIP_TYPE:
				sexp_val = sexp_is_ship_type(node);
				break;

			case OP_IS_SHIP_CLASS:
				sexp_val = sexp_is_ship_class(node);
				break;

			case OP_CHANGE_SOUNDTRACK:
				sexp_change_soundtrack(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_PLAY_SOUND_FROM_TABLE:
				sexp_play_sound_from_table(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_PLAY_SOUND_FROM_FILE:
				sexp_play_sound_from_file(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_CLOSE_SOUND_FROM_FILE:
				sexp_close_sound_from_file(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_PAUSE_SOUND_FROM_FILE:
				sexp_pause_sound_from_file(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_SOUND_ENVIRONMENT:
				sexp_set_sound_environment(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_UPDATE_SOUND_ENVIRONMENT:
				sexp_update_sound_environment(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_ADJUST_AUDIO_VOLUME:
				sexp_adjust_audio_volume(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_HUD_DISABLE:
				sexp_hud_disable(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_HUD_DISABLE_EXCEPT_MESSAGES:
				sexp_hud_disable_except_messages(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_HUD_SET_TEXT:
				sexp_hud_set_text(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_HUD_SET_TEXT_NUM:
				sexp_hud_set_text_num(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_HUD_SET_COORDS:
				sexp_hud_set_coords(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_HUD_SET_FRAME:
				sexp_hud_set_frame(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_HUD_SET_COLOR:
				sexp_hud_set_color(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_HUD_SET_MAX_TARGETING_RANGE:
				sexp_hud_set_max_targeting_range(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_HUD_DISPLAY_GAUGE:
				sexp_hud_display_gauge(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_HUD_SET_MESSAGE:
				sexp_hud_set_message(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_PLAYER_USE_AI:
			case OP_PLAYER_NOT_USE_AI:
				sexp_player_use_ai(op_num == OP_PLAYER_USE_AI);
				sexp_val = SEXP_TRUE;
				break;

			//Karajorma
			case OP_ALLOW_TREASON:
				sexp_allow_treason(node);
				sexp_val = SEXP_TRUE;
				break; 

			//Karajorma
			case OP_SET_PLAYER_ORDERS:
				sexp_set_player_orders(node);
				sexp_val = SEXP_TRUE;
				break; 

			// Goober5000
			case OP_EXPLOSION_EFFECT:
				sexp_explosion_effect(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_WARP_EFFECT:
				sexp_warp_effect(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SEND_MESSAGE:
				sexp_send_message(node);
				sexp_val = SEXP_TRUE;
				break;

			// Karajorma
			case OP_ENABLE_BUILTIN_MESSAGES:
			case OP_DISABLE_BUILTIN_MESSAGES:
				sexp_toggle_builtin_messages (node, op_num == OP_ENABLE_BUILTIN_MESSAGES);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_PERSONA:
				sexp_set_persona (node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_MISSION_MOOD:
				sexp_set_mission_mood (node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SEND_MESSAGE_LIST:
				sexp_send_message_list(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SEND_RANDOM_MESSAGE:
				sexp_send_random_message(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SELF_DESTRUCT:
				sexp_self_destruct(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_NEXT_MISSION:
				sexp_next_mission(node);
				sexp_val = SEXP_TRUE;
				break;
				
			case OP_END_OF_CAMPAIGN:
				sexp_end_of_campaign(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_END_CAMPAIGN:
				sexp_end_campaign(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SABOTAGE_SUBSYSTEM:
				sexp_sabotage_subsystem(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_REPAIR_SUBSYSTEM:
				sexp_repair_subsystem(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_SUBSYSTEM_STRNGTH:
				sexp_set_subsystem_strength(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_DESTROY_SUBSYS_INSTANTLY:
				sexp_destroy_subsys_instantly(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_INVALIDATE_GOAL:
			case OP_VALIDATE_GOAL:
				sexp_change_goal_validity( node, (op_num==OP_INVALIDATE_GOAL?0:1) );
				sexp_val = SEXP_TRUE;
				break;

			case OP_TRANSFER_CARGO:
				sexp_transfer_cargo(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_EXCHANGE_CARGO:
				sexp_exchange_cargo(node);
				sexp_val = SEXP_TRUE;
				break;


			case OP_JETTISON_CARGO:
				sexp_jettison_cargo(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_DOCKED:
				sexp_set_docked(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_CARGO_NO_DEPLETE:
				sexp_cargo_no_deplete(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_SCANNED:	// Goober5000
			case OP_SET_UNSCANNED:
				sexp_set_scanned_unscanned(node, op_num == OP_SET_SCANNED);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_SPECIAL_WARPOUT_NAME:
				sexp_special_warpout_name(node);
				sexp_val = SEXP_TRUE;
				break;

			//-WMC
			case OP_MISSION_SET_NEBULA:
				sexp_mission_set_nebula(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_MISSION_SET_SUBSPACE:
				sexp_mission_set_subspace(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_ADD_BACKGROUND_BITMAP:
				sexp_add_background_bitmap(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_REMOVE_BACKGROUND_BITMAP:
				sexp_remove_background_bitmap(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_ADD_SUN_BITMAP:
				sexp_add_sun_bitmap(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_REMOVE_SUN_BITMAP:
				sexp_remove_sun_bitmap(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_NEBULA_CHANGE_STORM:
				sexp_nebula_change_storm(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_NEBULA_TOGGLE_POOF:
				sexp_nebula_toggle_poof(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_NEBULA_CHANGE_PATTERN:
				sexp_nebula_change_pattern(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_END_MISSION:
				sexp_end_mission(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_SET_DEBRIEFING_TOGGLED:
				sexp_set_debriefing_toggled(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_FORCE_JUMP:
				sexp_force_jump();
				sexp_val = SEXP_TRUE;
				break;

				// sexpressions for setting flag for good/bad time for someone to reasm
			case OP_GOOD_REARM_TIME:
				sexp_good_time_to_rearm(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_GRANT_PROMOTION:
				sexp_grant_promotion();
				sexp_val = SEXP_TRUE;
				break;

			case OP_GRANT_MEDAL:
				sexp_grant_medal(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_VAPORIZE:
			case OP_SHIP_NO_VAPORIZE:
				sexp_ships_vaporize( node, (op_num == OP_SHIP_VAPORIZE) );
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_EXPLOSION_OPTION:
				sexp_set_explosion_option(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_DONT_COLLIDE_INVISIBLE:
			case OP_COLLIDE_INVISIBLE:
				sexp_dont_collide_invisible( node, (op_num == OP_DONT_COLLIDE_INVISIBLE) );
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_MOBILE:
			case OP_SET_IMMOBILE:
				sexp_set_immobile(node, (op_num == OP_SET_IMMOBILE));
				sexp_val = SEXP_TRUE;
				break;

			case OP_IGNORE_KEY:
				sexp_ignore_key(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000 - sigh, was this messed up all along?
			case OP_WARP_BROKEN:
			case OP_WARP_NOT_BROKEN:
			case OP_WARP_NEVER:
			case OP_WARP_ALLOWED:
				sexp_deal_with_warp( node, (op_num==OP_WARP_BROKEN) || (op_num==OP_WARP_NOT_BROKEN),
					(op_num==OP_WARP_BROKEN) || (op_num==OP_WARP_NEVER) );
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_SET_SUBSPACE_DRIVE:
				sexp_set_subspace_drive(node);
				break;

			case OP_GOOD_SECONDARY_TIME:
				sexp_good_secondary_time(node);
				sexp_val = SEXP_TRUE;
				break;

			// sexpressions to allow shpis/weapons during the course of a mission
			case OP_ALLOW_SHIP:
				sexp_allow_ship(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_ALLOW_WEAPON:
				sexp_allow_weapon(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_TECH_ADD_SHIP:
				sexp_tech_add_ship(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_TECH_ADD_WEAPON:
				sexp_tech_add_weapon(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_TECH_ADD_INTEL:
				sexp_tech_add_intel(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_TECH_ADD_INTEL_XSTR:
				sexp_tech_add_intel_xstr(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_TECH_RESET_TO_DEFAULT:
				sexp_tech_reset_to_default();
				sexp_val = SEXP_TRUE;
				break;

			case OP_CHANGE_PLAYER_SCORE:
				sexp_change_player_score(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_CHANGE_TEAM_SCORE:
				sexp_change_team_score(node);
				sexp_val = SEXP_TRUE;
				break;

				// in the case of a red_alert mission, simply call the red alert function to close
				// the current campaign's mission and move forward to the next mission
			case OP_RED_ALERT:
				red_alert_start_mission();
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_OBJECT_SPEED_X:
			case OP_SET_OBJECT_SPEED_Y:
			case OP_SET_OBJECT_SPEED_Z:
				sexp_set_object_speed(node, op_num - OP_SET_OBJECT_SPEED_X);
				sexp_val = SEXP_TRUE;
				break;

			case OP_GET_OBJECT_SPEED_X:
			case OP_GET_OBJECT_SPEED_Y:
			case OP_GET_OBJECT_SPEED_Z:
				sexp_val = sexp_get_object_speed(node, op_num - OP_GET_OBJECT_SPEED_X);
				break;

			case OP_GET_OBJECT_X:
			case OP_GET_OBJECT_Y:
			case OP_GET_OBJECT_Z:
				sexp_val = sexp_get_object_coordinate(node, op_num - OP_GET_OBJECT_X);
				break;

			case OP_GET_OBJECT_PITCH:
			case OP_GET_OBJECT_BANK:
			case OP_GET_OBJECT_HEADING:
				sexp_val = sexp_get_object_angle(node, op_num - OP_GET_OBJECT_PITCH);
				break;

			case OP_SET_OBJECT_POSITION:
				sexp_set_object_position(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_OBJECT_ORIENTATION:
				sexp_set_object_orientation(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_OBJECT_FACING:
			case OP_SET_OBJECT_FACING_OBJECT:
				sexp_set_object_facing(node, op_num == OP_SET_OBJECT_FACING_OBJECT);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SHIP_MANEUVER:
			case OP_SHIP_ROT_MANEUVER:
			case OP_SHIP_LAT_MANEUVER:
				sexp_set_ship_maneuver(node, op_num);
				sexp_val = SEXP_TRUE;
				break;

			// training operators
			case OP_KEY_PRESSED:
				sexp_val = sexp_key_pressed(node);
				break;

			case OP_SPECIAL_CHECK:
				sexp_val = sexp_special_training_check(node);
				break;

			case OP_KEY_RESET:
				sexp_key_reset(node);
				sexp_val = SEXP_KNOWN_TRUE;  // only do it first time in repeating events.
				break;

			case OP_KEY_RESET_MULTIPLE:
				sexp_key_reset(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_MISSILE_LOCKED:
				sexp_val = sexp_missile_locked(node);
				break;

			case OP_TARGETED:
				sexp_val = sexp_targeted(node);
				break;

			case OP_NODE_TARGETED:
				sexp_val = sexp_node_targeted(node);
				break;

			case OP_SPEED:
				sexp_val = sexp_speed(node);
				break;

			case OP_GET_THROTTLE_SPEED:
				sexp_val = sexp_get_throttle_speed(node);
				break;

			case OP_SET_PLAYER_THROTTLE_SPEED:
				sexp_set_player_throttle_speed(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_PRIMARIES_DEPLETED:
				sexp_val = sexp_primaries_depleted(node);
				break;

			case OP_SECONDARIES_DEPLETED:
				sexp_val = sexp_secondaries_depleted(node);
				break;

			case OP_FACING:
				sexp_val = sexp_facing(node);
				break;

			case OP_IS_FACING:
				sexp_val = sexp_is_facing(node);
				break;

			case OP_FACING2:
				sexp_val = sexp_facing2(node);
				break;

			case OP_ORDER:
				sexp_val = sexp_order(node);
				break;

			case OP_QUERY_ORDERS:
				sexp_val = sexp_query_orders(node);
				break;

			// Karajorma
			case OP_RESET_ORDERS:
				sexp_reset_orders(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_WAYPOINT_MISSED:
				sexp_val = sexp_waypoint_missed();
				break;

			case OP_WAYPOINT_TWICE:
				sexp_val = sexp_waypoint_twice();
				break;

			case OP_PATH_FLOWN:
				sexp_val = sexp_path_flown();
				break;

			case OP_TRAINING_MSG:
				sexp_send_training_message(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_FLASH_HUD_GAUGE:
				sexp_flash_hud_gauge(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_TRAINING_CONTEXT_FLY_PATH:
				sexp_set_training_context_fly_path(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_TRAINING_CONTEXT_SPEED:
				sexp_set_training_context_speed(node);
				sexp_val = SEXP_TRUE;
				break;
			
			// Karajorma
			case OP_STRING_TO_INT:
				sexp_val = sexp_string_to_int(node);
				break;

			// Goober5000
			case OP_INT_TO_STRING:
				sexp_int_to_string(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_STRING_CONCATENATE:
				sexp_string_concatenate(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_STRING_GET_SUBSTRING:
				sexp_string_get_substring(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_STRING_SET_SUBSTRING:
				sexp_string_set_substring(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_STRING_GET_LENGTH:
				sexp_val = sexp_string_get_length(node);
				break;

			// Karajorma
			case OP_DEBUG:
				sexp_debug(node);
				sexp_val = SEXP_TRUE;
				break;

			case 0: // zero represents a non-operator
				return eval_num(cur_node);

			case OP_NOP:
				sexp_val = SEXP_TRUE;
				break;

			case OP_BEAM_FIRE:
			case OP_BEAM_FIRE_COORDS:
				sexp_beam_fire(node, op_num == OP_BEAM_FIRE_COORDS);
				sexp_val = SEXP_TRUE;
				break;

			case OP_BEAM_FLOATING_FIRE:
				sexp_beam_floating_fire(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_IS_TAGGED:
				sexp_val = sexp_is_tagged(node);
				break;

			case OP_IS_PLAYER:
				sexp_val = sexp_is_player(node);
				break;

			case OP_NUM_KILLS:
			case OP_NUM_ASSISTS:
			case OP_SHIP_SCORE: 
			case OP_SHIP_DEATHS: 
			case OP_RESPAWNS_LEFT:
				sexp_val = sexp_return_player_data(node, op_num);
				break;

			case OP_SET_RESPAWNS:
				sexp_set_respawns(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_REMOVE_WEAPONS:
				sexp_remove_weapons(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_NUM_TYPE_KILLS:
				sexp_val = sexp_num_type_kills(node);
				break;

			case OP_NUM_CLASS_KILLS:
				sexp_val = sexp_num_class_kills(node);
				break;

			case OP_BEAM_FREE:
				sexp_val = SEXP_TRUE;
				sexp_beam_free(node);
				break;

			case OP_BEAM_FREE_ALL:
				sexp_val = SEXP_TRUE;
				sexp_beam_free_all(node);
				break;

			case OP_BEAM_LOCK:
				sexp_val = SEXP_TRUE;
				sexp_beam_lock(node);
				break;

			case OP_BEAM_LOCK_ALL:
				sexp_val = SEXP_TRUE;
				sexp_beam_lock_all(node);
				break;

			case OP_TURRET_FREE:
				sexp_val = SEXP_TRUE;
				sexp_turret_free(node);
				break;

			case OP_TURRET_FREE_ALL:
				sexp_val = SEXP_TRUE;
				sexp_turret_free_all(node);
				break;

			case OP_TURRET_LOCK:
				sexp_val = SEXP_TRUE;
				sexp_turret_lock(node);
				break;

			case OP_TURRET_LOCK_ALL:
				sexp_val = SEXP_TRUE;
				sexp_turret_lock_all(node);
				break;

			case OP_TURRET_CHANGE_WEAPON:
				sexp_val = SEXP_TRUE;
				sexp_turret_change_weapon(node);
				break;

			case OP_TURRET_SET_DIRECTION_PREFERENCE:
				sexp_val = SEXP_TRUE;
				sexp_turret_set_direction_preference(node);
				break;

			case OP_TURRET_SET_RATE_OF_FIRE:
				sexp_val = SEXP_TRUE;
				sexp_turret_set_rate_of_fire(node);
				break;

			case OP_TURRET_SET_OPTIMUM_RANGE:
				sexp_val = SEXP_TRUE;
				sexp_turret_set_optimum_range(node);
				break;

			case OP_TURRET_SET_TARGET_PRIORITIES:
				sexp_val = SEXP_TRUE;
				sexp_turret_set_target_priorities(node);
				break;

			case OP_TURRET_SET_TARGET_ORDER:
				sexp_val = SEXP_TRUE;
				sexp_turret_set_target_order(node);
				break;

			case OP_SET_ARMOR_TYPE:
				sexp_val = SEXP_TRUE;
				sexp_set_armor_type(node);
				break;

			case OP_WEAPON_SET_DAMAGE_TYPE:
				sexp_val = SEXP_TRUE;
				sexp_weapon_set_damage_type(node);
				break;

			case OP_SHIP_SET_DAMAGE_TYPE:
				sexp_val = SEXP_TRUE;
				sexp_ship_set_damage_type(node);
				break;

			case OP_SHIP_SHOCKWAVE_SET_DAMAGE_TYPE:
				sexp_val = SEXP_TRUE;
				sexp_ship_shockwave_set_damage_type(node);
				break;

			case OP_FIELD_SET_DAMAGE_TYPE:
				sexp_val = SEXP_TRUE;
				sexp_field_set_damage_type(node);
				break;

			case OP_SHIP_TURRET_TARGET_ORDER:
				sexp_val = SEXP_TRUE;
				sexp_ship_turret_target_order(node);
				break;

			case OP_ADD_REMOVE_ESCORT:
				sexp_val = SEXP_TRUE;
				sexp_add_remove_escort(node);
				break;
			
			case OP_DAMAGED_ESCORT_LIST:
				sexp_val = SEXP_TRUE;
				sexp_damage_escort_list(node);
				break;

			case OP_DAMAGED_ESCORT_LIST_ALL:
				sexp_val = SEXP_TRUE;
				sexp_damage_escort_list_all(node);
				break;

			case OP_AWACS_SET_RADIUS:
				sexp_val = SEXP_TRUE;
				sexp_awacs_set_radius(node);
				break;

			case OP_PRIMITIVE_SENSORS_SET_RANGE:
				sexp_primitive_sensors_set_range(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_CAP_WAYPOINT_SPEED:
				sexp_val = SEXP_TRUE;
				sexp_cap_waypoint_speed(node);
				break;

			case OP_TURRET_TAGGED_ONLY_ALL:
				sexp_val = SEXP_TRUE;
				sexp_turret_tagged_only_all(node);
				break;

			case OP_TURRET_TAGGED_CLEAR_ALL:
				sexp_val = SEXP_TRUE;
				sexp_turret_tagged_clear_all(node);
				break;

			case OP_SUBSYS_SET_RANDOM:
				sexp_val = SEXP_TRUE;
				sexp_subsys_set_random(node);
				break;

			case OP_SUPERNOVA_START:
				sexp_val = SEXP_TRUE;
				sexp_supernova_start(node);
				break;

			case OP_SUPERNOVA_STOP:
				sexp_val = SEXP_TRUE;
				sexp_supernova_stop(node);
				break;

			case OP_SET_MOTION_DEBRIS:
				sexp_val = SEXP_TRUE;
				sexp_set_motion_debris(node);
				break;

			case OP_SHIELD_RECHARGE_PCT:
				sexp_val = sexp_shield_recharge_pct(node);
				break;

			case OP_ENGINE_RECHARGE_PCT:
				sexp_val = sexp_engine_recharge_pct(node);
				break;

			case OP_WEAPON_RECHARGE_PCT:
				sexp_val = sexp_weapon_recharge_pct(node);
				break;

			case OP_GET_ETS_VALUE:
				sexp_val = sexp_get_ets_value(node);
				break;

			case OP_SET_ETS_VALUES:
				sexp_val = SEXP_TRUE;
				sexp_set_ets_values(node);
				break;

			case OP_SHIELD_QUAD_LOW:
				sexp_val = sexp_shield_quad_low(node);
				break;

			case OP_PRIMARY_AMMO_PCT:
				sexp_val = sexp_primary_ammo_pct(node);
				break;

			case OP_SECONDARY_AMMO_PCT:
				sexp_val = sexp_secondary_ammo_pct(node);
				break;

			// Karajorma
			case OP_GET_PRIMARY_AMMO:
				sexp_val = sexp_get_primary_ammo(node);
				break;

			// Karajorma
			case OP_GET_SECONDARY_AMMO:
				sexp_val = sexp_get_secondary_ammo(node);
				break;

			// Karajorma
			case OP_GET_NUM_COUNTERMEASURES:
				sexp_val = sexp_get_countermeasures(node);
				break;

			case OP_IS_SECONDARY_SELECTED:
				sexp_val = sexp_is_secondary_selected(node);
				break;

			case OP_IS_PRIMARY_SELECTED:
				sexp_val = sexp_is_primary_selected(node);
				break;

			// Goober5000
			case OP_SET_SUPPORT_SHIP:
				sexp_set_support_ship(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_SET_ARRIVAL_INFO:
				sexp_set_arrival_info(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_SET_DEPARTURE_INFO:
				sexp_set_departure_info(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_CHANGE_SHIP_CLASS:
				sexp_change_ship_class(node);
				sexp_val = SEXP_TRUE;
				break;

			// Goober5000
			case OP_SHIP_COPY_DAMAGE:
				sexp_ship_copy_damage(node);
				sexp_val = SEXP_TRUE;
				break;

			//-Bobboau
			case OP_ACTIVATE_GLOW_POINTS:
			case OP_DEACTIVATE_GLOW_POINTS:
				sexp_activate_deactivate_glow_points(node, op_num == OP_ACTIVATE_GLOW_POINTS);
				sexp_val = SEXP_TRUE;
				break;

			//-Bobboau
			case OP_ACTIVATE_GLOW_MAPS:
			case OP_DEACTIVATE_GLOW_MAPS:
				sexp_activate_deactivate_glow_maps(node, op_num == OP_ACTIVATE_GLOW_MAPS);
				sexp_val = SEXP_TRUE;
				break;

			//-Bobboau
			case OP_ACTIVATE_GLOW_POINT_BANK:
			case OP_DEACTIVATE_GLOW_POINT_BANK:
				sexp_activate_deactivate_glow_point_bank(node, op_num == OP_ACTIVATE_GLOW_POINT_BANK);
				sexp_val = SEXP_TRUE;
				break;

			// taylor
			case OP_SET_SKYBOX_MODEL:
				sexp_set_skybox_model(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_SKYBOX_ORIENT:
				sexp_set_skybox_orientation(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_TURRET_TAGGED_SPECIFIC:
				sexp_turret_tagged_specific(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_TURRET_TAGGED_CLEAR_SPECIFIC:
				sexp_turret_tagged_clear_specific(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_LOCK_ROTATING_SUBSYSTEM:
			case OP_FREE_ROTATING_SUBSYSTEM:
				sexp_set_subsys_rotation_lock_free(node, op_num == OP_LOCK_ROTATING_SUBSYSTEM);
				sexp_val = SEXP_TRUE;
				break;

			case OP_REVERSE_ROTATING_SUBSYSTEM:
				sexp_reverse_rotating_subsystem(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_ROTATING_SUBSYS_SET_TURN_TIME:
				sexp_rotating_subsys_set_turn_time(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_TRIGGER_SUBMODEL_ANIMATION:
				sexp_trigger_submodel_animation(node);
				sexp_val = SEXP_TRUE;
				break;
				
			// Karajorma
			case OP_SET_PRIMARY_AMMO:
				sexp_set_primary_ammo(node);
				sexp_val = SEXP_TRUE;
				break;
				
			// Karajorma
			case OP_SET_SECONDARY_AMMO:
				sexp_set_secondary_ammo(node);
				sexp_val = SEXP_TRUE;
				break;
				
			// Karajorma
			case OP_SET_PRIMARY_WEAPON:
			case OP_SET_SECONDARY_WEAPON:
				sexp_set_weapon(node, op_num == OP_SET_PRIMARY_WEAPON);
				sexp_val = SEXP_TRUE;
				break;

			// Karajorma
			case OP_SET_NUM_COUNTERMEASURES:
				sexp_set_countermeasures(node);
				sexp_val = SEXP_TRUE;
				break;

			// Karajorma
			case OP_LOCK_PRIMARY_WEAPON:
			case OP_UNLOCK_PRIMARY_WEAPON:
				sexp_deal_with_primary_lock(node, op_num == OP_LOCK_PRIMARY_WEAPON);
				sexp_val = SEXP_TRUE;
				break;

			case OP_LOCK_SECONDARY_WEAPON:
			case OP_UNLOCK_SECONDARY_WEAPON:
				sexp_deal_with_secondary_lock(node, op_num == OP_LOCK_SECONDARY_WEAPON);
				sexp_val = SEXP_TRUE;
				break;

			// KeldorKatarn
			case OP_LOCK_AFTERBURNER:
			case OP_UNLOCK_AFTERBURNER:
				sexp_deal_with_afterburner_lock(node, op_num == OP_LOCK_AFTERBURNER);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_AFTERBURNER_ENERGY: 
			case OP_SET_WEAPON_ENERGY:
			case OP_SET_SHIELD_ENERGY:
				sexp_set_energy_pct(node, op_num);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_AMBIENT_LIGHT: 
				sexp_set_ambient_light(node); 
				sexp_val = SEXP_TRUE;
				break;

			case OP_SET_POST_EFFECT:
				sexp_set_post_effect(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_PRIMARY_FIRED_SINCE:
			case OP_SECONDARY_FIRED_SINCE:
				sexp_val = sexp_weapon_fired_delay(node, op_num); 
				break;

			case OP_HAS_PRIMARY_WEAPON:
			case OP_HAS_SECONDARY_WEAPON:
				sexp_val = sexp_has_weapon(node, op_num);
				break;

			case OP_DIRECTIVE_VALUE:
				sexp_val = sexp_directive_value(node);
				break;

			case OP_CHANGE_SUBSYSTEM_NAME:
				sexp_change_subsystem_name(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_NUM_SHIPS_IN_BATTLE:	// phreak
				sexp_val = sexp_num_ships_in_battle(node);
				break;

			// Karajorma
			case OP_NUM_SHIPS_IN_WING:
				sexp_val=sexp_num_ships_in_wing(node);
				break;

			case OP_CURRENT_SPEED:
				sexp_val = sexp_current_speed(node);
				break;

			case OP_NAV_IS_VISITED: //kazan
				sexp_val = is_nav_visited(node);
				break;

			case OP_NAV_DISTANCE: //kazan
				sexp_val = distance_to_nav(node);
				break;

			case OP_NAV_ADD_WAYPOINT: //kazan
				sexp_val = SEXP_TRUE;
				add_nav_waypoint(node);
				break;

			case OP_NAV_ADD_SHIP: //kazan
				sexp_val = SEXP_TRUE;
				add_nav_ship(node);
				break;

			case OP_NAV_DEL: //kazan
				sexp_val = SEXP_TRUE;
				del_nav(node);
				break;

			case OP_NAV_HIDE: //kazan
				sexp_val = SEXP_TRUE;
				hide_nav(node);
				break;

			case OP_NAV_RESTRICT: //kazan
				sexp_val = SEXP_TRUE;
				restrict_nav(node);
				break;

			case OP_NAV_UNHIDE: //kazan
				sexp_val = SEXP_TRUE;
				unhide_nav(node);
				break;

			case OP_NAV_UNRESTRICT: //kazan
				sexp_val = SEXP_TRUE;
				unrestrict_nav(node);
				break;

			case OP_NAV_SET_VISITED: //kazan
				sexp_val = SEXP_TRUE;
				set_nav_visited(node);
				break;

			case OP_NAV_UNSET_VISITED: //kazan
				sexp_val = SEXP_TRUE;
				unset_nav_visited(node);
				break;

			case OP_NAV_SET_CARRY: //kazan
				sexp_val = SEXP_TRUE;
				set_nav_carry_status(node);
				break;

			case OP_NAV_UNSET_CARRY: //kazan
				sexp_val = SEXP_TRUE;
				unset_nav_carry_status(node);
				break;

			case OP_NAV_SET_NEEDSLINK:
				sexp_val = SEXP_TRUE;
				set_nav_needslink(node);
				break;

			case OP_NAV_UNSET_NEEDSLINK:
				sexp_val = SEXP_TRUE;
				unset_nav_needslink(node);
				break;

			case OP_NAV_ISLINKED:
				sexp_val = is_nav_linked(node);
				break;
			
			case OP_NAV_USEAP:
				sexp_val = SEXP_TRUE;
				set_use_ap(node);
				break;

			case OP_NAV_USECINEMATICS:
				sexp_val = SEXP_TRUE;
				set_use_ap_cinematics(node);
				break;
			
			//Talon1024
			case OP_NAV_SELECT:
				sexp_val = SEXP_TRUE;
				select_nav(node);
				break;
				
			//Talon1024
			case OP_NAV_UNSELECT:
				sexp_val = SEXP_TRUE;
				unselect_nav();
				break;

			case OP_SCRAMBLE_MESSAGES:
			case OP_UNSCRAMBLE_MESSAGES:
				sexp_scramble_messages(node, op_num == OP_SCRAMBLE_MESSAGES );
				sexp_val = SEXP_TRUE;
				break;

			case OP_CUTSCENES_SET_CUTSCENE_BARS:
			case OP_CUTSCENES_UNSET_CUTSCENE_BARS:
				sexp_val = SEXP_TRUE;
				sexp_toggle_cutscene_bars(node, op_num == OP_CUTSCENES_SET_CUTSCENE_BARS);
				break;

			case OP_CUTSCENES_FADE_IN:
			case OP_CUTSCENES_FADE_OUT:
				sexp_val = SEXP_TRUE;
				sexp_fade(node, op_num == OP_CUTSCENES_FADE_IN);
				break;

			case OP_CUTSCENES_SET_CAMERA:
				sexp_val = SEXP_TRUE;
				sexp_set_camera(node);
				break;
			case OP_CUTSCENES_SET_CAMERA_FACING:
				sexp_val = SEXP_TRUE;
				sexp_set_camera_facing(node);
				break;
			case OP_CUTSCENES_SET_CAMERA_FACING_OBJECT:
				sexp_val = SEXP_TRUE;
				sexp_set_camera_facing_object(node);
				break;
			case OP_CUTSCENES_SET_CAMERA_FOV:
				sexp_val = SEXP_TRUE;
				sexp_set_camera_fov(node);
				break;
			case OP_CUTSCENES_SET_CAMERA_HOST:
				sexp_val = SEXP_TRUE;
				sexp_set_camera_host(node);
				break;
			case OP_CUTSCENES_SET_CAMERA_POSITION:
				sexp_val = SEXP_TRUE;
				sexp_set_camera_position(node);
				break;
			case OP_CUTSCENES_SET_CAMERA_ROTATION:
				sexp_val = SEXP_TRUE;
				sexp_set_camera_rotation(node);
				break;
			case OP_CUTSCENES_SET_CAMERA_TARGET:
				sexp_val = SEXP_TRUE;
				sexp_set_camera_target(node);
				break;
			case OP_CUTSCENES_SET_FOV:
				sexp_val = SEXP_TRUE;
				sexp_set_fov(node);
				break;
			case OP_CUTSCENES_GET_FOV:	
				sexp_val = sexp_get_fov();
				break;
			case OP_CUTSCENES_RESET_FOV:
				sexp_val = SEXP_TRUE;
				sexp_reset_fov();
				break;
			case OP_CUTSCENES_RESET_CAMERA:
				sexp_val = SEXP_TRUE;
				sexp_reset_camera(node);
				break;
			case OP_CUTSCENES_SHOW_SUBTITLE:
				sexp_val = SEXP_TRUE;
				sexp_show_subtitle(node);
				break;
			case OP_CUTSCENES_SHOW_SUBTITLE_TEXT:
				sexp_val = SEXP_TRUE;
				sexp_show_subtitle_text(node);
				break;
			case OP_CUTSCENES_SHOW_SUBTITLE_IMAGE:
				sexp_val = SEXP_TRUE;
				sexp_show_subtitle_image(node);
				break;
			case OP_CUTSCENES_SET_TIME_COMPRESSION:
				sexp_val = SEXP_TRUE;
				sexp_set_time_compression(node);
				break;
			case OP_CUTSCENES_RESET_TIME_COMPRESSION:
				sexp_val = SEXP_TRUE;
				sexp_reset_time_compression();
				break;
			case OP_CUTSCENES_FORCE_PERSPECTIVE:
				sexp_val = SEXP_TRUE;
				sexp_force_perspective(node);
				break;

			case OP_SET_CAMERA_SHUDDER:
				sexp_val = SEXP_TRUE;
				sexp_set_camera_shudder(node);
				break;

			case OP_JUMP_NODE_SET_JUMPNODE_NAME: //CommanderDJ
				sexp_val = SEXP_TRUE;
				sexp_set_jumpnode_name(node);
				break;

			case OP_JUMP_NODE_SET_JUMPNODE_COLOR:
				sexp_val = SEXP_TRUE;
				sexp_set_jumpnode_color(node);
				break;
			case OP_JUMP_NODE_SET_JUMPNODE_MODEL:
				sexp_val = SEXP_TRUE;
				sexp_set_jumpnode_model(node);
				break;
			case OP_JUMP_NODE_SHOW_JUMPNODE:
			case OP_JUMP_NODE_HIDE_JUMPNODE:
				sexp_show_hide_jumpnode(node, op_num == OP_JUMP_NODE_SHOW_JUMPNODE);
				sexp_val = SEXP_TRUE;
				break;

			case OP_SCRIPT_EVAL_NUM:
				sexp_val = sexp_script_eval(node, OPR_NUMBER);
				break;

			case OP_SCRIPT_EVAL_STRING:
				sexp_val = sexp_script_eval(node, OPR_STRING);
				break;

			case OP_SCRIPT_EVAL:
				sexp_val = sexp_script_eval(node, OPR_NULL);
				break;
				
			case OP_SCRIPT_EVAL_BLOCK:
				sexp_val = sexp_script_eval(node, OPR_NULL, true);
				break;

			case OP_SCRIPT_EVAL_MULTI:
				sexp_script_eval_multi(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_CHANGE_IFF_COLOR:
				sexp_change_iff_color(node);
				sexp_val = SEXP_TRUE;
				break;

			case OP_DISABLE_ETS:
			case OP_ENABLE_ETS:
				sexp_disable_ets(node, (op_num == OP_DISABLE_ETS));
				sexp_val = SEXP_TRUE;
				break;

			case OP_FORCE_GLIDE:
				sexp_val = SEXP_TRUE;
				sexp_force_glide(node);
				break;

			case OP_HUD_SET_DIRECTIVE:
				sexp_val = SEXP_TRUE;
				sexp_hud_set_directive(node);
				break;

			case OP_HUD_GAUGE_SET_ACTIVE:
				sexp_val = SEXP_TRUE;
				sexp_hud_gauge_set_active(node);
				break;

			case OP_HUD_SET_CUSTOM_GAUGE_ACTIVE:
				sexp_val = SEXP_TRUE;
				sexp_hud_set_custom_gauge_active(node);
				break;

			case OP_HUD_CLEAR_MESSAGES:
				sexp_val = SEXP_TRUE;
				sexp_hud_clear_messages();
				break;

			case OP_HUD_ACTIVATE_GAUGE_TYPE:
				sexp_val = SEXP_TRUE;
				sexp_hud_activate_gauge_type(node);
				break;

			case OP_HUD_SET_RETAIL_GAUGE_ACTIVE:
				sexp_val = SEXP_TRUE;
				sexp_hud_set_retail_gauge_active(node);
				break;

			case OP_ADD_TO_COLGROUP:
				sexp_val = SEXP_TRUE;
				sexp_manipulate_colgroup(node, true);
				break;

			case OP_REMOVE_FROM_COLGROUP:
				sexp_val = SEXP_TRUE;
				sexp_manipulate_colgroup(node, false);
				break;

			case OP_GET_COLGROUP_ID:
				sexp_val = sexp_get_colgroup(node);
				break;

			case OP_SHIP_EFFECT:
				sexp_val = SEXP_TRUE;
				sexp_ship_effect(node);
				break;

			case OP_CLEAR_SUBTITLES:
				sexp_val = SEXP_TRUE;
				sexp_clear_subtitles();
				break;

			case OP_SET_THRUSTERS:
				sexp_val = SEXP_TRUE;
				sexp_set_thrusters(node);
				break;

			case OP_CHANGE_TEAM_COLOR:
				sexp_val = SEXP_TRUE;
				sexp_change_team_color(node);
				break;

			case OP_CALL_SSM_STRIKE:
				sexp_val = SEXP_TRUE;
				sexp_call_ssm_strike(node);
				break;

			case OP_PLAYER_IS_CHEATING_BASTARD:
				sexp_val = sexp_player_is_cheating_bastard();
				break;

			case OP_TURRET_GET_PRIMARY_AMMO:
				sexp_val = sexp_get_turret_primary_ammo(node);
				break;

			case OP_TURRET_GET_SECONDARY_AMMO:
				sexp_val = sexp_get_turret_secondary_ammo(node);
				break;

			case OP_TURRET_SET_PRIMARY_AMMO:
				sexp_val = SEXP_TRUE;
				sexp_set_turret_primary_ammo(node);
				break;

			case OP_TURRET_SET_SECONDARY_AMMO:
				sexp_val = SEXP_TRUE;
				sexp_set_turret_secondary_ammo(node);
				break;

			default:
				Error(LOCATION, "Looking for SEXP operator, found '%s'.\n", CTEXT(cur_node));
				break;
		}

		if (Log_event) {
			add_to_event_log_buffer(get_operator_index(cur_node), sexp_val);
		}

		Assert(!Current_sexp_operator.empty()); 
		Current_sexp_operator.pop_back();

		Assert(sexp_val != UNINITIALIZED);		

		// if we haven't returned, check the sexp value of the sexpression evaluation.  A special
		// value of known true or known false means that we should set the sexp.value field for
		// short circuit eval.
		if (sexp_val == SEXP_KNOWN_TRUE) {
			Sexp_nodes[cur_node].value = SEXP_KNOWN_TRUE;
			return SEXP_TRUE;
		}

		if (sexp_val == SEXP_KNOWN_FALSE) {
			Sexp_nodes[cur_node].value = SEXP_KNOWN_FALSE;
			return SEXP_FALSE;
		}

		if ( sexp_val == SEXP_NAN ) {
			Sexp_nodes[cur_node].value = SEXP_NAN;			// not a number values are false I would suspect
			return SEXP_FALSE;
		}

		if ( sexp_val == SEXP_NAN_FOREVER ) {
			Sexp_nodes[cur_node].value = SEXP_NAN_FOREVER;
			return SEXP_FALSE;	// Goober5000 changed from sexp_val to SEXP_FALSE on 2/21/2006 in accordance with above comment
		}

		if ( sexp_val == SEXP_CANT_EVAL ) {
			Sexp_nodes[cur_node].value = SEXP_CANT_EVAL;
			Sexp_useful_number = 0;  // indicate sexp isn't current yet
			return SEXP_FALSE;
		}

		if ( Sexp_nodes[cur_node].value == SEXP_NAN ) {	// if we had a nan, but now don't, reset the value
			Sexp_nodes[cur_node].value = SEXP_UNKNOWN;
			return sexp_val;
		}

		// now, reconcile positive and negative - Goober5000
		if (sexp_val < 0)
		{
			int parent_node = find_parent_operator(cur_node);
			int arg_num = find_argnum(parent_node, cur_node);

			// make sure everything works okay
			if (arg_num == -1)
			{
				SCP_string sexp_text;
				convert_sexp_to_string(sexp_text, cur_node, SEXP_ERROR_CHECK_MODE);
				Error(LOCATION, "Error finding sexp argument.  Received value %d for sexp:\n%s", sexp_val, sexp_text.c_str());
			}

			// if we need a positive value, make it positive
			if (query_operator_argument_type(get_operator_index(parent_node), arg_num) == OPF_POSITIVE)
			{
				sexp_val *= -1;
			}
		}

		if ( sexp_val ){
			Sexp_nodes[cur_node].value = SEXP_TRUE;
		} else {
			Sexp_nodes[cur_node].value = SEXP_FALSE;
		}

		return sexp_val;
	}
}

/**
 * Only runs on the client machines not the server. Evaluates the contents of a SEXP packet and calls the relevent multi_sexp_x 
 * function(s). 
 */
void multi_sexp_eval()
{
	int op_num; 

	Assert (MULTIPLAYER_CLIENT); 

	while (Multi_sexp_bytes_left > 0) {
		op_num = multi_sexp_get_next_operator(); 

		Assert (Multi_sexp_bytes_left); 

		if (op_num < 0) {
			Warning(LOCATION, "Received invalid operator number from host in multi_sexp_eval(). Entire packet may be corrupt. Discarding packet"); 
			Int3(); 
			return; 	
		}

		switch(op_num) {

			case OP_CHANGE_SOUNDTRACK:
				multi_sexp_change_soundtrack();
				break; 

			case OP_SET_PERSONA:
				multi_sexp_set_persona();
				break; 
			
			case OP_CHANGE_SUBSYSTEM_NAME:
				multi_sexp_change_subsystem_name();
				break;

			case OP_SHIP_SUBSYS_NO_REPLACE:
				multi_sexp_deal_with_subsys_flag(SSF_NO_REPLACE);
				break;
			case OP_SHIP_SUBSYS_NO_LIVE_DEBRIS:
				multi_sexp_deal_with_subsys_flag(SSF_NO_LIVE_DEBRIS);
				break;
			case OP_SHIP_SUBSYS_VANISHED:
				multi_sexp_deal_with_subsys_flag(SSF_VANISHED);
				break;
			case OP_SHIP_SUBSYS_IGNORE_IF_DEAD:
				multi_sexp_deal_with_subsys_flag(SSF_MISSILES_IGNORE_IF_DEAD);
				break;
			case OP_SHIP_SUBSYS_TARGETABLE:
			case OP_SHIP_SUBSYS_UNTARGETABLE:
				multi_sexp_deal_with_subsys_flag(SSF_UNTARGETABLE);
				break;

			case OP_SHIP_CHANGE_CALLSIGN:
				multi_sexp_ship_change_callsign();
				break;

			case OP_SET_RESPAWNS:
				multi_sexp_set_respawns();
				break;

			case OP_REMOVE_WEAPONS:
				multi_sexp_remove_weapons();
				break;

			case OP_CHANGE_SHIP_CLASS:
				multi_sexp_change_ship_class();
				break;
					
			case OP_PLAY_SOUND_FROM_TABLE:
				multi_sexp_play_sound_from_table();
				break;
					
			case OP_PLAY_SOUND_FROM_FILE:
				multi_sexp_play_sound_from_file();
				break;

			case OP_CLOSE_SOUND_FROM_FILE:
				multi_sexp_close_sound_from_file();
				break;

			case OP_PAUSE_SOUND_FROM_FILE:
				multi_sexp_pause_sound_from_file();
				break;

			case OP_SHIP_BOMB_TARGETABLE:
			case OP_SHIP_BOMB_UNTARGETABLE:
			case OP_SHIP_INVISIBLE:
			case OP_SHIP_VISIBLE:
			case OP_SHIP_STEALTHY:
			case OP_SHIP_UNSTEALTHY:
			case OP_FRIENDLY_STEALTH_INVISIBLE:
			case OP_FRIENDLY_STEALTH_VISIBLE:
			case OP_LOCK_AFTERBURNER:
			case OP_UNLOCK_AFTERBURNER:
			case OP_LOCK_PRIMARY_WEAPON:
			case OP_UNLOCK_PRIMARY_WEAPON:
			case OP_LOCK_SECONDARY_WEAPON:
			case OP_UNLOCK_SECONDARY_WEAPON:
			case OP_SHIELDS_ON:
			case OP_SHIELDS_OFF:
				multi_sexp_deal_with_ship_flag();
				break;

			case OP_ALTER_SHIP_FLAG:
				multi_sexp_alter_ship_flag();
				break;

			case OP_SET_AFTERBURNER_ENERGY: 
				multi_sexp_set_energy_pct();
				break;

			case OP_SET_AMBIENT_LIGHT:
				multi_sexp_set_ambient_light();
				break;

			case OP_MODIFY_VARIABLE:
				multi_sexp_modify_variable();
				break;

			case OP_NAV_ADD_WAYPOINT:
				multi_sexp_add_nav_waypoint();
				break;

			case OP_CUTSCENES_FADE_IN:
			case OP_CUTSCENES_FADE_OUT:
				multi_sexp_fade(op_num == OP_CUTSCENES_FADE_IN);
				break;

			case OP_NAV_ADD_SHIP:
				multi_add_nav_ship();
				break;

			case OP_NAV_DEL:
				multi_del_nav();
				break;

			case OP_ADD_REMOVE_ESCORT:
				multi_sexp_add_remove_escort();
				break;

			case OP_CUTSCENES_SHOW_SUBTITLE_TEXT:
				 multi_sexp_show_subtitle_text();
				 break;

			case OP_CUTSCENES_SHOW_SUBTITLE_IMAGE:
				 multi_sexp_show_subtitle_image();
				 break;

			case OP_TRAINING_MSG:
				multi_sexp_send_training_message(); 
				break;

			case OP_HUD_DISABLE:
				multi_sexp_hud_disable();
				break;
			
			case OP_HUD_DISABLE_EXCEPT_MESSAGES:
				multi_sexp_hud_disable_except_messages();
				break;

			case OP_FLASH_HUD_GAUGE:
				multi_sexp_flash_hud_gauge();
				break;

			case OP_HUD_DISPLAY_GAUGE:
				multi_sexp_hud_display_gauge();
				break;

			case OP_CUTSCENES_SET_CUTSCENE_BARS:
			case OP_CUTSCENES_UNSET_CUTSCENE_BARS:
				multi_sexp_toggle_cutscene_bars(op_num == OP_CUTSCENES_SET_CUTSCENE_BARS );
				break;

			case OP_CUTSCENES_SET_CAMERA_FACING:
				multi_sexp_set_camera_facing();
				break;

			case OP_CUTSCENES_SET_CAMERA_FACING_OBJECT:
				multi_sexp_set_camera_facing_object();
				break;

			case OP_CUTSCENES_SET_CAMERA_TARGET :
				multi_sexp_set_camera_target();
				break;

			case OP_CUTSCENES_SET_CAMERA_ROTATION:
				multi_sexp_set_camera_rotation();
				break;

			case OP_CUTSCENES_SET_CAMERA_FOV:
				multi_sexp_set_camera_fov();
				break;

			case OP_CUTSCENES_SET_CAMERA_POSITION:
				multi_sexp_set_camera_position();
				break;

			case OP_SET_CAMERA_SHUDDER:
				multi_sexp_set_camera_shudder();
				break;

			case OP_CUTSCENES_RESET_CAMERA:
				multi_sexp_reset_camera();
				break;

			case OP_CUTSCENES_SET_FOV:
				multi_sexp_set_fov();
				break;

			case OP_CUTSCENES_RESET_FOV:
				multi_sexp_reset_fov();
				break;

			case OP_JUMP_NODE_SET_JUMPNODE_NAME:
				multi_sexp_set_jumpnode_name();
				break;

			case OP_IGNORE_KEY:
				multi_sexp_ignore_key();
				break;

			case OP_JUMP_NODE_SET_JUMPNODE_COLOR:
				multi_sexp_set_jumpnode_color();
				break;

			case OP_JUMP_NODE_SET_JUMPNODE_MODEL:
				multi_sexp_set_jumpnode_model();
				break;

			case OP_JUMP_NODE_SHOW_JUMPNODE:
			case OP_JUMP_NODE_HIDE_JUMPNODE:
				multi_sexp_show_hide_jumpnode(op_num == OP_JUMP_NODE_SHOW_JUMPNODE);
				break;

			case OP_CLEAR_SUBTITLES:
				multi_sexp_clear_subtitles();
				break;

			case OP_SET_OBJECT_SPEED_X:
			case OP_SET_OBJECT_SPEED_Y:
			case OP_SET_OBJECT_SPEED_Z:
				multi_sexp_set_object_speed();
				break;
			case OP_SET_OBJECT_POSITION:
				multi_sexp_set_object_position();
				break;

			case OP_CHANGE_TEAM_COLOR:
				multi_sexp_change_team_color();
				break;

			case OP_HUD_SET_MAX_TARGETING_RANGE:
				multi_sexp_hud_set_max_targeting_range();
				break;

			case OP_CUTSCENES_SET_TIME_COMPRESSION:
				multi_sexp_set_time_compression();
				break;

			case OP_CUTSCENES_RESET_TIME_COMPRESSION:
				sexp_reset_time_compression();
				break;

			case OP_SET_ETS_VALUES:
				multi_sexp_set_ets_values();
				break;

			case OP_SCRIPT_EVAL_MULTI:
				multi_sexp_script_eval_multi();
				break;

			case OP_TURRET_SET_PRIMARY_AMMO:
				multi_sexp_set_turret_primary_ammo();
				break;

			case OP_TURRET_SET_SECONDARY_AMMO:
				multi_sexp_set_turret_secondary_ammo();
				break;

			// bad sexp in the packet
			default: 
				// probably just a version error where the host supports a SEXP but a client does not
				if (multi_sexp_discard_operator()) {
					Warning(LOCATION, "Received invalid SEXP operator number from host. Operator number %d is not supported by this version.", op_num); 
				}
				// a more major problem
				else {
					Warning(LOCATION, "Received invalid SEXP packet from host. Function involving operator %d lacks termination. Entire packet may be corrupt. Discarding remaining packet", op_num); 
					Int3(); 
					return; 
				}			
		}

		multi_finished_callback();
	}
}

//	get_sexp_main reads and builds the internal representation for a
//	symbolic expression.
//	On entry:
//		Mp points at first character in expression.
//	The symbolic expression is built in Sexp_nodes beginning at node 0.
int get_sexp_main()
{
	int	start_node, op;

	ignore_white_space();

	if (*Mp != '(')
	{
		char buf[512];
		strncpy(buf, Mp, 512);
		if (buf[511] != '\0')
			strcpy(&buf[506], "[...]");

		Error(LOCATION, "Expected to find an open parenthesis in the following sexp:\n%s", buf);
		return -1;
	}

	Mp++;
	start_node = get_sexp();

	// only need to check syntax if we have a operator
	if (!Fred_running && (start_node >= 0))
	{
		op = get_operator_index(CTEXT(start_node));
		if (op < 0)
		{
			Error(LOCATION, "Can't find operator %s in operator list!\n", CTEXT(start_node));
			return -1;
		}
	}

	return start_node;
}

int run_sexp(const char* sexpression)
{
	char* oldMp = Mp;
	int n, i, sexp_val = UNINITIALIZED;
	char buf[8192];

	strcpy_s(buf, sexpression);

	// HACK: ! -> "
	for (i = 0; i < (int)strlen(buf); i++)
		if (buf[i] == '!')
			buf[i]='\"';

	Mp = buf;

	n = get_sexp_main();
	if (n != -1)
	{
		sexp_val = eval_sexp(n);
		free_sexp2(n);
	}
	Mp = oldMp;

	return sexp_val;
}

DCF(sexpc, "Always runs the given sexp command (Warning! There is no undo for this!)")
{
	SCP_string sexp;
	SCP_string sexp_always;
	
	if (dc_optional_string_either("help", "--help")) {
		dc_printf( "Usage: sexpc sexpression\n. Always runs the given sexp as '( when ( true ) ( sexp ) )' .\n" );
		return;
	}

	dc_stuff_string(sexp);

	sexp_always = "( when ( true ) ( " + sexp + " ) )";

	int sexp_val = run_sexp(sexp_always.c_str());
	dc_printf("SEXP '%s' run, sexp_val = %d\n", sexp_always.c_str(), sexp_val);
}


DCF(sexp,"Runs the given sexp")
{
	SCP_string sexp;

	if (dc_optional_string_either("help", "--help")) {
		dc_printf( "Usage: sexp 'sexpression'\n. Runs the given sexp.\n");
		return;
	}

	dc_stuff_string(sexp);

	int sexp_val = run_sexp(sexp.c_str());
	dc_printf("SEXP '%s' run, sexp_val = %d\n", sexp.c_str(), sexp_val);
}

// returns the data type returned by an operator
int query_operator_return_type(int op)
{
	if (op < FIRST_OP)
	{
		Assert(op >= 0 && op < Num_operators);
		op = Operators[op].value;
	}

	switch (op)
	{
		case OP_TRUE:
		case OP_FALSE:
		case OP_AND:
		case OP_AND_IN_SEQUENCE:
		case OP_OR:
		case OP_NOT:
		case OP_XOR:
		case OP_EQUALS:
		case OP_GREATER_THAN:
		case OP_LESS_THAN:
		case OP_NOT_EQUAL:
		case OP_GREATER_OR_EQUAL:
		case OP_LESS_OR_EQUAL:
		case OP_STRING_EQUALS:
		case OP_STRING_GREATER_THAN:
		case OP_STRING_LESS_THAN:
		case OP_PERFORM_ACTIONS:
		case OP_IS_DESTROYED:
		case OP_IS_SUBSYSTEM_DESTROYED:
		case OP_IS_DISABLED:
		case OP_IS_DISARMED:
		case OP_HAS_DOCKED:
		case OP_HAS_UNDOCKED:
		case OP_HAS_ARRIVED:
		case OP_HAS_DEPARTED:
		case OP_IS_DESTROYED_DELAY:
		case OP_WAS_DESTROYED_BY_DELAY:
		case OP_IS_SUBSYSTEM_DESTROYED_DELAY:
		case OP_IS_DISABLED_DELAY:
		case OP_IS_DISARMED_DELAY:
		case OP_HAS_DOCKED_DELAY:
		case OP_HAS_UNDOCKED_DELAY:
		case OP_HAS_ARRIVED_DELAY:
		case OP_HAS_DEPARTED_DELAY:
		case OP_IS_IFF:
		case OP_IS_AI_CLASS:
		case OP_IS_SHIP_TYPE:
		case OP_IS_SHIP_CLASS:
		case OP_HAS_TIME_ELAPSED:
		case OP_GOAL_INCOMPLETE:
		case OP_GOAL_TRUE_DELAY:
		case OP_GOAL_FALSE_DELAY:
		case OP_EVENT_INCOMPLETE:
		case OP_EVENT_TRUE_DELAY:
		case OP_EVENT_FALSE_MSECS_DELAY:
		case OP_EVENT_TRUE_MSECS_DELAY:
		case OP_EVENT_FALSE_DELAY:
		case OP_PREVIOUS_EVENT_TRUE:
		case OP_PREVIOUS_EVENT_FALSE:
		case OP_PREVIOUS_EVENT_INCOMPLETE:
		case OP_PREVIOUS_GOAL_TRUE:
		case OP_PREVIOUS_GOAL_FALSE:
		case OP_PREVIOUS_GOAL_INCOMPLETE:
		case OP_WAYPOINTS_DONE:
		case OP_WAYPOINTS_DONE_DELAY:
		case OP_SHIP_TYPE_DESTROYED:
		case OP_LAST_ORDER_TIME:
		case OP_KEY_PRESSED:
		case OP_TARGETED:
		case OP_NODE_TARGETED:
		case OP_SPEED:
		case OP_FACING:
		case OP_FACING2:
		case OP_ORDER:
		case OP_QUERY_ORDERS:
		case OP_WAYPOINT_MISSED:
		case OP_WAYPOINT_TWICE:
		case OP_PATH_FLOWN:
		case OP_EVENT_TRUE:
		case OP_EVENT_FALSE:
		case OP_SKILL_LEVEL_AT_LEAST:
		case OP_IS_CARGO_KNOWN:
		case OP_HAS_BEEN_TAGGED_DELAY:
		case OP_CAP_SUBSYS_CARGO_KNOWN_DELAY:
		case OP_CARGO_KNOWN_DELAY:
		case OP_WAS_PROMOTION_GRANTED:
		case OP_WAS_MEDAL_GRANTED:
		case OP_PERCENT_SHIPS_DEPARTED:
		case OP_PERCENT_SHIPS_DESTROYED:
		case OP_PERCENT_SHIPS_DISARMED:
		case OP_PERCENT_SHIPS_DISABLED:
		case OP_PERCENT_SHIPS_ARRIVED:
		case OP_DEPART_NODE_DELAY:
		case OP_DESTROYED_DEPARTED_DELAY:
		case OP_SPECIAL_CHECK:
		case OP_IS_TAGGED:
		case OP_PRIMARIES_DEPLETED:
		case OP_SECONDARIES_DEPLETED:
		case OP_SHIELD_QUAD_LOW:
		case OP_IS_SECONDARY_SELECTED:
		case OP_IS_PRIMARY_SELECTED:
		case OP_IS_SHIP_STEALTHY:
		case OP_IS_FRIENDLY_STEALTH_VISIBLE:
		case OP_IS_CARGO:
		case OP_MISSILE_LOCKED:
		case OP_NAV_IS_VISITED:
		case OP_NAV_ISLINKED:
		case OP_IS_PLAYER:
		case OP_PRIMARY_FIRED_SINCE:
		case OP_SECONDARY_FIRED_SINCE:
		case OP_IS_FACING:
		case OP_HAS_PRIMARY_WEAPON:
		case OP_HAS_SECONDARY_WEAPON:
		case OP_IS_BIT_SET:
		case OP_DIRECTIVE_VALUE:
		case OP_IS_IN_BOX:
		case OP_IS_IN_MISSION:
		case OP_PLAYER_IS_CHEATING_BASTARD:
		case OP_ARE_SHIP_FLAGS_SET:
			return OPR_BOOL;

		case OP_PLUS:
		case OP_MINUS:
		case OP_MOD:
		case OP_MUL:
		case OP_DIV:
		case OP_RAND:
		case OP_RAND_MULTIPLE:
		case OP_MIN:
		case OP_MAX:
		case OP_AVG:
		case OP_POW:
		case OP_SIGNUM:
		case OP_GET_OBJECT_X:
		case OP_GET_OBJECT_Y:
		case OP_GET_OBJECT_Z:
		case OP_GET_OBJECT_PITCH:
		case OP_GET_OBJECT_BANK:
		case OP_GET_OBJECT_HEADING:
		case OP_GET_OBJECT_SPEED_X:
		case OP_GET_OBJECT_SPEED_Y:
		case OP_GET_OBJECT_SPEED_Z:
		case OP_SCRIPT_EVAL_NUM:
		case OP_STRING_TO_INT:
		case OP_GET_THROTTLE_SPEED:
		case OP_GET_VARIABLE_BY_INDEX:
		case OP_GET_COLGROUP_ID:
			return OPR_NUMBER;

		case OP_ABS:
		case OP_SET_BIT:
		case OP_UNSET_BIT:
		case OP_BITWISE_AND:
		case OP_BITWISE_OR:
		case OP_BITWISE_NOT:
		case OP_BITWISE_XOR:
		case OP_TIME_SHIP_DESTROYED:
		case OP_TIME_SHIP_ARRIVED:
		case OP_TIME_SHIP_DEPARTED:
		case OP_TIME_WING_DESTROYED:
		case OP_TIME_WING_ARRIVED:
		case OP_TIME_WING_DEPARTED:
		case OP_MISSION_TIME:
		case OP_MISSION_TIME_MSECS:
		case OP_TIME_DOCKED:
		case OP_TIME_UNDOCKED:
		case OP_AFTERBURNER_LEFT:
		case OP_WEAPON_ENERGY_LEFT:
		case OP_SHIELDS_LEFT:
		case OP_HITS_LEFT:
		case OP_HITS_LEFT_SUBSYSTEM:
		case OP_HITS_LEFT_SUBSYSTEM_GENERIC:
		case OP_HITS_LEFT_SUBSYSTEM_SPECIFIC:
		case OP_SIM_HITS_LEFT:
		case OP_DISTANCE:
		case OP_DISTANCE_SUBSYSTEM:
		case OP_NUM_WITHIN_BOX:
		case OP_NUM_PLAYERS:
		case OP_NUM_KILLS:
		case OP_NUM_ASSISTS:
		case OP_SHIP_DEATHS: 
		case OP_RESPAWNS_LEFT:
		case OP_SHIP_SCORE:
		case OP_NUM_TYPE_KILLS:
		case OP_NUM_CLASS_KILLS:
		case OP_SHIELD_RECHARGE_PCT:
		case OP_ENGINE_RECHARGE_PCT:
		case OP_WEAPON_RECHARGE_PCT:
		case OP_PRIMARY_AMMO_PCT:
		case OP_SECONDARY_AMMO_PCT:
		case OP_GET_PRIMARY_AMMO:
		case OP_GET_SECONDARY_AMMO:
		case OP_GET_NUM_COUNTERMEASURES:
		case OP_SPECIAL_WARP_DISTANCE:
		case OP_IS_SHIP_VISIBLE:
		case OP_TEAM_SCORE:
		case OP_NUM_SHIPS_IN_BATTLE:
		case OP_NUM_SHIPS_IN_WING:
		case OP_CURRENT_SPEED:
		case OP_NAV_DISTANCE:
		case OP_GET_DAMAGE_CAUSED:
		case OP_CUTSCENES_GET_FOV:
		case OP_NUM_VALID_ARGUMENTS:
		case OP_STRING_GET_LENGTH:
		case OP_GET_ETS_VALUE:
		case OP_TURRET_GET_PRIMARY_AMMO:
		case OP_TURRET_GET_SECONDARY_AMMO:
			return OPR_POSITIVE;

		case OP_COND:
		case OP_WHEN:
		case OP_WHEN_ARGUMENT:
		case OP_EVERY_TIME:
		case OP_EVERY_TIME_ARGUMENT:
		case OP_IF_THEN_ELSE:
		case OP_INVALIDATE_ARGUMENT:
		case OP_VALIDATE_ARGUMENT:
		case OP_INVALIDATE_ALL_ARGUMENTS:
		case OP_VALIDATE_ALL_ARGUMENTS:
		case OP_DO_FOR_VALID_ARGUMENTS:
		case OP_CHANGE_IFF:
		case OP_CHANGE_AI_CLASS:
		case OP_CLEAR_SHIP_GOALS:
		case OP_CLEAR_WING_GOALS:
		case OP_CLEAR_GOALS:
		case OP_ADD_SHIP_GOAL:
		case OP_ADD_WING_GOAL:
		case OP_ADD_GOAL:
		case OP_REMOVE_GOAL:
		case OP_PROTECT_SHIP:
		case OP_UNPROTECT_SHIP:
		case OP_BEAM_PROTECT_SHIP:
		case OP_BEAM_UNPROTECT_SHIP:
		case OP_TURRET_PROTECT_SHIP:
		case OP_TURRET_UNPROTECT_SHIP:
		case OP_NOP:
		case OP_GOALS_ID:
		case OP_SEND_MESSAGE:
		case OP_SELF_DESTRUCT:
		case OP_NEXT_MISSION:
		case OP_END_CAMPAIGN:
		case OP_END_OF_CAMPAIGN:
		case OP_SABOTAGE_SUBSYSTEM:
		case OP_REPAIR_SUBSYSTEM:
		case OP_INVALIDATE_GOAL:
		case OP_VALIDATE_GOAL:
		case OP_SEND_RANDOM_MESSAGE:
		case OP_TRANSFER_CARGO:
		case OP_EXCHANGE_CARGO:
		case OP_SET_CARGO:
		case OP_JETTISON_CARGO:
		case OP_SET_DOCKED:
		case OP_CARGO_NO_DEPLETE:
		case OP_SET_SCANNED:
		case OP_SET_UNSCANNED:
		case OP_KEY_RESET:
		case OP_KEY_RESET_MULTIPLE:
		case OP_TRAINING_MSG:
		case OP_SET_TRAINING_CONTEXT_FLY_PATH:
		case OP_SET_TRAINING_CONTEXT_SPEED:
		case OP_END_MISSION:
		case OP_SET_DEBRIEFING_TOGGLED:
		case OP_FORCE_JUMP:
		case OP_SET_SUBSYSTEM_STRNGTH:
		case OP_DESTROY_SUBSYS_INSTANTLY:
		case OP_GOOD_REARM_TIME:
		case OP_GRANT_PROMOTION:
		case OP_GRANT_MEDAL:
		case OP_ALLOW_SHIP:
		case OP_ALLOW_WEAPON:
		case OP_TECH_ADD_SHIP:
		case OP_TECH_ADD_WEAPON:
		case OP_TECH_ADD_INTEL:
		case OP_TECH_ADD_INTEL_XSTR:
		case OP_TECH_RESET_TO_DEFAULT:
		case OP_CHANGE_PLAYER_SCORE:
		case OP_CHANGE_TEAM_SCORE:
		case OP_WARP_BROKEN:
		case OP_WARP_NOT_BROKEN:
		case OP_WARP_NEVER:
		case OP_WARP_ALLOWED:
		case OP_SET_SUBSPACE_DRIVE:
		case OP_FLASH_HUD_GAUGE:
		case OP_GOOD_SECONDARY_TIME:
		case OP_SHIP_VISIBLE:
		case OP_SHIP_INVISIBLE:
		case OP_SHIP_TAG:
		case OP_SHIP_UNTAG:
		case OP_SHIP_VULNERABLE:
		case OP_SHIP_INVULNERABLE:
		case OP_SHIP_BOMB_TARGETABLE:
		case OP_SHIP_BOMB_UNTARGETABLE:
		case OP_SHIP_GUARDIAN:
		case OP_SHIP_NO_GUARDIAN:
		case OP_SHIP_GUARDIAN_THRESHOLD:
		case OP_SHIP_SUBSYS_GUARDIAN_THRESHOLD:
		case OP_SHIP_VANISH:
		case OP_DESTROY_INSTANTLY:
		case OP_SHIELDS_ON:
		case OP_SHIELDS_OFF:
		case OP_SHIP_STEALTHY:
		case OP_SHIP_UNSTEALTHY:
		case OP_FRIENDLY_STEALTH_INVISIBLE:
		case OP_FRIENDLY_STEALTH_VISIBLE:
		case OP_SHIP_SUBSYS_NO_REPLACE:
		case OP_SHIP_SUBSYS_NO_LIVE_DEBRIS:
		case OP_SHIP_SUBSYS_VANISHED:
		case OP_SHIP_SUBSYS_IGNORE_IF_DEAD:
		case OP_SHIP_SUBSYS_TARGETABLE:
		case OP_SHIP_SUBSYS_UNTARGETABLE:
		case OP_RED_ALERT:
		case OP_MODIFY_VARIABLE:
		case OP_SET_VARIABLE_BY_INDEX:
		case OP_BEAM_FIRE:
		case OP_BEAM_FIRE_COORDS:
		case OP_BEAM_FLOATING_FIRE:
		case OP_BEAM_FREE:
		case OP_BEAM_FREE_ALL:
		case OP_BEAM_LOCK:
		case OP_BEAM_LOCK_ALL:
		case OP_TURRET_FREE:
		case OP_TURRET_FREE_ALL:
		case OP_TURRET_LOCK:
		case OP_TURRET_LOCK_ALL:
		case OP_TURRET_CHANGE_WEAPON:
		case OP_TURRET_SET_DIRECTION_PREFERENCE:
		case OP_TURRET_SET_RATE_OF_FIRE:
		case OP_TURRET_SET_OPTIMUM_RANGE:
		case OP_TURRET_SET_TARGET_PRIORITIES:
		case OP_TURRET_SET_TARGET_ORDER:
		case OP_SET_ARMOR_TYPE:
		case OP_WEAPON_SET_DAMAGE_TYPE:
		case OP_SHIP_SET_DAMAGE_TYPE:
		case OP_SHIP_SHOCKWAVE_SET_DAMAGE_TYPE:
		case OP_FIELD_SET_DAMAGE_TYPE:
		case OP_SHIP_TURRET_TARGET_ORDER:
		case OP_TURRET_SUBSYS_TARGET_DISABLE:
		case OP_TURRET_SUBSYS_TARGET_ENABLE:
		case OP_ADD_REMOVE_ESCORT:
		case OP_DAMAGED_ESCORT_LIST:
		case OP_DAMAGED_ESCORT_LIST_ALL:
		case OP_AWACS_SET_RADIUS:
		case OP_PRIMITIVE_SENSORS_SET_RANGE:
		case OP_SEND_MESSAGE_LIST:
		case OP_CAP_WAYPOINT_SPEED:
		case OP_TURRET_TAGGED_ONLY_ALL:
		case OP_TURRET_TAGGED_CLEAR_ALL:
		case OP_SUBSYS_SET_RANDOM:
		case OP_SUPERNOVA_START:
		case OP_SUPERNOVA_STOP:
		case OP_SET_SPECIAL_WARPOUT_NAME:
		case OP_SHIP_VAPORIZE:
		case OP_SHIP_NO_VAPORIZE:
		case OP_SET_EXPLOSION_OPTION:
		case OP_DONT_COLLIDE_INVISIBLE:
		case OP_COLLIDE_INVISIBLE:
		case OP_SET_MOBILE:
		case OP_SET_IMMOBILE:
		case OP_IGNORE_KEY:
		case OP_CHANGE_SHIP_CLASS:
		case OP_SHIP_COPY_DAMAGE:
		case OP_DEACTIVATE_GLOW_POINTS:
		case OP_ACTIVATE_GLOW_POINTS:
		case OP_DEACTIVATE_GLOW_MAPS:
		case OP_ACTIVATE_GLOW_MAPS:
		case OP_DEACTIVATE_GLOW_POINT_BANK:
		case OP_ACTIVATE_GLOW_POINT_BANK:
		case OP_SET_SKYBOX_MODEL:
		case OP_SET_SKYBOX_ORIENT:
		case OP_SET_SUPPORT_SHIP:
		case OP_SET_ARRIVAL_INFO:
		case OP_SET_DEPARTURE_INFO:
		case OP_CHANGE_SOUNDTRACK:
		case OP_PLAY_SOUND_FROM_FILE:
		case OP_CLOSE_SOUND_FROM_FILE:
		case OP_PAUSE_SOUND_FROM_FILE:
		case OP_PLAY_SOUND_FROM_TABLE:
		case OP_SET_SOUND_ENVIRONMENT:
		case OP_UPDATE_SOUND_ENVIRONMENT:
		case OP_ADJUST_AUDIO_VOLUME:
		case OP_EXPLOSION_EFFECT:
		case OP_WARP_EFFECT:
		case OP_SET_OBJECT_POSITION:
		case OP_SET_OBJECT_ORIENTATION:
		case OP_SET_OBJECT_FACING:
		case OP_SET_OBJECT_FACING_OBJECT:
		case OP_SHIP_MANEUVER:
		case OP_SHIP_ROT_MANEUVER:
		case OP_SHIP_LAT_MANEUVER:
		case OP_HUD_DISABLE:
		case OP_HUD_DISABLE_EXCEPT_MESSAGES:
		case OP_KAMIKAZE:
		case OP_TURRET_TAGGED_SPECIFIC:
		case OP_TURRET_TAGGED_CLEAR_SPECIFIC:
		case OP_LOCK_ROTATING_SUBSYSTEM:
		case OP_FREE_ROTATING_SUBSYSTEM:
		case OP_REVERSE_ROTATING_SUBSYSTEM:
		case OP_ROTATING_SUBSYS_SET_TURN_TIME:
		case OP_TRIGGER_SUBMODEL_ANIMATION:
		case OP_PLAYER_USE_AI:
		case OP_PLAYER_NOT_USE_AI:
		case OP_ALLOW_TREASON:
		case OP_SET_PLAYER_ORDERS:
		case OP_NAV_ADD_WAYPOINT:
		case OP_NAV_ADD_SHIP:
		case OP_NAV_DEL:
		case OP_NAV_HIDE:
		case OP_NAV_RESTRICT:
		case OP_NAV_UNHIDE:
		case OP_NAV_UNRESTRICT:
		case OP_NAV_SET_VISITED:
		case OP_NAV_UNSET_VISITED:
		case OP_NAV_SET_CARRY:
		case OP_NAV_UNSET_CARRY:
		case OP_NAV_SET_NEEDSLINK:
		case OP_NAV_UNSET_NEEDSLINK:
		case OP_NAV_USECINEMATICS:
		case OP_NAV_USEAP:
		case OP_NAV_SELECT:
		case OP_NAV_UNSELECT:
		case OP_HUD_SET_TEXT:
		case OP_HUD_SET_TEXT_NUM:
		case OP_HUD_SET_MESSAGE:
		case OP_HUD_SET_COORDS:
		case OP_HUD_SET_FRAME:
		case OP_HUD_SET_COLOR:
		case OP_HUD_SET_MAX_TARGETING_RANGE:
		case OP_HUD_CLEAR_MESSAGES:
		case OP_SHIP_CHANGE_ALT_NAME:
		case OP_SHIP_CHANGE_CALLSIGN:
		case OP_SET_DEATH_MESSAGE:
		case OP_SCRAMBLE_MESSAGES:
		case OP_UNSCRAMBLE_MESSAGES:
		case OP_CUTSCENES_SET_CUTSCENE_BARS:
		case OP_CUTSCENES_UNSET_CUTSCENE_BARS:
		case OP_CUTSCENES_FADE_IN:
		case OP_CUTSCENES_FADE_OUT:
		case OP_CUTSCENES_SET_CAMERA:
		case OP_CUTSCENES_SET_CAMERA_FACING:
		case OP_CUTSCENES_SET_CAMERA_FACING_OBJECT:
		case OP_CUTSCENES_SET_CAMERA_FOV:
		case OP_CUTSCENES_SET_CAMERA_HOST:
		case OP_CUTSCENES_SET_CAMERA_POSITION:
		case OP_CUTSCENES_SET_CAMERA_ROTATION:
		case OP_CUTSCENES_SET_CAMERA_TARGET:
		case OP_CUTSCENES_SET_FOV:
		case OP_CUTSCENES_RESET_FOV:
		case OP_CUTSCENES_RESET_CAMERA:
		case OP_CUTSCENES_SHOW_SUBTITLE:
		case OP_CUTSCENES_SHOW_SUBTITLE_TEXT:
		case OP_CUTSCENES_SHOW_SUBTITLE_IMAGE:
		case OP_CUTSCENES_SET_TIME_COMPRESSION:
		case OP_CUTSCENES_RESET_TIME_COMPRESSION:
		case OP_CUTSCENES_FORCE_PERSPECTIVE:
		case OP_SET_CAMERA_SHUDDER:
		case OP_JUMP_NODE_SET_JUMPNODE_NAME:
		case OP_JUMP_NODE_SET_JUMPNODE_COLOR:
		case OP_JUMP_NODE_SET_JUMPNODE_MODEL:
		case OP_JUMP_NODE_SHOW_JUMPNODE:
		case OP_JUMP_NODE_HIDE_JUMPNODE:
		case OP_SET_OBJECT_SPEED_X:
		case OP_SET_OBJECT_SPEED_Y:
		case OP_SET_OBJECT_SPEED_Z:
		case OP_SHIP_CREATE:
		case OP_WEAPON_CREATE:
		case OP_MISSION_SET_NEBULA:
		case OP_ADD_BACKGROUND_BITMAP:
		case OP_REMOVE_BACKGROUND_BITMAP:
		case OP_ADD_SUN_BITMAP:
		case OP_REMOVE_SUN_BITMAP:
		case OP_NEBULA_CHANGE_STORM:
		case OP_NEBULA_TOGGLE_POOF:
		case OP_SET_PRIMARY_AMMO:
		case OP_SET_SECONDARY_AMMO:
		case OP_SET_PRIMARY_WEAPON:
		case OP_SET_SECONDARY_WEAPON:
		case OP_SET_NUM_COUNTERMEASURES:
		case OP_SCRIPT_EVAL:
		case OP_SCRIPT_EVAL_BLOCK:
		case OP_SCRIPT_EVAL_STRING:
		case OP_SCRIPT_EVAL_MULTI:
		case OP_ENABLE_BUILTIN_MESSAGES:
		case OP_DISABLE_BUILTIN_MESSAGES:
		case OP_LOCK_PRIMARY_WEAPON:
		case OP_UNLOCK_PRIMARY_WEAPON:
		case OP_LOCK_SECONDARY_WEAPON:
		case OP_UNLOCK_SECONDARY_WEAPON:
		case OP_LOCK_AFTERBURNER:
		case OP_UNLOCK_AFTERBURNER:
		case OP_RESET_ORDERS:
		case OP_SET_PERSONA:
		case OP_SET_MISSION_MOOD:
		case OP_CHANGE_SUBSYSTEM_NAME:
		case OP_SET_RESPAWNS:
		case OP_SET_AFTERBURNER_ENERGY: 
		case OP_SET_WEAPON_ENERGY:
		case OP_SET_SHIELD_ENERGY:
		case OP_SET_AMBIENT_LIGHT:
		case OP_SET_POST_EFFECT:
		case OP_CHANGE_IFF_COLOR:
		case OP_REMOVE_WEAPONS:
		case OP_MISSION_SET_SUBSPACE:
		case OP_HUD_DISPLAY_GAUGE:
		case OP_FORCE_GLIDE:
		case OP_HUD_SET_DIRECTIVE:
		case OP_HUD_GAUGE_SET_ACTIVE:
		case OP_HUD_ACTIVATE_GAUGE_TYPE:
		case OP_STRING_CONCATENATE:
		case OP_INT_TO_STRING:
		case OP_DISABLE_ETS:
		case OP_ENABLE_ETS:
		case OP_STRING_GET_SUBSTRING:
		case OP_STRING_SET_SUBSTRING:
		case OP_ADD_TO_COLGROUP:
		case OP_REMOVE_FROM_COLGROUP:
		case OP_SHIP_EFFECT:
		case OP_CLEAR_SUBTITLES:
		case OP_SET_THRUSTERS:
		case OP_SET_PLAYER_THROTTLE_SPEED:
		case OP_DEBUG:
		case OP_HUD_SET_CUSTOM_GAUGE_ACTIVE:
		case OP_HUD_SET_RETAIL_GAUGE_ACTIVE:
		case OP_ALTER_SHIP_FLAG:
		case OP_CHANGE_TEAM_COLOR:
		case OP_NEBULA_CHANGE_PATTERN:
		case OP_COPY_VARIABLE_FROM_INDEX:
		case OP_COPY_VARIABLE_BETWEEN_INDEXES:
		case OP_SET_ETS_VALUES:
		case OP_CALL_SSM_STRIKE:
		case OP_SET_MOTION_DEBRIS:
		case OP_TURRET_SET_PRIMARY_AMMO:
		case OP_TURRET_SET_SECONDARY_AMMO:
			return OPR_NULL;

		case OP_AI_CHASE:
		case OP_AI_DOCK:
		case OP_AI_UNDOCK:
		case OP_AI_WARP:						// this particular operator is obsolete
		case OP_AI_WARP_OUT:
		case OP_AI_WAYPOINTS:
		case OP_AI_WAYPOINTS_ONCE:
		case OP_AI_DESTROY_SUBSYS:
		case OP_AI_CHASE_WING:
		case OP_AI_DISABLE_SHIP:
		case OP_AI_DISARM_SHIP:
		case OP_AI_GUARD:
		case OP_AI_GUARD_WING:
		case OP_AI_CHASE_ANY:
		case OP_AI_EVADE_SHIP:
		case OP_AI_STAY_NEAR_SHIP:
		case OP_AI_KEEP_SAFE_DISTANCE:
		case OP_AI_IGNORE:
		case OP_AI_IGNORE_NEW:
		case OP_AI_STAY_STILL:
		case OP_AI_PLAY_DEAD:
		case OP_AI_FORM_ON_WING:
			return OPR_AI_GOAL;

		case OP_ANY_OF:
		case OP_EVERY_OF:
		case OP_RANDOM_OF:
		case OP_RANDOM_MULTIPLE_OF:
		case OP_NUMBER_OF:
		case OP_IN_SEQUENCE:
		case OP_FOR_COUNTER:
			return OPR_FLEXIBLE_ARGUMENT;

		default:
			Int3();
	}

	return 0;
}

/**
 * Return the data type of a specified argument to an operator.  
 *
 * @param op operator index
 * @param argnum is 0 indexed.
 */
int query_operator_argument_type(int op, int argnum)
{
	int index = op;

	if (op < FIRST_OP)
	{
		Assert(index >= 0 && index < Num_operators);
		op = Operators[index].value;

	} else {
		Warning(LOCATION, "Possible unnecessary search for operator index.  Trace out and see if this is necessary.\n");

		for (index=0; index<Num_operators; index++)
			if (Operators[index].value == op)
				break;

		Assert(index < Num_operators);
	}

	if (argnum >= Operators[index].max)
		return OPF_NONE;

	switch (op) {
		case OP_TRUE:
		case OP_FALSE:
		case OP_MISSION_TIME:
		case OP_MISSION_TIME_MSECS:
		case OP_NOP:
		case OP_WAYPOINT_MISSED:
		case OP_WAYPOINT_TWICE:
		case OP_PATH_FLOWN:
		case OP_GRANT_PROMOTION:
		case OP_WAS_PROMOTION_GRANTED:
		case OP_RED_ALERT:
		case OP_FORCE_JUMP:
		case OP_RESET_ORDERS:
		case OP_INVALIDATE_ALL_ARGUMENTS:
		case OP_VALIDATE_ALL_ARGUMENTS:
		case OP_NUM_VALID_ARGUMENTS:
		case OP_SUPERNOVA_STOP:
		case OP_NAV_UNSELECT:
		case OP_PLAYER_IS_CHEATING_BASTARD:
			return OPF_NONE;

		case OP_AND:
		case OP_AND_IN_SEQUENCE:
		case OP_OR:
		case OP_NOT:
		case OP_XOR:
			return OPF_BOOL;

		case OP_PLUS:
		case OP_MINUS:
		case OP_MOD:
		case OP_MUL:
		case OP_DIV:
		case OP_EQUALS:
		case OP_GREATER_THAN:
		case OP_LESS_THAN:
		case OP_NOT_EQUAL:
		case OP_GREATER_OR_EQUAL:
		case OP_LESS_OR_EQUAL:
		case OP_RAND:
		case OP_RAND_MULTIPLE:
		case OP_ABS:
		case OP_MIN:
		case OP_MAX:
		case OP_AVG:
			return OPF_NUMBER;

		case OP_POW:
			if (argnum == 0)
				return OPF_NUMBER;
			else
				return OPF_POSITIVE;

		case OP_SIGNUM:
			return OPF_NUMBER;

		case OP_STRING_EQUALS:
		case OP_STRING_GREATER_THAN:
		case OP_STRING_LESS_THAN:
		case OP_STRING_TO_INT:		// Karajorma
		case OP_STRING_GET_LENGTH:	// Goober5000
			return OPF_STRING;

		case OP_STRING_CONCATENATE:
			if (argnum == 0 || argnum == 1) {
				return OPF_STRING;
			} else if (argnum == 2) {
				return OPF_VARIABLE_NAME;
			}

		case OP_INT_TO_STRING:
			if (argnum == 0) {
				return OPF_NUMBER;
			} else if (argnum == 1) {
				return OPF_VARIABLE_NAME;
			}

		case OP_STRING_GET_SUBSTRING:
			if (argnum == 0) {
				return OPF_STRING;
			} else if (argnum == 1 || argnum == 2) {
				return OPF_POSITIVE;
			} else if (argnum == 3) {
				return OPF_VARIABLE_NAME;
			}

		case OP_STRING_SET_SUBSTRING:
			if (argnum == 0) {
				return OPF_STRING;
			} else if (argnum == 1 || argnum == 2) {
				return OPF_POSITIVE;
			} else if (argnum == 3) {
				return OPF_STRING;
			} else if (argnum == 4) {
				return OPF_VARIABLE_NAME;
			}

		case OP_DEBUG:
			if (argnum == 0) {
				return OPF_BOOL;
			}else if (argnum == 1) {
				return OPF_MESSAGE; 
			}else  {
				return OPF_STRING;
			}

		case OP_HAS_TIME_ELAPSED:
		case OP_SPEED:
		case OP_SET_TRAINING_CONTEXT_SPEED:
		case OP_SPECIAL_CHECK:
		case OP_AI_WARP_OUT:
		case OP_TEAM_SCORE:
		case OP_HUD_SET_MAX_TARGETING_RANGE:
		case OP_MISSION_SET_NEBULA:	//WMC
		case OP_MISSION_SET_SUBSPACE:
		case OP_SET_BIT:
		case OP_UNSET_BIT:
		case OP_IS_BIT_SET:
		case OP_BITWISE_AND:
		case OP_BITWISE_OR:
		case OP_BITWISE_NOT:
		case OP_BITWISE_XOR:
			return OPF_POSITIVE;

		case OP_AI_WARP:								// this operator is obsolete
		case OP_SET_TRAINING_CONTEXT_FLY_PATH:
			if ( !argnum )
				return OPF_WAYPOINT_PATH;
			else
				return OPF_NUMBER;
		
		case OP_AI_WAYPOINTS:
		case OP_AI_WAYPOINTS_ONCE:
			if ( argnum == 0 )
				return OPF_WAYPOINT_PATH;
			else
				return OPF_POSITIVE;

		case OP_TURRET_PROTECT_SHIP:
		case OP_TURRET_UNPROTECT_SHIP:
			if (argnum == 0)
				return OPF_STRING;
			else
				return OPF_SHIP;

		case OP_IS_DISABLED:
		case OP_IS_DISARMED:
		case OP_TIME_SHIP_DESTROYED:
		case OP_TIME_SHIP_ARRIVED:
		case OP_TIME_SHIP_DEPARTED:
		case OP_AFTERBURNER_LEFT:
		case OP_WEAPON_ENERGY_LEFT:
		case OP_SHIELDS_LEFT:
		case OP_HITS_LEFT:
		case OP_SIM_HITS_LEFT:
		case OP_CLEAR_SHIP_GOALS:
		case OP_PROTECT_SHIP:
		case OP_UNPROTECT_SHIP:
		case OP_BEAM_PROTECT_SHIP:
		case OP_BEAM_UNPROTECT_SHIP:
		case OP_TRANSFER_CARGO:
		case OP_EXCHANGE_CARGO:
		case OP_SHIP_INVISIBLE:
		case OP_SHIP_VISIBLE:	
		case OP_SHIP_INVULNERABLE:
		case OP_SHIP_VULNERABLE:
		case OP_SHIP_BOMB_TARGETABLE:
		case OP_SHIP_BOMB_UNTARGETABLE:
		case OP_SHIP_GUARDIAN:
		case OP_SHIP_NO_GUARDIAN:
		case OP_SHIP_VANISH:
		case OP_DESTROY_INSTANTLY:
		case OP_SHIELDS_ON:
		case OP_SHIELDS_OFF:
		case OP_SHIP_STEALTHY:
		case OP_SHIP_UNSTEALTHY:
		case OP_FRIENDLY_STEALTH_INVISIBLE:
		case OP_FRIENDLY_STEALTH_VISIBLE:
		case OP_PRIMARIES_DEPLETED:
		case OP_SECONDARIES_DEPLETED:
		case OP_SPECIAL_WARP_DISTANCE:
		case OP_SET_SPECIAL_WARPOUT_NAME:
		case OP_IS_SHIP_VISIBLE:
		case OP_IS_SHIP_STEALTHY:
		case OP_IS_FRIENDLY_STEALTH_VISIBLE:
		case OP_GET_DAMAGE_CAUSED:
		case OP_GET_THROTTLE_SPEED:
			return OPF_SHIP;

		case OP_ALTER_SHIP_FLAG:
			if(argnum == 0)
				return OPF_SHIP_FLAG;
			if(argnum == 1 || argnum == 2)
				return OPF_BOOL;
			else
				return OPF_SHIP_WING_WHOLETEAM;
		
		case OP_SET_PLAYER_THROTTLE_SPEED:
			if(argnum == 0)
				return OPF_SHIP;
			else
				return OPF_POSITIVE;

		case OP_SHIP_CREATE:
			if(argnum == 0)
				return OPF_STRING;
			else if(argnum == 1)
				return OPF_SHIP_CLASS_NAME;
			else
				return OPF_NUMBER;

		case OP_WEAPON_CREATE:
			if (argnum == 0)
				return OPF_SHIP_OR_NONE;
			else if (argnum == 1)
				return OPF_WEAPON_NAME;
			else if (argnum == 8)
				return OPF_SHIP;
			else if (argnum == 9)
				return OPF_SUBSYSTEM;
			else
				return OPF_NUMBER;

		case OP_REMOVE_WEAPONS:
			return OPF_WEAPON_NAME;

		case OP_SHIP_GUARDIAN_THRESHOLD:
			if (argnum == 0)
				return OPF_POSITIVE;
			else
				return OPF_SHIP;

		case OP_SHIP_SUBSYS_GUARDIAN_THRESHOLD:
			if (argnum == 0)
				return OPF_POSITIVE;
			else if (argnum == 1)
				return OPF_SHIP;
			else
				return OPF_SUBSYS_OR_GENERIC;

		case OP_SHIP_SUBSYS_TARGETABLE:
		case OP_SHIP_SUBSYS_UNTARGETABLE:
			if (argnum == 0)
				return OPF_SHIP;
			else
				return OPF_SUBSYS_OR_GENERIC;

		case OP_SHIP_SUBSYS_NO_REPLACE:
		case OP_SHIP_SUBSYS_NO_LIVE_DEBRIS:
		case OP_SHIP_SUBSYS_VANISHED:
		case OP_SHIP_SUBSYS_IGNORE_IF_DEAD:
			if (argnum == 0)
				return OPF_SHIP;
			else if (argnum == 1)
				return OPF_BOOL;
			else
				return OPF_SUBSYS_OR_GENERIC;

		case OP_IS_DESTROYED:
		case OP_HAS_ARRIVED:
		case OP_HAS_DEPARTED:
		case OP_CLEAR_GOALS:
			return OPF_SHIP_WING;

		case OP_IS_DISABLED_DELAY:
		case OP_IS_DISARMED_DELAY:
			if ( argnum == 0 )
				return OPF_POSITIVE;
			else
				return OPF_SHIP;

		case OP_SHIP_TAG:
			if (argnum == 0)
				return OPF_SHIP;
			else if (argnum == 3)
				return OPF_SSM_CLASS;
            else if (argnum == 7)
                return OPF_IFF;
			else if (argnum > 3)	// SSM origin coordinates shouldn't be limited to positive numbers
				return OPF_NUMBER;
			else
				return OPF_POSITIVE;

		case OP_SHIP_UNTAG:
			return OPF_SHIP;

		case OP_FACING:
			if (argnum == 0)
				return OPF_SHIP;
			else
				return OPF_POSITIVE;

		case OP_FACING2:
			if (argnum == 0) {
				return OPF_WAYPOINT_PATH;
			} else {
				return OPF_POSITIVE;
			}

		case OP_ORDER:
			if (argnum == 1)
				return OPF_AI_ORDER;
			else
				return OPF_SHIP_WING;	// arg 0 or 2

		case OP_QUERY_ORDERS:
			if (argnum == 0)
				return OPF_ORDER_RECIPIENT;
			if (argnum == 1)
				return OPF_AI_ORDER;
			if (argnum == 2)
				return OPF_POSITIVE;
			if (argnum == 5)
				return OPF_SUBSYSTEM;
			else
				return OPF_SHIP_WING;

		case OP_WAS_DESTROYED_BY_DELAY:
			if (argnum == 0)
				return OPF_POSITIVE;
			else
				return OPF_SHIP;

		case OP_IS_DESTROYED_DELAY:
		case OP_HAS_ARRIVED_DELAY:
		case OP_HAS_DEPARTED_DELAY:
		case OP_LAST_ORDER_TIME:
			if ( argnum == 0 )
				return OPF_POSITIVE;
			else
				return OPF_SHIP_WING;

		case OP_SHIP_CHANGE_ALT_NAME:
			if (argnum == 0)
				return OPF_STRING;
			else
				return OPF_SHIP_WING;

		case OP_SHIP_CHANGE_CALLSIGN:
			if (argnum == 0)
				return OPF_STRING;
			else
				return OPF_SHIP;

		case OP_SET_DEATH_MESSAGE:
			return OPF_MESSAGE_OR_STRING;

		case OP_DISTANCE:
			return OPF_SHIP_WING_SHIPONTEAM_POINT;

		case OP_SET_OBJECT_SPEED_X:
		case OP_SET_OBJECT_SPEED_Y:
		case OP_SET_OBJECT_SPEED_Z:
			if (argnum == 0)
				return OPF_SHIP_WING;
			else if (argnum == 1)
				return OPF_NUMBER;
			else
				return OPF_BOOL;

		case OP_GET_OBJECT_SPEED_X:
		case OP_GET_OBJECT_SPEED_Y:
		case OP_GET_OBJECT_SPEED_Z:
			if (argnum == 0)
				return OPF_SHIP_WING;
			else
				return OPF_BOOL;

		case OP_GET_OBJECT_X:
		case OP_GET_OBJECT_Y:
		case OP_GET_OBJECT_Z:
			if (argnum == 0)
				return OPF_SHIP_WING_POINT;
			else if (argnum == 1)
				return OPF_SUBSYSTEM_OR_NONE;
			else
				return OPF_NUMBER;

		case OP_GET_OBJECT_PITCH:
		case OP_GET_OBJECT_BANK:
		case OP_GET_OBJECT_HEADING:
			return OPF_SHIP_WING;

		case OP_SET_OBJECT_POSITION:
			if(argnum == 0)
				return OPF_SHIP_WING_POINT;
			else
				return OPF_NUMBER;

		case OP_SET_OBJECT_ORIENTATION:
			if (argnum == 0)
				return OPF_SHIP_WING;
			else
				return OPF_NUMBER;

		case OP_SET_OBJECT_FACING:
			if (argnum == 0)
				return OPF_SHIP_WING;
			else if (argnum < 4)
				return OPF_NUMBER;
			else
				return OPF_POSITIVE;

		case OP_SET_OBJECT_FACING_OBJECT:
			if (argnum == 0)
				return OPF_SHIP_WING;
			else if (argnum == 1)
				return OPF_SHIP_WING_POINT;
			else
				return OPF_POSITIVE;

		case OP_SHIP_MANEUVER:
			if (argnum == 0)
				return OPF_SHIP_WING;
			else if (argnum == 1)
				return OPF_POSITIVE;
			else if (argnum < 5)
				return OPF_NUMBER;
			else if (argnum == 5)
				return OPF_BOOL;
			else if (argnum < 9)
				return OPF_NUMBER;
			else
				return OPF_BOOL;

		case OP_SHIP_ROT_MANEUVER:
		case OP_SHIP_LAT_MANEUVER:
			if (argnum == 0)
				return OPF_SHIP_WING;
			else if (argnum == 1)
				return OPF_POSITIVE;
			else if (argnum < 5)
				return OPF_NUMBER;
			else
				return OPF_BOOL;

		case OP_MODIFY_VARIABLE:
			if (argnum == 0) {
				return OPF_VARIABLE_NAME;
			} else {
				return OPF_AMBIGUOUS; 
			}

		case OP_GET_VARIABLE_BY_INDEX:
		case OP_COPY_VARIABLE_BETWEEN_INDEXES:
			return OPF_POSITIVE;

		case OP_COPY_VARIABLE_FROM_INDEX:
			if (argnum == 0) {
				return OPF_POSITIVE;
			} else {
				return OPF_VARIABLE_NAME;
			}

		case OP_SET_VARIABLE_BY_INDEX:
			if (argnum == 0) {
				return OPF_POSITIVE;
			} else {
				return OPF_AMBIGUOUS;
			}

		case OP_HAS_DOCKED:
		case OP_HAS_UNDOCKED:
		case OP_HAS_DOCKED_DELAY:
		case OP_HAS_UNDOCKED_DELAY:
		case OP_TIME_DOCKED:
		case OP_TIME_UNDOCKED:
			if ( argnum < 2 )
				return OPF_SHIP;
			else
				return OPF_POSITIVE;

		case OP_TIME_WING_DESTROYED:
		case OP_TIME_WING_ARRIVED:
		case OP_TIME_WING_DEPARTED:
		case OP_CLEAR_WING_GOALS:
			return OPF_WING;

		case OP_SET_SCANNED:
		case OP_SET_UNSCANNED:
		case OP_IS_SUBSYSTEM_DESTROYED:
			if (!argnum)
				return OPF_SHIP;
			else
				return OPF_SUBSYSTEM;
			
		case OP_HITS_LEFT_SUBSYSTEM:
			if (argnum == 0)
				return OPF_SHIP;
			else if (argnum == 1) 
				return OPF_SUBSYSTEM;
			else 
				return OPF_BOOL;

		case OP_HITS_LEFT_SUBSYSTEM_GENERIC:
			if (argnum == 0)
				return OPF_SHIP;
			else
				return OPF_SUBSYSTEM_TYPE;

		case OP_HITS_LEFT_SUBSYSTEM_SPECIFIC:
			if (argnum == 0)
				return OPF_SHIP;
			else if (argnum == 1)
				return OPF_SUBSYSTEM;

		case OP_DISTANCE_SUBSYSTEM:
			if (argnum == 0)
				return OPF_SHIP_WING_SHIPONTEAM_POINT;
			else if (argnum == 1)
				return OPF_SHIP;
			else if (argnum == 2)
				return OPF_SUBSYSTEM;
			else
				Int3();		// shouldn't happen

		case OP_NUM_WITHIN_BOX:
			if(argnum < 3)
				return OPF_NUMBER;
			else if(argnum < 6)
				return OPF_POSITIVE;
			else
				return OPF_SHIP_WING;

		case OP_IS_IN_BOX:
			if (argnum == 0) // First arg is a ship/wing/point
				return OPF_SHIP_WING_POINT;
			else if (argnum <= 6) // Next 6 args are coordinates
				return OPF_NUMBER;
			else // Next arg is a ship
				return OPF_SHIP;

		case OP_IS_IN_MISSION:
			return OPF_STRING;

		// Sesquipedalian
		case OP_MISSILE_LOCKED:
			if (argnum == 0)
				return OPF_POSITIVE;
			else if (argnum == 1)
				return OPF_SHIP;
			else
				return OPF_SUBSYSTEM;

		case OP_TARGETED:
			if (!argnum)
				return OPF_SHIP;
			else if (argnum == 1)
				return OPF_POSITIVE;
			else
				return OPF_SUBSYSTEM;

		case OP_NODE_TARGETED:
			if (!argnum)
				return OPF_JUMP_NODE_NAME;
			else if (argnum == 1)
				return OPF_POSITIVE;

		case OP_IS_SUBSYSTEM_DESTROYED_DELAY:
			if ( argnum == 0 )
				return OPF_SHIP;
			else if ( argnum == 1 )
				return OPF_SUBSYSTEM;
			else
				return OPF_POSITIVE;

		case OP_IS_IFF:
		case OP_CHANGE_IFF:
			if (!argnum)
				return OPF_IFF;
			else
				return OPF_SHIP_WING;

		case OP_ADD_SHIP_GOAL:
			if (!argnum)
				return OPF_SHIP;
			else
				return OPF_AI_GOAL;

		case OP_ADD_WING_GOAL:
			if (!argnum)
				return OPF_WING;
			else
				return OPF_AI_GOAL;

		case OP_ADD_GOAL:
		case OP_REMOVE_GOAL:
			if ( argnum == 0 )
				return OPF_SHIP_WING;
			else
				return OPF_AI_GOAL;

		case OP_COND:
		case OP_WHEN:
		case OP_EVERY_TIME:
		case OP_IF_THEN_ELSE:
		case OP_PERFORM_ACTIONS:
			if (!argnum)
				return OPF_BOOL;
			else
				return OPF_NULL;

		case OP_WHEN_ARGUMENT:
		case OP_EVERY_TIME_ARGUMENT:
			if (argnum == 0)
				return OPF_FLEXIBLE_ARGUMENT;
			else if (argnum == 1)
				return OPF_BOOL;
			else
				return OPF_NULL;
			
		case OP_DO_FOR_VALID_ARGUMENTS:
			return OPF_NULL;

		case OP_ANY_OF:
		case OP_EVERY_OF:
		case OP_RANDOM_OF:
		case OP_RANDOM_MULTIPLE_OF:
		case OP_IN_SEQUENCE:
			return OPF_ANYTHING;

		case OP_NUMBER_OF:
			if (argnum == 0)
				return OPF_POSITIVE;
			else
				return OPF_ANYTHING;

		case OP_FOR_COUNTER:
			return OPF_NUMBER;

		case OP_INVALIDATE_ARGUMENT:
		case OP_VALIDATE_ARGUMENT:
			return OPF_ANYTHING;

		case OP_AI_DISABLE_SHIP:
		case OP_AI_DISARM_SHIP:
			if (argnum == 0)
				return OPF_SHIP;
			else if (argnum == 1)
				return OPF_POSITIVE;
			else
				return OPF_BOOL;

		case OP_AI_EVADE_SHIP:
		case OP_AI_STAY_NEAR_SHIP:
		case OP_AI_IGNORE:
		case OP_AI_IGNORE_NEW:
			if (!argnum)
				return OPF_SHIP;
			else
				return OPF_POSITIVE;

		case OP_AI_CHASE:
			if (argnum == 0)
				return OPF_SHIP_WING;
			else if (argnum == 1)
				return OPF_POSITIVE;
			else
				return OPF_BOOL;

		case OP_AI_GUARD:
			if (!argnum)
				return OPF_SHIP_WING;
			else
				return OPF_POSITIVE;

		case OP_AI_KEEP_SAFE_DISTANCE:
			return OPF_POSITIVE;

		case OP_AI_DOCK:
			if (!argnum)
				return OPF_SHIP;
			else if (argnum == 1)
				return OPF_DOCKER_POINT;
			else if (argnum == 2)
				return OPF_DOCKEE_POINT;
			else
				return OPF_POSITIVE;

		case OP_AI_UNDOCK:
			if (argnum == 0)
				return OPF_POSITIVE;
			else
				return OPF_SHIP;

		case OP_AI_CHASE_WING:
			if (argnum == 0)
				return OPF_WING;
			else if (argnum == 1)
				return OPF_POSITIVE;
			else
				return OPF_BOOL;

		case OP_AI_GUARD_WING:
			if (!argnum)
				return OPF_WING;
			else
				return OPF_POSITIVE;

		case OP_AI_DESTROY_SUBSYS:
			if (!argnum)
				return OPF_SHIP;
			else if (argnum == 1)
				return OPF_SUBSYSTEM;
			else if (argnum == 2)
				return OPF_POSITIVE;
			else
				return OPF_BOOL;
			
		case OP_GOALS_ID:
			return OPF_AI_GOAL;

		case OP_SET_CARGO:
		case OP_IS_CARGO:
			if (argnum == 0)
				return OPF_CARGO;
			else if (argnum == 1)
				return OPF_SHIP;
			else
				return OPF_SUBSYSTEM;

		case OP_CHANGE_AI_CLASS:
		case OP_IS_AI_CLASS:
			if (argnum == 0)
				return OPF_AI_CLASS;
			else if (argnum == 1)
				return OPF_SHIP;
			else
				return OPF_SUBSYSTEM;

		case OP_IS_SHIP_TYPE:
			if (argnum == 0)
				return OPF_SHIP_TYPE;
			else
				return OPF_SHIP;

		case OP_IS_SHIP_CLASS:
			if (argnum == 0)
				return OPF_SHIP_CLASS_NAME;
			else
				return OPF_SHIP;

		case OP_CHANGE_SOUNDTRACK:
			return OPF_SOUNDTRACK_NAME;

		case OP_PLAY_SOUND_FROM_TABLE:
			if (argnum == 3)
				return OPF_GAME_SND;
			else
				return OPF_POSITIVE;

		case OP_PLAY_SOUND_FROM_FILE:
			if (argnum==0)
				return OPF_STRING;
			else
				return OPF_POSITIVE;

		case OP_CLOSE_SOUND_FROM_FILE:
		case OP_PAUSE_SOUND_FROM_FILE:
		case OP_ALLOW_TREASON:
		case OP_END_MISSION:
		case OP_SET_DEBRIEFING_TOGGLED:
			return OPF_BOOL;

		case OP_SET_PLAYER_ORDERS:
			if (argnum==0)
				return OPF_SHIP;
			if (argnum==1)
				return OPF_BOOL;
			else 
				return OPF_AI_ORDER;

		case OP_SET_SOUND_ENVIRONMENT:
			if (argnum == 0)
				return OPF_SOUND_ENVIRONMENT;

			// fall through
			argnum--;

		case OP_UPDATE_SOUND_ENVIRONMENT:
		{
			// every two, the value repeats
			int a_mod = argnum % 2;

			if (a_mod == 0)
				return OPF_SOUND_ENVIRONMENT_OPTION;
			else
				return OPF_POSITIVE;
		}

		case OP_ADJUST_AUDIO_VOLUME:
		{
			if (argnum == 0)
				return OPF_AUDIO_VOLUME_OPTION;
			else
				return OPF_POSITIVE;
		}

		case OP_SET_EXPLOSION_OPTION:
		{
			// editing a ship
			if (argnum == 0)
				return OPF_SHIP;

			// every two, the value repeats
			int a_mod = (argnum - 1) % 2;

			if (a_mod == 0)
				return OPF_EXPLOSION_OPTION;
			else
				return OPF_POSITIVE;
		}

		case OP_HUD_DISABLE:
		case OP_HUD_DISABLE_EXCEPT_MESSAGES:
			return OPF_POSITIVE;

		case OP_HUD_SET_TEXT:
			return OPF_STRING;

		case OP_HUD_SET_MESSAGE:
			if(argnum == 0)
				return OPF_STRING;
			else
				return OPF_MESSAGE;

		case OP_HUD_SET_TEXT_NUM:
		case OP_HUD_SET_COORDS:
		case OP_HUD_SET_FRAME:
		case OP_HUD_SET_COLOR:
			if(argnum == 0)
				return OPF_STRING;
			else
				return OPF_POSITIVE;

		case OP_HUD_CLEAR_MESSAGES:
			return OPF_NONE;

		case OP_PLAYER_USE_AI:
		case OP_PLAYER_NOT_USE_AI:
			return OPF_NONE;

		case OP_EXPLOSION_EFFECT:
			if (argnum <= 2)
				return OPF_NUMBER;
			else if (argnum == 10)
				return OPF_GAME_SND;
			else
				return OPF_POSITIVE;

		case OP_WARP_EFFECT:
			if (argnum <= 5)
				return OPF_NUMBER;
			else if (argnum == 8 || argnum == 9)
				return OPF_GAME_SND;
			else
				return OPF_POSITIVE;

		case OP_SEND_MESSAGE:
		case OP_SEND_RANDOM_MESSAGE:
			if ( argnum == 0 )
				return OPF_WHO_FROM;
			else if ( argnum == 1 )
				return OPF_PRIORITY;
			else
				return OPF_MESSAGE;

		case OP_SEND_MESSAGE_LIST:
		{
			// every four, the value repeats
			int a_mod = argnum % 4;

			// who from
			if(a_mod == 0)
				return OPF_WHO_FROM;
			else if(a_mod == 1)
				return OPF_PRIORITY;
			else if(a_mod == 2)
				return OPF_MESSAGE;
			else if(a_mod == 3)
				return OPF_POSITIVE;
		}

		case OP_TRAINING_MSG:
			if (argnum < 2)
				return OPF_MESSAGE;
			else
				return OPF_POSITIVE;

		// Karajorma
		case OP_ENABLE_BUILTIN_MESSAGES:
		case OP_DISABLE_BUILTIN_MESSAGES:
				return OPF_WHO_FROM;

		case OP_SET_PERSONA:
			if (argnum == 0) 
				return OPF_PERSONA;
			else
				return OPF_SHIP;

		case OP_SET_MISSION_MOOD:
			return OPF_MISSION_MOOD;

		case OP_CHANGE_TEAM_COLOR:
			if (argnum == 0)
				return OPF_TEAM_COLOR;
			else if (argnum == 1)
				return OPF_NUMBER;
			else
				return OPF_SHIP;

		case OP_CALL_SSM_STRIKE:
			if (argnum == 0)
				return OPF_SSM_CLASS;
			else if (argnum == 1)
				return OPF_IFF;
			else
				return OPF_SHIP;

		case OP_SELF_DESTRUCT:
			return OPF_SHIP;

		case OP_NEXT_MISSION:
			return OPF_MISSION_NAME;

		case OP_END_CAMPAIGN:
			return OPF_BOOL;

		case OP_END_OF_CAMPAIGN:
			return OPF_NONE;

		case OP_PREVIOUS_GOAL_TRUE:
		case OP_PREVIOUS_GOAL_FALSE:
			if ( argnum == 0 )
				return OPF_MISSION_NAME;
			else if (argnum == 1 )
				return OPF_GOAL_NAME;
			else
				return OPF_BOOL;

		case OP_PREVIOUS_GOAL_INCOMPLETE:
			return OPF_GOAL_NAME;

		case OP_PREVIOUS_EVENT_TRUE:
		case OP_PREVIOUS_EVENT_FALSE:
		case OP_PREVIOUS_EVENT_INCOMPLETE:
			if (!argnum)
				return OPF_MISSION_NAME;
			else if ( argnum == 1 )
				return OPF_EVENT_NAME;
			else
				return OPF_BOOL;

		case OP_SABOTAGE_SUBSYSTEM:
			if (!argnum)
				return OPF_SHIP;		// changed from OPF_SHIP_NOT_PLAYER by Goober5000: now it can be the player ship also
			else if (argnum == 1 )
				return OPF_SUBSYS_OR_GENERIC;
			else
				return OPF_POSITIVE;

		case OP_REPAIR_SUBSYSTEM:
		case OP_SET_SUBSYSTEM_STRNGTH:
			if (!argnum)
				return OPF_SHIP;		// changed from OPF_SHIP_NOT_PLAYER by Goober5000: now it can be the player ship also
			else if (argnum == 1 )
				return OPF_SUBSYS_OR_GENERIC;
			else if (argnum == 2)
				return OPF_POSITIVE;
			else 
				return OPF_BOOL;

		case OP_DESTROY_SUBSYS_INSTANTLY:
			if (argnum == 0)
				return OPF_SHIP;
			else
				return OPF_SUBSYS_OR_GENERIC;

		case OP_WAYPOINTS_DONE:
			if ( argnum == 0 )
				return OPF_SHIP_WING;
			else
				return OPF_WAYPOINT_PATH;

		case OP_WAYPOINTS_DONE_DELAY:
			if ( argnum == 0 )
				return OPF_SHIP_WING;
			else if ( argnum == 1 )
				return OPF_WAYPOINT_PATH;
			else
				return OPF_POSITIVE;

		case OP_INVALIDATE_GOAL:
		case OP_VALIDATE_GOAL:
			return OPF_GOAL_NAME;

		case OP_SHIP_TYPE_DESTROYED:
			if ( argnum == 0 )
				return OPF_POSITIVE;
			else
				return OPF_SHIP_TYPE;

		case OP_KEY_PRESSED:
			if (!argnum)
				return OPF_KEYPRESS;
			else
				return OPF_POSITIVE;

		case OP_KEY_RESET:
		case OP_KEY_RESET_MULTIPLE:
			return OPF_KEYPRESS;

		case OP_EVENT_TRUE:
		case OP_EVENT_FALSE:
			return OPF_EVENT_NAME;

		case OP_EVENT_INCOMPLETE:
		case OP_EVENT_TRUE_DELAY:
		case OP_EVENT_FALSE_DELAY:
		case OP_EVENT_TRUE_MSECS_DELAY:
		case OP_EVENT_FALSE_MSECS_DELAY:
			if (argnum == 0)
				return OPF_EVENT_NAME;
			else if (argnum == 1)
				return OPF_POSITIVE;
			else if (argnum == 2)
				return OPF_BOOL;

		case OP_GOAL_INCOMPLETE:
		case OP_GOAL_TRUE_DELAY:
		case OP_GOAL_FALSE_DELAY:
			if (!argnum)
				return OPF_GOAL_NAME;
			else
				return OPF_POSITIVE;

		case OP_AI_PLAY_DEAD:
		case OP_AI_CHASE_ANY:
			return OPF_POSITIVE;

		case OP_AI_STAY_STILL:
			if (!argnum)
				return OPF_SHIP_POINT;
			else
				return OPF_POSITIVE;

		case OP_AI_FORM_ON_WING:
			return OPF_SHIP;

		case OP_GOOD_REARM_TIME:
			if ( argnum == 0 )
				return OPF_IFF;
			else
				return OPF_POSITIVE;

		case OP_NUM_PLAYERS:
			return OPF_POSITIVE;

		case OP_SKILL_LEVEL_AT_LEAST:
			return OPF_SKILL_LEVEL;

		case OP_GRANT_MEDAL:
		case OP_WAS_MEDAL_GRANTED:
			return OPF_MEDAL_NAME;

		case OP_IS_CARGO_KNOWN:
			return OPF_SHIP;

		case OP_CARGO_KNOWN_DELAY:
			if ( argnum == 0 )
				return OPF_POSITIVE;
			else
				return OPF_SHIP;

		case OP_HAS_BEEN_TAGGED_DELAY:
			if ( argnum == 0 ) {
				return OPF_POSITIVE;
			} else {
				return OPF_SHIP;
			}

		case OP_ARE_SHIP_FLAGS_SET:
			if (argnum == 0) {
				return OPF_SHIP;
			} else {
				return OPF_SHIP_FLAG;
			}

		case OP_CAP_SUBSYS_CARGO_KNOWN_DELAY:
			if ( argnum == 0 ) {
				return OPF_POSITIVE;
			} else if ( argnum == 1 ) {
				return OPF_SHIP;
			} else {
				return OPF_SUBSYSTEM;
			}

		case OP_ALLOW_SHIP:
		case OP_TECH_ADD_SHIP:
			return OPF_SHIP_CLASS_NAME;

		case OP_ALLOW_WEAPON:
		case OP_TECH_ADD_WEAPON:
			return OPF_WEAPON_NAME;

		case OP_TECH_ADD_INTEL:
			return OPF_INTEL_NAME;

		case OP_TECH_ADD_INTEL_XSTR:
			return !(argnum % 2) ? OPF_INTEL_NAME : OPF_NUMBER;

		case OP_TECH_RESET_TO_DEFAULT:
			return OPF_NONE;

		case OP_CHANGE_PLAYER_SCORE:
			if (argnum == 0)
				return OPF_NUMBER;
			else 
				return OPF_SHIP;

		case OP_CHANGE_TEAM_SCORE:
			return OPF_NUMBER;

		case OP_SHIP_VAPORIZE:
		case OP_SHIP_NO_VAPORIZE:
			return OPF_SHIP;

		case OP_DONT_COLLIDE_INVISIBLE:
		case OP_COLLIDE_INVISIBLE:
			return OPF_SHIP;

		case OP_SET_MOBILE:
		case OP_SET_IMMOBILE:
			return OPF_SHIP;

		case OP_IGNORE_KEY:
			if (argnum == 0) 
				return OPF_NUMBER;
			else 
				return OPF_KEYPRESS;


		case OP_WARP_BROKEN:
		case OP_WARP_NOT_BROKEN:
		case OP_WARP_NEVER:
		case OP_WARP_ALLOWED:
			return OPF_SHIP;

		case OP_SET_SUBSPACE_DRIVE:
			if (argnum == 0)
				return OPF_BOOL;
			else
				return OPF_SHIP;

		case OP_FLASH_HUD_GAUGE:
			return OPF_HUD_GAUGE_NAME;

		case OP_GOOD_SECONDARY_TIME:
			if ( argnum == 0 )
				return OPF_IFF;
			else if ( argnum == 1 )
				return OPF_POSITIVE;
			else if ( argnum == 2 )
				return OPF_HUGE_WEAPON;
			else
				return OPF_SHIP;

		case OP_PERCENT_SHIPS_ARRIVED:
		case OP_PERCENT_SHIPS_DEPARTED:
		case OP_PERCENT_SHIPS_DESTROYED:
			if ( argnum == 0 ){
				return OPF_POSITIVE;
			} else {
				return OPF_SHIP_WING;
			}
			break;

		case OP_PERCENT_SHIPS_DISARMED:
		case OP_PERCENT_SHIPS_DISABLED:
			if ( argnum == 0 ){
				return OPF_POSITIVE;
			} else {
				return OPF_SHIP;
			}
			break;

		case OP_DEPART_NODE_DELAY:	
			if ( argnum == 0 ){
				return OPF_POSITIVE;
			} else if ( argnum == 1 ){
				return OPF_JUMP_NODE_NAME;
			} else {
				return OPF_SHIP;
			}

		case OP_DESTROYED_DEPARTED_DELAY:
			if ( argnum == 0 ){
				return OPF_POSITIVE;
			} else {
				return OPF_SHIP_WING;
			}

		case OP_JETTISON_CARGO:
			if(argnum == 1){
				return OPF_POSITIVE;
			} else {
				return OPF_SHIP;
			}

		case OP_SET_DOCKED:
			if (argnum == 0) {
				return OPF_SHIP;
			} else if (argnum == 1) {
				return OPF_DOCKER_POINT;
			} else if (argnum == 2) {
				return OPF_SHIP;
			} else {
				return OPF_DOCKEE_POINT;
			}

		case OP_CARGO_NO_DEPLETE:
			if (argnum == 0) {
				return OPF_SHIP;
			} else {
				return OPF_NUMBER;
			}

		case OP_BEAM_FIRE:
			switch(argnum) {
				case 0:
					return OPF_SHIP;
				case 1:
					return OPF_SUBSYSTEM;
				case 2:
					return OPF_SHIP;
				case 3:
					return OPF_SUBSYSTEM;
				case 4:
					return OPF_BOOL;
			}

		case OP_BEAM_FIRE_COORDS:
			switch(argnum) {
				case 0:
					return OPF_SHIP;
				case 1:
					return OPF_SUBSYSTEM;
				case 5:
					return OPF_BOOL;
				default:
					return OPF_NUMBER;
			}

		case OP_BEAM_FLOATING_FIRE:
			switch(argnum) {
				case 0:
					return OPF_WEAPON_NAME;
				case 1:
				case 6:
					return OPF_SHIP_OR_NONE;
				case 2:
					return OPF_IFF;
				case 7:
					return OPF_SUBSYSTEM_OR_NONE;
				default:
					return OPF_NUMBER;
			}

		case OP_IS_TAGGED:
			return OPF_SHIP;

		case OP_IS_PLAYER:
			if (argnum == 0) {
				return OPF_BOOL;
			} else {
				return OPF_SHIP;
			}

		case OP_NUM_KILLS:
		case OP_NUM_ASSISTS:
		case OP_SHIP_SCORE:
		case OP_SHIP_DEATHS: 
		case OP_RESPAWNS_LEFT:
			return OPF_SHIP;

		case OP_SET_RESPAWNS:
			if (argnum == 0 ) {
				return OPF_POSITIVE;
			}
			else {
				return OPF_SHIP;
			}

		case OP_NUM_TYPE_KILLS:
			if(argnum == 0){
				return OPF_SHIP;
			} else {
				return OPF_SHIP_TYPE;
			}

		case OP_NUM_CLASS_KILLS:
			if(argnum == 0){
				return OPF_SHIP;
			} else {
				return OPF_SHIP_CLASS_NAME;
			}

		case OP_BEAM_FREE:
		case OP_BEAM_LOCK:
		case OP_TURRET_FREE:
		case OP_TURRET_LOCK:
		case OP_TURRET_TAGGED_SPECIFIC:
		case OP_TURRET_TAGGED_CLEAR_SPECIFIC:
			if(argnum == 0){
				return OPF_SHIP;
			} else {
				return OPF_SUBSYSTEM;
			}

		case OP_TURRET_SUBSYS_TARGET_DISABLE:
		case OP_TURRET_SUBSYS_TARGET_ENABLE:
			if(argnum == 0){
				return OPF_SHIP;
			} else {
				return OPF_SUBSYS_OR_GENERIC;
			}
		
		case OP_TURRET_CHANGE_WEAPON:
			if(argnum == 0) {
				return OPF_SHIP;
			} else if(argnum == 1) {
				return OPF_SUBSYSTEM;
			} else if(argnum == 2) {
				return OPF_WEAPON_NAME;
			} else if(argnum > 2) {
				return OPF_POSITIVE;
			}

		case OP_TURRET_SET_DIRECTION_PREFERENCE:
			if(argnum == 0) {
				return OPF_SHIP;
			} else if(argnum == 1) {
				return OPF_NUMBER;
			} else {
				return OPF_SUBSYSTEM;
			}

		case OP_TURRET_SET_RATE_OF_FIRE:
			if(argnum == 0) {
				return OPF_SHIP;
			} else if(argnum == 1) {
				return OPF_NUMBER;
			} else {
				return OPF_SUBSYSTEM;
			}

		case OP_TURRET_SET_OPTIMUM_RANGE:
			if(argnum == 0) {
				return OPF_SHIP;
			} else if(argnum == 1) {
				return OPF_NUMBER;
			} else {
				return OPF_SUBSYSTEM;
			}

		case OP_TURRET_SET_TARGET_PRIORITIES:
			if(argnum == 0) {
				return OPF_SHIP;
			} else if(argnum == 1) {
				return OPF_SUBSYSTEM;
			} else if(argnum == 2) {
				return OPF_BOOL;
			} else {
				return OPF_TARGET_PRIORITIES;
			}

		case OP_SET_ARMOR_TYPE:
			if(argnum == 0) {
				return OPF_SHIP;
			} else if(argnum == 1) {
				return OPF_BOOL;
			} else if(argnum == 2) {
				return OPF_ARMOR_TYPE;
			} else {
				return OPF_SUBSYSTEM;
			}

		case OP_WEAPON_SET_DAMAGE_TYPE:
			if(argnum == 0) {
				return OPF_BOOL;
			} else if(argnum == 1) {
				return OPF_DAMAGE_TYPE;
			} else if(argnum == 2) {
				return OPF_BOOL;
			} else {
				return OPF_WEAPON_NAME;
			}

		case OP_SHIP_SET_DAMAGE_TYPE:
			if(argnum == 0) {
				return OPF_BOOL;
			} else if(argnum == 1) {
				return OPF_DAMAGE_TYPE;
			} else if(argnum == 2) {
				return OPF_BOOL;
			} else {
				return OPF_SHIP;
			}

		case OP_SHIP_SHOCKWAVE_SET_DAMAGE_TYPE:
			if(argnum == 0) {
				return OPF_DAMAGE_TYPE;
			} else if(argnum == 1) {
				return OPF_BOOL;
			} else {
				return OPF_SHIP_CLASS_NAME;
			}

		case OP_FIELD_SET_DAMAGE_TYPE:
			if(argnum == 0) {
				return OPF_DAMAGE_TYPE;
			} else {
				return OPF_BOOL;
			}

		case OP_TURRET_SET_TARGET_ORDER:
			if(argnum == 0) {
				return OPF_SHIP;
			} else if(argnum == 1) {
				return OPF_SUBSYSTEM;
			} else {
				return OPF_TURRET_TARGET_ORDER;
			}

		case OP_SHIP_TURRET_TARGET_ORDER:
			if(argnum == 0) {
				return OPF_SHIP;
			} else {
				return OPF_TURRET_TARGET_ORDER;
			}

		case OP_LOCK_ROTATING_SUBSYSTEM:
		case OP_FREE_ROTATING_SUBSYSTEM:
		case OP_REVERSE_ROTATING_SUBSYSTEM:
			if (argnum == 0)
				return OPF_SHIP;
			else
				return OPF_ROTATING_SUBSYSTEM;

		case OP_ROTATING_SUBSYS_SET_TURN_TIME:
			if (argnum == 0)
				return OPF_SHIP;
			else if (argnum == 1)
				return OPF_ROTATING_SUBSYSTEM;
			else if (argnum == 2)
				return OPF_NUMBER;
			else
				return OPF_POSITIVE;

		case OP_TRIGGER_SUBMODEL_ANIMATION:
			if (argnum == 0)
				return OPF_SHIP;
			else if (argnum == 1)
				return OPF_ANIMATION_TYPE;
			else if (argnum == 2 || argnum == 3)
				return OPF_NUMBER;
			else if (argnum == 4)
				return OPF_BOOL;
			else if (argnum == 5)
				return OPF_SUBSYSTEM;

		case OP_BEAM_FREE_ALL:
		case OP_BEAM_LOCK_ALL:
		case OP_TURRET_FREE_ALL:
		case OP_TURRET_LOCK_ALL:
		case OP_TURRET_TAGGED_ONLY_ALL:
		case OP_TURRET_TAGGED_CLEAR_ALL:
			return OPF_SHIP;

		case OP_ADD_REMOVE_ESCORT:
			if(argnum == 0){
				return OPF_SHIP;
			} else {
				return OPF_NUMBER;
			}

		case OP_AWACS_SET_RADIUS:
			if(argnum == 0){
				return OPF_SHIP;
			} else if(argnum == 1){
				return OPF_AWACS_SUBSYSTEM;
			} else {
				return OPF_NUMBER;
			}

		case OP_PRIMITIVE_SENSORS_SET_RANGE:
			if (!argnum)
				return OPF_SHIP;
			else
				return OPF_NUMBER;

		case OP_CAP_WAYPOINT_SPEED:
			if (argnum == 0) {
				return OPF_SHIP;
			} else {
				return OPF_NUMBER;
			}

		case OP_SUBSYS_SET_RANDOM:
			if (argnum == 0) {
				return OPF_SHIP;
			} else if (argnum == 1 || argnum == 2) {
				return OPF_NUMBER;
			} else {
				return OPF_SUBSYSTEM;
			}

		case OP_SUPERNOVA_START:
			return OPF_POSITIVE;

		case OP_SHIELD_RECHARGE_PCT:
		case OP_WEAPON_RECHARGE_PCT:
		case OP_ENGINE_RECHARGE_PCT:
			return OPF_SHIP;			

		case OP_GET_ETS_VALUE:
			if (argnum == 0) {
				return OPF_STRING;
			} else {
				return OPF_SHIP;
			}

		case OP_SET_ETS_VALUES:
			if (argnum < 3) {
				return OPF_POSITIVE;
			} else {
				return OPF_SHIP;
			}

		case OP_SHIELD_QUAD_LOW:
			if(argnum == 0){
				return OPF_SHIP;
			} else {
				return OPF_NUMBER;
			}

		case OP_PRIMARY_AMMO_PCT:
		case OP_SECONDARY_AMMO_PCT:
			if(argnum == 0){
				return OPF_SHIP;
			} else {
				return OPF_NUMBER;
			}
			
		// Karajorma
		case OP_GET_PRIMARY_AMMO:
		case OP_SET_PRIMARY_AMMO:
		case OP_GET_SECONDARY_AMMO:
		case OP_SET_SECONDARY_AMMO:
			if(argnum == 0){
				return OPF_SHIP;
			} else {
				return OPF_NUMBER;
			}
		
		// Karajorma
		case OP_SET_PRIMARY_WEAPON:
		case OP_SET_SECONDARY_WEAPON:
			if(argnum == 0)
			{
				return OPF_SHIP;
			}
				
			else if (argnum == 2)
			{
				return OPF_WEAPON_NAME;
			}
			else 
			{
				return OPF_NUMBER;
			}

		// DahBlount
		case OP_TURRET_GET_PRIMARY_AMMO:
		case OP_TURRET_GET_SECONDARY_AMMO:
		case OP_TURRET_SET_PRIMARY_AMMO:
		case OP_TURRET_SET_SECONDARY_AMMO:
			if (argnum == 0){
				return OPF_SHIP;
			} else if (argnum == 1){
				return OPF_SUBSYSTEM;
			} else {
				return OPF_NUMBER;
			}

		case OP_GET_NUM_COUNTERMEASURES:
			return OPF_SHIP;

		case OP_SET_NUM_COUNTERMEASURES:
			if (argnum == 0)
				return OPF_SHIP;
			else 
				return OPF_POSITIVE;

		// Karajorma	
		case OP_LOCK_PRIMARY_WEAPON:
		case OP_UNLOCK_PRIMARY_WEAPON:
		case OP_LOCK_SECONDARY_WEAPON:
		case OP_UNLOCK_SECONDARY_WEAPON:
		// KeldorKatarn		
		case OP_LOCK_AFTERBURNER:
		case OP_UNLOCK_AFTERBURNER:
			return OPF_SHIP;

		
		case OP_SET_AFTERBURNER_ENERGY: 
		case OP_SET_WEAPON_ENERGY:
		case OP_SET_SHIELD_ENERGY:
			if (argnum == 0) {
				return OPF_POSITIVE;
			}
			else {
				return OPF_SHIP;
			}

		case OP_SET_AMBIENT_LIGHT:
			return OPF_POSITIVE;
			
		case OP_SET_POST_EFFECT:
			if (argnum == 0)
				return OPF_POST_EFFECT;
			else
				return OPF_POSITIVE;

		case OP_CHANGE_SUBSYSTEM_NAME:
			if (argnum == 0) {
				return OPF_SHIP;
			}
			else if (argnum == 1) {
				return OPF_STRING;
			}
			else {
				return OPF_SUBSYSTEM;
			}
		
		case OP_IS_SECONDARY_SELECTED:
		case OP_IS_PRIMARY_SELECTED:
			if(argnum == 0){
				return OPF_SHIP;
			} else {
				return OPF_NUMBER;
			}

		case OP_DAMAGED_ESCORT_LIST:
			if (argnum < 2)
			{
				return OPF_NUMBER;
			}
			else
			{
				return OPF_SHIP;
			}

		case OP_DAMAGED_ESCORT_LIST_ALL:
			return OPF_POSITIVE;

		case OP_CHANGE_SHIP_CLASS:
			if (!argnum)
				return OPF_SHIP_CLASS_NAME;
			else
				return OPF_SHIP;

		case OP_SHIP_COPY_DAMAGE:
			return OPF_SHIP;

		case OP_DEACTIVATE_GLOW_POINTS:	//-Bobboau
		case OP_ACTIVATE_GLOW_POINTS:	//-Bobboau
		case OP_DEACTIVATE_GLOW_MAPS:	//-Bobboau
		case OP_ACTIVATE_GLOW_MAPS:		//-Bobboau
			return OPF_SHIP;	//a list of ships that are to be activated/deactivated
		case OP_DEACTIVATE_GLOW_POINT_BANK:
		case OP_ACTIVATE_GLOW_POINT_BANK:
			if (!argnum)
				return OPF_SHIP;		//the ship
			else
				return OPF_POSITIVE;		//the glow bank to disable

		// taylor
		case OP_SET_SKYBOX_MODEL:
			if (argnum == 0)
				return OPF_SKYBOX_MODEL_NAME;
			else if (argnum == 1)
				return OPF_BOOL;
			else
				return OPF_SKYBOX_FLAGS;

		case OP_SET_SKYBOX_ORIENT:
			return OPF_NUMBER;

		// Goober5000 - this is complicated :)
		case OP_SET_SUPPORT_SHIP:
			if ((argnum == 0) || (argnum == 2))
				return OPF_DEPARTURE_LOCATION;	// use this for both because we don't want Near Ship or In Front of Ship
			if ((argnum == 1) || (argnum == 3))
				return OPF_SHIP_WITH_BAY;		// same - we don't want to anchor around anything without a docking bay
			if (argnum == 4)
				return OPF_SUPPORT_SHIP_CLASS;
			if (argnum == 5)
				return OPF_NUMBER;
			if (argnum == 6)
				return OPF_NUMBER;
			break;

		// Goober5000
		case OP_SET_ARRIVAL_INFO:
			if (argnum == 0)
				return OPF_SHIP_WING;
			else if (argnum == 1)
				return OPF_ARRIVAL_LOCATION;
			else if (argnum == 2)
				return OPF_ARRIVAL_ANCHOR_ALL;
			else if (argnum == 3)
				return OPF_NUMBER;
			else if (argnum == 4 || argnum == 5)
				return OPF_POSITIVE;
			else if (argnum == 6)
				return OPF_BOOL;
			break;

		// Goober5000
		case OP_SET_DEPARTURE_INFO:
			if (argnum == 0)
				return OPF_SHIP_WING;
			else if (argnum == 1)
				return OPF_DEPARTURE_LOCATION;
			else if (argnum == 2)
				return OPF_SHIP_WITH_BAY;
			else if (argnum == 3 || argnum == 4)
				return OPF_NUMBER;
			else if (argnum == 5)
				return OPF_BOOL;
			break;

		case OP_KAMIKAZE:
			if (argnum==0)
				return OPF_POSITIVE;
			else
				return OPF_SHIP_WING;

		case OP_NUM_SHIPS_IN_BATTLE:	//phreak modified by FUBAR
			return OPF_SHIP_WING_WHOLETEAM;

		case OP_NUM_SHIPS_IN_WING:	// Karajorma	
			return OPF_WING;

		case OP_CURRENT_SPEED:
			return OPF_SHIP_WING;
			
		case OP_PRIMARY_FIRED_SINCE:
		case OP_SECONDARY_FIRED_SINCE:
			if (argnum == 0) 
				return OPF_SHIP;
			else 
				return OPF_POSITIVE;

		case OP_HAS_PRIMARY_WEAPON:
		case OP_HAS_SECONDARY_WEAPON:
			if (argnum == 0)
				return OPF_SHIP;
			else if (argnum == 1) 
				return OPF_WEAPON_BANK_NUMBER;
			else 
				return OPF_WEAPON_NAME;
			
		case OP_DIRECTIVE_VALUE:
			if (argnum == 0)
				return OPF_NUMBER;
			else 
				return OPF_BOOL;			

		case OP_NAV_IS_VISITED:		//Kazan
		case OP_NAV_DISTANCE:		//kazan
		case OP_NAV_DEL:			//kazan
		case OP_NAV_HIDE:			//kazan
		case OP_NAV_RESTRICT:		//kazan
		case OP_NAV_UNHIDE:			//kazan
		case OP_NAV_UNRESTRICT:		//kazan
		case OP_NAV_SET_VISITED:	//kazan
		case OP_NAV_UNSET_VISITED:	//kazan
		case OP_NAV_SELECT:			//Talon1024
			return OPF_STRING;
		
		case OP_NAV_SET_CARRY:		//kazan
		case OP_NAV_UNSET_CARRY:	//kazan
			return OPF_SHIP_WING;

		case OP_NAV_SET_NEEDSLINK: // kazan
		case OP_NAV_UNSET_NEEDSLINK:
		case OP_NAV_ISLINKED:
				return OPF_SHIP;

		case OP_NAV_USECINEMATICS:
		case OP_NAV_USEAP:
			return OPF_BOOL;

		case OP_NAV_ADD_WAYPOINT:	//kazan
			if (argnum==0)
				return OPF_STRING;
			else if (argnum==1)
				return OPF_WAYPOINT_PATH;
			else if (argnum==2)
				return OPF_POSITIVE;
			else 
				return OPF_SHIP_WING_WHOLETEAM;

		case OP_NAV_ADD_SHIP:		//kazan
			if (argnum==0)
				return OPF_STRING;
			else
				return OPF_SHIP;

		//<Cutscenes>
		case OP_SCRAMBLE_MESSAGES:
		case OP_UNSCRAMBLE_MESSAGES:
			return OPF_SHIP;

		case OP_CUTSCENES_GET_FOV:
			return OPF_NONE;

		case OP_CUTSCENES_SET_CUTSCENE_BARS:
		case OP_CUTSCENES_UNSET_CUTSCENE_BARS:
		case OP_CUTSCENES_FADE_IN:
		case OP_CUTSCENES_FADE_OUT:
		case OP_CUTSCENES_SET_TIME_COMPRESSION:
			return OPF_POSITIVE;

		case OP_CUTSCENES_SET_FOV:
			return OPF_NUMBER;

		case OP_CUTSCENES_SET_CAMERA:
			return OPF_STRING;
		
		case OP_CUTSCENES_SET_CAMERA_POSITION:
		case OP_CUTSCENES_SET_CAMERA_FACING:
		case OP_CUTSCENES_SET_CAMERA_ROTATION:
			if(argnum < 3)
				return OPF_NUMBER;
			else
				return OPF_POSITIVE;

		case OP_CUTSCENES_SET_CAMERA_FACING_OBJECT:
			if(argnum < 1)
				return OPF_SHIP_WING_POINT;
			else
				return OPF_POSITIVE;

		case OP_CUTSCENES_SET_CAMERA_FOV:
			return OPF_POSITIVE;
		
		case OP_CUTSCENES_SET_CAMERA_HOST:
		case OP_CUTSCENES_SET_CAMERA_TARGET:
			if(argnum < 1)
				return OPF_SHIP_WING_POINT_OR_NONE;
			else
				return OPF_SUBSYSTEM_OR_NONE;

		case OP_CUTSCENES_RESET_CAMERA:
			return OPF_BOOL;

		case OP_CUTSCENES_RESET_FOV:
		case OP_CUTSCENES_RESET_TIME_COMPRESSION:
			return OPF_NONE;

		case OP_CUTSCENES_FORCE_PERSPECTIVE:
			if(argnum==0)
				return OPF_BOOL;
			else
				return OPF_POSITIVE;

		case OP_SET_CAMERA_SHUDDER:
			return OPF_POSITIVE;

		case OP_CUTSCENES_SHOW_SUBTITLE:
			if(argnum < 2)
				return OPF_NUMBER;
			else if (argnum == 2)
				return OPF_STRING;
			else if (argnum == 3)
				return OPF_POSITIVE;
			else if (argnum == 4)
				return OPF_STRING;
			else if (argnum == 5)
				return OPF_POSITIVE;
			else if (argnum < 8)
				return OPF_BOOL;
			else if (argnum < 12)
				return OPF_POSITIVE;
			else if (argnum == 12 )
				return OPF_BOOL;

		case OP_CUTSCENES_SHOW_SUBTITLE_TEXT:
			if (argnum == 0)
				return OPF_MESSAGE_OR_STRING;
			else if (argnum == 1 || argnum == 2)
				return OPF_NUMBER;
			else if (argnum == 3 || argnum == 4)
				return OPF_BOOL;
			else if (argnum >= 5 && argnum <= 10)
				return OPF_POSITIVE;
			else if (argnum == 11)
				return OPF_FONT;
			else if (argnum == 12)
				return OPF_BOOL;

		case OP_CUTSCENES_SHOW_SUBTITLE_IMAGE:
			if (argnum == 0)
				return OPF_STRING;
			else if (argnum == 1 || argnum == 2)
				return OPF_NUMBER;
			else if (argnum == 3 || argnum == 4)
				return OPF_BOOL;
			else if (argnum >= 5 && argnum <= 8)
				return OPF_POSITIVE;
			else if (argnum == 9)
				return OPF_BOOL;

		//</Cutscenes>

		case OP_JUMP_NODE_SET_JUMPNODE_NAME: //CommanderDJ
			if(argnum==0)
				return OPF_JUMP_NODE_NAME;
			else if (argnum==1)
				return OPF_STRING;

		case OP_JUMP_NODE_SET_JUMPNODE_COLOR:
			if(argnum==0)
				return OPF_JUMP_NODE_NAME;
			else
				return OPF_POSITIVE;

		case OP_JUMP_NODE_SET_JUMPNODE_MODEL:
			if(argnum==0)
				return OPF_JUMP_NODE_NAME;
			else if (argnum == 1)
				return OPF_STRING;
			else
				return OPF_BOOL;

		case OP_JUMP_NODE_SHOW_JUMPNODE:
		case OP_JUMP_NODE_HIDE_JUMPNODE:
				return OPF_JUMP_NODE_NAME;

		case OP_ADD_BACKGROUND_BITMAP:
			if (argnum == 0)
				return OPF_BACKGROUND_BITMAP;
			else if (argnum == 8)
				return OPF_VARIABLE_NAME;
			else
				return OPF_POSITIVE;

		case OP_REMOVE_BACKGROUND_BITMAP:
			return OPF_POSITIVE;

		case OP_ADD_SUN_BITMAP:
			if (argnum == 0)
				return OPF_SUN_BITMAP;
			else if (argnum == 5)
				return OPF_VARIABLE_NAME;
			else
				return OPF_POSITIVE;

		case OP_REMOVE_SUN_BITMAP:
			return OPF_POSITIVE;

		case OP_NEBULA_CHANGE_STORM:
			return OPF_NEBULA_STORM_TYPE;

		case OP_NEBULA_CHANGE_PATTERN:
			return OPF_NEBULA_PATTERN;

		case OP_NEBULA_TOGGLE_POOF:
			if (!argnum)
				return OPF_NEBULA_POOF;
			else
				return OPF_BOOL;

		case OP_SCRIPT_EVAL_NUM:
		case OP_SCRIPT_EVAL_BLOCK:
		case OP_SCRIPT_EVAL:
			return OPF_STRING;

		case OP_SCRIPT_EVAL_STRING:
			if (!argnum)
				return OPF_STRING;
			else
				return OPF_VARIABLE_NAME;

		case OP_SCRIPT_EVAL_MULTI:
			if (argnum == 0) 
				return OPF_STRING;
			else if (argnum == 1) 
				return OPF_BOOL;
			else 
				return OPF_SHIP;

		case OP_CHANGE_IFF_COLOR:
			if ((argnum == 0) || (argnum == 1))
				return OPF_IFF;
			else if ((argnum >= 2) && (argnum <=4))
				return OPF_POSITIVE;
			else return OPF_SHIP_WING;

		case OP_HUD_DISPLAY_GAUGE:
			if ( argnum == 0 ) {
				return OPF_POSITIVE;
			} else {
				return OPF_HUD_ELEMENT;
			}

		case OP_DISABLE_ETS:
		case OP_ENABLE_ETS:
				return OPF_SHIP;

		case OP_IS_FACING:
			if (argnum == 0)
				return OPF_SHIP;
			else if (argnum == 1)
				return OPF_SHIP_POINT;
			else
				return OPF_POSITIVE;

		case OP_FORCE_GLIDE:
			if (argnum == 0)
				return OPF_SHIP;
			else
				return OPF_BOOL;

		case OP_HUD_SET_DIRECTIVE:
			return OPF_STRING;

		case OP_HUD_GAUGE_SET_ACTIVE:
			if (argnum == 0)
				return OPF_STRING;
			else
				return OPF_BOOL;

		case OP_HUD_ACTIVATE_GAUGE_TYPE:
			if (argnum == 0)
				return OPF_HUD_GAUGE;
			else
				return OPF_BOOL;

		case OP_HUD_SET_CUSTOM_GAUGE_ACTIVE:
			if (argnum == 0)
				return OPF_BOOL;
			else
				return OPF_STRING;

		case OP_HUD_SET_RETAIL_GAUGE_ACTIVE:
			if (argnum == 0)
				return OPF_BOOL;
			else
				return OPF_HUD_GAUGE;

		case OP_GET_COLGROUP_ID:
			return OPF_SHIP;

		case OP_ADD_TO_COLGROUP:
			if (argnum == 0)
				return OPF_SHIP;
			else
				return OPF_POSITIVE;

		case OP_REMOVE_FROM_COLGROUP:
			if (argnum == 0)
				return OPF_SHIP;
			else
				return OPF_POSITIVE;

		case OP_SHIP_EFFECT:
			if (argnum == 0)
				return OPF_SHIP_EFFECT;
			else if (argnum == 1)
				return OPF_NUMBER;
			else
				return OPF_SHIP_WING;

		case OP_CLEAR_SUBTITLES:
			return OPF_NONE;

		case OP_SET_THRUSTERS:
			if (argnum == 0)
				return OPF_BOOL;
			else
				return OPF_SHIP;

		case OP_SET_MOTION_DEBRIS:
			return OPF_BOOL;

		default:
			Int3();
	}

	return 0;
}

// DA: 1/7/99  Used to rename ships and waypoints, not variables
// Strictly used in FRED
void update_sexp_references(const char *old_name, const char *new_name)
{
	int i;

	Assert(strlen(new_name) < TOKEN_LENGTH);
	for (i = 0; i < Num_sexp_nodes; i++)
	{
		if ((SEXP_NODE_TYPE(i) == SEXP_ATOM) && (Sexp_nodes[i].subtype == SEXP_ATOM_STRING))
			if (!stricmp(CTEXT(i), old_name))
				strcpy(CTEXT(i), new_name);
	}
}

// DA: 1/7/99  Used to rename event names, goal names, not variables
// Strictly used in FRED
void update_sexp_references(const char *old_name, const char *new_name, int format)
{
	int i;
	if (!strcmp(old_name, new_name)) {
		return;
	}

	Assert(strlen(new_name) < TOKEN_LENGTH);
	for (i = 0; i < Num_sexp_nodes; i++)
	{
		if (is_sexp_top_level(i))
			update_sexp_references(old_name, new_name, format, i);
	}
}

// DA: 1/7/99  Used to rename event names, goal names, not variables
// recursive function to update references to a certain type of data
void update_sexp_references(const char *old_name, const char *new_name, int format, int node)
{
	int i, n, op;

	if (node < 0)
		return;

	if ((SEXP_NODE_TYPE(node) == SEXP_LIST) && (Sexp_nodes[node].subtype == SEXP_ATOM_LIST))
	{
		if (Sexp_nodes[node].first)
			update_sexp_references(old_name, new_name, format, Sexp_nodes[node].first);

		if (Sexp_nodes[node].rest)
			update_sexp_references(old_name, new_name, format, Sexp_nodes[node].rest);

		return;
	}

	if (SEXP_NODE_TYPE(node) != SEXP_ATOM)
		return;

	if (Sexp_nodes[node].subtype != SEXP_ATOM_OPERATOR)
		return;

	op = get_operator_index(CTEXT(node));
	Assert(Sexp_nodes[node].first < 0);
	n = Sexp_nodes[node].rest;
	i = 0;
	while (n >= 0)
	{
		if (SEXP_NODE_TYPE(n) == SEXP_LIST)
		{
			update_sexp_references(old_name, new_name, format, Sexp_nodes[n].first);
		}
		else
		{
			Assert((SEXP_NODE_TYPE(n) == SEXP_ATOM) && ((Sexp_nodes[n].subtype == SEXP_ATOM_NUMBER) || (Sexp_nodes[n].subtype == SEXP_ATOM_STRING)));

			if (query_operator_argument_type(op, i) == format)
			{
				if (!stricmp(CTEXT(n), old_name))
					strcpy(CTEXT(n), new_name);
			}
		}

		n = Sexp_nodes[n].rest;
		i++;
	}
}

int query_referenced_in_sexp(int mode, char *name, int *node)
{
	int i, n, j;

	for (n=0; n<Num_sexp_nodes; n++){
		if ((SEXP_NODE_TYPE(n) == SEXP_ATOM) && (Sexp_nodes[n].subtype == SEXP_ATOM_STRING)){
			if (!stricmp(CTEXT(n), name)){
				break;
			}
		}
	}

	if (n == Num_sexp_nodes){
		return 0;
	}

	if (node){
		*node = n;
	}

	// so we know it's being used somewhere..  Time to find out where..
	for (i=0; i<MAX_SHIPS; i++)
		if (Ships[i].objnum >= 0) {
			if (query_node_in_sexp(n, Ships[i].arrival_cue)){
				return i | SRC_SHIP_ARRIVAL;
			}
			if (query_node_in_sexp(n, Ships[i].departure_cue)){
				return i | SRC_SHIP_DEPARTURE;
			}
		}

	for (i=0; i<MAX_WINGS; i++){
		if (Wings[i].wave_count) {
			if (query_node_in_sexp(n, Wings[i].arrival_cue)){
				return i | SRC_WING_ARRIVAL;
			}
			if (query_node_in_sexp(n, Wings[i].departure_cue)){
				return i | SRC_WING_DEPARTURE;
			}
		}
	}

	for (i=0; i<Num_mission_events; i++){
		if (query_node_in_sexp(n, Mission_events[i].formula)){
			return i | SRC_EVENT;
		}
	}

	for (i=0; i<Num_goals; i++){
		if (query_node_in_sexp(n, Mission_goals[i].formula)){
			return i | SRC_MISSION_GOAL;
		}
	}

	for (j=0; j<Num_teams; j++) {
		for (i=0; i<Debriefings[j].num_stages; i++) {
			if (query_node_in_sexp(n, Debriefings[j].stages[i].formula)){
				return i | SRC_DEBRIEFING;
			}
		}
	}

	for (j=0; j<Num_teams; j++) {
		for (i=0; i<Briefings[j].num_stages; i++) {
			if (query_node_in_sexp(n, Briefings[j].stages[i].formula)){
				return i | SRC_BRIEFING;
			}
		}
	}

	return SRC_UNKNOWN;
}

int verify_vector(char *text)
{
	char *str;
	int len = 0;

	if (text == NULL)
		return -1;

	len = strlen(text);
	if (text[0] != '(' || text[len - 1] != ')'){
		return -1;
	}

	str = &text[0];
	skip_white(&str);
	if (*str != '('){
		return -1;
	}

	str++;
	skip_white(&str);
	if (validate_float(&str)){
		return -1;
	}

	skip_white(&str);
	if (validate_float(&str)){
		return -1;
	}

	skip_white(&str);
	if (validate_float(&str)){
		return -1;
	}

	skip_white(&str);
	if (*str != ')'){
		return -1;
	}

	str++;
	skip_white(&str);
	if (*str){
		return -1;
	}

	return 0;
}

void skip_white(char **str)
{
	if ((**str == ' ') || (**str == '\t')){
		(*str)++;
	}
}

int validate_float(char **str)
{
	int count = 0, dot = 0;

	while (isdigit(**str) || **str == '.') {
		if (**str == '.') {
			if (dot){
				return -1;
			}

			dot = 1;
		}

		(*str)++;
		count++;
	}

	if (!count){
		return -1;
	}

	return 0;
}

/**
 * Check if operator return type opr is a valid match for operator argument type opf
 */
int sexp_query_type_match(int opf, int opr)
{
	switch (opf) {
		case OPF_NUMBER:
			return ((opr == OPR_NUMBER) || (opr == OPR_POSITIVE));

		case OPF_POSITIVE:
			// Goober5000's number hack
			return ((opr == OPR_POSITIVE) || (opr == OPR_NUMBER));

		case OPF_BOOL:
			return (opr == OPR_BOOL);

		case OPF_NULL:
			return (opr == OPR_NULL);

		// Goober5000
		case OPF_FLEXIBLE_ARGUMENT:
			return (opr == OPR_FLEXIBLE_ARGUMENT);

		// Goober5000
		case OPF_ANYTHING:
			// don't match any operators, only data
			return 0;

		case OPF_AI_GOAL:
			return (opr == OPR_AI_GOAL);
	}

	return 0;
}

char *sexp_error_message(int num)
{
	switch (num) {
		case SEXP_CHECK_NONOP_ARGS:
			return "Data shouldn't have arguments";

		case SEXP_CHECK_OP_EXPECTED:
			return "Operator expected instead of data";

		case SEXP_CHECK_UNKNOWN_OP:
			return "Unrecognized operator";

		case SEXP_CHECK_TYPE_MISMATCH:
			return "Argument type mismatch";

		case SEXP_CHECK_BAD_ARG_COUNT:
			return "Argument count is illegal";

		case SEXP_CHECK_UNKNOWN_TYPE:
			return "Unknown operator argument type";

		case SEXP_CHECK_INVALID_NUM:
			return "Not a number";

		case SEXP_CHECK_INVALID_SHIP:
			return "Invalid ship name";

		case SEXP_CHECK_INVALID_WING:
			return "Invalid wing name";

		case SEXP_CHECK_INVALID_SUBSYS:
			return "Invalid subsystem name";

		case SEXP_CHECK_INVALID_SUBSYS_TYPE:
			return "Invalid subsystem type";

		case SEXP_CHECK_INVALID_IFF:
			return "Invalid team name";

		case SEXP_CHECK_INVALID_AI_CLASS:
			return "Invalid AI class name";

		case SEXP_CHECK_INVALID_POINT:
			return "Invalid point";

		case SEXP_CHECK_NEGATIVE_NUM:
			return "Negative number not allowed";

		case SEXP_CHECK_INVALID_SHIP_WING:
			return "Invalid ship/wing name";

		case SEXP_CHECK_INVALID_SHIP_TYPE:
			return "Invalid ship type";

		case SEXP_CHECK_UNKNOWN_MESSAGE:
			return "Invalid message name";

		case SEXP_CHECK_INVALID_PRIORITY:
			return "Invalid priority";

		case SEXP_CHECK_INVALID_MISSION_NAME:
			return "Invalid mission filename";

		case SEXP_CHECK_INVALID_GOAL_NAME:
			return "Invalid goal name";

		case SEXP_CHECK_INVALID_LEVEL:
			return "Mission level too low in tree";

		case SEXP_CHECK_INVALID_MSG_SOURCE:
			return "Invalid message source";

		case SEXP_CHECK_INVALID_DOCKER_POINT:
			return "Invalid docker point";

		case SEXP_CHECK_INVALID_DOCKEE_POINT:
			return "Invalid dockee point";

		case SEXP_CHECK_ORDER_NOT_ALLOWED:
			return "Ship not allowed to have this order";

		case SEXP_CHECK_DOCKING_NOT_ALLOWED:
			return "Ship can't dock with target ship";

		case SEXP_CHECK_NUM_RANGE_INVALID:
			return "Number is out of range";

		case SEXP_CHECK_INVALID_EVENT_NAME:
			return "Event name is invalid (not known)";

		case SEXP_CHECK_INVALID_SKILL_LEVEL:
			return "Skill level name is invalid (not known)";

		case SEXP_CHECK_INVALID_MEDAL_NAME:
			return "Invalid medal name";

		case SEXP_CHECK_INVALID_WEAPON_NAME:
			return "Invalid weapon name";

		case SEXP_CHECK_INVALID_INTEL_NAME:
			return "Invalid intel name";

		case SEXP_CHECK_INVALID_SHIP_CLASS_NAME:
			return "Invalid ship class name";

		case SEXP_CHECK_INVALID_GAUGE_NAME:
			return "Invalid HUD gauges name";

		case SEXP_CHECK_INVALID_JUMP_NODE:
			return "Invalid Jump Node name";

		case SEXP_CHECK_UNKNOWN_ERROR:
			return "Unknown error";

		case SEXP_CHECK_INVALID_SUPPORT_SHIP_CLASS:
			return "Invalid support ship class";

		case SEXP_CHECK_INVALID_SHIP_WITH_BAY:
			return "Ship does not have a fighter bay";

		case SEXP_CHECK_INVALID_ARRIVAL_LOCATION:
			return "Invalid arrival location";

		case SEXP_CHECK_INVALID_DEPARTURE_LOCATION:
			return "Invalid departure location";

		case SEXP_CHECK_INVALID_ARRIVAL_ANCHOR_ALL:
			return "Invalid universal arrival anchor";

		case SEXP_CHECK_INVALID_SOUNDTRACK_NAME:
			return "Invalid soundtrack name";

		case SEXP_CHECK_INVALID_PERSONA_NAME:
			return "Invalid persona name";

		case SEXP_CHECK_INVALID_VARIABLE:
			return "Invalid variable name"; 

		case SEXP_CHECK_INVALID_VARIABLE_TYPE:
			return "Invalid variable type";

		case SEXP_CHECK_INVALID_FONT:
			return "Invalid font";

		case SEXP_CHECK_INVALID_HUD_ELEMENT:
			return "Invalid hud element magic name";

		case SEXP_CHECK_INVALID_SOUND_ENVIRONMENT:
			return "Invalid sound environment";

		case SEXP_CHECK_INVALID_SOUND_ENVIRONMENT_OPTION:
			return "Invalid sound environment option";

		case SEXP_CHECK_INVALID_AUDIO_VOLUME_OPTION:
			return "Invalid audio volume option";

		case SEXP_CHECK_INVALID_EXPLOSION_OPTION:
			return "Invalid explosion option";

		case SEXP_CHECK_INVALID_SHIP_EFFECT:
			return "Invalid ship effect name";

		case SEXP_CHECK_INVALID_TURRET_TARGET_ORDER:
			return "Invalid turret target order";

		case SEXP_CHECK_INVALID_ARMOR_TYPE:
			return "Invalid armor type";

		case SEXP_CHECK_INVALID_DAMAGE_TYPE:
			return "Invalid damage type";

		case SEXP_CHECK_INVALID_HUD_GAUGE:
			return "Invalid hud gauge";

		case SEXP_CHECK_INVALID_TARGET_PRIORITIES:
			return "Invalid target priorities";
			
		case SEXP_CHECK_INVALID_ANIMATION_TYPE:
			return "Invalid animation type";

		case SEXP_CHECK_INVALID_MISSION_MOOD:
			return "Invalid mission mood";

		case SEXP_CHECK_INVALID_SHIP_FLAG:
			return "Invalid ship flag";

		case SEXP_CHECK_INVALID_TEAM_COLOR:
			return "Not a valid Team Color setting";

		case SEXP_CHECK_INVALID_GAME_SND:
			return "Invalid game sound";

		case SEXP_CHECK_INVALID_SSM_CLASS:
			return "Invalid SSM class";

		default:
			Warning(LOCATION, "Unhandled sexp error code %d!", num);
			return "Unhandled sexp error code!";
	}
}

int query_sexp_ai_goal_valid(int sexp_ai_goal, int ship_num)
{
	int i, op;

	for (op=0; op<Num_operators; op++)
		if (Operators[op].value == sexp_ai_goal)
			break;

	Assert(op < Num_operators);
	for (i=0; i<Num_sexp_ai_goal_links; i++)
		if (Sexp_ai_goal_links[i].op_code == sexp_ai_goal)
			break;

	Assert(i < Num_sexp_ai_goal_links);
	return ai_query_goal_valid(ship_num, Sexp_ai_goal_links[i].ai_goal);
}

// Takes an Sexp_node.text pointing to a variable (of form "Sexp_variables[xx]=string" or "Sexp_variables[xx]=number")
// and returns the index into the Sexp_variables array of the actual value 
int extract_sexp_variable_index(int node)
{
	char *text = Sexp_nodes[node].text;
	char char_index[8];
	char *start_index;
	int variable_index;

	// get past the '['
	start_index = text + 15;
	Assert(isdigit(*start_index));

	int len = 0;

	while ( *start_index != ']' ) {
		char_index[len++] = *(start_index++);
		Assert(len < 3);
	}

	Assert(len > 0);
	char_index[len] = 0;	// append null termination to string

	variable_index = atoi(char_index);
	Assert( (variable_index >= 0) && (variable_index < MAX_SEXP_VARIABLES) );

	return variable_index;
}


/**
 * Wrapper around Sexp_node[xx].text for normal and variable
 */
char *CTEXT(int n)
{
	int sexp_variable_index = -1;
	char variable_name[TOKEN_LENGTH];
	char *current_argument; 

	Assertion(n >= 0 && n < Num_sexp_nodes, "Passed an out-of-range node index (%d) to CTEXT!", n);
	if ( n < 0 ) {
		return NULL;
	}

	// Goober5000 - MWAHAHAHAHAHAHAHA!  Thank you, Volition programmers!  Without
	// the CTEXT wrapper, when-argument would probably be infeasibly difficult to code.
	if (!strcmp(Sexp_nodes[n].text, SEXP_ARGUMENT_STRING))
	{
		if (Fred_running)
		{
			// CTEXT is used when writing sexps to savefiles, so don't translate the argument
			return Sexp_nodes[n].text;
		}
		else
		{
			// make sure we have an argument to replace it with
			if (Sexp_replacement_arguments.empty())
				return Sexp_nodes[n].text;
		}

		// if the replacement argument is a variable name, get the variable index
		sexp_variable_index = get_index_sexp_variable_name(Sexp_replacement_arguments.back());

		current_argument = Sexp_replacement_arguments.back();

		// if the replacement argument is a formatted variable name, get the variable index
		if (current_argument[0] == SEXP_VARIABLE_CHAR)
		{
			get_unformatted_sexp_variable_name(variable_name, current_argument);
			sexp_variable_index = get_index_sexp_variable_name(variable_name);
		}

		// if we have a variable, return the variable value, else return the regular argument
		if (sexp_variable_index != -1)
			return Sexp_variables[sexp_variable_index].text;
		else
			return Sexp_replacement_arguments.back();
	}

	// Goober5000 - if not special argument, proceed as normal
	if (Sexp_nodes[n].type & SEXP_FLAG_VARIABLE)
	{
		if (Fred_running)
		{
			sexp_variable_index = get_index_sexp_variable_name(Sexp_nodes[n].text);
			Assert(sexp_variable_index != -1);
		}
		else
		{
			sexp_variable_index = atoi(Sexp_nodes[n].text);
		}
		// Reference a Sexp_variable
		// string format -- "Sexp_variables[xx]=number" or "Sexp_variables[xx]=string", where xx is the index

		Assert( !(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_NOT_USED) );
		Assert(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_SET);

		if (Log_event) {
			Current_event_log_variable_buffer->push_back(Sexp_variables[sexp_variable_index].text); 
			Current_event_log_variable_buffer->push_back(Sexp_variables[sexp_variable_index].variable_name); 
		}

		return Sexp_variables[sexp_variable_index].text;
	}
	else
	{
		return Sexp_nodes[n].text;
	}
}


/**
 * Set all Sexp_variables to type uninitialized
 */
void init_sexp_vars()
{
	for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
		Sexp_variables[i].type = SEXP_VARIABLE_NOT_USED;
		Block_variables[i].type = SEXP_VARIABLE_NOT_USED;
	}
}

/**
 * Add a variable to the block variable array rather than the Sexp_variables array
 */
void add_block_variable(const char *text, const char *var_name, int type, int index)
{
	Assert( (index >= 0) && (index < MAX_SEXP_VARIABLES) );

	strcpy_s(Block_variables[index].text, text);
	strcpy_s(Block_variables[index].variable_name, var_name);
	Block_variables[index].type &= ~SEXP_VARIABLE_NOT_USED;
	Block_variables[index].type = (type | SEXP_VARIABLE_SET);
	
}

/**
 * Add a Sexp_variable to be used in a mission.
 *
 * This should be called from within mission parse.
 */
int sexp_add_variable(const char *text, const char *var_name, int type, int index)
{
	// if index == -1, find next open slot
	if (index == -1) {
		for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
			if (Sexp_variables[i].type == SEXP_VARIABLE_NOT_USED) {
				index = i;
				break;
			}
		}
	} else {
		Assert( (index >= 0) && (index < MAX_SEXP_VARIABLES) );
	}

	if (index >= 0) {
		strcpy_s(Sexp_variables[index].text, text);
		strcpy_s(Sexp_variables[index].variable_name, var_name);
		Sexp_variables[index].type &= ~SEXP_VARIABLE_NOT_USED;
		Sexp_variables[index].type = (type | SEXP_VARIABLE_SET);
	}

	return index;
}

// Goober5000 - minor variant of the above that is now required for variable arrays
void sexp_add_array_block_variable(int index, bool is_numeric)
{
	Assert(index >= 0 && index < MAX_SEXP_VARIABLES);

	strcpy_s(Sexp_variables[index].text, "");
	strcpy_s(Sexp_variables[index].variable_name, "variable array block");

	if (is_numeric)
		Sexp_variables[index].type = SEXP_VARIABLE_NUMBER | SEXP_VARIABLE_SET;
	else
		Sexp_variables[index].type = SEXP_VARIABLE_STRING | SEXP_VARIABLE_SET;
}

/**
 * Modify a Sexp_variable to be used in a mission
 *
 * This should be called in mission when an sexp_variable is to be modified
 */
void sexp_modify_variable(char *text, int index, bool sexp_callback)
{
	Assert(index >= 0 && index < MAX_SEXP_VARIABLES);
	Assert(Sexp_variables[index].type & SEXP_VARIABLE_SET);
	Assert( !MULTIPLAYER_CLIENT );

	if (strchr(text, '$') != NULL)
	{
		// we want to use the same variable substitution that's in messages etc.
		SCP_string temp_text = text;
		sexp_replace_variable_names_with_values(temp_text);

		// copy to original buffer
		int len = temp_text.copy(Sexp_variables[index].text, TOKEN_LENGTH);
		text[len] = 0;
	}
	else
	{
		// no variables, so no substitution
		strcpy_s(Sexp_variables[index].text, text);
	}
	Sexp_variables[index].type |= SEXP_VARIABLE_MODIFIED;

	// do multi_callback_here
	// if we're called from the sexp code send a SEXP packet (more efficient) 
	if( MULTIPLAYER_MASTER && (Sexp_variables[index].type & SEXP_VARIABLE_NETWORK) && sexp_callback) {
		multi_start_callback();
		multi_send_int(index);
		multi_send_string(Sexp_variables[index].text);
		multi_end_callback();
	}
	// otherwise send a SEXP variable packet
	else if ( (Game_mode & GM_MULTIPLAYER) && (Sexp_variables[index].type & SEXP_VARIABLE_NETWORK) ) {
		send_variable_update_packet(index, Sexp_variables[index].text);
	}
}

void multi_sexp_modify_variable()
{
	char value[TOKEN_LENGTH];
	int variable_index = -1;

	// get the data
	multi_get_int(variable_index);
	if (!multi_get_string(value)) {
		return;
	}

	// set the sexp_variable
	if ( (variable_index >= 0) && (variable_index < MAX_SEXP_VARIABLES) ) {
		// maybe create it first
		if (!(Sexp_variables[variable_index].type & SEXP_VARIABLE_SET)) {
			mprintf(("Warning; received multi packet for variable index which is not set!  Assuming this should be an array block variable...\n"));
			sexp_add_array_block_variable(variable_index, can_construe_as_integer(value));
		}

		strcpy_s(Sexp_variables[variable_index].text, value);
	}	
}

void sexp_modify_variable(int n)
{
	int sexp_variable_index;
	int new_number;
	char *new_text;
	char number_as_str[TOKEN_LENGTH];

	Assert(n >= 0);

	// Only do single player or multi host
	if ( MULTIPLAYER_CLIENT )
		return;

	// get sexp_variable index
	Assert(Sexp_nodes[n].first == -1);
	sexp_variable_index = atoi(Sexp_nodes[n].text);

	// verify variable set
	Assert(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_SET);

	if (Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_NUMBER)
	{
		// get new numerical value
		new_number = eval_sexp(CDR(n));
		sprintf(number_as_str, "%d", new_number);

		// assign to variable
		sexp_modify_variable(number_as_str, sexp_variable_index);
	}
	else if (Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_STRING)
	{
		// get new string
		new_text = CTEXT(CDR(n));

		// assign to variable
		sexp_modify_variable(new_text, sexp_variable_index);
	}
	else
	{
		Error(LOCATION, "Invalid variable type.\n");
	}
}

bool is_sexp_node_numeric(int node)
{
	Assert(node >= 0);

	// make the common case fast: if the node has a CAR node, that means it uses an operator;
	// and operators cannot currently return strings
	if (Sexp_nodes[node].first >= 0)
		return true;
	
	// if the node text is numeric, the node is too
	if (can_construe_as_integer(Sexp_nodes[node].text))
		return true;

	// otherwise it's gotta be text
	return false;
}

// By Goober5000. Very similar to sexp_modify_variable(). Even uses the same multi code! :)	
void sexp_set_variable_by_index(int node)
{
	int sexp_variable_index;
	int new_number;
	char *new_text;
	char number_as_str[TOKEN_LENGTH];

	Assert(node >= 0);

	// Only do single player or multi host
	if ( MULTIPLAYER_CLIENT )
		return;

	// get sexp_variable index
	sexp_variable_index = eval_num(node);

	// check range
	if (sexp_variable_index < 0 || sexp_variable_index >= MAX_SEXP_VARIABLES)
	{
		Warning(LOCATION, "set-variable-by-index: sexp variable index %d out of range!  min is 0; max is %d", sexp_variable_index, MAX_SEXP_VARIABLES - 1);
		return;
	}

	// verify variable set
	if (!(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_SET))
	{
		// well phooey.  go ahead and create it
		sexp_add_array_block_variable(sexp_variable_index, is_sexp_node_numeric(CDR(node)));
	}

	if (Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_NUMBER)
	{
		// get new numerical value
		new_number = eval_sexp(CDR(node));
		sprintf(number_as_str, "%d", new_number);

		// assign to variable
		sexp_modify_variable(number_as_str, sexp_variable_index);
	}
	else if (Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_STRING)
	{
		// get new string
		new_text = CTEXT(CDR(node));

		// assign to variable
		sexp_modify_variable(new_text, sexp_variable_index);
	}
	else
	{
		Error(LOCATION, "Invalid variable type.\n");
	}
}

// Goober5000
int sexp_get_variable_by_index(int node)
{
	int sexp_variable_index;

	Assert(node >= 0);

	// get sexp_variable index
	sexp_variable_index = eval_num(node);

	// check range
	if (sexp_variable_index < 0 || sexp_variable_index >= MAX_SEXP_VARIABLES)
	{
		Warning(LOCATION, "get-variable-by-index: sexp variable index %d out of range!  min is 0; max is %d", sexp_variable_index, MAX_SEXP_VARIABLES - 1);
		return 0;
	}

	if (Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_NOT_USED)
	{
		mprintf(("warning: retrieving a value from a sexp variable which is not in use!\n"));
	}
	else if (!(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_SET))
	{
		mprintf(("warning: retrieving a value from a sexp variable which is not set!\n"));
	}

	if (Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_STRING)
	{
		mprintf(("warning: variable %d is a string but it is not possible to return a string value through a sexp!\n", sexp_variable_index));
		return SEXP_NAN_FOREVER;
	}

	return atoi(Sexp_variables[sexp_variable_index].text);
}

// Goober5000
// (yes, this reuses a lot of code, but it's a major pain to consolidate it)
void sexp_copy_variable_from_index(int node)
{
	int from_index;
	int to_index;

	Assert(node >= 0);

	// Only do single player or multi host
	if ( MULTIPLAYER_CLIENT )
		return;

	// get sexp_variable index
	from_index = eval_num(node);

	// check range
	if (from_index < 0 || from_index >= MAX_SEXP_VARIABLES)
	{
		Warning(LOCATION, "copy-variable-from-index: sexp variable index %d out of range!  min is 0; max is %d", from_index, MAX_SEXP_VARIABLES - 1);
		return;
	}

	if (Sexp_variables[from_index].type & SEXP_VARIABLE_NOT_USED)
	{
		mprintf(("warning: retrieving a value from a sexp variable which is not in use!\n"));
	}
	else if (!(Sexp_variables[from_index].type & SEXP_VARIABLE_SET))
	{
		mprintf(("warning: retrieving a value from a sexp variable which is not set!\n"));
	}

	// now get the variable we are modifying
	to_index = atoi(Sexp_nodes[CDR(node)].text);

	// verify variable set
	Assert(Sexp_variables[to_index].type & SEXP_VARIABLE_SET);

	// verify matching types
	if ( ((Sexp_variables[from_index].type & SEXP_VARIABLE_NUMBER) && !(Sexp_variables[to_index].type & SEXP_VARIABLE_NUMBER))
		|| ((Sexp_variables[from_index].type & SEXP_VARIABLE_STRING) && !(Sexp_variables[to_index].type & SEXP_VARIABLE_STRING)) )
	{
		Warning(LOCATION, "copy-variable-from-index: cannot copy variables of different types!  source = '%s', destination = '%s'", Sexp_variables[from_index].variable_name, Sexp_variables[to_index].variable_name);
		return;
	}

	// assign to variable
	sexp_modify_variable(Sexp_variables[from_index].text, to_index);
}

// Goober5000
// (yes, this reuses a lot of code, but it's a major pain to consolidate it)
// (and yes, that reused a comment :p)
void sexp_copy_variable_between_indexes(int node)
{
	int from_index;
	int to_index;

	Assert(node >= 0);

	// Only do single player or multi host
	if ( MULTIPLAYER_CLIENT )
		return;

	// get sexp_variable indexes
	from_index = eval_num(node);
	to_index = eval_num(CDR(node));

	// check ranges
	if (from_index < 0 || from_index >= MAX_SEXP_VARIABLES)
	{
		Warning(LOCATION, "copy-variable-between-indexes: sexp variable index %d out of range!  min is 0; max is %d", from_index, MAX_SEXP_VARIABLES - 1);
		return;
	}
	if (to_index < 0 || to_index >= MAX_SEXP_VARIABLES)
	{
		Warning(LOCATION, "copy-variable-between-indexes: sexp variable index %d out of range!  min is 0; max is %d", to_index, MAX_SEXP_VARIABLES - 1);
		return;
	}

	if (Sexp_variables[from_index].type & SEXP_VARIABLE_NOT_USED)
	{
		mprintf(("warning: retrieving a value from a sexp variable which is not in use!\n"));
	}
	else if (!(Sexp_variables[from_index].type & SEXP_VARIABLE_SET))
	{
		mprintf(("warning: retrieving a value from a sexp variable which is not set!\n"));
	}

	if (!(Sexp_variables[to_index].type & SEXP_VARIABLE_SET))
	{
		// well phooey.  go ahead and create it
		sexp_add_array_block_variable(to_index, (Sexp_variables[from_index].type & SEXP_VARIABLE_NUMBER) != 0);
	}

	// verify matching types
	if ( ((Sexp_variables[from_index].type & SEXP_VARIABLE_NUMBER) && !(Sexp_variables[to_index].type & SEXP_VARIABLE_NUMBER))
		|| ((Sexp_variables[from_index].type & SEXP_VARIABLE_STRING) && !(Sexp_variables[to_index].type & SEXP_VARIABLE_STRING)) )
	{
		Warning(LOCATION, "copy-variable-between-indexes: cannot copy variables of different types!  source = '%s', destination = '%s'", Sexp_variables[from_index].variable_name, Sexp_variables[to_index].variable_name);
		return;
	}

	// assign to variable
	sexp_modify_variable(Sexp_variables[from_index].text, to_index);
}

// Different type needed for Fred (1) allow modification of type (2) no callback required
void sexp_fred_modify_variable(const char *text, const char *var_name, int index, int type)
{
	Assert(index >= 0 && index < MAX_SEXP_VARIABLES);
	Assert(Sexp_variables[index].type & SEXP_VARIABLE_SET);
	Assert( (type & SEXP_VARIABLE_NUMBER) || (type & SEXP_VARIABLE_STRING) );

	strcpy_s(Sexp_variables[index].text, text);
	strcpy_s(Sexp_variables[index].variable_name, var_name);
	Sexp_variables[index].type = (SEXP_VARIABLE_SET | SEXP_VARIABLE_MODIFIED | type);
}

/**
 * Given a sexp node return the index of the variable at that node, -1 if not found
 */
int get_index_sexp_variable_from_node (int node)
{
	int var_index; 

	if (!(Sexp_nodes[node].type & SEXP_FLAG_VARIABLE)) {
		return -1;
	}

	if (Fred_running) {
		var_index = get_index_sexp_variable_name(Sexp_nodes[node].text);
	}
	else {
		var_index = atoi(Sexp_nodes[node].text);
	}

	return var_index; 
}

/**
 * Return index of sexp_variable_name, -1 if not found
 */
int get_index_sexp_variable_name(const char *text)
{
	for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
		if (Sexp_variables[i].type & SEXP_VARIABLE_SET) {
			// check case sensitive
			if ( !strcmp(Sexp_variables[i].variable_name, text) ) {
				return i;
			}
		}
	}

	// not found
	return -1;
}

/**
 * Return index of sexp_variable_name, -1 if not found
 */
int get_index_sexp_variable_name(SCP_string &text)
{
	for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
		if (Sexp_variables[i].type & SEXP_VARIABLE_SET) {
			// check case sensitive
			if ( text == Sexp_variables[i].variable_name ) {
				return i;
			}
		}
	}

	// not found
	return -1;
}

// Goober5000 - tests whether a variable name starts here
// return index of sexp_variable_name, -1 if not found
int get_index_sexp_variable_name_special(const char *startpos)
{
	for (int i = MAX_SEXP_VARIABLES - 1; i >= 0; i--) {
		if (Sexp_variables[i].type & SEXP_VARIABLE_SET) {
			// check case sensitive
			// check number of chars in variable name
			if ( !strncmp(startpos, Sexp_variables[i].variable_name, strlen(Sexp_variables[i].variable_name)) ) {
				return i;
			}
		}
	}

	// not found
	return -1;
}

// Goober5000 - tests whether a variable name starts here
// return index of sexp_variable_name, -1 if not found
int get_index_sexp_variable_name_special(SCP_string &text, size_t startpos)
{
	for (int i = MAX_SEXP_VARIABLES - 1; i >= 0; i--) {
		if (Sexp_variables[i].type & SEXP_VARIABLE_SET) {
			// check case sensitive
			// check that the variable name starts here, as opposed to farther down the string
			size_t pos = text.find(Sexp_variables[i].variable_name, startpos);
			if (pos != SCP_string::npos && pos == startpos) {
				return i;
			}
		}
	}

	// not found
	return -1;
}

// Goober5000
bool sexp_replace_variable_names_with_values(char *text, int max_len)
{
	Assert(text != NULL);
	Assert(max_len >= 0);

	bool replaced_anything = false;
	char *pos = text;
	do {
		// look for the meta-character
		pos = strchr(pos, '$');

		// found?
		if (pos != NULL)
		{
			// see if a variable starts at the next char
			int var_index = get_index_sexp_variable_name_special(pos+1);
			if (var_index >= 0)
			{
				// get the replacement string ($variable)
				char what_to_replace[TOKEN_LENGTH+1];
				memset(what_to_replace, 0, TOKEN_LENGTH+1);
				strncpy(what_to_replace, pos, strlen(Sexp_variables[var_index].variable_name) + 1);

				// replace it
				pos = text + replace_one(text, what_to_replace, Sexp_variables[var_index].text, max_len);
				replaced_anything = true;
			}
			// no match... so keep iterating along the string
			else
			{
				pos++;
			}
		}
	} while (pos != NULL);

	return replaced_anything;
}

// Goober5000
bool sexp_replace_variable_names_with_values(SCP_string &text)
{
	bool replaced_anything = false;

	size_t lookHere = 0;
	size_t foundHere;

	do {
		// look for the meta-character
		foundHere = text.find('$', lookHere);

		// found?
		if (foundHere != SCP_string::npos)
		{
			// see if a variable starts at the next char
			int var_index = get_index_sexp_variable_name_special(text, foundHere+1);
			if (var_index >= 0)
			{
				// replace $variable with the value
				text.replace(foundHere, strlen(Sexp_variables[var_index].variable_name)+1, Sexp_variables[var_index].text);
				replaced_anything = true;

				lookHere = foundHere + strlen(Sexp_variables[var_index].text);
			}
			// no match... so keep iterating along the string
			else
			{
				lookHere = foundHere + 1;
			}
		}
	} while (foundHere != SCP_string::npos);

	return replaced_anything;
}

// returns the index of the nth variable of the type given or -1 if there aren't that many
// NOTE : Not 0th order. If you want the 4th string variable call it as get_nth_variable_index(4, SEXP_VARIABLE_STRING)
int get_nth_variable_index(int nth, int variable_type)
{
	// Loop through Sexp_variables until we have found the one corresponding to the argument
	Assert ((nth > 0) && (nth < MAX_SEXP_VARIABLES));
	for (int i=0; i < MAX_SEXP_VARIABLES; i++)	{
		if ((Sexp_variables[i].type & variable_type)) {
			nth--; 
		}

		if (!nth) {
			return i; 
		}
	}
	return -1;
}

/**
 * Count number of sexp_variables that are set
 */
int sexp_variable_count()
{
	int count = 0;

	for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
		if ( Sexp_variables[i].type & SEXP_VARIABLE_SET) {
			count++;
		}
	}

	return count;
}

/**
 * Count number of campaign-persistent sexp_variables that are set
 */
int sexp_campaign_persistent_variable_count()
{
	int count = 0;

	for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
		if ( (Sexp_variables[i].type & SEXP_VARIABLE_SET) && (Sexp_variables[i].type & SEXP_VARIABLE_CAMPAIGN_PERSISTENT) ) {
			count++;
		}
	}

	return count;
}

/**
 * Given an index in Sexp_variables, returns the number variables of a type in the array until this point
 */
int sexp_variable_typed_count(int sexp_variables_index, int variable_type)
{
	Assert ((sexp_variables_index >= 0) && (sexp_variables_index < MAX_SEXP_VARIABLES));
	// Loop through Sexp_variables until we have found the one corresponding to the argument
	int count = 0;
	for (int i=0; i < MAX_SEXP_VARIABLES; i++)	{
		if (!(Sexp_variables[i].type & variable_type)) {
			continue; 
		}

		if (i == sexp_variables_index) {
			return count ; 
		}
		count++;
	}
	// shouldn't ever get here
	Int3();
	return -1;
}

/**
 * Delete sexp_variable from active
 */
void sexp_variable_delete(int index)
{
	Assert(Sexp_variables[index].type & SEXP_VARIABLE_SET);

	Sexp_variables[index].type = SEXP_VARIABLE_NOT_USED;
}

int sexp_var_compare(const void *var1, const void *var2)
{
	int set1, set2;
	sexp_variable *sexp_var1, *sexp_var2;

	sexp_var1 = (sexp_variable*) var1;
	sexp_var2 = (sexp_variable*) var2;

	set1 = sexp_var1->type & SEXP_VARIABLE_SET;
	set2 = sexp_var2->type & SEXP_VARIABLE_SET;

	if (!set1 && !set2) {
		return 0;
	} else if (set1 && !set2) {
		return -1;
	} else if (!set1 && set2) {
		return 1;
	} else {
		return stricmp( sexp_var1->variable_name, sexp_var2->variable_name);
	}
}

/**
 * Sort sexp_variable list lexigraphically, with set before unset
 */
void sexp_variable_sort()
{
	insertion_sort( (void *)Sexp_variables, (size_t)(MAX_SEXP_VARIABLES), sizeof(sexp_variable), sexp_var_compare );
}

/**
 * Evaluate number which may result from an operator or may be text
 */
int eval_num(int n)
{
	if (n < 0)
	{
		Int3();
		return 0;
	}

	if (CAR(n) != -1)				// if argument is a sexp
		return eval_sexp(CAR(n));
	else
		return atoi(CTEXT(n));		// otherwise, just get the number
}

// Goober5000
int get_sexp_id(char *sexp_name)
{
	for (int i = 0; i < Num_operators; i++)
	{
		if (!stricmp(sexp_name, Operators[i].text))
			return Operators[i].value;
	}
	return -1;
}

// Goober5000
int get_category(int sexp_id)
{
	int category = (sexp_id & OP_CATEGORY_MASK);

	// hack so that CHANGE and CHANGE2 show up in the same menu
	if (category == OP_CATEGORY_CHANGE2)
		category = OP_CATEGORY_CHANGE;

	return category;
}

// Goober5000
int category_of_subcategory(int subcategory_id)
{
	int category = (subcategory_id & OP_CATEGORY_MASK);

	// hack so that CHANGE and CHANGE2 show up in the same menu
	if (category == OP_CATEGORY_CHANGE2)
		category = OP_CATEGORY_CHANGE;

	return category;
}

// Goober5000 - for FRED2 menu subcategories
int get_subcategory(int sexp_id)
{
	switch(sexp_id)
	{
		case OP_SEND_MESSAGE_LIST:
		case OP_SEND_MESSAGE:
		case OP_SEND_RANDOM_MESSAGE:
		case OP_SCRAMBLE_MESSAGES:
		case OP_UNSCRAMBLE_MESSAGES:
		case OP_ENABLE_BUILTIN_MESSAGES:
		case OP_DISABLE_BUILTIN_MESSAGES:
		case OP_SET_DEATH_MESSAGE:
		case OP_SET_PERSONA:
		case OP_SET_MISSION_MOOD:
			return CHANGE_SUBCATEGORY_MESSAGING;

		case OP_ADD_GOAL:
		case OP_REMOVE_GOAL:
		case OP_CLEAR_GOALS:
		case OP_GOOD_REARM_TIME:
		case OP_GOOD_SECONDARY_TIME:
		case OP_CHANGE_AI_CLASS:
		case OP_PLAYER_USE_AI:
		case OP_PLAYER_NOT_USE_AI:
		case OP_SET_PLAYER_ORDERS:
		case OP_CAP_WAYPOINT_SPEED:
			return CHANGE_SUBCATEGORY_AI_CONTROL;

		case OP_ALTER_SHIP_FLAG:
		case OP_PROTECT_SHIP:
		case OP_UNPROTECT_SHIP:
		case OP_BEAM_PROTECT_SHIP:
		case OP_BEAM_UNPROTECT_SHIP:
		case OP_TURRET_PROTECT_SHIP:
		case OP_TURRET_UNPROTECT_SHIP:
		case OP_SHIP_INVISIBLE:
		case OP_SHIP_VISIBLE:
		case OP_SHIP_STEALTHY:
		case OP_SHIP_UNSTEALTHY:
		case OP_FRIENDLY_STEALTH_INVISIBLE:
		case OP_FRIENDLY_STEALTH_VISIBLE:
		case OP_PRIMITIVE_SENSORS_SET_RANGE:
		case OP_SHIP_BOMB_TARGETABLE:
		case OP_SHIP_BOMB_UNTARGETABLE:
		case OP_KAMIKAZE:
		case OP_CHANGE_IFF:
		case OP_CHANGE_IFF_COLOR:
		case OP_ADD_REMOVE_ESCORT:
		case OP_SHIP_CHANGE_ALT_NAME:
		case OP_SHIP_CHANGE_CALLSIGN:
		case OP_SHIP_TAG:
		case OP_SHIP_UNTAG:
		case OP_SET_ARRIVAL_INFO:
		case OP_SET_DEPARTURE_INFO:
			return CHANGE_SUBCATEGORY_SHIP_STATUS;

		case OP_SET_WEAPON_ENERGY:
		case OP_SET_SHIELD_ENERGY:
		case OP_SET_PLAYER_THROTTLE_SPEED:
		case OP_SET_AFTERBURNER_ENERGY:
		case OP_SET_SUBSPACE_DRIVE:
		case OP_SET_SPECIAL_WARPOUT_NAME:
		case OP_SET_PRIMARY_WEAPON:		// Karajorma
		case OP_SET_SECONDARY_WEAPON:	// Karajorma
		case OP_SET_PRIMARY_AMMO:		// Karajorma
		case OP_SET_SECONDARY_AMMO:		// Karajorma
		case OP_SET_NUM_COUNTERMEASURES: // Karajorma
		case OP_LOCK_PRIMARY_WEAPON:
		case OP_UNLOCK_PRIMARY_WEAPON:
		case OP_LOCK_SECONDARY_WEAPON:
		case OP_UNLOCK_SECONDARY_WEAPON:
		case OP_LOCK_AFTERBURNER:	// KeldorKatarn
		case OP_UNLOCK_AFTERBURNER:	// KeldorKatarn
		case OP_SHIELDS_ON:
		case OP_SHIELDS_OFF:
		case OP_FORCE_GLIDE:
		case OP_DISABLE_ETS:
		case OP_ENABLE_ETS:
		case OP_WARP_BROKEN:
		case OP_WARP_NOT_BROKEN:
		case OP_WARP_NEVER:
		case OP_WARP_ALLOWED:
		case OP_SET_ETS_VALUES:
			return CHANGE_SUBCATEGORY_SHIELDS_ENGINES_AND_WEAPONS;

		case OP_SHIP_INVULNERABLE:
		case OP_SHIP_VULNERABLE:
		case OP_SHIP_GUARDIAN:
		case OP_SHIP_NO_GUARDIAN:
		case OP_SHIP_GUARDIAN_THRESHOLD:
		case OP_SHIP_SUBSYS_GUARDIAN_THRESHOLD:
		case OP_SELF_DESTRUCT:
		case OP_DESTROY_INSTANTLY:
		case OP_DESTROY_SUBSYS_INSTANTLY:
		case OP_SABOTAGE_SUBSYSTEM:
		case OP_REPAIR_SUBSYSTEM:
		case OP_SHIP_COPY_DAMAGE:
		case OP_SET_SUBSYSTEM_STRNGTH:
		case OP_SUBSYS_SET_RANDOM:
		case OP_LOCK_ROTATING_SUBSYSTEM:
		case OP_FREE_ROTATING_SUBSYSTEM:
		case OP_REVERSE_ROTATING_SUBSYSTEM:
		case OP_ROTATING_SUBSYS_SET_TURN_TIME:
		case OP_TRIGGER_SUBMODEL_ANIMATION:
		case OP_CHANGE_SUBSYSTEM_NAME:
		case OP_SHIP_SUBSYS_TARGETABLE:
		case OP_SHIP_SUBSYS_UNTARGETABLE:
		case OP_SHIP_SUBSYS_NO_REPLACE:
		case OP_SHIP_SUBSYS_NO_LIVE_DEBRIS:
		case OP_SHIP_SUBSYS_VANISHED:
		case OP_SHIP_SUBSYS_IGNORE_IF_DEAD:
		case OP_AWACS_SET_RADIUS:
			return CHANGE_SUBCATEGORY_SUBSYSTEMS;

		case OP_TRANSFER_CARGO:
		case OP_EXCHANGE_CARGO:
		case OP_SET_CARGO:
		case OP_JETTISON_CARGO:
		case OP_SET_DOCKED:
		case OP_CARGO_NO_DEPLETE:
		case OP_SET_SCANNED:
		case OP_SET_UNSCANNED:
			return CHANGE_SUBCATEGORY_CARGO;

		case OP_SET_ARMOR_TYPE:
		case OP_WEAPON_SET_DAMAGE_TYPE:
		case OP_SHIP_SET_DAMAGE_TYPE:
		case OP_SHIP_SHOCKWAVE_SET_DAMAGE_TYPE:
		case OP_FIELD_SET_DAMAGE_TYPE:
			return CHANGE_SUBCATEGORY_ARMOR_AND_DAMAGE_TYPES;

		case OP_BEAM_FIRE:
		case OP_BEAM_FIRE_COORDS:
		case OP_BEAM_FLOATING_FIRE:
		case OP_BEAM_FREE:
		case OP_BEAM_FREE_ALL:
		case OP_BEAM_LOCK:
		case OP_BEAM_LOCK_ALL:
		case OP_TURRET_FREE:
		case OP_TURRET_FREE_ALL:
		case OP_TURRET_LOCK:
		case OP_TURRET_LOCK_ALL:
		case OP_TURRET_TAGGED_ONLY_ALL:
		case OP_TURRET_TAGGED_CLEAR_ALL:
		case OP_TURRET_TAGGED_SPECIFIC:
		case OP_TURRET_TAGGED_CLEAR_SPECIFIC:
		case OP_TURRET_CHANGE_WEAPON:
		case OP_TURRET_SET_DIRECTION_PREFERENCE:
		case OP_TURRET_SET_RATE_OF_FIRE:
		case OP_TURRET_SET_OPTIMUM_RANGE:
		case OP_TURRET_SET_TARGET_PRIORITIES:
		case OP_TURRET_SET_TARGET_ORDER:
		case OP_SHIP_TURRET_TARGET_ORDER:
		case OP_TURRET_SUBSYS_TARGET_DISABLE:
		case OP_TURRET_SUBSYS_TARGET_ENABLE:
		case OP_TURRET_SET_PRIMARY_AMMO:
		case OP_TURRET_SET_SECONDARY_AMMO:
		case OP_TURRET_GET_PRIMARY_AMMO:
		case OP_TURRET_GET_SECONDARY_AMMO:
			return CHANGE_SUBCATEGORY_BEAMS_AND_TURRETS;

		case OP_CHANGE_SHIP_CLASS:
		case OP_DEACTIVATE_GLOW_MAPS:
		case OP_ACTIVATE_GLOW_MAPS:
		case OP_DEACTIVATE_GLOW_POINTS:
		case OP_ACTIVATE_GLOW_POINTS:
		case OP_DEACTIVATE_GLOW_POINT_BANK:
		case OP_ACTIVATE_GLOW_POINT_BANK:
		case OP_SET_THRUSTERS:
		case OP_DONT_COLLIDE_INVISIBLE:
		case OP_COLLIDE_INVISIBLE:
		case OP_ADD_TO_COLGROUP:
		case OP_REMOVE_FROM_COLGROUP:
		case OP_GET_COLGROUP_ID:
		case OP_CHANGE_TEAM_COLOR:
			return CHANGE_SUBCATEGORY_MODELS_AND_TEXTURES;

		case OP_SET_OBJECT_POSITION:
		case OP_SET_OBJECT_ORIENTATION:
		case OP_SET_OBJECT_FACING:
		case OP_SET_OBJECT_FACING_OBJECT:
		case OP_SET_OBJECT_SPEED_X:
		case OP_SET_OBJECT_SPEED_Y:
		case OP_SET_OBJECT_SPEED_Z:
		case OP_SHIP_MANEUVER:
		case OP_SHIP_ROT_MANEUVER:
		case OP_SHIP_LAT_MANEUVER:
		case OP_SET_MOBILE:
		case OP_SET_IMMOBILE:
			return CHANGE_SUBCATEGORY_COORDINATE_MANIPULATION;

		case OP_INVALIDATE_GOAL:
		case OP_VALIDATE_GOAL:
		case OP_RED_ALERT:
		case OP_END_MISSION:
		case OP_FORCE_JUMP:
		case OP_END_CAMPAIGN:
		case OP_SET_DEBRIEFING_TOGGLED:
		case OP_ALLOW_TREASON:
		case OP_GRANT_PROMOTION:
		case OP_GRANT_MEDAL:
		case OP_ALLOW_SHIP:
		case OP_ALLOW_WEAPON:
		case OP_TECH_ADD_SHIP:
		case OP_TECH_ADD_WEAPON:
		case OP_TECH_ADD_INTEL:
		case OP_TECH_ADD_INTEL_XSTR:
		case OP_TECH_RESET_TO_DEFAULT:
		case OP_CHANGE_PLAYER_SCORE:
		case OP_CHANGE_TEAM_SCORE:
		case OP_SET_RESPAWNS:
			return CHANGE_SUBCATEGORY_MISSION_AND_CAMPAIGN;

		case OP_CHANGE_SOUNDTRACK:
		case OP_PLAY_SOUND_FROM_TABLE:
		case OP_PLAY_SOUND_FROM_FILE:
		case OP_CLOSE_SOUND_FROM_FILE:
		case OP_PAUSE_SOUND_FROM_FILE:
		case OP_SET_SOUND_ENVIRONMENT:
		case OP_UPDATE_SOUND_ENVIRONMENT:
		case OP_ADJUST_AUDIO_VOLUME:
			return CHANGE_SUBCATEGORY_MUSIC_AND_SOUND;

		case OP_HUD_DISABLE:
		case OP_HUD_DISABLE_EXCEPT_MESSAGES:
		case OP_HUD_SET_CUSTOM_GAUGE_ACTIVE:
		case OP_HUD_SET_RETAIL_GAUGE_ACTIVE:
		case OP_HUD_SET_TEXT:
		case OP_HUD_SET_TEXT_NUM:
		case OP_HUD_SET_MESSAGE:
		case OP_HUD_SET_DIRECTIVE:
		case OP_HUD_SET_FRAME:
		case OP_HUD_SET_COLOR:
		case OP_HUD_SET_COORDS:
		case OP_HUD_DISPLAY_GAUGE:
		case OP_HUD_GAUGE_SET_ACTIVE:
		case OP_HUD_ACTIVATE_GAUGE_TYPE:
		case OP_HUD_CLEAR_MESSAGES:
		case OP_HUD_SET_MAX_TARGETING_RANGE:
			return CHANGE_SUBCATEGORY_HUD;

		case OP_NAV_ADD_WAYPOINT:
		case OP_NAV_ADD_SHIP:
		case OP_NAV_DEL:
		case OP_NAV_HIDE:
		case OP_NAV_RESTRICT:
		case OP_NAV_UNHIDE:
		case OP_NAV_UNRESTRICT:
		case OP_NAV_SET_VISITED:
		case OP_NAV_SET_CARRY:
		case OP_NAV_UNSET_CARRY:
		case OP_NAV_UNSET_VISITED:
		case OP_NAV_SET_NEEDSLINK:
		case OP_NAV_UNSET_NEEDSLINK:
		case OP_NAV_USECINEMATICS:
		case OP_NAV_USEAP:
		case OP_NAV_SELECT:
		case OP_NAV_UNSELECT:
			return CHANGE_SUBCATEGORY_NAV;

		case OP_CUTSCENES_SET_CUTSCENE_BARS:
		case OP_CUTSCENES_UNSET_CUTSCENE_BARS:
		case OP_CUTSCENES_FADE_IN:
		case OP_CUTSCENES_FADE_OUT:
		case OP_CUTSCENES_SET_CAMERA:
		case OP_CUTSCENES_SET_CAMERA_POSITION:
		case OP_CUTSCENES_SET_CAMERA_FACING:
		case OP_CUTSCENES_SET_CAMERA_FACING_OBJECT:
		case OP_CUTSCENES_SET_CAMERA_ROTATION:
		case OP_CUTSCENES_SET_CAMERA_HOST:
		case OP_CUTSCENES_SET_CAMERA_TARGET:
		case OP_CUTSCENES_SET_CAMERA_FOV:
		case OP_CUTSCENES_SET_FOV:
		case OP_CUTSCENES_GET_FOV:
		case OP_CUTSCENES_RESET_FOV:
		case OP_CUTSCENES_RESET_CAMERA:
		case OP_CUTSCENES_SHOW_SUBTITLE:
		case OP_CUTSCENES_SHOW_SUBTITLE_TEXT:
		case OP_CUTSCENES_SHOW_SUBTITLE_IMAGE:
		case OP_CLEAR_SUBTITLES:
		case OP_CUTSCENES_FORCE_PERSPECTIVE:
		case OP_SET_CAMERA_SHUDDER:
		case OP_SUPERNOVA_START:
		case OP_SUPERNOVA_STOP:
		case OP_SET_MOTION_DEBRIS:
			return CHANGE_SUBCATEGORY_CUTSCENES;

		case OP_SET_SKYBOX_MODEL:
		case OP_SET_SKYBOX_ORIENT:
		case OP_MISSION_SET_NEBULA:
		case OP_MISSION_SET_SUBSPACE:
		case OP_ADD_BACKGROUND_BITMAP:
		case OP_REMOVE_BACKGROUND_BITMAP:
		case OP_ADD_SUN_BITMAP:
		case OP_REMOVE_SUN_BITMAP:
		case OP_NEBULA_CHANGE_STORM:
		case OP_NEBULA_TOGGLE_POOF:
		case OP_NEBULA_CHANGE_PATTERN:
		case OP_SET_AMBIENT_LIGHT:
			return CHANGE_SUBCATEGORY_BACKGROUND_AND_NEBULA;

		case OP_JUMP_NODE_SET_JUMPNODE_NAME: //CommanderDJ
		case OP_JUMP_NODE_SET_JUMPNODE_COLOR:
		case OP_JUMP_NODE_SET_JUMPNODE_MODEL:
		case OP_JUMP_NODE_SHOW_JUMPNODE:
		case OP_JUMP_NODE_HIDE_JUMPNODE:
			return CHANGE_SUBCATEGORY_JUMP_NODES;

		case OP_SET_POST_EFFECT:
		case OP_SHIP_EFFECT:
		case OP_SHIP_CREATE:
		case OP_WEAPON_CREATE:
		case OP_SHIP_VANISH:
		case OP_SHIP_VAPORIZE:
		case OP_SHIP_NO_VAPORIZE:
		case OP_SET_EXPLOSION_OPTION:
		case OP_EXPLOSION_EFFECT:
		case OP_WARP_EFFECT:
		case OP_REMOVE_WEAPONS:
		case OP_CUTSCENES_SET_TIME_COMPRESSION:
		case OP_CUTSCENES_RESET_TIME_COMPRESSION:
		case OP_CALL_SSM_STRIKE:
			return CHANGE_SUBCATEGORY_SPECIAL_EFFECTS;

		case OP_MODIFY_VARIABLE:
		case OP_GET_VARIABLE_BY_INDEX:
		case OP_SET_VARIABLE_BY_INDEX:
		case OP_COPY_VARIABLE_FROM_INDEX:
		case OP_COPY_VARIABLE_BETWEEN_INDEXES:
		case OP_INT_TO_STRING:
		case OP_STRING_CONCATENATE:
		case OP_STRING_GET_SUBSTRING:
		case OP_STRING_SET_SUBSTRING:
			return CHANGE_SUBCATEGORY_VARIABLES;

		case OP_DAMAGED_ESCORT_LIST:
		case OP_DAMAGED_ESCORT_LIST_ALL:
		case OP_SET_SUPPORT_SHIP:
		case OP_SCRIPT_EVAL_STRING:
		case OP_SCRIPT_EVAL_BLOCK:
		case OP_SCRIPT_EVAL:
		case OP_SCRIPT_EVAL_MULTI:
			return CHANGE_SUBCATEGORY_OTHER;

		case OP_NUM_SHIPS_IN_BATTLE:
		case OP_NUM_SHIPS_IN_WING:
		case OP_DIRECTIVE_VALUE:
			return STATUS_SUBCATEGORY_MISSION;

		case OP_WAS_PROMOTION_GRANTED:
		case OP_WAS_MEDAL_GRANTED:
		case OP_SKILL_LEVEL_AT_LEAST:
		case OP_NUM_KILLS:
		case OP_NUM_ASSISTS:
		case OP_NUM_TYPE_KILLS:
		case OP_NUM_CLASS_KILLS:
		case OP_SHIP_SCORE:
		case OP_LAST_ORDER_TIME:
		case OP_PLAYER_IS_CHEATING_BASTARD:
			return STATUS_SUBCATEGORY_PLAYER;

		case OP_NUM_PLAYERS:
		case OP_TEAM_SCORE:
		case OP_SHIP_DEATHS:
		case OP_RESPAWNS_LEFT:
		case OP_IS_PLAYER:
			return STATUS_SUBCATEGORY_MULTIPLAYER;

		case OP_HAS_BEEN_TAGGED_DELAY:
		case OP_IS_TAGGED:
		case OP_IS_SHIP_VISIBLE:
		case OP_IS_SHIP_STEALTHY:
		case OP_IS_FRIENDLY_STEALTH_VISIBLE:
		case OP_IS_IFF:
		case OP_IS_AI_CLASS:
		case OP_IS_SHIP_CLASS:
		case OP_IS_SHIP_TYPE:
		case OP_CURRENT_SPEED:
		case OP_GET_THROTTLE_SPEED:
		case OP_IS_FACING:
		case OP_IS_IN_MISSION:
		case OP_NAV_ISLINKED:
		case OP_ARE_SHIP_FLAGS_SET:
			return STATUS_SUBCATEGORY_SHIP_STATUS;

		case OP_SHIELD_RECHARGE_PCT:
		case OP_ENGINE_RECHARGE_PCT:
		case OP_WEAPON_RECHARGE_PCT:
		case OP_SHIELD_QUAD_LOW:
		case OP_PRIMARY_AMMO_PCT:
		case OP_SECONDARY_AMMO_PCT:
		case OP_IS_PRIMARY_SELECTED:
		case OP_IS_SECONDARY_SELECTED:
		case OP_GET_PRIMARY_AMMO:
		case OP_GET_SECONDARY_AMMO:
		case OP_GET_NUM_COUNTERMEASURES:
		case OP_AFTERBURNER_LEFT:
		case OP_WEAPON_ENERGY_LEFT:
		case OP_PRIMARY_FIRED_SINCE:
		case OP_SECONDARY_FIRED_SINCE:
		case OP_HAS_PRIMARY_WEAPON:
		case OP_HAS_SECONDARY_WEAPON:
		case OP_GET_ETS_VALUE:
			return STATUS_SUBCATEGORY_SHIELDS_ENGINES_AND_WEAPONS;
			
		case OP_CARGO_KNOWN_DELAY:
		case OP_CAP_SUBSYS_CARGO_KNOWN_DELAY:
		case OP_IS_CARGO:
			return STATUS_SUBCATEGORY_CARGO;
			
		case OP_SHIELDS_LEFT:
		case OP_HITS_LEFT:
		case OP_HITS_LEFT_SUBSYSTEM:
		case OP_HITS_LEFT_SUBSYSTEM_GENERIC:
		case OP_HITS_LEFT_SUBSYSTEM_SPECIFIC:
		case OP_SIM_HITS_LEFT:
		case OP_GET_DAMAGE_CAUSED:
			return STATUS_SUBCATEGORY_DAMAGE;
		
		case OP_DISTANCE:
		case OP_DISTANCE_SUBSYSTEM:
		case OP_NAV_DISTANCE:
		case OP_GET_OBJECT_X:
		case OP_GET_OBJECT_Y:
		case OP_GET_OBJECT_Z:
		case OP_GET_OBJECT_PITCH:
		case OP_GET_OBJECT_BANK:
		case OP_GET_OBJECT_HEADING:
		case OP_GET_OBJECT_SPEED_X:
		case OP_GET_OBJECT_SPEED_Y:
		case OP_GET_OBJECT_SPEED_Z:
		case OP_NUM_WITHIN_BOX:
		case OP_SPECIAL_WARP_DISTANCE:
		case OP_IS_IN_BOX:
			return STATUS_SUBCATEGORY_DISTANCE_AND_COORDINATES;

		case OP_STRING_TO_INT:
		case OP_STRING_GET_LENGTH:
			return STATUS_SUBCATEGORY_VARIABLES;

		case OP_SCRIPT_EVAL_NUM:
			return STATUS_SUBCATEGORY_OTHER;

		default:
			return -1;		// sexp doesn't have a subcategory
	}
}

sexp_help_struct Sexp_help[] = {
	{ OP_PLUS, "Plus (Arithmetic operator)\r\n"
		"\tAdds numbers and returns results.\r\n\r\n"
		"Returns a number.  Takes 2 or more numeric arguments." },

	{ OP_MINUS, "Minus (Arithmetic operator)\r\n"
		"\tSubtracts numbers and returns results.\r\n\r\n"
		"Returns a number.  Takes 2 or more numeric arguments." },

	{ OP_MOD, "Mod (Arithmetic operator)\r\n"
		"\tDivides numbers and returns the remainer.\r\n\r\n"
		"Returns a number.  Takes 2 or more numeric arguments." },

	{ OP_MUL, "Multiply (Arithmetic operator)\r\n"
		"\tMultiplies numbers and returns results.\r\n\r\n"
		"Returns a number.  Takes 2 or more numeric arguments." },

	{ OP_DIV, "Divide (Arithmetic operator)\r\n"
		"\tDivides numbers and returns results.\r\n\r\n"
		"Returns a number.  Takes 2 or more numeric arguments." },

	{ OP_RAND, "Rand (Arithmetic operator)\r\n"
		"\tGets a random number.  This number will not change on successive calls to this sexp.\r\n\r\n"
		"Returns a number.  Takes 2 or 3 numeric arguments...\r\n"
		"\t1:\tLow range of random number.\r\n"
		"\t2:\tHigh range of random number.\r\n" 
		"\t3:\t(optional) A seed to use when generating numbers. (Setting this to 0 is the same as having no seed at all)" },

	// Goober5000
	{ OP_RAND_MULTIPLE, "Rand-multiple (Arithmetic operator)\r\n"
		"\tGets a random number.  This number can and will change between successive calls to this sexp.\r\n\r\n"
		"Returns a number.  Takes 2 or 3 numeric arguments...\r\n"
		"\t1:\tLow range of random number.\r\n"
		"\t2:\tHigh range of random number.\r\n" 
		"\t3:\t(optional) A seed to use when generating numbers. (Setting this to 0 is the same as having no seed at all)" },

	// -------------------------- Nav Points --- Kazan -------------------------- 
	{ OP_NAV_IS_VISITED, "is-nav-visited\r\n"
		"Returns true when the player has visited the given navpoint (Has closed to within 1000m of it). Takes 1 argument...\r\n"
		"\t1:\tThe name of the navpoint" },

	{ OP_NAV_DISTANCE, "distance-to-nav\r\n"
		"Returns the distance from the player ship to that nav point. Takes 1 argument..."
		"\t1:\tThe name of the navpoint" },

	{ OP_NAV_ADD_WAYPOINT, "add-nav-waypoint\r\n"
		"Adds a Navpoint to a navpoint path. Takes 3 or 4 Arguments...\r\n"
		"\t1:\tName of the new navpoint.\r\n"
		"\t2:\tName of the navpoint path the new navpoint should be added to.\r\n"
		"\t3:\tPosition where the new navpoint will be inserted. Note: This is 1-indexed, so the first waypoint in a path has position 1.\r\n"
		"\t4:\t(Optional Argument) Controls the visibility of the new navpoint. Only entities belonging to the chosen category will be able to see it.\r\n" },

	{ OP_NAV_ADD_SHIP, "add-nav-ship\r\n"
		"Binds the named navpoint to the named ship - when the ship moves, the waypoint moves with it. Takes 2 Arguments...\r\n"
		"\t1:\tThe NavPoint's Name\r\n"
		"\t2:\tThe Ship's Name\r\n" },

	{ OP_NAV_DEL, "del-nav\r\n"
		"Deletes a nav point. Takes 1 Argument...\r\n"
		"\t1:\tNavPoint Name" },

	{ OP_NAV_HIDE, "hide-nav\r\n"
		"Hides a nav point. Takes 1 Argument...\r\n"
		"\t1:\tNavPoint Name, it then 'hides' that Nav Point\r\n" },

	{ OP_NAV_RESTRICT, "restrict-nav\r\n"
		"This causes the nav point to be unselectable. Takes 1 Argument...\r\n"
		"\t1:\tThe Navpoint name\r\n" },

	{ OP_NAV_UNHIDE, "unhide-nav\r\n"
		"Restores a hidden navpoint. Takes 1 Argument...\r\n"
		"\t1:\tThe Navpoint Name\r\n" },

	{ OP_NAV_UNRESTRICT, "unrestrict-nav\r\n"
		"Removes restrictions from a Navpoint. Takes 1 Argument...\r\n"	
		"\t1:\tThe Navpoint Name\r\n" },

	{ OP_NAV_SET_VISITED, "set-nav-visited\r\n"
		"Sets the status of the given Navpoint to \"visited\". Takes 1 Argument...\r\n"
		"\t1:\tThe Navpoint Name\r\n" },

	{ OP_NAV_UNSET_VISITED, "unset-nav-visited\r\n"
		"Removes the \"visited\" status from a Navpoint. Takes 1 Argument...\r\n"	
		"\t1:\tThe Navpoint Name\r\n" },

	{ OP_NAV_SET_CARRY, "nav-set-carry\r\n"
		"Sets the Nav Carry flag for all listed ships. Vessels with this flag will follow the player into and out of autopilot.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1:\tShips and Wings that should receive the Nav Carry flag.\r\n" },

	{ OP_NAV_UNSET_CARRY, "unset-nav-carry\r\n"
		"Removes the Nav Carry flag from all listed ships and wings. Takes 1 or more arguments...\r\n"
		"\t1:\tShips and Wings to remove the Nav Carry flag from\r\n" },

	{ OP_NAV_SET_NEEDSLINK, "set-nav-needslink\r\n"
		"Marks all listed ships as needing to link up before entering autopilot.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1:\tShips to mark\r\n" },

	{ OP_NAV_UNSET_NEEDSLINK, "unset-nav-needslink\r\n"
		"Removes the requirement for the listed ships to link up before entering autopilot.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1:\tShips to mark\r\n" },

	{ OP_NAV_ISLINKED, "is-nav-linked\r\n"
		"Determines if a ship is linked for autopilot (\"set-nav-carry\" or \"set-nav-needslink\" + linked)"
		"Takes 1 argument...\r\n"
		"\t1:\tShip to check\r\n"},

	{ OP_NAV_USECINEMATICS, "use-nav-cinematics\r\n"
		"Controls the use of the cinematic autopilot camera. Takes 1 Argument..."
		"\t1:\tSet to true to enable automatic cinematics, set to false to disable automatic cinematics." },

	{ OP_NAV_USEAP, "use-autopilot\r\n"
		"Takes 1 boolean argument.\r\n"
		"\t1:\tSet to true to enable autopilot, set to false to disable autopilot." },

	{ OP_NAV_SELECT, "nav-select (Action operator)\r\n"
		"\tSelects a nav point.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tName of the nav point." },

	{ OP_NAV_UNSELECT, "nav-deselect (Action operator)\r\n"
		"\tDeselects any navpoint selected.\r\n\r\n"
		"Takes no arguments..." },
	
	// -------------------------- -------------------------- -------------------------- 

	// Goober5000
	{ OP_ABS, "Absolute value (Arithmetic operator)\r\n"
		"\tReturns the absolute value of a number.  Takes 1 numeric argument.\r\n" },

	// Goober5000
	{ OP_MIN, "Minimum value (Arithmetic operator)\r\n"
		"\tReturns the minimum of a set of numbers.  Takes 1 or more numeric arguments.\r\n" },

	// Goober5000
	{ OP_MAX, "Maximum value (Arithmetic operator)\r\n"
		"\tReturns the maximum of a set of numbers.  Takes 1 or more numeric arguments.\r\n" },

	// Goober5000
	{ OP_AVG, "Average value (Arithmetic operator)\r\n"
		"\tReturns the average (rounded to the nearest integer) of a set of numbers.  Takes 1 or more numeric arguments.\r\n" },

	// Goober5000
	{ OP_POW, "Power (Arithmetic operator)\r\n"
		"\tRaises one number to the power of the next number.  If the result will be larger than INT_MAX or smaller than INT_MIN, the appropriate limit will be returned.  Takes 2 numeric arguments.\r\n" },

	// Goober5000
	{ OP_SIGNUM, "Signum (Arithmetic operator)\r\n"
		"\tReturns the sign of a number: -1 if it is negative, 0 if it is 0, and 1 if it is positive.  Takes one argument.\r\n" },

	// Goober5000
	{ OP_SET_BIT, "set-bit\r\n"
		"\tTurns on (sets to 1) a certain bit in the provided number, returning the result.  This allows numbers to store up to 32 boolean flags, from 2^0 to 2^31.  Takes 2 numeric arguments...\r\n"
		"\t1: The number whose bit should be set\r\n"
		"\t2: The index of the bit to set.  Valid indexes are between 0 and 31, inclusive.\r\n" },

	// Goober5000
	{ OP_UNSET_BIT, "unset-bit\r\n"
		"\tTurns off (sets to 0) a certain bit in the provided number, returning the result.  This allows numbers to store up to 32 boolean flags, from 2^0 to 2^31.  Takes 2 numeric arguments...\r\n"
		"\t1: The number whose bit should be unset\r\n"
		"\t2: The index of the bit to unset.  Valid indexes are between 0 and 31, inclusive.\r\n" },

	// Goober5000
	{ OP_IS_BIT_SET, "is-bit-set\r\n"
		"\tReturns true if the specified bit is set (equal to 1) in the provided number.  Takes 2 numeric arguments...\r\n"
		"\t1: The number whose bit should be tested\r\n"
		"\t2: The index of the bit to test.  Valid indexes are between 0 and 31, inclusive.\r\n" },

	// Goober5000
	{ OP_BITWISE_AND, "bitwise-and\r\n"
		"\tPerforms the bitwise AND operator on its arguments.  This is the same as if the logical AND operator was performed on each successive bit.  Takes 2 or more numeric arguments.\r\n" },

	// Goober5000
	{ OP_BITWISE_OR, "bitwise-or\r\n"
		"\tPerforms the bitwise OR operator on its arguments.  This is the same as if the logical OR operator was performed on each successive bit.  Takes 2 or more numeric arguments.\r\n" },

	// Goober5000
	{ OP_BITWISE_NOT, "bitwise-not\r\n"
		"\tPerforms the bitwise NOT operator on its argument.  This is the same as if the logical NOT operator was performed on each successive bit.\r\n\r\n"
		"Note that the operation is performed as if on an unsigned integer whose maximum value is INT_MAX.  In other words, there is no need to worry about the sign bit.\r\n\r\n"
		"Takes only 1 argument.\r\n" },

	// Goober5000
	{ OP_BITWISE_XOR, "bitwise-xor\r\n"
		"\tPerforms the bitwise XOR operator on its arguments.  This is the same as if the logical XOR operator was performed on each successive bit.  Takes 2 or more numeric arguments.\r\n" },

	{ OP_SET_OBJECT_SPEED_X, "set-object-speed-x\r\n"
		"\tSets the X speed of a ship or wing."
		"Takes 2 or 3 arguments...\r\n"
		"\t1: The name of the object.\r\n"
		"\t2: The speed to set.\r\n"
		"\t3: Whether the speed on the axis should be set according to the universe grid (when false) or according to the object's facing (when true); You almost always want to set this to true; (optional; defaults to false).\r\n" },

	{ OP_SET_OBJECT_SPEED_Y, "set-object-speed-y\r\n"
		"\tSets the Y speed of a ship or wing."
		"Takes 2 or 3 arguments...\r\n"
		"\t1: The name of the object.\r\n"
		"\t2: The speed to set.\r\n"
		"\t3: Whether the speed on the axis should be set according to the universe grid (when false) or according to the object's facing (when true); You almost always want to set this to true; (optional; defaults to false).\r\n" },

	{ OP_SET_OBJECT_SPEED_Z, "set-object-speed-z\r\n"
		"\tSets the Z speed of a ship or wing."
		"Takes 2 or 3 arguments...\r\n"
		"\t1: The name of the object.\r\n"
		"\t2: The speed to set.\r\n"
		"\t3: Whether the speed on the axis should be set according to the universe grid (when false) or according to the object's facing (when true); You almost always want to set this to true; (optional; defaults to false).\r\n" },

	{ OP_GET_OBJECT_SPEED_X, "get-object-speed-x\r\n"
		"\tReturns the X speed of a ship or wing as an integer."
		"Takes 2 or 3 arguments...\r\n"
		"\t1: The name of the object.\r\n"
		"\t2: Whether the speed on the axis should be set according to the universe grid (when false) or according to the object's facing (when true); You almost always want to set this to true; (optional; defaults to false).\r\n" },

	{ OP_GET_OBJECT_SPEED_Y, "get-object-speed-y\r\n"
		"\tReturns the Y speed of a ship or wing as an integer."
		"Takes 2 or 3 arguments...\r\n"
		"\t1: The name of the object.\r\n"
		"\t2: Whether the speed on the axis should be set according to the universe grid (when false) or according to the object's facing (when true); You almost always want to set this to true; (optional; defaults to false).\r\n" },

	{ OP_GET_OBJECT_SPEED_Z, "get-object-speed-z\r\n"
		"\tReturns the Z speed of a ship or wing as an integer."
		"Takes 2 or 3 arguments...\r\n"
		"\t1: The name of the object.\r\n"
		"\t2: Whether the speed on the axis should be set according to the universe grid (when false) or according to the object's facing (when true); You almost always want to set this to true; (optional; defaults to false).\r\n" },

	// Goober5000
	{ OP_GET_OBJECT_X, "get-object-x\r\n"
		"\tReturns the absolute X coordinate of a set of coordinates relative to a particular object (or object's "
		"subsystem).  The input coordinates are the coordinates relative to the object's position and orientation.  "
		"If no input coordinates are specified, the coordinate returned is the coordinate of the object (or object's "
		"subsystem) itself.  Takes 1 to 5 arguments...\r\n"
		"\t1: The name of a ship, wing, or waypoint.\r\n"
		"\t2: A ship subsystem (or \"" SEXP_NONE_STRING "\" if the first argument is not a ship - optional).\r\n"
		"\t3: The relative X coordinate (optional).\r\n"
		"\t4: The relative Y coordinate (optional).\r\n"
		"\t5: The relative Z coordinate (optional).\r\n" },

	// Goober5000
	{ OP_GET_OBJECT_Y, "get-object-y\r\n"
		"\tReturns the absolute Y coordinate of a set of coordinates relative to a particular object (or object's "
		"subsystem).  The input coordinates are the coordinates relative to the object's position and orientation.  "
		"If no input coordinates are specified, the coordinate returned is the coordinate of the object (or object's "
		"subsystem) itself.  Takes 1 to 5 arguments...\r\n"
		"\t1: The name of a ship, wing, or waypoint.\r\n"
		"\t2: A ship subsystem (or \"" SEXP_NONE_STRING "\" if the first argument is not a ship - optional).\r\n"
		"\t3: The relative X coordinate (optional).\r\n"
		"\t4: The relative Y coordinate (optional).\r\n"
		"\t5: The relative Z coordinate (optional).\r\n" },

	// Goober5000
	{ OP_GET_OBJECT_Z, "get-object-z\r\n"
		"\tReturns the absolute Z coordinate of a set of coordinates relative to a particular object (or object's "
		"subsystem).  The input coordinates are the coordinates relative to the object's position and orientation.  "
		"If no input coordinates are specified, the coordinate returned is the coordinate of the object (or object's "
		"subsystem) itself.  Takes 1 to 5 arguments...\r\n"
		"\t1: The name of a ship, wing, or waypoint.\r\n"
		"\t2: A ship subsystem (or \"" SEXP_NONE_STRING "\" if the first argument is not a ship - optional).\r\n"
		"\t3: The relative X coordinate (optional).\r\n"
		"\t4: The relative Y coordinate (optional).\r\n"
		"\t5: The relative Z coordinate (optional).\r\n" },

	// Goober5000
	{ OP_SET_OBJECT_POSITION, "set-object-position\r\n"
		"\tInstantaneously sets an object's spatial coordinates."
		"Takes 4 arguments...\r\n"
		"\t1: The name of a ship, wing, or waypoint.\r\n"
		"\t2: The new X coordinate.\r\n"
		"\t3: The new Y coordinate.\r\n"
		"\t4: The new Z coordinate." },

	// Goober5000
	{ OP_GET_OBJECT_PITCH, "get-object-pitch\r\n"
		"\tReturns the pitch angle, in degrees, of a particular object.  The returned value will be between 0 and 360.  Takes 1 argument...\r\n"
		"\t1: The name of a ship or wing.\r\n" },

	// Goober5000
	{ OP_GET_OBJECT_BANK, "get-object-bank\r\n"
		"\tReturns the bank angle, in degrees, of a particular object.  The returned value will be between 0 and 360.  Takes 1 argument...\r\n"
		"\t1: The name of a ship or wing.\r\n" },

	// Goober5000
	{ OP_GET_OBJECT_HEADING, "get-object-heading\r\n"
		"\tReturns the heading angle, in degrees, of a particular object.  The returned value will be between 0 and 360.  Takes 1 argument...\r\n"
		"\t1: The name of a ship or wing.\r\n" },

	// Goober5000
	{ OP_SET_OBJECT_ORIENTATION, "set-object-orientation\r\n"
		"\tInstantaneously sets an object's spatial orientation."
		"Takes 4 arguments...\r\n"
		"\t1: The name of a ship or wing.\r\n"
		"\t2: The new pitch angle, in degrees.  The angle can be any number; it does not have to be between 0 and 360.\r\n"
		"\t3: The new bank angle, in degrees.  The angle can be any can be any number; it does not have to be between 0 and 360.\r\n"
		"\t4: The new heading angle, in degrees.  The angle can be any number; it does not have to be between 0 and 360." },

	{ OP_TRUE, "True (Boolean operator)\r\n"
		"\tA true boolean state\r\n\r\n"
		"Returns a boolean value." },

	{ OP_FALSE, "False (Boolean operator)\r\n"
		"\tA false boolean state\r\n\r\n"
		"Returns a boolean value." },

	{ OP_AND, "And (Boolean operator)\r\n"
		"\tAnd is true if all of its arguments are true.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more boolean arguments." },

	{ OP_OR, "Or (Boolean operator)\r\n"
		"\tOr is true if any of its arguments are true.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more boolean arguments." },

	{ OP_XOR, "Xor (Boolean operator)\r\n"
		"\tXor is true if exactly one of its arguments is true.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more boolean arguments." },

	{ OP_EQUALS, "Equals (Boolean operator)\r\n"
		"\tIs true if all of its arguments are equal.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more numeric arguments." },

	{ OP_GREATER_THAN, "Greater Than (Boolean operator)\r\n"
		"\tTrue if the first argument is greater than the subsequent argument(s).\r\n\r\n"
		"Returns a boolean value.  Takes 2 numeric arguments." },

	{ OP_LESS_THAN, "Less Than (Boolean operator)\r\n"
		"\tTrue if the first argument is less than the subsequent argument(s).\r\n\r\n"
		"Returns a boolean value.  Takes 2 numeric arguments." },

	{ OP_NOT_EQUAL, "Not Equal To (Boolean operator)\r\n"
		"\tIs true if the first argument is not equal to any of the subsequent arguments.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more numeric arguments." },

	{ OP_GREATER_OR_EQUAL, "Greater Than Or Equal To (Boolean operator)\r\n"
		"\tTrue if the first argument is greater than or equal to the subsequent argument(s).\r\n\r\n"
		"Returns a boolean value.  Takes 2 numeric arguments." },

	{ OP_LESS_OR_EQUAL, "Less Than Or Equal To (Boolean operator)\r\n"
		"\tTrue if the first argument is less than or equal to the subsequent argument(s).\r\n\r\n"
		"Returns a boolean value.  Takes 2 numeric arguments." },

	// Goober5000
	{ OP_PERFORM_ACTIONS, "perform-actions\r\n"
		"\tThis sexp allows actions to be performed as part of a conditional test.  It is most useful for assigning variables or performing some sort of pre-test action within the conditional part of \"when\", etc.  "
		"It works well as the first branch of an \"and\" sexp, provided it returns true so as to not affect the return value of the \"and\".\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments.\r\n"
		"\t1:\tA boolean value to return after all successive actions have been performed.\r\n"
		"\tRest:\tActions to perform, which would normally appear in a \"when\" sexp.\r\n" },

	// Goober5000
	{ OP_STRING_EQUALS, "String Equals (Boolean operator)\r\n"
		"\tIs true if all of its arguments are equal.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more string arguments." },

	// Goober5000
	{ OP_STRING_GREATER_THAN, "String Greater Than (Boolean operator)\r\n"
		"\tTrue if the first argument is greater than the second argument.\r\n\r\n"
		"Returns a boolean value.  Takes 2 string arguments." },

	// Goober5000
	{ OP_STRING_LESS_THAN, "String Less Than (Boolean operator)\r\n"
		"\tTrue if the first argument is less than the second argument.\r\n\r\n"
		"Returns a boolean value.  Takes 2 string arguments." },

	// Goober5000 - added wing capability
	{ OP_IS_IFF, "Is IFF (Boolean operator)\r\n"
		"\tTrue if ship(s) or wing(s) are all of the specified team.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tTeam (\"friendly\", \"hostile\", \"neutral\", or \"unknown\").\r\n"
		"\tRest:\tName of ship or wing to check." },

	// Goober5000
	{ OP_IS_AI_CLASS, "Is AI Class (Boolean operator)\r\n"
		"\tTrue if ship or ship subsystem(s) is/are all of the specified AI class.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tAI class (\"None\", \"Coward\", \"Lieutenant\", etc.)\r\n"
		"\t2:\tName of ship to check.\r\n"
		"\tRest:\tName of ship subsystem(s) to check (optional)" },

	// Goober5000
	{ OP_IS_SHIP_TYPE, "Is Ship Type (Boolean operator)\r\n"
		"\tTrue if ship or ships is/are all of the specified ship type.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tShip type (\"fighter\", \"bomber\", etc.)\r\n"
		"\t2:\tName of ship to check.\r\n" },

	// Goober5000
	{ OP_IS_SHIP_CLASS, "Is Ship Class (Boolean operator)\r\n"
		"\tTrue if ship or ships is/are all of the specified ship class.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tShip class\r\n"
		"\t2:\tName of ship to check.\r\n" },

	{ OP_HAS_TIME_ELAPSED, "Has time elapsed (Boolean operator)\r\n"
		"\tBecomes true when the specified amount of time has elapsed (Mission time "
		"becomes greater than the specified time).\r\n"
		"Returns a boolean value.  Takes 1 numeric argument...\r\n"
		"\t1:\tThe amount of time in seconds." },

	{ OP_NOT, "Not (Boolean operator)\r\n"
		"\tReturns opposite boolean value of argument (True becomes false, and "
		"false becomes true).\r\n\r\n"
		"Returns a boolean value.  Takes 1 boolean argument." },

	{ OP_PREVIOUS_GOAL_TRUE, "Previous Mission Goal True (Boolean operator)\r\n"
		"\tReturns true if the specified goal in the specified mission is true "
		"(or succeeded).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the mission.\r\n"
		"\t2:\tName of the goal in the mission.\r\n"
		"\t3:\t(Optional) True/False which signifies what this sexpression should return when "
		"this mission is played as a single mission." },

	{ OP_PREVIOUS_GOAL_FALSE, "Previous Mission Goal False (Boolean operator)\r\n"
		"\tReturns true if the specified goal in the specified mission "
		"is false (or failed).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the mission.\r\n"
		"\t2:\tName of the goal in the mission.\r\n"
		"\t3:\t(Optional) True/False which signifies what this sexpression should return when "
		"this mission is played as a single mission." },

	{ OP_PREVIOUS_GOAL_INCOMPLETE, "Previous Mission Goal Incomplete (Boolean operator)\r\n"
		"\tReturns true if the specified goal in the specified mission "
		"is incomplete (not true or false).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the mission.\r\n"
		"\t2:\tName of the goal in the mission.\r\n"
		"\t3:\t(Optional) True/False which signifies what this sexpression should return when "
		"this mission is played as a single mission." },

	{ OP_PREVIOUS_EVENT_TRUE, "Previous Mission Event True (Boolean operator)\r\n"
		"\tReturns true if the specified event in the specified mission is true "
		"(or succeeded).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the mission.\r\n"
		"\t2:\tName of the event in the mission.\r\n"
		"\t3:\t(Optional) True/False which signifies what this sexpression should return when "
		"this mission is played as a single mission." },

	{ OP_PREVIOUS_EVENT_FALSE, "Previous Mission Event False (Boolean operator)\r\n"
		"\tReturns true if the specified event in the specified mission "
		"is false (or failed).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the mission.\r\n"
		"\t2:\tName of the event in the mission.\r\n"
		"\t3:\t(Optional) True/False which signifies what this sexpression should return when "
		"this mission is played as a single mission." },

	{ OP_PREVIOUS_EVENT_INCOMPLETE, "Previous Mission Event Incomplete (Boolean operator)\r\n"
		"\tReturns true if the specified event in the specified mission "
		"is incomplete (not true or false).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the mission.\r\n"
		"\t2:\tName of the event in the mission.\r\n"
		"\t3:\t(Optional) True/False which signifies what this sexpression should return when "
		"this mission is played as a single mission." },

	{ OP_GOAL_TRUE_DELAY, "Mission Goal True (Boolean operator)\r\n"
		"\tReturns true N seconds after the specified goal in the this mission is true "
		"(or succeeded).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the event in the mission.\r\n"
		"\t2:\tNumber of seconds to delay before returning true."},

	{ OP_GOAL_FALSE_DELAY, "Mission Goal False (Boolean operator)\r\n"
		"\tReturns true N seconds after the specified goal in the this mission is false "
		"(or failed).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the event in the mission.\r\n"
		"\t2:\tNumber of seconds to delay before returning true."},

	{ OP_GOAL_INCOMPLETE, "Mission Goal Incomplete (Boolean operator)\r\n"
		"\tReturns true if the specified goal in the this mission is incomplete.  This "
		"sexpression will only be useful in conjunction with another sexpression like"
		"has-time-elapsed.  Used alone, it will return true upon misison startup."
		"Returns a boolean value.  Takes 1 argument...\r\n"
		"\t1:\tName of the event in the mission."},

	{ OP_EVENT_TRUE_DELAY, "Mission Event True (Boolean operator)\r\n"
		"\tReturns true N seconds after the specified event in the this mission is true "
		"(or succeeded).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the event in the mission.\r\n"
		"\t2:\tNumber of seconds to delay before returning true.\r\n"
		"\t3:\t(Optional) Defaults to False. When set to false, directives will only appear as soon as the specified event is true.\r\n"
		"\t\tWhen set to true, the event only affects whether the directive succeeds/fails, and has no effect on when it appears"},

	{ OP_EVENT_FALSE_DELAY, "Mission Event False (Boolean operator)\r\n"
		"\tReturns true N seconds after the specified event in the this mission is false "
		"(or failed).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the event in the mission.\r\n"
		"\t2:\tNumber of seconds to delay before returning true.\r\n"
		"\t3:\t(Optional) Defaults to False. When set to false, directives will only appear as soon as the specified event is true.\r\n"
		"\t\tWhen set to true, the event only affects whether the directive succeeds/fails, and has no effect on when it appears"},

	{ OP_EVENT_TRUE_MSECS_DELAY, "Mission Event True (Boolean operator)\r\n"
		"\tReturns true N milliseconds after the specified event in the this mission is true "
		"(or succeeded).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the event in the mission.\r\n"
		"\t2:\tNumber of milliseconds to delay before returning true.\r\n"
		"\t3:\t(Optional) Defaults to False. When set to false, directives will only appear as soon as the specified event is true.\r\n"
		"\t\tWhen set to true, the event only affects whether the directive succeeds/fails, and has no effect on when it appears"},

	{ OP_EVENT_FALSE_MSECS_DELAY, "Mission Event False (Boolean operator)\r\n"
		"\tReturns true N milliseconds after the specified event in the this mission is false "
		"(or failed).  It returns false otherwise.\r\n\r\n"
		"Returns a boolean value.  Takes 2 required arguments and 1 optional argument...\r\n"
		"\t1:\tName of the event in the mission.\r\n"
		"\t2:\tNumber of milliseconds to delay before returning true.\r\n"
		"\t3:\t(Optional) Defaults to False. When set to false, directives will only appear as soon as the specified event is true.\r\n"
		"\t\tWhen set to true, the event only affects whether the directive succeeds/fails, and has no effect on when it appears"},

	{ OP_EVENT_INCOMPLETE, "Mission Event Incomplete (Boolean operator)\r\n"
		"\tReturns true if the specified event in the this mission is incomplete.  This "
		"sexpression will only be useful in conjunction with another sexpression like"
		"has-time-elapsed.  Used alone, it will return true upon misison startup."
		"Returns a boolean value.  Takes 1 argument...\r\n"
		"\t1:\tName of the event in the mission."},

	{ OP_IS_DESTROYED_DELAY, "Is destroyed delay (Boolean operator)\r\n"
		"\tBecomes true <delay> seconds after all specified ships have been destroyed.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tTime delay in seconds (see above).\r\n"
		"\tRest:\tName of ship (or wing) to check status of." },

	{ OP_WAS_DESTROYED_BY_DELAY, "Was destroyed by delay (Boolean operator)\r\n"
		"\tBecomes true <delay> seconds after all specified ships have been destroyed by the specified first ship.\r\n\r\n"
		"Returns a boolean value.  Takes 3 or more arguments...\r\n"
		"\t1:\tTime delay in seconds (see above).\r\n"
		"\t2:\tShip that should have destroyed the other ships (see below).\r\n"
		"\tRest:\tName of ships to check status of." },

	{ OP_IS_SUBSYSTEM_DESTROYED_DELAY, "Is subsystem destroyed delay (Boolean operator)\r\n"
		"\tBecomes true <delay> seconds after the specified subsystem of the specified "
		"ship is destroyed.\r\n\r\n"
		"Returns a boolean value.  Takes 3 arguments...\r\n"
		"\t1:\tName of ship the subsystem we are checking is on.\r\n"
		"\t2:\tThe name of the subsystem we are checking status of.\r\n"
		"\t3:\tTime delay in seconds (see above)." },

	{ OP_IS_DISABLED_DELAY, "Is disabled delay (Boolean operator)\r\n"
		"\tBecomes true <delay> seconds after the specified ship(s) are disabled.  A "
		"ship is disabled when all of its engine subsystems are destroyed.  All "
		"ships must be diabled for this function to return true.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tTime delay is seconds (see above).\r\n"
		"\tRest:\tNames of ships to check disabled status of." },

	{ OP_IS_DISARMED_DELAY, "Is disarmed delay (Boolean operator)\r\n"
		"\tBecomes true <delay> seconds after the specified ship(s) are disarmed.  A "
		"ship is disarmed when all of its turret subsystems are destroyed.  All "
		"ships must be disarmed for this function to return true.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tTime delay is seconds (see above).\r\n"
		"\tRest:\tNames of ships to check disarmed status of." },

	{ OP_HAS_DOCKED_DELAY, "Has docked delay (Boolean operator)\r\n"
		"\tBecomes true <delay> seconds after the specified ships have docked the "
		"specified number of times.\r\n\r\n"
		"Returns a boolean value.  Takes 4 arguments...\r\n"
		"\t1:\tThe name of the docker ship\r\n"
		"\t2:\tThe name of the dockee ship\r\n"
		"\t3:\tThe number of times they have to have docked\r\n"
		"\t4:\tTime delay in seconds (see above)." },

	{ OP_HAS_UNDOCKED_DELAY, "Has undocked delay (Boolean operator)\r\n"
		"\tBecomes true <delay> seconds after the specified ships have undocked the "
		"specified number of times.\r\n\r\n"
		"Returns a boolean value.  Takes 4 arguments...\r\n"
		"\t1:\tThe name of the docker ship\r\n"
		"\t2:\tThe name of the dockee ship\r\n"
		"\t3:\tThe number of times they have to have undocked\r\n"
		"\t4:\tTime delay in seconds (see above)." },

	{ OP_HAS_ARRIVED_DELAY, "Has arrived delay (Boolean operator)\r\n"
		"\tBecomes true <delay> seconds after the specified ship(s) have arrived into the mission\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tTime delay in seconds (see above).\r\n"
		"\tRest:\tName of ship (or wing) we want to check has arrived." },

	{ OP_HAS_DEPARTED_DELAY, "Has departed delay (Boolean operator)\r\n"
		"\tBecomes true <delay> seconds after the specified ship(s) or wing(s) have departed "
		"from the mission by warping out.  If any ship was destroyed, this operator will "
		"never be true.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tTime delay in seconds (see above).\r\n"
		"\tRest:\tName of ship (or wing) we want to check has departed." },

	{ OP_WAYPOINTS_DONE_DELAY, "Waypoints done delay (Boolean operator)\r\n"
		"\tBecomes true <delay> seconds after the specified ship has completed flying the "
		"specified waypoint path.\r\n\r\n"
		"Returns a boolean value.  Takes 3 or 4 arguments...\r\n"
		"\t1:\tName of ship we are checking.\r\n"
		"\t2:\tWaypoint path we want to check if ship has flown.\r\n"
		"\t3:\tTime delay in seconds (see above).\r\n"
		"\t4:\tHow many times the ship has completed the waypoint path (optional)." },

	{ OP_SHIP_TYPE_DESTROYED, "Ship Type Destroyed (Boolean operator)\r\n"
		"\tBecomes true when the specified percentage of ship types in this mission "
		"have been destroyed.  The ship type is a generic type such as fighter/bomber, "
		"transport, etc.  Fighters and bombers count as the same type.\r\n\r\n"
		"Returns a boolean value.  Takes 2 arguments...\r\n"
		"\t1:\tPercentage of ships that must be destroyed.\r\n"
		"\t2:\tShip type to check for." },

	{ OP_TIME_SHIP_DESTROYED, "Time ship destroyed (Time operator)\r\n"
		"\tReturns the time the specified ship was destroy.\r\n\r\n"
		"Returns a numeric value.  Takes 1 argument...\r\n"
		"\t1:\tName of ship we want to check." },

	{ OP_TIME_SHIP_ARRIVED, "Time ship arrived (Time operator)\r\n"
		"\tReturns the time the specified ship arrived into the mission.\r\n\r\n"
		"Returns a numeric value.  Takes 1 argument...\r\n"
		"\t1:\tName of ship we want to check." },

	{ OP_TIME_SHIP_DEPARTED, "Time ship departed (Time operator)\r\n"
		"\tReturns the time the specified ship departed the mission by warping out.  Being "
		"destroyed doesn't count departed.\r\n\r\n"
		"Returns a numeric value.  Takes 1 argument...\r\n"
		"\t1:\tName of ship we want to check." },

	{ OP_TIME_WING_DESTROYED, "Time wing destroyed (Time operator)\r\n"
		"\tReturns the time the specified wing was destroy.\r\n\r\n"
		"Returns a numeric value.  Takes 1 argument...\r\n"
		"\t1:\tName of wing we want to check." },

	{ OP_TIME_WING_ARRIVED, "Time wing arrived (Time operator)\r\n"
		"\tReturns the time the specified wing arrived into the mission.\r\n\r\n"
		"Returns a numeric value.  Takes 1 argument...\r\n"
		"\t1:\tName of wing we want to check." },

	{ OP_TIME_WING_DEPARTED, "Time wing departed (Time operator)\r\n"
		"\tReturns the time the specified wing departed the mission by warping out.  All "
		"ships in the wing have to have warped out.  If any are destroyed, the wing can "
		"never be considered departed.\r\n\r\n"
		"Returns a numeric value.  Takes 1 argument...\r\n"
		"\t1:\tName of ship we want to check." },

	{ OP_MISSION_TIME, "Mission time (Time operator)\r\n"
		"\tReturns the current time into the mission.\r\n\r\n"
		"Returns a numeric value.  Takes no arguments." },

	{ OP_MISSION_TIME_MSECS, "Mission time, in milliseconds (Time operator)\r\n"
		"\tReturns the current time into the mission, in milliseconds.  Useful for more fine-grained timing than possible with normal second-based sexps.  (Tip: when an event occurs, assign the result of mission-time-msecs to a variable.  Then, in another event, wait until mission-time-msecs is greater than the value of that variable plus some delay amount.  This second event should be chained or coupled with additional conditions so that it doesn't accidentally fire on an uninitialized variable!)\r\n\r\n"
		"Returns a numeric value.  Takes no arguments." },

	{ OP_TIME_DOCKED, "Time docked (Time operator)\r\n"
		"\tReturns the time the specified ships docked.\r\n\r\n"
		"Returns a numeric value.  Takes 3 arguments...\r\n"
		"\t1:\tThe name of the docker ship.\r\n"
		"\t2:\tThe name of the dockee ship.\r\n"
		"\t3:\tThe number of times they must have docked to be true." },

	{ OP_TIME_UNDOCKED, "Time undocked (Time operator)\r\n"
		"\tReturns the time the specified ships undocked.\r\n\r\n"
		"Returns a numeric value.  Takes 3 arguments...\r\n"
		"\t1:\tThe name of the docker ship.\r\n"
		"\t2:\tThe name of the dockee ship.\r\n"
		"\t3:\tThe number of times they must have undocked to be true." },

	{ OP_AFTERBURNER_LEFT, "Afterburner left\r\n"
		"\tReturns a ship's current engine energy as a percentage.\r\n"
		"\t1: Ship name\r\n" },

	{ OP_WEAPON_ENERGY_LEFT, "Weapon energy left\r\n"
		"\tReturns a ship's current weapon energy as a percentage.\r\n"
		"\t1: Ship name\r\n" },

	{ OP_SHIELDS_LEFT, "Shields left (Status operator)\r\n"
		"\tReturns the current level of the specified ship's shields as a percentage.\r\n\r\n"
		"Returns a numeric value.  Takes 1 argument...\r\n"
		"\t1:\tName of ship to check." },

	{ OP_HITS_LEFT, "Hits left (Status operator)\r\n"
		"\tReturns the current level of the specified ship's hull as a percentage.\r\n\r\n"
		"Returns a numeric value.  Takes 1 argument...\r\n"
		"\t1:\tName of ship to check." },

	{ OP_HITS_LEFT_SUBSYSTEM, "Hits left subsystem (status operator, deprecated)\r\n"
		"\tReturns the current level of the specified ship's subsystem integrity as a percentage of the damage done to *all "
		"subsystems of the same type*.  This operator provides the same functionality as the new hits-left-subsystem-generic "
		"operator, except that it gets the subsystem type in a very misleading way.  Common consensus among SCP programmers is "
		"that this operator was intended to behave like hits-left-subsystem-specific but was programmed incorrectly.  As such, "
		"this operator is deprecated.  Mission designers are strongly encouraged to use hits-left-subsystem-specific rather than "
		"the optional boolean parameter.\r\n\r\n"
		"Returns a numeric value.  Takes 2 or 3 arguments...\r\n"
		"\t1:\tName of ship to check.\r\n"
		"\t2:\tName of subsystem on ship to check.\r\n"
		"\t3:\t(Optional) True/False. When set to true only the subsystem supplied will be tested; when set to false (the default), "
		"all subsystems of that type will be tested." },

	{ OP_HITS_LEFT_SUBSYSTEM_GENERIC, "hits-left-subsystem-generic (status operator)\r\n"
		"\tReturns the current level of integrity of a generic subsystem type, as a percentage.  A \"generic subsystem type\" "
		"is a subsystem *category*, (for example, Engines), that includes one or more *individual* subsystems (for example, engine01, "
		"engine02, and engine03) on a ship.\r\n\r\nThis is the way FreeSpace tests certain subsystem thresholds internally; for "
		"example, if the integrity of all engine subsystems (that is, the combined strength of all engines divided by the maximum "
		"total strength of all engines) is less than 30%, the player cannot warp out.\r\n\r\n"
		"Returns a numeric value.  Takes 2 arguments...\r\n"
		"\t1:\tName of ship to check\r\n"
		"\t2:\tName of subsystem type to check\r\n" },

	{ OP_HITS_LEFT_SUBSYSTEM_SPECIFIC, "hits-left-subsystem-specific (status operator)\r\n"
		"\tReturns the current level of integrity of a specific subsystem, as a percentage.\r\n\r\n(If you were looking for the old "
		"hits-left-subsystem operator, this is almost certainly the operator you want.  The hits-left-subsystem operator "
		"suffers from a serious design flaw that causes it to behave like hits-left-subsystem-generic.  As such it has been deprecated "
		"and will not appear in the operator list; it can only be used if you type it in manually.  Old missions using hits-left-subsystem "
		"will still work, but mission designers are strongly encouraged to use the new operators instead.)\r\n\r\n"
		"Returns a numeric value.  Takes 2 arguments...\r\n"
		"\t1:\tName of ship to check\r\n"
		"\t2:\tName of subsystem to check\r\n" },

	{ OP_SIM_HITS_LEFT, "Simulated Hits left (Status operator)\r\n"
		"\tReturns the current level of the specified ship's simulated hull as a percentage.\r\n\r\n"
		"Returns a numeric value.  Takes 1 argument...\r\n"
		"\t1:\tName of ship to check." },

	{ OP_DISTANCE, "Distance (Status operator)\r\n"
		"\tReturns the distance between two objects.  These objects can be either a ship, "
		"a wing, or a waypoint.\r\n"
		"When a wing or team is given (for either argument) the answer will be the shortest distance. \r\n\r\n"
		"Returns a numeric value.  Takes 2 arguments...\r\n"
		"\t1:\tThe name of one of the objects.\r\n"
		"\t2:\tThe name of the other object." },

	{ OP_DISTANCE_SUBSYSTEM, "Distance from ship subsystem (Status operator)\r\n"
		"\tReturns the distance between an object and a ship subsystem.  The object can be either a ship, "
		"a wing, or a waypoint.\r\n\r\n"
		"Returns a numeric value.  Takes 3 arguments...\r\n"
		"\t1:\tThe name of the object.\r\n"
		"\t2:\tThe name of the ship which houses the subsystem.\r\n"
		"\t3:\tThe name of the subsystem." },

	{ OP_NUM_WITHIN_BOX, "Number of specified objects in the box specified\r\n"
		"\t1: Box center (X)\r\n"
		"\t2: Box center (Y)\r\n"
		"\t3: Box center (Z)\r\n"
		"\t4: Box width\r\n"
		"\t5: Box height\r\n"
		"\t6: Box depth\r\n"
		"\tRest:\tShips or wings to check" },

	{ OP_IS_IN_BOX, "Whether an object is in the box specified. If a second ship is specified, "
		"the box is relative to that ship's reference frame. \r\n"
		"\t1: Ships, wings, or points to check\r\n"
		"\t2: Min X\r\n"
		"\t3: Max X\r\n"
		"\t4: Min Y\r\n"
		"\t5: Max Y\r\n"
		"\t6: Min Z\r\n"
		"\t7: Max Z\r\n"
		"\t8: Ship to use as reference frame (optional)." },

	{ OP_IS_IN_MISSION, "Checks whether a given ship is presently in the mission.  This sexp doesn't check the arrival list or exited status; it only tests to see if the "
		"ship is active.  This means that internally the sexp only returns SEXP_TRUE or SEXP_FALSE and does not use any of the special shortcut values.  This is useful "
		"for ships created with ship-create, as those ships will not have used the conventional ship arrival list.\r\n\r\n"
		"Takes 1 or more string arguments, which are checked against the ship list." },

	{ OP_GET_DAMAGE_CAUSED, "Get damage caused (Status operator)\r\n"
		"\tReturns the amount of damage one or more ships have done to a ship.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tShip that has been damaged.\r\n"
		"\t2:\tName of ships that may have damaged it." },

	{ OP_LAST_ORDER_TIME, "Last order time (Status operator)\r\n"
		"\tReturns true if <count> seconds have elapsed since one or more ships have received "
		"a meaningful order from the player.  A meaningful order is currently any order that "
		"is not the warp out order.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tTime in seconds that must elapse.\r\n"
		"\tRest:\tName of ship or wing to check for having received orders." },

	{ OP_WHEN, "When (Conditional operator)\r\n"
		"\tPerforms specified actions when a condition becomes true\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tBoolean expression that must be true for actions to take place.\r\n"
		"\tRest:\tActions to take when boolean expression becomes true." },

	{ OP_COND, "Blah" },

	// Goober5000
	{ OP_WHEN_ARGUMENT, "When-argument (Conditional operator)\r\n"
		"\tPerforms specified actions when a condition, given a set of arguments, becomes true.\r\n\r\n"
		"Takes 3 or more arguments...\r\n"
		"\t1:\tThe arguments to evaluate (see any-of, every-of, random-of, etc.).\r\n"
		"\t2:\tBoolean expression that must be true for actions to take place.\r\n"
		"\tRest:\tActions to take when the boolean expression becomes true." },

	// Goober5000
	{ OP_EVERY_TIME, "Every-time (Conditional operator)\r\n"
		"\tThis is a version of \"when\" that will always evaluate its arguments.  It's useful "
		"in situations where you need to repeatedly check things that may become true more than "
		"once.  Since this sexp will execute every time it's evaluated, you may need to use it as "
		"an argument to \"when\" if you want to impose restrictions on how it's called.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tBoolean expression that must be true for actions to take place.\r\n"
		"\tRest:\tActions to take when boolean expression is true." },

	// Goober5000
	{ OP_EVERY_TIME_ARGUMENT, "Every-time-argument (Conditional operator)\r\n"
		"\tThis is a version of \"when-argument\" that will always evaluate its arguments.  It's useful "
		"in situations where you need to repeatedly check things that may become true more than "
		"once.  Since this sexp will execute every time it's evaluated, you may need to use it as "
		"an argument to \"when\" (not \"when-argument\") if you want to impose restrictions on how it's called.\r\n\r\n"
		"Takes 3 or more arguments...\r\n"
		"\t1:\tThe arguments to evaluate (see any-of, all-of, random-of, etc.).\r\n"
		"\t2:\tBoolean expression that must be true for actions to take place.\r\n"
		"\tRest:\tActions to take when the boolean expression becomes true." },

	// Goober5000
	{ OP_IF_THEN_ELSE, "If-then-else (Conditional operator)\r\n"
		"\tPerforms one action if a condition is true (like \"when\"), or another action (or set of actions) if the condition is false.  "
		"Note that this sexp only completes one of its branches once the condition has been determined; "
		"it does not come back later and evaluate the other branch if the condition happens to switch truth values.\r\n\r\n"
		"Takes 3 or more arguments...\r\n"
		"\t1:\tBoolean expression to evaluate.\r\n"
		"\t2:\tActions to take if that expression becomes true.\r\n"
		"\tRest:\tActions to take if that expression becomes false.\r\n" },

	// Karajorma
	{ OP_DO_FOR_VALID_ARGUMENTS, "Do-for-valid-arguments (Conditional operator)\r\n"
		"\tPerforms specified actions once for each valid " SEXP_ARGUMENT_STRING " in the parent conditional.\r\n"
		"\tMust not be used for any SEXP that actually contains " SEXP_ARGUMENT_STRING " as these are already being executed\r\n"
		"\tmultiple times without using Do-for-valid-arguments. Any use of "  SEXP_ARGUMENT_STRING " and will \r\n" 
		"\tprevent execution of the entire SEXP unless it is nested inside another when(or every-time)-argument SEXP.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tActions to take." },

	// Karajorma
	{ OP_NUM_VALID_ARGUMENTS, "num-valid-arguments (Conditional operator)\r\n"
		"\tReturns the number of valid arguments in the argument list.\r\n\r\n"
		"Takes no arguments...\r\n"},

	// Goober5000
	{ OP_ANY_OF, "Any-of (Conditional operator)\r\n"
		"\tSupplies arguments for the " SEXP_ARGUMENT_STRING " special data item.  Any of the supplied arguments can satisfy the expression(s) "
		"in which " SEXP_ARGUMENT_STRING " is used.\r\n\r\n"
		"In practice, this will behave like a standard \"for-each\" statement, evaluating the action operators for each argument that satisfies the condition.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tAnything that could be used in place of " SEXP_ARGUMENT_STRING "." },

	// Goober5000
	{ OP_EVERY_OF, "Every-of (Conditional operator)\r\n"
		"\tSupplies arguments for the " SEXP_ARGUMENT_STRING " special data item.  Every one of the supplied arguments will be evaluated to satisfy the expression(s) "
		"in which " SEXP_ARGUMENT_STRING " is used.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tAnything that could be used in place of " SEXP_ARGUMENT_STRING "." },

	// Goober5000
	{ OP_RANDOM_OF, "Random-of (Conditional operator)\r\n"
		"\tSupplies arguments for the " SEXP_ARGUMENT_STRING " special data item.  A random supplied argument will be selected to satisfy the expression(s) "
		"in which " SEXP_ARGUMENT_STRING " is used. The same argument will be returned by all subsequent calls\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tAnything that could be used in place of " SEXP_ARGUMENT_STRING "." },

	// Karajorma
	{ OP_RANDOM_MULTIPLE_OF, "Random-multiple-of (Conditional operator)\r\n"
		"\tSupplies arguments for the " SEXP_ARGUMENT_STRING " special data item.  A random supplied argument will be selected to satisfy the expression(s) "
		"in which " SEXP_ARGUMENT_STRING " is used.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tAnything that could be used in place of " SEXP_ARGUMENT_STRING "." },

	// Goober5000
	{ OP_NUMBER_OF, "Number-of (Conditional operator)\r\n"
		"\tSupplies arguments for the " SEXP_ARGUMENT_STRING " special data item.  Any [number] of the supplied arguments can satisfy the expression(s) "
		"in which " SEXP_ARGUMENT_STRING " is used.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tNumber of arguments, as above\r\n"
		"\tRest:\tAnything that could be used in place of " SEXP_ARGUMENT_STRING "." },

	// Karajorma
	{ OP_IN_SEQUENCE, "In-Sequence (Conditional operator)\r\n"
		"\tSupplies arguments for the " SEXP_ARGUMENT_STRING " special data item.  The first argument in the list will be selected to satisfy the expression(s) "
		"in which " SEXP_ARGUMENT_STRING " is used. The same argument will be returned by all subsequent calls\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tAnything that could be used in place of " SEXP_ARGUMENT_STRING "." },

	// Goober5000
	{ OP_FOR_COUNTER, "For-Counter (Conditional operator)\r\n"
		"\tSupplies counter values for the " SEXP_ARGUMENT_STRING " special data item.  This sexp will count up from the start value to the stop value, and each value will be provided as an argument to the action operators.  "
		"The default increment is 1, but if the optional increment parameter is provided, the counter will increment by that number.  The stop value will be supplied if appropriate; e.g. counting from 0 to 10 by 2 will supply 0, 2, 4, 6, 8, and 10; "
		"but counting by 3 will supply 0, 3, 6, and 9.\r\n\r\n"
		"Note that the counter values are all treated as valid arguments, and it is impossible to invalidate a counter argument.  If you want to invalidate a counter value, use Any-of and list the values explicitly.\r\n\r\n"
		"This sexp will usually need to be accompanied by the string-to-int sexp, as the counter variables are provided in string format but are most useful in integer format.\r\n\r\n"
		"Takes 2 or 3 arguments...\r\n"
		"\t1:\tCounter start value\r\n"
		"\t2:\tCounter stop value\r\n"
		"\t3:\tCounter increment (optional)" },

	// Goober5000
	{ OP_INVALIDATE_ARGUMENT, "Invalidate-argument (Conditional operator)\r\n"
		"\tRemoves an argument from future consideration as a " SEXP_ARGUMENT_STRING " special data item.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tThe argument to remove from the preceding argument list." },

	// Karajorma
	{ OP_VALIDATE_ARGUMENT, "Validate-argument (Conditional operator)\r\n"
		"\tRestores an argument for future consideration as a " SEXP_ARGUMENT_STRING " special data item.\r\n"
		"\tIf the argument hasn't been previously invalidated, it will do nothing.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tThe argument to restore to the preceding argument list." },

	// Karajorma
	{ OP_INVALIDATE_ALL_ARGUMENTS, "Invalidate-all-arguments (Conditional operator)\r\n"
		"\tRemoves all argument from future consideration as " SEXP_ARGUMENT_STRING " special data items.\r\n"
		"Takes no arguments." },

	// Karajorma
	{ OP_VALIDATE_ALL_ARGUMENTS, "Validate-all-arguments (Conditional operator)\r\n"
		"\tRestores all arguments for future consideration as " SEXP_ARGUMENT_STRING " special data items.\r\n"
		"\tIf the argument hasn't been previously invalidated, it will do nothing.\r\n"
		"Takes no arguments." },

	// Goober5000 - added wing capability
	{ OP_CHANGE_IFF, "Change IFF (Action operator)\r\n"
		"\tSets the specified ship(s) or wing(s) to the specified team.\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tTeam to change to (\"friendly\", \"hostile\" or \"unknown\").\r\n"
		"\tRest:\tName of ship or wing to change team status of." },

	// Wanderer
	{ OP_CHANGE_IFF_COLOR, "Change IFF Color (Action operator)\r\n"
		"\tSets the specified ship(s) or wing(s) apparent color.\r\n"
		"Takes 6 or more arguments...\r\n"
		"\t1:\tName of the team from which target is observed from.\r\n"
		"\t2:\tName of the team of the observed target to receive the alternate color.\r\n"
		"\t3:\tRed color (value from 0 to 255).\r\n"
		"\t4:\tGreen color (value from 0 to 255).\r\n"
		"\t5:\tBlue color (value from 0 to 255).\r\n"
		"\tRest:\tName of ship or wing to change team status of." },

	// Goober5000
	{ OP_CHANGE_AI_CLASS, "Change AI Class (Action operator)\r\n"
		"\tSets the specified ship or ship subsystem(s) to the specified ai class.\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tAI Class to change to (\"None\", \"Coward\", \"Lieutenant\", etc.)\r\n"
		"\t2:\tName of ship to change AI class of\r\n"
		"\tRest:\tName of subsystem to change AI class of (optional)" },

	{ OP_MODIFY_VARIABLE, "Modify-variable (Misc. operator)\r\n"
		"\tModifies variable to specified value\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of Variable.\r\n"
		"\t2:\tValue to be set." },

	{ OP_GET_VARIABLE_BY_INDEX, "get-variable-by-index (originally variable-array-get)\r\n"
		"\tGets the value of the variable specified by the given index.  This is an alternate way "
		"to access variables rather than by their names, and it enables cool features such as "
		"arrays and pointers.\r\n\r\nPlease note that only numeric variables are supported.  Any "
		"attempt to access a string variable will result in a value of SEXP_NAN_FOREVER being returned.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tIndex of variable, from 0 to MAX_SEXP_VARIABLES - 1." },

	{ OP_SET_VARIABLE_BY_INDEX, "set-variable-by-index (originally variable-array-set)\r\n"
		"\tSets the value of the variable specified by the given index.  This is an alternate way "
		"to modify variables rather than by their names, and it enables cool features such as "
		"arrays and pointers.\r\n\r\nIn contrast to get-variable-by-index, note that this sexp "
		"*does* allow the modification of string variables.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tIndex of variable, from 0 to MAX_SEXP_VARIABLES - 1.\r\n"
		"\t2:\tValue to be set." },

	{ OP_COPY_VARIABLE_FROM_INDEX, "copy-variable-from-index\r\n"
		"\tRetrieves the value of the variable specified by the given index and stores it in another variable.  "
		"This is very similar to variable-array-get, except the result is stored in a new variable rather than "
		"being returned by value.  One important difference is that this sexp can be used to copy string variables as well as numeric variables.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tIndex of source variable, from 0 to MAX_SEXP_VARIABLES - 1.\r\n"
		"\t2:\tDestination variable.  The type of this variable must match the type of the variable referenced by the index." },

	{ OP_COPY_VARIABLE_BETWEEN_INDEXES, "copy-variable-between-indexes\r\n"
		"\tRetrieves the value of the variable specified by the first index and stores it in the variable specified by the second index.  The first variable is not modified.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tIndex of source variable, from 0 to MAX_SEXP_VARIABLES - 1.\r\n"
		"\t2:\tIndex of destination variable, from 0 to MAX_SEXP_VARIABLES - 1.  The types of both variables must match." },

	{ OP_PROTECT_SHIP, "Protect ship (Action operator)\r\n"
		"\tProtects a ship from being attacked by any enemy ship.  Any ship "
		"that is protected will not come under enemy fire.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ship(s) to protect." },

	{ OP_UNPROTECT_SHIP, "Unprotect ship (Action operator)\r\n"
		"\tUnprotects a ship from being attacked by any enemy ship.  Any ship "
		"that is not protected can come under enemy fire.  This function is the opposite "
		"of protect-ship.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ship(s) to unprotect." },

	{ OP_BEAM_PROTECT_SHIP, "Beam Protect ship (Action operator)\r\n"
		"\tProtects a ship from being attacked with beam weapon.  Any ship "
		"that is beam protected will not come under enemy beam fire.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ship(s) to protect." },

	{ OP_BEAM_UNPROTECT_SHIP, "Beam Unprotect ship (Action operator)\r\n"
		"\tUnprotects a ship from being attacked with beam weapon.  Any ship "
		"that is not beam protected can come under enemy beam fire.  This function is the opposite "
		"of beam-protect-ship.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ship(s) to unprotect." },

	// Goober5000
	{ OP_TURRET_PROTECT_SHIP, "Turret Protect ship (Action operator)\r\n"
		"\tProtects a ship from being attacked with a turret weapon of a given type.  Any ship "
		"that is turret protected will not come under enemy fire from that type of turret, though it may come under fire by other turrets.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tType of turret (currently supported types are \"beam\", \"flak\", \"laser\", and \"missile\")\r\n"
		"\tRest:\tName of ship(s) to protect." },

	// Goober5000
	{ OP_TURRET_UNPROTECT_SHIP, "Turret Unprotect ship (Action operator)\r\n"
		"\tUnprotects a ship from being attacked with a turret weapon of a given type.  Any ship "
		"that is not turret protected can come under enemy fire from that type of turret.  This function is the opposite "
		"of turret-protect-ship.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tType of turret (currently supported types are \"beam\", \"flak\", \"laser\", and \"missile\")\r\n"
		"\tRest:\tName of ship(s) to unprotect." },

	{ OP_SEND_MESSAGE, "Send message (Action operator)\r\n"
		"\tSends a message to the player.  Can be send by a ship, wing, or special "
		"source.  To send it from a special source, make the first character of the first "
		"argument a \"#\".\r\n\r\n"
		"Takes 3 arguments...\r\n"
		"\t1:\tName of who the message is from.\r\n"
		"\t2:\tPriority of message (\"Low\", \"Normal\" or \"High\").\r\n"
		"\t3:\tName of message (from message editor)." },

	// Karajorma	
	{ OP_ENABLE_BUILTIN_MESSAGES, "Enable builtin messages (Action operator)\r\n"
		"\tTurns the built in messages sent by command or pilots on\r\n"
		"Takes 0 or more arguments...\r\n"
		"If no arguments are supplied any ships not given individual silence orders will be able\r\n"
		"to send built in messages. Command will also be unsilenced\r\n"
		"Using the Any Wingman option cancels radio silence for all ships in wings.\r\n"
		"\tAll:\tName of ship to allow to talk." },
		
	// Karajorma
	{ OP_DISABLE_BUILTIN_MESSAGES, "Disable builtin messages (Action operator)\r\n"
		"\tTurns the built in messages sent by command or pilots off\r\n"
		"Takes 0 or more arguments....\r\n"
		"If no arguments are supplied all built in messages are disabled.\r\n"
		"Using the Any Wingman option silences for all ships in wings.\r\n"
		"\tAll:\tName of ship to be silenced." },

	// Karajorma	
	{ OP_SET_MISSION_MOOD, "set Mission Mood (Action operator)\r\n"
		"\tSets the mood of the mission, this affects the choice of builtin messages sent by wingmen\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tMission mood (from messages.tbl) to use." },

	// Karajorma	
	{ OP_SET_PERSONA, "Set Persona (Action operator)\r\n"
		"\tSets the persona of the supplied ship to the persona supplied\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tPersona to use."
		"\tRest:\tName of the ship." },

	{ OP_SELF_DESTRUCT, "Self destruct (Action operator)\r\n"
		"\tCauses the specified ship(s) to self destruct.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ship to self destruct." },

	{ OP_NEXT_MISSION, "Next Mission (Action operator)\r\n"
		"\tThe next mission operator is used for campaign branching in the campaign editor.  "
		"It specifies which mission should played be next in the campaign.  This operator "
		"generally follows a 'when' or 'cond' statment in the campaign file.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tName of mission (filename) to proceed to." },

	{ OP_CLEAR_GOALS, "Clear goals (Action operator)\r\n"
		"\tClears the goals for the specified ships and/or wings.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ship or wing." },

	{ OP_ADD_GOAL, "Add goal (Action operator)\r\n"
		"\tAdds a goal to a ship or wing.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of ship or wing to add goal to.\r\n"
		"\t2:\tGoal to add." },

	// Goober5000
	{ OP_REMOVE_GOAL, "Remove goal (Action operator)\r\n"
		"\tRemoves a goal from a ship or wing.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of ship or wing to remove goal from.\r\n"
		"\t2:\tGoal to remove." },

	{ OP_SABOTAGE_SUBSYSTEM, "Sabotage subystem (Action operator)\r\n"
		"\tReduces the specified subsystem integrity by the specified percentage."
		"If the percntage strength of the subsystem (after completion) is less than 0%,"
		"subsystem strength is set to 0%.\r\n\r\n"
		"Takes 3 arguments...\r\n"
		"\t1:\tName of ship subsystem is on.\r\n"
		"\t2:\tName of subsystem to sabotage.\r\n"
		"\t3:\tPercentage to reduce subsystem integrity by." },

	{ OP_REPAIR_SUBSYSTEM, "Repair Subystem (Action operator)\r\n"
		"\tIncreases the specified subsystem integrity by the specified percentage."
		"If the percntage strength of the subsystem (after completion) is greater than 100%,"
		"subsystem strength is set to 100%.\r\n\r\n"
		"Takes 4 arguments...\r\n"
		"\t1:\tName of ship subsystem is on.\r\n"
		"\t2:\tName of subsystem to repair.\r\n"
		"\t3:\tPercentage to increase subsystem integrity by.\r\n"
		"\t4:\tRepair turret submodel.  Optional argument that defaults to true."},

	{ OP_SET_SUBSYSTEM_STRNGTH, "Set Subsystem Strength (Action operator)\r\n"
		"\tSets the specified subsystem to the the specified percentage."
		"If the percentage specified is < 0, strength is set to 0.  If the percentage is "
		"> 100 % the subsystem strength is set to 100%.\r\n\r\n"
		"Takes 3 arguments...\r\n"
		"\t1:\tName of ship subsystem is on.\r\n"
		"\t2:\tName of subsystem to set strength.\r\n"
		"\t3:\tPercentage to set subsystem integrity to.\r\n" 
		"\t4:\tRepair turret submodel.  Optional argument that defaults to true."},

	{ OP_DESTROY_SUBSYS_INSTANTLY, "destroy-subsys-instantly\r\n"
		"\tDetroys the specified subsystems without effects."
		"\tSingle player only!"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tName of ship subsystem is on.\r\n"
		"\tRest:\tName of subsystem to destroy.\r\n"},

	{ OP_INVALIDATE_GOAL, "Invalidate goal (Action operator)\r\n"
		"\tMakes a mission goal invalid, which causes it to not show up on mission goals "
		"screen, or be evaluated.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of mission goal to invalidate." },

	{ OP_VALIDATE_GOAL, "Validate goal (Action operator)\r\n"
		"\tMakes a mission goal valid again, so it shows up on mission goals screen.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of mission goal to validate." },

	{ OP_SEND_RANDOM_MESSAGE, "Send random message (Action operator)\r\n"
		"\tSends a random message to the player from those supplied.  Can be send by a "
		"ship, wing, or special source.  To send it from a special source, make the first "
		"character of the first argument a \"#\".\r\n\r\n"
		"Takes 3 or more arguments...\r\n"
		"\t1:\tName of who the message is from.\r\n"
		"\t2:\tPriority of message (\"Low\", \"Normal\" or \"High\")."
		"\tRest:\tName of message (from message editor)." },

	{ OP_TRANSFER_CARGO, "Transfer Cargo (Action operator)\r\n"
		"\tTransfers the cargo from one ship to another ship.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of ship that cargo is being transferred from.\r\n"
		"\t2:\tName of ship that cargo is being transferred to." },

	{ OP_EXCHANGE_CARGO, "Exchange Cargo (Action operator)\r\n"
		"\tExchanges the cargos of two ships.  If one of the two ships contains no cargo, "
		"the cargo is transferred instead.\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of one of the ships.\r\n"
		"\t2:\tName of the other ship." },

	// Goober5000
	{ OP_SET_CARGO, "Set Cargo (Action operator)\r\n"
		"\tSets the cargo on a ship or ship subsystem.  The cargo-no-deplete flag status is carried through to the new cargo.\r\n"
		"Takes 2 or 3 arguments...\r\n"
		"\t1:\tName of the cargo\r\n"
		"\t2:\tName of the ship\r\n"
		"\t3:\tName of the ship subsystem (optional)" },

	// Goober5000
	{ OP_IS_CARGO, "Is Cargo (Status operator)\r\n"
		"\tChecks whether the specified ship or ship subsystem contains a particular cargo.\r\n"
		"Takes 2 or 3 arguments...\r\n"
		"\t1:\tName of the cargo\r\n"
		"\t2:\tName of the ship\r\n"
		"\t3:\tName of the ship subsystem (optional)" },

	// Goober5000
	{ OP_CHANGE_SOUNDTRACK, "change-soundtrack\r\n"
		"\tChanges the mission music.  Takes 1 argument...\r\n"
		"\t1: Name of the music selection (taken from music.tbl)" },

	// Goober5000
	{ OP_PLAY_SOUND_FROM_TABLE, "play-sound-from-table\r\n"
		"\tPlays a sound listed in the Game Sounds section of sounds.tbl.  Note that if the sound is a non-3D sound (if the min and max radius are 0, or unspecified), the sound will just play without being fixed at a particular position in space.  "
		"In this case, the origin coordinates will be ignored.  (A better design would have put the sound index first and made the origin arguments optional, but the difference between 2D and 3D sounds was not understood at the time.  C'est la vie.)\r\n\r\n"
		"Takes 4 arguments...\r\n"
		"\t1: Origin X\r\n"
		"\t2: Origin Y\r\n"
		"\t3: Origin Z\r\n"
		"\t4: Sound (index into sounds.tbl or name of the sound entry)" },

	// Goober5000
	{ OP_PLAY_SOUND_FROM_FILE, "play-sound-from-file\r\n"
		"\tPlays a sound, such as a music soundtrack, from a file.  Important: Only one sound at a time can be played with this sexp!\r\n"
		"Takes 1 to 3 arguments...\r\n"
		"\t1: Sound (file name)\r\n"
		"\t2: Enter a non-zero number to loop. default is off (optional).\r\n"
		"\t3: Enter a non-zero number to use environment effects. default is off (optional)."
	},

	// Goober5000
	{ OP_CLOSE_SOUND_FROM_FILE, "close-sound-from-file\r\n"
		"\tCloses the currently playing sound started by play-sound-from-file, if there is any.  Takes 1 argument...\r\n"
		"\t1: Fade (default is true)" },

	// Goober5000
	{ OP_PAUSE_SOUND_FROM_FILE, "pause-sound-from-file\r\n"
		"\tPauses or unpauses the currently playing sound started by play-sound-from-file, if there is any.  Takes 1 argument...\r\n"
		"\t1: Boolean - True to pause, False to unpause" },

	// Taylor
	{ OP_SET_SOUND_ENVIRONMENT, "set-sound-environment\r\n"
		"Sets the EAX environment for all sound effects.  Optionally sets one or more parameters specific to the environment.  Takes 1 or more arguments...\r\n"
		"\t1:\tSound environment name (a value of \"" SEXP_NONE_STRING "\" will disable the effects)\r\n"
		"\t2:\tEnvironment option (optional)\r\n"
		"\t3:\tEnvironment value x 1000, e.g. 10 is 0.01 (optional)\r\n"
		"Use Add-Data to specify additional environment options in repeating option-value pairs, just like Send-Message-List can have additional messages in source-priority-message-delay groups.\r\n\r\n"
		"IMPORTANT: each additional option in the list MUST HAVE two entries; any option without the two proper fields will be ignored, as will any successive options." },

	// Taylor
	{ OP_UPDATE_SOUND_ENVIRONMENT, "update-sound-environment\r\n"
		"Updates the current EAX environment with new values.  Takes 2 or more arguments...\r\n"
		"\t1:\tEnvironment option\r\n"
		"\t2:\tEnvironment value x 1000, e.g. 10 is 0.01\r\n"
		"Use Add-Data to specify additional environment options in repeating option-value pairs, just like Send-Message-List can have additional messages in source-priority-message-delay groups.\r\n\r\n"
		"IMPORTANT: Each additional option in the list MUST HAVE two entries; any option without the two proper fields will be ignored, as will any successive options." },
	
	//The E
	{ OP_ADJUST_AUDIO_VOLUME, "adjust-audio-volume\r\n"
		"Adjusts the relative volume of one sound type. Takes 1 to 3 arguments....\r\n"
		"\t1:\tSound Type to adjust, either Music, Voice or Effects. Will act as a reset for the given category, if no other argument present\r\n"
		"\t2:\tPercentage of the users' settings to adjust to (optional), 0 will be silence, 100 means the maximum volume as set by the user\r\n"
		"\t3:\tFade time (optional), time in milliseconds to adjust the volume"},

	// Goober5000
	{ OP_SET_EXPLOSION_OPTION, "set-explosion-option\r\n"
		"Sets an explosion option on a particular ship.  Takes 3 or more arguments...\r\n"
		"\t1:\tShip name\r\n"
		"\t2:\tExplosion option\r\n"
		"\t3:\tExplosion value (for shockwave speed, 0 will produce no shockwave; for death roll time, 0 will use the default time)\r\n"
		"Use Add-Data to specify additional explosion options in repeating option-value pairs, just like Send-Message-List can have additional messages in source-priority-message-delay groups.\r\n\r\n"
		"IMPORTANT: Each additional option in the list MUST HAVE two entries; any option without the two proper fields will be ignored, as will any successive options." },

	// Goober5000
	{ OP_EXPLOSION_EFFECT, "explosion-effect\r\n"
		"\tCauses an explosion at a given origin, with the given parameters.  "
		"Takes 11 or 13 arguments...\r\n"
		"\t1:  Origin X\r\n"
		"\t2:  Origin Y\r\n"
		"\t3:  Origin Z\r\n"
		"\t4:  Damage\r\n"
		"\t5:  Blast force\r\n"
		"\t6:  Size of explosion (if 0, explosion will not be visible)\r\n"
		"\t7:  Inner radius to apply damage (if 0, explosion will not be visible)\r\n"
		"\t8:  Outer radius to apply damage (if 0, explosion will not be visible)\r\n"
		"\t9:  Shockwave speed (if 0, there will be no shockwave)\r\n"
		"\t10: Type - For backward compatibility 0 = medium, 1 = large1 (4th in table), 2 = large2 (5th in table)\r\n"
		"           3 or greater link to respctive entry in fireball.tbl\r\n"
		"\t11: Sound (index into sounds.tbl or name of the sound entry)\r\n"
		"\t12: EMP intensity (optional)\r\n"
		"\t13: EMP duration in seconds (optional)" },

	// Goober5000
	{ OP_WARP_EFFECT, "warp-effect\r\n"
		"\tCauses a subspace warp effect at a given origin, facing toward a given location, with the given parameters.\r\n"
		"Takes 12 arguments...\r\n"
		"\t1:  Origin X\r\n"
		"\t2:  Origin Y\r\n"
		"\t3:  Origin Z\r\n"
		"\t4:  Location X\r\n"
		"\t5:  Location Y\r\n"
		"\t6:  Location Z\r\n"
		"\t7:  Radius\r\n"
		"\t8:  Duration in seconds (values smaller than 4 are ignored)\r\n"
		"\t9:  Warp opening sound (index into sounds.tbl or name of the sound entry)\r\n"
		"\t10: Warp closing sound (index into sounds.tbl or name of the sound entry)\r\n"
		"\t11: Type (0 for standard blue [default], 1 for Knossos green)\r\n"
		"\t12: Shape (0 for 2-D [default], 1 for 3-D)" },

	// Goober5000
	{ OP_SET_OBJECT_FACING, "set-object-facing\r\n"
		"\tSets an object's orientation to face the specified coordinates.  "
		"Takes 4 arguments...\r\n"
		"\t1: The name of a ship or wing.\r\n"
		"\t2: The X coordinate to face.\r\n"
		"\t3: The Y coordinate to face.\r\n"
		"\t4: The Z coordinate to face.\r\n"
		"\t5: Turn time in milliseconds (optional)\r\n"
		"\t6: Bank (optional). Enter a non-zero value to enable banking." },

	// Goober5000
	{ OP_SET_OBJECT_FACING_OBJECT, "set-object-facing-object\r\n"
		"\tSets an object's orientation to face the specified object.  "
		"Takes 2 arguments...\r\n"
		"\t1: The name of a ship or wing.\r\n"
		"\t2: The object to face.\r\n"
		"\t3: Turn time in milliseconds (optional)\r\n"
		"\t4: Bank (optional). Enter a non-zero value to enable banking." },

	// Wanderer
	{ OP_SHIP_MANEUVER, "ship-maneuver\r\n"
		"\tCombines the effects of the ship-rot-maneuver and ship-lat-maneuver sexps.  Takes 10 arguments:\r\n"
		"\t1: The name of a ship or wing\r\n"
		"\t2: Duration of the maneuver, in milliseconds\r\n"
		"\t3: Heading movement velocity, as a percentage (-100 to 100) of the tabled maximum heading velocity, or 0 to not modify the ship's current value\r\n"
		"\t4: Pitch movement velocity, as a percentage (-100 to 100) of the tabled maximum pitch velocity, or 0 to not modify the ship's current value\r\n"
		"\t5: Bank movement velocity, as a percentage (-100 to 100) of the tabled maximum bank velocity, or 0 to not modify the ship's current value\r\n"
		"\t6: Whether to apply all of the rotational velocity values even if any of them are 0\r\n"
		"\t7: Vertical movement velocity, as a percentage (-100 to 100) of the tabled maximum vertical velocity, or 0 to not modify the ship's current value\r\n"
		"\t8: Sideways movement velocity, as a percentage (-100 to 100) of the tabled maximum sideways velocity, or 0 to not modify the ship's current value\r\n"
		"\t9: Forward movement velocity, as a percentage (-100 to 100) of the tabled maximum forward velocity, or 0 to not modify the ship's current value\r\n"
		"\t10: Whether to apply all of the lateral velocity values even if any of them are 0\r\n" },

	// Wanderer
	{ OP_SHIP_ROT_MANEUVER, "ship-rot-maneuver\r\n"
		"\tCauses a ship to move in a rotational direction.  For the purposes of this sexp, this means the ship rotates along its own heading, pitch, or bank axis (or a combination of axes) without regard to normal ship rotation rules.  "
		"You may find it necessary to disable the ship AI (e.g. by issuing a play-dead order) before running this sexp.\r\n\r\n"
		"Takes 6 arguments:\r\n"
		"\t1: The name of a ship or wing\r\n"
		"\t2: Duration of the maneuver, in milliseconds\r\n"
		"\t3: Heading movement velocity, as a percentage (-100 to 100) of the tabled maximum heading velocity, or 0 to not modify the ship's current value\r\n"
		"\t4: Pitch movement velocity, as a percentage (-100 to 100) of the tabled maximum pitch velocity, or 0 to not modify the ship's current value\r\n"
		"\t5: Bank movement velocity, as a percentage (-100 to 100) of the tabled maximum bank velocity, or 0 to not modify the ship's current value\r\n"
		"\t6: Whether to apply all of the above velocity values even if any of them are 0\r\n" },
	
	// Wanderer
	{ OP_SHIP_LAT_MANEUVER, "ship-lat-maneuver\r\n"
		"\tCauses a ship to move in a lateral direction.  For the purposes of this sexp, this means the ship translates along its own X, Y, or Z axis (or a combination of axes) without regard to normal ship movement rules.  "
		"You may find it necessary to disable the ship AI (e.g. by issuing a play-dead order) before running this sexp.\r\n\r\n"
		"Takes 6 arguments:\r\n"
		"\t1: The name of a ship or wing\r\n"
		"\t2: Duration of the maneuver, in milliseconds\r\n"
		"\t3: Vertical movement velocity, as a percentage (-100 to 100) of the tabled maximum vertical velocity, or 0 to not modify the ship's current value\r\n"
		"\t4: Sideways movement velocity, as a percentage (-100 to 100) of the tabled maximum sideways velocity, or 0 to not modify the ship's current value\r\n"
		"\t5: Forward movement velocity, as a percentage (-100 to 100) of the tabled maximum forward velocity, or 0 to not modify the ship's current value\r\n"
		"\t6: Whether to apply all of the above velocity values even if any of them are 0\r\n" },

	// Goober5000
	{ OP_SHIP_TAG, "ship-tag\r\n"
		"\tTags a ship.  Takes 3 or 8 arguments...\r\n"
		"\t1: The name of a ship.\r\n"
		"\t2: The tag level (currently 1, 2, or 3).\r\n"
		"\t3: The tag time (in seconds).\r\n"
		"\t4: A SSM missile (optional - used only for TAG-C).\r\n"
		"\t5: The X origin of the SSM missile (optional - used only for TAG-C).\r\n"
		"\t6: The Y origin of the SSM missile (optional - used only for TAG-C).\r\n"
		"\t7: The Z origin of the SSM missile (optional - used only for TAG-C).\r\n" 
        "\t8: The team the SSM missile belongs to (optional - used only for TAG-C).\r\n" },

/*	made obsolete by Goober5000 - it only works in debug builds anyway
	{ OP_INT3, "Error (Debug directive)\r\n"
		"Causes the game to halt with an error." },
*/

	{ OP_AI_CHASE, "Ai-chase (Ship goal)\r\n"
		"\tCauses the specified ship to chase and attack the specified target.\r\n\r\n"
		"Takes 2 or 3 arguments...\r\n"
		"\t1:\tName of ship to chase.\r\n"
		"\t2:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100).\r\n"
		"\t3 (optional):\tWhether to attack the target even if it is on the same team; defaults to false."
	},

	{ OP_AI_DOCK, "Ai-dock (Ship goal)\r\n"
		"\tCauses one ship to dock with another ship.\r\n\r\n"
		"Takes 4 arguments...\r\n"
		"\t1:\tName of dockee ship (The ship that \"docker\" will dock with).\r\n"
		"\t2:\tDocker's docking point - Which dock point docker uses to dock.\r\n"
		"\t3:\tDockee's docking point - Which dock point on dockee docker will move to.\r\n"
		"\t4:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100)." },

	{ OP_AI_UNDOCK, "Ai-undock (Ship goal)\r\n"
		"\tCauses the specified ship to undock from who it is currently docked with.\r\n\r\n"
		"Takes 1 or 2 arguments...\r\n"
		"\t1:\tGoal priority (number between 0 and 89).\r\n"
		"\t2 (optional):\tShip to undock from.  If none is specified, the code will pick the first docked ship." },

	{ OP_AI_WARP_OUT, "Ai-warp-out (Ship/Wing Goal)\r\n"
		"\tCauses the specified ship/wing to immediately warp out of the mission, from its current location.  "
		"It will warp even if its departure cue is specified as a hangar bay.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of waypoint path to follow to warp out (not used).\r\n"
		"\t2:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100)." },

	{ OP_AI_WAYPOINTS, "Ai-waypoints (Ship goal)\r\n"
		"\tCauses the specified ship to fly a waypoint path continuously.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of waypoint path to fly.\r\n"
		"\t2:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100)." },

	{ OP_AI_WAYPOINTS_ONCE, "Ai-waypoints once (Ship goal)\r\n"
		"\tCauses the specified ship to fly a waypoint path.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of waypoint path to fly.\r\n"
		"\t2:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100)." },

	{ OP_AI_DESTROY_SUBSYS, "Ai-destroy subsys (Ship goal)\r\n"
		"\tCauses the specified ship to attack and try and destroy the specified subsystem "
		"on the specified ship.\r\n\r\n"
		"Takes 3 or 4 arguments...\r\n"
		"\t1:\tName of ship subsystem is on.\r\n"
		"\t2:\tName of subsystem on the ship to attack and destroy.\r\n"
		"\t3:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100).\r\n"
		"\t4 (optional):\tWhether to attack the target even if it is on the same team; defaults to false."
	},

	{ OP_AI_CHASE_WING, "Ai-chase wing (Ship goal)\r\n"
		"\tCauses the specified ship to chase and attack the specified target.\r\n\r\n"
		"Takes 2 or 3 arguments...\r\n"
		"\t1:\tName of wing to chase.\r\n"
		"\t2:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100).\r\n"
		"\t3 (optional):\tWhether to attack the target even if it is on the same team; defaults to false."
	},

	{ OP_AI_DISABLE_SHIP, "Ai-disable-ship (Ship/wing goal)\r\n"
		"\tThis AI goal causes a ship/wing to destroy all of the engine subsystems on "
		"the specified ship.  This goal is different than ai-destroy-subsystem since a ship "
		"may have multiple engine subsystems requiring the use of > 1 ai-destroy-subsystem "
		"goals.\r\n"
		"Please note that this goal may call \"protect-ship\" on the target "
		"to prevent overzealous AI ships from destroying it in the process of disabling it.  "
		"If the ship must be destroyed later on, be sure to call an \"unprotect-ship\" sexp.\r\n\r\n"
		"Takes 2 or 3 arguments...\r\n"
		"\t1:\tName of ship whose engine subsystems should be destroyed\r\n"
		"\t2:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100).\r\n"
		"\t3 (optional):\tWhether to attack the target even if it is on the same team; defaults to false."
	},

	{ OP_AI_DISARM_SHIP, "Ai-disarm-ship (Ship/wing goal)\r\n"
		"\tThis AI goal causes a ship/wing to destroy all of the turret subsystems on "
		"the specified ship.  This goal is different than ai-destroy-subsystem since a ship "
		"may have multiple turret subsystems requiring the use of > 1 ai-destroy-subsystem "
		"goals.\r\n"
		"Please note that this goal may call \"protect-ship\" on the target "
		"to prevent overzealous AI ships from destroying it in the process of disarming it.  "
		"If the ship must be destroyed later on, be sure to call an \"unprotect-ship\" sexp.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of ship whose turret subsystems should be destroyed\r\n"
		"\t2:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100).\r\n"
		"\t3 (optional):\tWhether to attack the target even if it is on the same team; defaults to false."
	},

	{ OP_AI_GUARD, "Ai-guard (Ship goal)\r\n"
		"\tCauses the specified ship to guard a ship from other ships not on the same team.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of ship to guard.\r\n"
		"\t2:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100)." },

	{ OP_AI_CHASE_ANY, "Ai-chase-any (Ship goal)\r\n"
		"\tCauses the specified ship to chase and attack any ship on the opposite team.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100)." },

	{ OP_AI_GUARD_WING, "Ai-guard wing (Ship goal)\r\n"
		"\tCauses the specified ship to guard a wing of ships from other ships not on the "
		"same team.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of wing to guard.\r\n"
		"\t2:\tGoal priority (number between 0 and 200. Player orders have a priority of 90-100)." },

	{ OP_NOP, "Do-nothing (Action operator)\r\n"
		"\tDoes nothing.  This is used as the default for any required action arguments "
		"of an operator." },

	{ OP_KEY_PRESSED, "Key-pressed (Boolean training operator)\r\n"
		"\tBecomes true when the specified default key has been pressed.  Default key "
		"refers to the what the key normally is when not remapped.  FreeSpace will "
		"automatically account for any keys that have been remapped.  If the optional "
		"delay is specified, becomes true that many seconds after the key has been pressed.\r\n\r\n"
		"Returns a boolean value.  Takes 1 or 2 arguments...\r\n"
		"\t1:\tDefault key to check for.\r\n"
		"\t2:\tDelay before operator registers as true (optional).\r\n" },

	{ OP_KEY_RESET, "Key-reset (Training operator)\r\n"
		"\tMarks the specified default key as having not been pressed, so key-pressed will be false "
		"until the player presses it again.  See key-pressed help for more information about "
		"what a default key is.\r\n\r\n"
		"\tNote that this sexp will not work properly in repeating events.  Use key-reset-multiple "
		"if this is to be called multiple times in one event.\r\n\r\n"
		"Returns a boolean value.  Takes 1 or more arguments...\r\n"
		"\tAll:\tDefault key to reset." },

	// Goober5000
	{ OP_KEY_RESET_MULTIPLE, "Key-reset-multiple (Training operator)\r\n"
		"\tMarks the specified default key as having not been pressed, so key-pressed will be false "
		"until the player presses it again.  See key-pressed help for more information about "
		"what a default key is.\r\n\r\n"
		"\tThis sexp, unlike key-reset, will work properly if called multiple times in one event.\r\n\r\n"
		"Returns a boolean value.  Takes 1 or more arguments...\r\n"
		"\tAll:\tDefault key to reset." },

	{ OP_TARGETED, "Targeted (Boolean training operator)\r\n"
		"\tIs true as long as the player has the specified ship (or ship's subsystem) targeted, "
		"or has been targeted for the specified amount of time.\r\n\r\n"
		"Returns a boolean value.  Takes 1 to 3 arguments (first required, rest optional):\r\n"
		"\t1:\tName of ship to check if targeted by player.\r\n"
		"\t2:\tLength of time target should have been kept for (optional).\r\n"
		"\t3:\tName of subsystem on ship to check if targeted (optional)." },

	{ OP_NODE_TARGETED, "Node-Targeted (Boolean training operator)\r\n"
		"\tIs true as long as the player has the specified jump node targeted, "
		"or has been targeted for the specified amount of time.\r\n\r\n"
		"Returns a boolean value.  Takes 1 to 2 arguments (first required, rest optional):\r\n"
		"\t1:\tName of Jump Node to check if targeted by player.\r\n"
		"\t2:\tLength of time target should have been kept for (optional)."},

	// Sesquipedalian
	{ OP_MISSILE_LOCKED, "Missile-locked (Boolean training operator)\r\n"
		"\tIs true as long as the player has had a missile lock for the specified amount of time. "
		"Optional arguments require lock to be maintained on a specified ship (or ship's subsystem).\r\n\r\n"
		"Returns a boolean value.  Takes 1 to 3 arguments (first required, rest optional):\r\n"
		"\t1:\tLength of time missile lock should have been kept for.\r\n"
		"\t2:\tName of ship to check if locked onto by player (optional).\r\n"
		"\t3:\tName of subsystem on ship to check if locked onto (optional)." },

	{ OP_SPEED, "Speed (Boolean training operator)\r\n"
		"\tBecomes true when the player has been within the specified speed range set by "
		"set-training-context-speed for the specified amount of time.\r\n\r\n"
		"Returns a boolean value.  Takes 1 argument...\r\n"
		"\t1:\tTime in seconds." },

	{ OP_GET_THROTTLE_SPEED, "Get-Throttle-Speed (Training operator)\r\n"
		"\tReturns the current throttle speed that the ship has been set to. Reverse speeds are returned as a negative value. "
		"Takes 1 argument...\r\n"
		"\t1:\tName of the player ship to check the throttle value for." },

	{ OP_FACING, "Facing (Boolean training operator)\r\n"
		"\tIs true as long as the specified ship is within the player's specified "
		"forward cone.  A forward cone is defined as any point that the angle between the "
		"vector of the point and the player, and the forward facing vector is within the "
		"given angle.\r\n\r\n"
		"Returns a boolean value.  Takes 2 argument...\r\n"
		"\t1:\tShip to check is withing forward cone.\r\n"
		"\t2:\tAngle in degrees of the forward cone." },

	{ OP_IS_FACING, "Is Facing (Boolean training operator)\r\n"
		"\tIs true as long as the second object is within the first ship's specified "
		"forward cone.  A forward cone is defined as any point that the angle between the "
		"vector of the ship and point, and the forward facing vector is within the "
		"given angle. If the distance between the two is greater than the fourth"
		"parameter, this will return false.\r\n\r\n"
		"Returns a boolean value.  Takes 3 or 4 argument...\r\n"
		"\t1:\tShip to check from.\r\n"
		"\t2:\tObject to check is within forward cone.\r\n"
		"\t3:\tAngle in degrees of the forward cone.\r\n"
		"\t4:\tRange in meters (optional)."},

	{ OP_FACING2, "Facing Waypoint(Boolean training operator)\r\n"
		"\tIs true as long as the specified first waypoint is within the player's specified "
		"forward cone.  A forward cone is defined as any point that the angle between the "
		"vector of the point and the player, and the forward facing vector is within the "
		"given angle.\r\n\r\n"
		"Returns a boolean value.  Takes 2 argument...\r\n"
		"\t1:\tName of waypoint path whose first point is within forward cone.\r\n"
		"\t2:\tAngle in degrees of the forward cone." },

	// fixed by Goober5000 and then deprecated by Karajorma
	{ OP_ORDER, "Order (Boolean training operator)\r\n"
		"\tDeprecated - Use Query-Orders in any new mission.\r\n\r\n"
		"\tBecomes true when the player had given the specified ship or wing the specified order.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or 3 arguments...\r\n"
		"\t1:\tName of ship or wing to check if given order to.\r\n"
		"\t2:\tName of order to check if player has given.\r\n"
		"\t3:\tName of the target of the order (optional)." },

	{ OP_QUERY_ORDERS, "Query-Orders (Boolean training operator)\r\n"
		"\tBecomes true when the player had given the specified ship or wing the specified order.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more arguments...\r\n"
		"\t1:\tName of ship or wing to check if given order to.\r\n"
		"\t2:\tName of order to check if player has given.\r\n"
		"\t3:\tMaximum length of time since order was given. Use 0 for any time in the mission.\r\n"
		"\t4:\tName of the target of the order (optional).\r\n"
		"\t5:\tName of player ship giving the order(optional).\r\n"
		"\t6:\tName of the subsystem for Destroy Subsystem orders.(optional)" },

	// Karajorma
	{ OP_RESET_ORDERS, "Reset-Orders (Action training operator)\r\n"
		"\tResets the list of orders the player has given.\r\n"
		"Takes no arguments." },

	{ OP_WAYPOINT_MISSED, "Waypoint-missed (Boolean training operator)\r\n"
		"\tBecomes true when a waypoint is flown, but the waypoint is ahead of the one "
		"they are supposed to be flying.  The one they are supposed to be flying is the "
		"next one in sequence in the path after the last one they have hit.\r\n\r\n"
		"Returns a boolean value.  Takes no arguments." },

	{ OP_PATH_FLOWN, "Path-flown (Boolean training operator)\r\n"
		"\tBecomes true when all the waypoints in the path have been flown, in sequence.\r\n\r\n"
		"Returns a boolean value.  Takes no arguments." },

	{ OP_WAYPOINT_TWICE, "Waypoint-twice (Boolean training operator)\r\n"
		"\tBecomes true when a waypoint is hit that is before the last one hit, which "
		"indicates they have flown a waypoint twice.\r\n\r\n"
		"Returns a boolean value.  Takes no arguments." },

	{ OP_TRAINING_MSG, "Training-msg (Action training operator)\r\n"
		"\tSends the player a training message.  Uses the same messages as normal messages, "
		"only they get displayed differently using this operator.  If a secondary message "
		"is specified, it is sent the last time, while the primary message is sent all other "
		"times (event should have a repeat count greater than 1).\r\n\r\n"
		"Takes 1-3 arguments...\r\n"
		"\t1:\tName of primary message to send.\r\n"
		"\t2:\tName of secondary message to send (optional).\r\n"
		"\t3:\tDelay (in seconds) to wait before sending message. (optional)\r\n"
		"\t4:\tAmount of Time (in seconds) to display message (optional)." },

	{ OP_SET_TRAINING_CONTEXT_FLY_PATH, "Set-training-context-fly-path (Training context operator)\r\n"
		"\tTells FreeSpace that the player is expected to fly a waypoint path.  This must be "
		"executed before waypoint-missed, waypoint-twice and path-flown operators become valid.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of waypoint path player should fly.\r\n"
		"\t2:\tDistance away a player needs to be from a waypoint for it to be registered as flown." },

	{ OP_SET_TRAINING_CONTEXT_SPEED, "Set-training-context-speed (Training context operator)\r\n"
		"\tTells FreeSpace that the player is expected to fly within a certain speed range.  Once "
		"this operator has been executed, you can measure how long they have been within this "
		"speed range with the speed operator.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tMinimum speed of range player is to fly between.\r\n"
		"\t2:\tMaximum speed of range player is to fly between." },

	// Karajorma
	{ OP_STRING_TO_INT, "string-to-int\r\n"
		"\tConverts a string into an integer.  All non-numeric characters (except for the negative sign) will be ignored, as will any fractional part of a decimal number.  This behavior is somewhat different than the atoi() function in C or C++, which will abort if it encounters any non-numeric character.  For a string like \"turret31\", this sexp will return 31, but atoi() will return 0.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tString to convert" },

	// Goober5000
	{ OP_STRING_GET_LENGTH, "string-get-length\r\n"
		"\tReturns the length of the specified string.  Takes 1 argument." },

	// Goober5000
	{ OP_INT_TO_STRING, "int-to-string\r\n"
		"\tConverts an integer into a string.  The destination must be a string variable.\r\n"
		"Takes 2 argument...\r\n"
		"\t1:\tInteger to convert\r\n"
		"\t2:\tString variable to contain the result\r\n" },

	// Goober5000
	{ OP_STRING_CONCATENATE, "string-concatenate\r\n"
		"\tConcatenates two strings, putting the result into a string variable.  If the length of the string will "
		"exceed the sexp variable token limit (currently 32), it will be truncated.\r\n\r\n"
		"Takes 3 arguments...\r\n"
		"\t1: First string\r\n"
		"\t2: Second string\r\n"
		"\t3: String variable to hold the result\r\n" },

	// Goober5000
	{ OP_STRING_GET_SUBSTRING, "string-get-substring\r\n"
		"\tExtracts a substring from a parent string, putting the result into a string variable.  If the length of the string will "
		"exceed the sexp variable token limit (currently 32), it will be truncated.\r\n\r\n"
		"Takes 3 arguments...\r\n"
		"\t1: Parent string\r\n"
		"\t2: Index at which the substring begins (0-based)\r\n"
		"\t3: Length of the substring\r\n"
		"\t4: String variable to hold the result\r\n" },

	// Goober5000
	{ OP_STRING_SET_SUBSTRING, "string-set-substring\r\n"
		"\tReplaces a substring from a parent string with a new string, putting the result into a string variable.  If the length of the string will "
		"exceed the sexp variable token limit (currently 32), it will be truncated.\r\n\r\n"
		"Takes 3 arguments...\r\n"
		"\t1: Parent string\r\n"
		"\t2: Index at which the substring begins (0-based)\r\n"
		"\t3: Length of the substring\r\n"
		"\t4: New substring (which can be a different length than the old substring)\r\n"
		"\t5: String variable to hold the result\r\n" },

	// Karajorma
	{ OP_DEBUG, "debug\r\n"
		"\tPops up a warning on debug builds (and optionally on release builds)\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1:\t If false, popup messages in release builds too. Defaults to true.\r\n"
		"\t2:\tName of a message which will appear in the warning (optional)\r\n"},

	{ OP_GRANT_PROMOTION, "Grant promotion (Action operator)\r\n"
		"\tIn a single player game, this function grants a player an automatic promotion to the "
		"next rank which the player can obtain.  If he is already at the highest rank, this "
		"operator has no effect.  It takes no arguments." },

	{ OP_GRANT_MEDAL, "Grant medal (Action operator)\r\n"
		"\tIn single player missions, this function grants the given medal to the player.  "
		"Currently, only 1 medal will be allowed to be given per mission.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tName of medal to grant to player." },

	{ OP_GOOD_SECONDARY_TIME, "Set preferred secondary weapons\r\n"
		"\tThis sexpression is used to inform the AI about preferred secondary weapons to "
		"fire during combat.  When this expression is evaluated, any AI ships of the given "
		"team prefer to fire the given weapon at the given ship. (Preferred over other "
		"secondary weapons)\r\n\r\n"
		"Takes 4 argument...\r\n"
		"\t1:\tTeam name which will prefer firing given weapon\r\n"
		"\t2:\tMaximum number of this type of weapon above team can fire.\r\n"
		"\t3:\tWeapon name (list includes only the valid weapons for this expression\r\n"
		"\t4:\tShip name at which the above named team should fire the above named weapon." },

	{ OP_AND_IN_SEQUENCE, "And in sequence (Boolean operator)\r\n"
		"\tReturns true if all of its arguments have become true in the order they are "
		"listed in.\r\n\r\n"
		"Returns a boolean value.  Takes 2 or more boolean arguments." },

	{ OP_SKILL_LEVEL_AT_LEAST, "Skill level at least (Boolean operator)\r\n"
		"\tReturns true if the player has selected the given skill level or higher.\r\n\r\n"
		"Returns a boolean value.  Takes 1 argument...\r\n"
		"\t1:\tName of the skill level to check." },

	{ OP_NUM_PLAYERS, "Num players (Status operator)\r\n"
		"\tReturns the current number of players (multiplayer) playing in the current mission.\r\n\r\n"
		"Returns a numeric value.  Takes no arguments." },

	{ OP_IS_CARGO_KNOWN, "Is cargo known (Boolean operator)\r\n"
		"\tReturns true if all of the specified objects' cargo is known by the player (i.e. they "
		"have scanned each one.\r\n\r\n"
		"Returns a boolean value.  Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ship to check if its cargo is known." },

	{ OP_HAS_BEEN_TAGGED_DELAY, "Has ship been tagged (delay) (Boolean operator)\r\n"
		"\tReturns true if all of the specified ships have been tagged.\r\n\r\n"
		"Returns a boolean value after <delay> seconds when all ships have been tagged.  Takes 2 or more arguments...\r\n"
		"\t1:\tDelay in seconds after which sexpression will return true when all cargo scanned."
		"\tRest:\tNames of ships to check if tagged.." },

	{ OP_ARE_SHIP_FLAGS_SET, "Are ship flags set (Boolean operator)\r\n"
		"\tReturns true if all of the specified flags have been set for this particular ship.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tName of the ship."
		"\tRest:\tShip, object or ai flags which might be set for this ship.." },

	{ OP_CAP_SUBSYS_CARGO_KNOWN_DELAY, "Is capital ship subsystem cargo known (delay) (Boolean operator)\r\n"
		"\tReturns true if all of the specified subsystem cargo is known by the player.\r\n"
		"\tNote: Cargo must be explicitly named.\r\n\r\n"
		"Returns a boolean value after <delay> seconds when all cargo is known.  Takes 3 or more arguments...\r\n"
		"\t1:\tDelay in seconds after which sexpression will return true when all cargo scanned.\r\n"
		"\t2:\tName of capital ship\r\n"
		"\tRest:\tNames of subsystems to check for cargo known.." },

	{ OP_CARGO_KNOWN_DELAY, "Is cargo known (delay) (Boolean operator)\r\n"
		"\tReturns true if all of the specified objects' cargo is known by the player (i.e. they "
		"have scanned each one.\r\n\r\n"
		"Returns a boolean value after <delay> seconds when all cargo is known.  Takes 2 or more arguments...\r\n"
		"\t1:\tDelay in seconds after which sexpression will return true when all cargo scanned."
		"\tRest:\tNames of ships/cargo to check for cargo known.." },

	{ OP_WAS_PROMOTION_GRANTED, "Was promotion granted (Boolean operator)\r\n"
		"\tReturns true if a promotion was granted via the 'Grant promotion' operator in the mission.\r\n\r\n"
		"Returns a boolean value.  Takes no arguments." },

	{ OP_WAS_MEDAL_GRANTED, "Was medal granted (Boolean operator)\r\n"
		"\tReturns true if a medal was granted via via the 'Grant medal' operator in the mission.  "
		"If you provide the optional argument to this operator, then true is only returned if the "
		"specified medal was granted.\r\n\r\n"
		"Returns a boolean value.  Takes 0 or 1 arguments...\r\n"
		"\t1:\tName of medal to specifically check for (optional)." },

	{ OP_GOOD_REARM_TIME, "Good rearm time (Action operator)\r\n"
		"\tInforms the game logic that right now is a good time for a given team to attempt to "
		"rearm their ships.  The time parameter specified how long the \"good time\" will last.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tTeam Name\r\n"
		"\t2:\tTime in seconds rearm window should last" },

	{ OP_ALLOW_SHIP, "Allow ship (Action operator)\r\n"
		"\tThis operator makes the given ship type available to the Terran team.  Players will be "
		"able to have ships of this type in their starting wings in all future missions of this "
		"campaign.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tName of ship type (or ship class) to allow." },

	{ OP_ALLOW_WEAPON, "Allow weapon (Action operator)\r\n"
		"\tThis operator makes the given weapon available to the Terran team.  Players will be "
		"able to equip ships with in all future missions of this campaign.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tName of weapon (primary or secondary) to allow." },

	{ OP_TECH_ADD_SHIP, "Tech add ship (Action operator)\r\n"
		"\tThis operator makes the given ship type available in the techroom database.  Players will "
		"then be able to view this ship's specs there.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ship type (or ship class) to add." },

	{ OP_TECH_ADD_WEAPON, "Tech add weapon (Action operator)\r\n"
		"\tThis operator makes the given weapon available in the techroom database.  Players will "
		"then be able to view this weapon's specs there.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of weapon (primary or secondary) to add." },

	{ OP_TECH_ADD_INTEL, "Tech add intel (Action operator, deprecated in favor of tech-add-intel-xstr)\r\n"
		"\tThis operator makes the given intel entry available in the techroom database.  Players will "
		"then be able to view this intel entry there.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of intel entry to add." },

	{ OP_TECH_ADD_INTEL_XSTR, "Tech add intel XSTR (Action operator)\r\n"
		"\tThis operator makes the given intel entry available in the techroom database.  Players will "
		"then be able to view this intel entry there.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tName of intel entry to add.\r\n"
		"\t2:\tXSTR ID of intel entry, or -1 if there is no XSTR entry.\r\n"
		"Use Add-Data for multiple entries.\r\n\r\n"
		"IMPORTANT: Each additional entry in the list MUST HAVE two fields; "
		"any entry without both fields will be ignored, as will any successive entries." },

	{ OP_TECH_RESET_TO_DEFAULT, "Tech reset to default (Action operator)\r\n"
		"\tThis operator resets the tech room to the default represented in the tables.  This is "
		"useful for starting new campaigns, so that the player will not see tech entries carried over "
		"from previous campaigns.\r\n\r\n"
		"Takes no arguments." },

	{ OP_CHANGE_PLAYER_SCORE, "Change Player Score (Action operator)\r\n"
		"\tThis operator allows direct alteration of the player's score for this mission.\r\n\r\n"
		"Takes 2 or more arguments." 
		"\t1:\tAmount to alter the player's score by.\r\n"
		"\tRest:\tName of ship the player is flying."},

	{ OP_CHANGE_TEAM_SCORE, "Change Team Score (Action operator)\r\n"
		"\tThis operator allows direct alteration of the team's score for a TvT mission (Does nothing otherwise).\r\n\r\n"
		"Takes 2 arguments." 
		"\t1:\tAmount to alter the team's score by.\r\n"
		"\t2:\tThe team to alter the score for. (0 will add the score to all teams!)"},

	{ OP_AI_EVADE_SHIP, "Ai-evade ship (Ship goal)\r\n"
		"\tCauses the specified ship to go into evade mode and run away like the weak "
		"sally-boy it is.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of ship to evade from.\r\n"
		"\t2:\tGoal priority (number between 0 and 89)." },

	{ OP_AI_STAY_NEAR_SHIP, "Ai-stay near ship (Ship goal)\r\n"
		"\tCauses the specified ship to keep itself near the given ship and not stray too far "
		"away from it.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of ship to stay near.\r\n"
		"\t2:\tGoal priority (number between 0 and 89)." },

	{ OP_AI_KEEP_SAFE_DISTANCE, "Ai-keep safe distance (Ship goal)\r\n"
		"\tTells the specified ship to stay a safe distance away from any ship that isn't on the "
		"same team as it.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tGoal priority (number between 0 and 89)." },

	{ OP_AI_IGNORE, "Ai-ignore (Ship goal)\r\n"
		"\tTells all ships to ignore the given ship and not consider it as a valid "
		"target to attack.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of ship to ignore.\r\n"
		"\t2:\tGoal priority (number between 0 and 89)." },

	// Goober5000
	{ OP_AI_IGNORE_NEW, "Ai-ignore-new (Ship goal)\r\n"
		"\tTells the specified ship to ignore the given ship and not consider it as a valid "
		"target to attack.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of ship to ignore.\r\n"
		"\t2:\tGoal priority (number between 0 and 89)." },

	{ OP_AI_STAY_STILL, "Ai-stay still (Ship goal)\r\n"
		"\tCauses the specified ship to stay still.  The ship will do nothing until attacked at "
		"which time the ship will come to life and defend itself.\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tShip or waypoint the ship staying still will directly face (currently not implemented)\r\n"
		"\t2:\tGoal priority (number between 0 and 89)." },

	{ OP_AI_PLAY_DEAD, "Ai-play dead (Ship goal)\r\n"
		"\tCauses the specified ship to pretend that it is dead and not do anything.  This "
		"expression should be used to indicate that a ship has no pilot and cannot respond "
		"to any enemy threats.  A ship playing dead will not respond to any attack.  This "
		"should really be named ai-is-dead\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tGoal priority (number between 0 and 89)." },

	{ OP_AI_FORM_ON_WING, "Ai-form-on-wing (Ship Goal)\r\n"
		"\tCauses the ship to form on the specified ship's wing. This works analogous to the "
		"player order, and will cause all other goals specified for the ship to be purged.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tShip to form on." },

	{ OP_FLASH_HUD_GAUGE, "Ai-flash hud gauge (Training goal)\r\n"
		"\tCauses the specified hud gauge to flash to draw the player's attention to it.\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tName of hud gauge to flash." },
		
	{ OP_ALTER_SHIP_FLAG, "alter-ship-flag\r\n"
		"\tSets a ships flag and/or parse flag.\r\n\r\n"
		"Takes 4 or more arguments...\r\n"
		"\t1:\tShip flag name\r\n"
		"\t2:\tTrue if turning on, false if turning off\r\n"
		"\t3:\tTrue\\False - Apply this flag to future waves of this wing. Apply to ship if not present\r\n"
		"\tRest:\t (optional) Name of ships, wings, or entire teams. If not supplied, will work on all ships in the mission\r\n\r\n"
		"Ship Flags:\r\n"
		"invulnerable - Stops ship from taking any damage\r\n"
		"protect-ship - Ship and Turret AI will ignore and not attack ship\r\n"
		"beam-protect-ship - Turrets with beam weapons will ignore and not attack ship\r\n"
		"no-shields - Ship will have no shields (ETS will be rebalanced if shields were off and are enabled)\r\n"
		"targetable-as-bomb - Allows ship to be targetted with the bomb targetting key\r\n"
		"flak-protect-ship - Turrets with flak weapons will ignore and not attack ship\r\n"
		"laser-protect-ship - Turrets with laser weapons will ignore and not attack ship\r\n"
		"missile-protect-ship - Turrets with missile weapons will ignore and not attack ship\r\n"
		"immobile - Will not let a ship move or rotate in any fashion\r\n"
		"vaporize - Causes a ship to vanish (no deathroll, no debris, no explosion) when destroyed\r\n"
		"break-warp - Causes a ship's subspace drive to break. Can be repaired by a support ship\r\n"
		"never-warp - Causes a ship's subspace drive to never work. Cannot be repaired by a support ship\r\n"
		"afterburner-locked - Will stop a ship from firing their afterburner\r\n"
		"primaries-locked - Will stop a ship from firing their primary weapons\r\n"
		"secondaries-locked - Will stop a ship from firing their secondary weapons\r\n"
		"no-subspace-drive - Will not allow a ship to jump into subspace\r\n"
		"don't-collide-invisible - Will cause polygons with an invisible texture to stop colliding with objects\r\n"
		"no-ets - Will not allow a ship to alter its ETS system\r\n"
		"toggle-subsystem-scanning - Switches between being able to scan a whole ship or individual subsystems\r\n"
		"scannable - Whether or not the ship can be scanned\r\n"
		"cargo-known - If set, the ships cargo can be seen without scanning the ship\r\n"
		"stealth - If set, the ship can't be targeted, is invisible on radar, and is ignored by AI unless firing\r\n"
		"friendly-stealth-invisible - If set, the ship can't be targeted even by ships on the same team\r\n"
		"hide-ship-name - If set, the ship name can't be seen when the ship is targeted\r\n"
		"hidden-from-sensors - If set, the ship can't be targeted and appears on radar as a blinking dot\r\n"
		"no-dynamic - Will stop allowing the AI to persue dynamic goals (eg: chasing ships it was not ordered to)\r\n"
		"no-secondary-lock-on - Will disable target acquisition for secondaries of all types (does not affect turrets)\r\n"},

	{ OP_SHIP_VISIBLE, "ship-visible\r\n"
		"\tCauses the ships listed in this sexpression to be visible with player sensors.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1+:\tName of ships to make visible to sensors." },

	{ OP_SHIP_INVISIBLE, "ship-invisible\r\n"
		"\tCauses the ships listed in this sexpression to be invisible to player sensors.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1+:\tName of ships to make invisible to sensors." },

	{ OP_SHIP_VULNERABLE, "ship-vulnerable\r\n"
		"\tCauses the ship listed in this sexpression to be vulnerable to weapons.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1+:\tName of ships to make vulnerable to weapons." },

	{ OP_SHIP_INVULNERABLE, "ship-invulnerable\r\n"
		"\tCauses the ships listed in this sexpression to be invulnerable to weapons.  Use with caution!!!!\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1+:\tName of ships to make invulnerable to weapons." },

	{ OP_SHIP_BOMB_TARGETABLE, "ship-targetable-as-bomb\r\n"
		"\tCauses the ships listed in this sexpression to be targetable with bomb targeting key.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1+:\tName of ships to make targetable with bomb targeting key." },

	{ OP_SHIP_BOMB_UNTARGETABLE, "ship-untargetable-as-bomb\r\n"
		"\tCauses the ships listed in this sexpression to not be targetable with bomb targeting key.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1+:\tName of ships to make nontargetable with bomb targeting key." },

	{ OP_SHIELDS_ON, "shields-on\r\n" //-Sesquipedalian
		"\tCauses the ship listed in this sexpression to have their shields activated.\r\n"
		"If the ship had no-shields prior to the sexp being called, the ETS will be rebalanced to default.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1+:\tName of ships to activate shields on." },

	{ OP_SHIELDS_OFF, "shields-off\r\n" //-Sesquipedalian
		"\tCauses the ships listed in this sexpression to have their shields deactivated.  \r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1+:\tName of ships to deactivate shields on." },

	{ OP_SHIP_GUARDIAN, "ship-guardian\r\n"
		"\tCauses the ships listed in this sexpression to not be killable by weapons.  Use with caution!!!!\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1+:\tName of ships to make unkillable." },

	{ OP_SHIP_NO_GUARDIAN, "ship-no-guardian\r\n"
		"\tCauses the ships listed in this sexpression to be killable by weapons, if not invulnerable.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1+:\tName of ships to make killable." },

	// Goober5000
 	{ OP_SHIP_GUARDIAN_THRESHOLD, "ship-guardian-threshold\r\n"
 		"\tSame as ship-guardian, except the lowest possible hull value is specified by the sexp rather than defaulting to 1.\r\n"
 		"Call with a threshold of 0 (or use ship-no-guardian) to deactivate.\r\n\r\n"
 		"Takes 2 or more arguments...\r\n"
 		"\t1:\tThreshold value.\r\n"
 		"\t2+:\tName of ships to make unkillable." },
 
 	// Goober5000
	{ OP_SHIP_SUBSYS_GUARDIAN_THRESHOLD, "ship-subsys-guardian-threshold\r\n"
		"\tSame as ship-guardian-threshold, but works on subsystems.\r\n"
		"Call with a threshold of 0 to deactivate.\r\n\r\n"
 		"Takes 3 or more arguments...\r\n"
		"\t1:\tThreshold value.\r\n"
		"\t2:\tShip housing the subsystem(s).\r\n"
		"\t3+:\tSubsystems to make unkillable." },

	// Goober5000
	{ OP_SHIP_STEALTHY, "ship-stealthy\r\n"
		"\tCauses the ships listed in this sexpression to become stealth ships (i.e. invisible to radar).\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ships to make stealthy." },

	// Goober5000
	{ OP_SHIP_UNSTEALTHY, "ship-unstealthy\r\n"
		"\tCauses the ships listed in this sexpression to become non-stealth ships (i.e. visible to radar).\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ships to make non-stealthy." },

	// Goober5000
	{ OP_FRIENDLY_STEALTH_INVISIBLE, "friendly-stealth-invisible\r\n"
		"\tCauses the friendly ships listed in this sexpression to be invisible to radar, just like hostile stealth ships."
		"It doesn't matter if the ship is friendly at the time this sexp executes: as long as it is a stealth ship, it will"
		"be invisible to radar both as hostile and as friendly.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ships" },

	// Goober5000
	{ OP_FRIENDLY_STEALTH_VISIBLE, "friendly-stealth-visible\r\n"
		"\tCauses the friendly ships listed in this sexpression to resume their normal behavior of being visible to radar as"
		"stealth friendlies.  Does not affect their visibility as stealth hostiles.\r\n\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tName of ships" },

	// Goober5000
	{ OP_SHIP_SUBSYS_TARGETABLE, "ship-subsys-targetable\r\n"
		"\tCauses the specified ship subsystem(s) to be targetable on radar.\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tName of a ship\r\n"
		"\tRest: Name of the ship's subsystem(s)" },

	// Goober5000
	{ OP_SHIP_SUBSYS_UNTARGETABLE, "ship-subsys-untargetable\r\n"
		"\tCauses the specified ship subsystem(s) to not be targetable on radar.\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tName of a ship\r\n"
		"\tRest: Name of the ship's subsystem(s)" },

	// FUBAR
	{ OP_SHIP_SUBSYS_NO_REPLACE, "ship-subsys-no-replace\r\n"
		"\tCauses the -destroyed version of specified ship subsystem(s) to not render when it's destroyed.\r\n"
		"Takes 3 or more arguments...\r\n"
		"\t1:\tName of a ship\r\n"
		"\t2:\tTrue = Do not render or False = render if exists\r\n"
		"\tRest: Name of the ship's subsystem(s)" 
		"\tNote: If subsystem is already dead it will vanish or reappear out of thin air" },


	// FUBAR
	{ OP_SHIP_SUBSYS_NO_LIVE_DEBRIS, "ship-subsys-no-live-debris\r\n"
		"\tCauses the specified ship subsystem(s) to not render live debris when it's destroyed.\r\n"
		"Takes 3 or more arguments...\r\n"
		"\t1:\tName of a ship\r\n"
		"\t2:\tTrue = Do not render or False = render if exists\r\n"
		"\tRest: Name of the ship's subsystem(s)" },

	// FUBAR
	{ OP_SHIP_SUBSYS_VANISHED, "ship-subsys-vanish\r\n"
		"\tCauses the subsystem to vanish without a trace - no fanfare, notification, or special effects.  See also ship-vanish.\r\n"
		"\tSingle Player Only!  Warning: This will cause subsystem destruction not to be logged, so 'has-departed', etc. will not work\r\n"
		"Takes 3 or more arguments...\r\n"
		"\t1:\tName of a ship\r\n"
		"\t2:\tTrue = vanish or False = don't vanish\r\n"
		"\tRest: Name of the ship's subsystem(s)" 
		"\tNote: Useful for replacing subsystems with actual docked models." },

	// FUBAR
	{ OP_SHIP_SUBSYS_IGNORE_IF_DEAD, "ship-subsys-ignore-if-dead\r\n"
		"\tCauses secondary weapons to ignore dead ship subsystem(s)and home on hull instead.\r\n"
		"Takes 3 or more arguments...\r\n"
		"\t1:\tName of a ship\r\n"
		"\t2:\tTrue = Ignore dead or False = don't ignore\r\n"
		"\tRest: Name of the ship's subsystem(s)" },

	// Goober5000
	{ OP_SHIP_CHANGE_ALT_NAME, "ship-change-alt-name\r\n"
		"\tChanges the alternate ship class name displayed in the HUD target window.  Takes 2 or more arguments...\r\n"
		"\t1:\tThe ship class name to display\r\n"
		"\tRest:\tThe ships to display the new class name" },

	// FUBAR
	{ OP_SHIP_CHANGE_CALLSIGN, "ship-change-callsign\r\n"
		"\tChanges the callsign of a ship.  Takes 2 or more arguments...\r\n"
		"\t1:\tThe callsign to display or empty to remove\r\n"
		"\tRest:\tThe ships to display the new callsign" },

	// Goober5000
	{ OP_SET_DEATH_MESSAGE, "set-death-message\r\n"
		"\tSets the message displayed when the specified players are killed.  Takes 1 or more arguments...\r\n"
		"\t1:\tThe message\r\n"
		"\tRest:\tThe players for whom this message is displayed (optional) (currently not implemented)" },

	{ OP_PERCENT_SHIPS_ARRIVED, "percent-ships-arrived\r\n"
		"\tBoolean function which returns true if the percentage of ships in the listed ships and wings "
		"which have arrived is greater or equal to the given percentage.  For wings, all ships of all waves "
		"are used for calculation for the total possible ships to arrive.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tPercentge of arriving ships at which this function will return true.\r\n"
		"\t2+:\tList of ships/wings whose arrival status should be determined." },

	{ OP_PERCENT_SHIPS_DEPARTED, "percent-ships-departed\r\n"
		"\tBoolean function which returns true if the percentage of ships in the listed ships and wings "
		"which have departed is greater or equal to the given percentage.  For wings, all ships of all waves "
		"are used for calculation for the total possible ships to depart.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tPercentge of departed ships at which this function will return true.\r\n"
		"\t2+:\tList of ships/wings whose departure status should be determined." },

	{ OP_PERCENT_SHIPS_DESTROYED, "percent-ships-destroyed\r\n"
		"\tBoolean function which returns true if the percentage of ships in the listed ships and wings "
		"which have been destroyed is greater or equal to the given percentage.  For wings, all ships of all waves "
		"are used for calculation for the total possible ships to be destroyed.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tPercentge of destroyed ships at which this function will return true.\r\n"
		"\t2+:\tList of ships/wings whose destroyed status should be determined." },

	// Goober5000
	{ OP_PERCENT_SHIPS_DISARMED, "percent-ships-disarmed\r\n"
		"\tBoolean function which returns true if the percentage of ships in the listed ships "
		"which have been disarmed is greater or equal to the given percentage.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tPercentge of disarmed ships at which this function will return true.\r\n"
		"\t2+:\tList of ships whose disarmed status should be determined." },

	// Goober5000
	{ OP_PERCENT_SHIPS_DISABLED, "percent-ships-disabled\r\n"
		"\tBoolean function which returns true if the percentage of ships in the listed ships "
		"which have been disabled is greater or equal to the given percentage.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tPercentge of disabled ships at which this function will return true.\r\n"
		"\t2+:\tList of ships whose disabled status should be determined." },

	{ OP_RED_ALERT, "red-alert\r\n"
		"\tCauses Red Alert status in a mission.  This function ends the current mission, and moves to "
		"the next mission in the campaign under red alert status.  There should only be one branch from "
		"a mission that uses this expression\r\n\r\n"
		"Takes no arguments."},

	{ OP_MISSION_SET_NEBULA, "mission-set-nebula\r\n" 
		"\tTurns nebula on/off\r\n"
		"\tTakes1 argument...\r\n"
		"\t1:\t0 for nebula off, 1 for nebula on" },

	{ OP_MISSION_SET_SUBSPACE, "mission-set-subspace\r\n"
		"\tTurns subspace on/off\r\n"
		"\tTakes 1 argument...\r\n"
		"\r1:\t0 for subspace off, 1 for subspace on" },

	//-Sesquipedalian
	{ OP_END_MISSION, "end-mission\r\n" 
		"\tEnds the mission as if the player had engaged his subspace drive, but without him doing so.  Dumps the player back into a normal debriefing.  Does not invoke red-alert status.\r\n"
		"\t1:\tEnd Mission even if the player is dead (optional; defaults to true)\r\n"
		"\t2:\tBoot the player out into the main hall instead of going to the debriefing (optional; defaults to false; not supported in multi)\r\n"
		"\t3:\tGo to the mainhall instead of starting the next mission (optional; defaults to false; not yet tested in multi)"
	},

	// Goober5000
	{ OP_SET_DEBRIEFING_TOGGLED, "set-debriefing-toggled\r\n"
		"\tSets or clears the \"toggle debriefing\" mission flag.  If set, the mission will have its debriefing turned off, unless it is a multiplayer dogfight mission, in which case its debriefing will be turned on.  Takes 1 argument.\r\n"
	},

	// Goober5000
	{ OP_FORCE_JUMP, "force-jump\r\n"
		"\tForces activation of the player's subspace drive, thus ending the mission.  Takes no arguments."
	},

	// Goober5000
	{ OP_SET_SCANNED, "set-scanned\r\n"
		"\tSets the cargo on the specified ship or ship subsystem as known or scanned.  Takes 1 or more arguments...\r\n"
		"\t1:\tName of a ship\r\n"
		"\tRest:\tName of a subsystem on that ship (optional)\r\n" },

	// Goober5000
	{ OP_SET_UNSCANNED, "set-unscanned\r\n"
		"\tSets the cargo on the specified ship or ship subsystem as unknown or unscanned.  Takes 1 or more arguments...\r\n"
		"\t1:\tName of a ship\r\n"
		"\tRest:\tName of a subsystem on that ship (optional)\r\n" },

	{ OP_DEPART_NODE_DELAY, "depart-node-delay\r\n"
		"\tReturns true N seconds after the listed ships depart, if those ships depart within the "
		"radius of the given jump node.  The delay value is given in seconds.\r\n\r\n"
		"Takes 3 or more arguments...r\n"
		"\t1:\tDelay in seconds after the last ship listed departed before this expression can return true.\r\n"
		"\t2:\tName of a jump node\r\n"
		"\t3+:\tList of ships to check for departure within radius of the jump node." },

	{ OP_DESTROYED_DEPARTED_DELAY, "destroyed-or-departed-delay\r\n"
		"\tReturns true N seconds after all the listed ships or wings have been destroyed or have "
		"departed.\r\n\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tDelay in seconds after the last ship/wing is destroyed or departed before this expression can return true.\r\n"
		"\t2+:\tName of a ship or wing" },

	// description added by Goober5000
	{ OP_SPECIAL_CHECK, "Special-check\r\n"
		"\tMike K.'s special training sexp.  Returns a boolean value.  Takes 1 argument as follows:\r\n"
		"\t0:    Ship \"Freighter 1\" is aspect locked by the player\r\n"
		"\t1:    Player has fired Interceptor#Weak at Freighter 1\r\n"
		"\t2:    Ship \"Freighter 1\", subsystem \"Weapons\" is aspect locked by the player\r\n"
		"\t3:    Apply 10 points of damage to player's forward shields (action operator)\r\n"
		"\t4:    Player's front shields are nearly gone\r\n"
		"\t5:    Quickly recharge player's front shields (action operator)\r\n"
		"\t6:    Reduce all shield quadrants except front to 0 (action operator)\r\n"
		"\t7:    Front shield quadrant is near maximum strength\r\n"
		"\t8:    Rear shield quadrant is near maximum strength\r\n"
		"\t9:    Reduce left and right shield quadrants to 0 (action operator)\r\n"
		"\t10:   Player has fewer than 8 missiles left\r\n"
		"\t11:   Player has 8 or more missiles left\r\n"
		"\t12:   Player has fewer than 4 missiles left\r\n"
		"\t13:   Reduce front shield quadrant to 0 (action operator)\r\n"
		"\t100:  Player is out of countermeasures\r\n"
		"\t2000: Training failed"
	},

	{ OP_END_CAMPAIGN, "end-campaign\r\n"
		"\tEnds the builtin campaign.  Should only be used by the main FreeSpace campaign\r\n"
		"\t1:\tEnd Campaign even if the player is dead (optional; defaults to true)\r\n" },

	{ OP_SHIP_VAPORIZE, "ship-vaporize\r\n"
		"\tSets the ship to vaporize when it is destroyed.  Does not actually destroy the ship - use self-destruct for that.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tList of ships on which to set the vaporize flag" },

	{ OP_SHIP_NO_VAPORIZE, "ship-no-vaporize\r\n"
		"\tSets the ship to not vaporize when it is destroyed.  Does not actually destroy the ship - use self-destruct for that.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tList of ships on which to unset the vaporize flag" },

	{ OP_DONT_COLLIDE_INVISIBLE, "don't-collide-invisible\r\n"
		"\tSets the \"don't collide invisible\" flag on a list of ships.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tList of ships on which to set the \"don't collide invisible\" flag" },

	{ OP_COLLIDE_INVISIBLE, "collide-invisible\r\n"
		"\tUnsets the \"don't collide invisible\" flag on a list of ships.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tList of ships on which to unset the \"don't collide invisible\" flag" },

	{ OP_SET_MOBILE, "set-mobile\r\n"
		"\tAllows the specified ship(s) to move.  Opposite of set-immobile.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tList of ships on which to unset the \"immobile\" flag" },

	{ OP_SET_IMMOBILE, "set-immobile\r\n"
		"\tPrevents the specified ship(s) from moving in any way.\r\n"
		"Takes 1 or more arguments...\r\n"
		"\tAll:\tList of ships on which to set the \"immobile\" flag" },

	{ OP_IGNORE_KEY, "ignore-key\r\n"
		"\tCauses the game to ignore (or stop ignoring) a certain key.\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1: Number of times to ignore this key (-1 = forever, 0 = stop ignoring). \r\n"
		"\tRest: Which key(s) to ignore.\r\n"
	},

	{ OP_WARP_BROKEN, "break-warp\r\n"
		"\tBreak the warp drive on the specified ship.  A broken warp drive can be repaired by "
		"a repair ship.  Takes 1 or more arguments...\r\n"
		"\tAll:\tList of ships to break the warp drive on" },

	{ OP_WARP_NOT_BROKEN, "fix-warp\r\n"
		"\tFixes a broken warp drive instantaneously.  This option applies to warp drives broken with "
		"the break-warp sepxression.  Takes 1 or more arguments...\r\n"
		"\tAll:\tList of ships whose warp drive should be fixed"},

	{ OP_WARP_NEVER, "never-warp\r\n"
		"\tNever allows a ship to warp out.  When this sexpression is used, the given ships will "
		"never be able to warp out.  The warp drive cannot be repaired.  Takes 1 or more arguments...\r\n"
		"\tAll:\tList of ships whose are not allowed to warp out under any condition"},

	{ OP_WARP_ALLOWED, "allow-warp\r\n"
		"\tAllows a ship which was previously not allowed to warp out to do so.  When this sexpression is "
		"used, the given ships will be able to warp out again.  Takes 1 or more arguments...\r\n"
		"\tAll:\tList of ships whose are allowed to warp out"},

	{ OP_SET_SUBSPACE_DRIVE, "set-subspace-drive\r\n"
		"\tTurns on or off the subspace edrive for the given ships.  A ship with no subspace drive will act "
		"as though it doesn't even occur to him to depart via subspace, and if ordered to do so, he will look "
		"for a friendly ship with a hangar bay.  If the ship is the player, pressing Alt-J will not not initiate "
		"a jump, nor give any indication that a jump failed.  Takes 2 or more arguments...\r\n"
		"\t1:\tTrue if the ship should have a drive; false otherwise\r\n"
		"\tRest:\tList of ships" },

	{ OP_JETTISON_CARGO, "jettison-cargo-delay\r\n"
		"\tCauses a cargo carrying ship to jettison its cargo without the undocking procedure.  Takes 2 or more arguments...\r\n"
		"\t1: Ship to jettison cargo\r\n"
		"\t2: Delay after which to jettison cargo (note that this isn't actually used)\r\n"
		"\tRest (optional): Cargo to jettison.  If no optional arguments are specified, the ship jettisons all cargo.\r\n"
	},

	{ OP_SET_DOCKED, "set-docked\r\n"
		"\tCauses one ship to become instantly docked to another at the specified docking ports.  Takes 4 arguments...\r\n"
		"\t1: Docker ship\r\n"
		"\t1: Docker point\r\n"
		"\t1: Dockee ship\r\n"
		"\t1: Dockee point\r\n"
	},

	{ OP_BEAM_FIRE, "fire-beam\r\n"
		"\tFire a beam weapon from a specified subsystem\r\n"
		"\t1:\tShip which will be firing\r\n"
		"\t2:\tTurret which will fire the beam (note, this turret must have at least 1 beam weapon on it)\r\n"
		"\t3:\tShip which will be targeted\r\n"
		"\t4:\tSubsystem to target (optional)\r\n"
		"\t5:\tWhether to force the beam to fire (disregarding FOV and subsystem status) (optional)\r\n" },

	{ OP_BEAM_FIRE_COORDS, "fire-beam-at-coordinates\r\n"
		"\tFire a beam weapon from a specified subsystem at a set of coordinates.  Not compatible with multiplayer.\r\n"
		"\t1:\tShip which will be firing\r\n"
		"\t2:\tTurret which will fire the beam (note, this turret must have at least 1 beam weapon on it)\r\n"
		"\t3:\tx coordinate to be targeted\r\n"
		"\t4:\ty coordinate to be targeted\r\n"
		"\t5:\tz coordinate to be targeted\r\n"
		"\t6:\t(Optional Operator) Whether to force the beam to fire (disregarding FOV and subsystem status). Defaults to False\r\n"
		"\t7:\tsecond x coordinate to be targeted (optional; only used for slash beams)\r\n"
		"\t8:\tsecond y coordinate to be targeted (optional; only used for slash beams)\r\n"
		"\t9:\tsecond z coordinate to be targeted (optional; only used for slash beams)\r\n" },

	{ OP_BEAM_FLOATING_FIRE, "beam-create\r\n"
		"\tFire a beam weapon from the specified coordinates to the specified target. Not compatible with multiplayer.\r\n"
		"\t1:\tBeam weapon to fire\r\n"
		"\t2:\tParent ship (for kill credit, if applicable; can be none)\r\n"
		"\t3:\tTeam for this beam to be on (related to difficulty-based damage)\r\n"
		"\t4:\tX coordinate to fire from\r\n"
		"\t5:\tY coordinate to fire from\r\n"
		"\t6:\tZ coordinate to fire from\r\n"
		"\t7:\tTarget ship (can be none)\r\n"
		"\t8:\tTarget subsystem (optional, can be none)\r\n"
		"\t9:\tX coordinate to fire at (optional)\r\n"
		"\t10:\tY coordinate to fire at (optional)\r\n"
		"\t11:\tZ coordinate to fire at (optional)\r\n"
		"\t12:\tSecond X coordinate to fire at (optional; used for slash beams)\r\n"
		"\t13:\tSecond Y coordinate to fire at (optional; used for slash beams)\r\n"
		"\t14:\tSecond Z coordinate to fire at (optional; used for slash beams)\r\n" },

	{ OP_IS_TAGGED, "is-tagged\r\n"
		"\tReturns whether a given ship is tagged or not\r\n"},

	{ OP_IS_PLAYER, "is-player\r\n"
		"\tReturns true if all the ships specified are currently under control of a player.\r\n"
		"\t1 \t(SinglePlayer) When true ships under AI control return false even if they are the player ship\r\n"
		"\t \t(Multiplayer) When true ships that are respawning return true if the player is still connected\r\n"
		"\tRest \tList of ships to test"},

	{ OP_NUM_KILLS, "num-kills\r\n"
		"\tReturns the # of kills a player has. The ship specified in the first field should be the ship the player is in.\r\n"
		"\tSo, for single player, this would be Alpha 1. For multiplayer, it can be any ship with a player in it. If, at any\r\n"
		"\ttime there is no player in a given ship, this sexpression will return 0"},

	{ OP_NUM_ASSISTS, "num-assists\r\n"
		"\tReturns the # of assists a player has. The ship specified in the first field should be the ship the player is in.\r\n"
		"\tSo, for single player, this would be Alpha 1. For multiplayer, it can be any ship with a player in it. If, at any\r\n"
		"\ttime there is no player in a given ship, this sexpression will return 0"},

	{ OP_SHIP_SCORE, "ship-score\r\n"
		"\tReturns the score a player has. The ship specified in the first field should be the ship the player is in.\r\n"
		"\tSo, for single player, this would be Alpha 1. For multiplayer, it can be any ship with a player in it. If, at any\r\n"
		"\ttime there is no player in a given ship, this sexpression will return 0"},

	{ OP_SHIP_DEATHS, "ship-deaths\r\n"
		"\tReturns the # times a ship that is a player start has died.\r\n"
		"\tThe ship specified in the first field should be the ship that could have a player in.it\r\n"
		"\tOnly really useful for multiplayer."},

	{ OP_RESPAWNS_LEFT, "respawns-left\r\n"
		"\tReturns the # respawns a player (or AI that could have been a player) has remaining.\r\n"
		"\tThe ship specified in the first field should be the player start.\r\n"
		"\tOnly really useful for multiplayer."},

	{ OP_REMOVE_WEAPONS, "remove-weapons\r\n"
		"\tRemoves all live weapons currently in the game"
		"\t1: (Optional) Remove only this specific weapon\r\n"},

	{ OP_SET_RESPAWNS, "set-respawns\r\n"
		"\tSet the # respawns a player (or AI that could have been a player) has used.\r\n"
		"\t1: Number of respawns used up\r\n"
		"\tRest: The player start ship to operate on.\r\n"
		"\tOnly really useful for multiplayer."},

	{ OP_NUM_TYPE_KILLS, "num-type-kills\r\n"
		"\tReturns the # of kills a player has on a given ship type (fighter, bomber, cruiser, etc).\r\n"
		"The ship specified in the first field should be the ship the player is in.\r\n"
		"\tSo, for single player, this would be Alpha 1. For multiplayer, it can be any ship with a player in it. If, at any\r\n"
		"\ttime there is no player in a given ship, this sexpression will return 0"},

	{ OP_NUM_CLASS_KILLS, "num-class-kills\r\n"
		"\tReturns the # of kills a player has on a specific ship class (Ulysses, Hercules, etc).\r\n"
		"The ship specified in the first field should be the ship the player is in.\r\n"
		"\tSo, for single player, this would be Alpha 1. For multiplayer, it can be any ship with a player in it. If, at any\r\n"
		"\ttime there is no player in a given ship, this sexpression will return 0"},	

	{ OP_BEAM_FREE, "beam-free\r\n"
		"\tSets one or more beam weapons to allow firing for a given ship\r\n"
		"\t1: Ship to be operated on\r\n"
		"\t2, 3, etc : List of turrets to activate\r\n"},

	{ OP_BEAM_FREE_ALL, "beam-free-all\r\n"
		"\tSets all beam weapons on the specified ship to be active\r\n"},

	{ OP_BEAM_LOCK, "beam-lock\r\n"
		"\tSets one or more beam weapons to NOT allow firing for a given ship\r\n"
		"\t1: Ship to be operated on\r\n"
		"\t2, 3, etc : List of turrets to deactivate\r\n"},

	{ OP_BEAM_LOCK_ALL, "beam-lock-all\r\n"
		"\tSets all beam weapons on the specified ship to be deactivated\r\n"},

	{ OP_TURRET_FREE, "turret-free\r\n"
		"\tSets one or more turret weapons to allow firing for a given ship\r\n"
		"\t1: Ship to be operated on\r\n"
		"\t2, 3, etc : List of turrets to activate\r\n"},

	{ OP_TURRET_FREE_ALL, "turret-free-all\r\n"
		"\tSets all turret weapons on the specified ship to be active\r\n"},

	{ OP_TURRET_LOCK, "turret-lock\r\n"
		"\tSets one or more turret weapons to NOT allow firing for a given ship\r\n"
		"\t1: Ship to be operated on\r\n"
		"\t2, 3, etc : List of turrets to deactivate\r\n"},

	{ OP_TURRET_LOCK_ALL, "turret-lock-all\r\n"
		"\tSets all turret weapons on the specified ship to be deactivated\r\n"},

	{ OP_TURRET_CHANGE_WEAPON, "turret-change-weapon\r\n"
		"\tSets a given turret weapon slot to the specified weapon\r\n"
		"\t1: Ship turret is on\r\n"
		"\t2: Turret\r\n"
		"\t3: Weapon to set slot to\r\n"
		"\t4: Primary slot (or 0 to use secondary)\r\n"
		"\t5: Secondary slot (or 0 to use primary)"},

	{ OP_TURRET_SET_DIRECTION_PREFERENCE, "turret-set-direction-preference\r\n"
		"\tSets specified ship turrets direction preference to the specified value\r\n"
		"\t1: Ship turrets are on\r\n"
		"\t2: Preference to set, 0 to disable, or negative to reset to default\r\n"
		"\trest: Turrets to set\r\n"},

	{ OP_TURRET_SET_RATE_OF_FIRE, "turret-set-rate-of-fire\r\n"
		"\tSets specified ship turrets rate of fire to the specified value\r\n"
		"\t1: Ship turrets are on\r\n"
		"\t2: Rate to set in percentage format (200 = 2x, 50 = .5x), 0 to set to number of fire points, or negative to reset to default\r\n"
		"\trest: Turrets to set\r\n"},

	{ OP_TURRET_SET_OPTIMUM_RANGE, "turret-set-optimum-range\r\n"
		"\tSets specified ship turrets optimum range to the specified value\r\n"
		"\t1: Ship turrets are on\r\n"
		"\t2: Priority to set, 0 to disable, or negative to reset to default\r\n"
		"\trest: Turrets to set\r\n"},

	{ OP_TURRET_SET_TARGET_PRIORITIES, "turret-set-target-priorities\r\n"
		"\tSets target priorities for the specified ship turret\r\n"
		"\t1: Ship turret is on\r\n"
		"\t2: Turret to set\r\n"
		"\t3: True = Set new list, False = Reset to turret default\r\n"
		"\trest: Priorities to set (max 32) or blank for no priorities\r\n"},

	{ OP_TURRET_GET_PRIMARY_AMMO, "turret-get-primary-ammo\r\n"
		"\tGets the turret's primary bank ammo, only works with ballistic weapons\r\n"
		"\t1: Ship turret is on\r\n"
		"\t2: Turret the bank is on\r\n"
		"\t3: Bank to check ammo\r\n"},

	{ OP_TURRET_GET_SECONDARY_AMMO, "turret-get-secondary-ammo\r\n"
		"\tGets the turret's secondary bank ammo\r\n"
		"\t1: Ship turret is on\r\n"
		"\t2: Turret to check ammo\r\n"
		"\t3: Bank to check ammo\r\n" },

	{ OP_TURRET_SET_PRIMARY_AMMO, "turret-set-primary-ammo\r\n"
		"\tSets the turret's primary bank ammo, only works with ballistic weapons\r\n"
		"\t1: Ship turret is on\r\n"
		"\t2: Turret the bank is on\r\n"
		"\t3: Bank to add ammo to\r\n" 
		"\t4: Amount to add" },

	{ OP_TURRET_SET_SECONDARY_AMMO, "turret-set-secondary-ammo\r\n"
		"\tSets the turret's secondary bank ammo\r\n"
		"\t1: Ship turret is on\r\n"
		"\t2: Turret the bank is on\r\n"
		"\t3: Bank to add ammo to\r\n"
		"\t4: Amount to add" },

	{ OP_SET_ARMOR_TYPE, "set-armor-type\r\n"
		"\tSets the armor type for a ship or subsystem\r\n"
		"\t1: Ship subsystem is on\r\n"
		"\t2: Set = true/Reset to defualt = false\r\n"
		"\t3: Armor type to set or <none>\r\n"
		"\trest: Subsystems to set (hull for ship, shield for shields)\r\n"},

	{ OP_WEAPON_SET_DAMAGE_TYPE, "weapon-set-damage-type\r\n"
		"\tSets the damage type for weapons or their shockwaves\r\n"
		"\t1: True = set weapon, False = set shockwave\r\n"
		"\t2: damage type to set or <none>\r\n"
		"\t3: Set = true/Reset to defualt = false\r\n"
		"\trest: Weapons to set\r\n"},

	{ OP_SHIP_SET_DAMAGE_TYPE, "ship-set-damage-type\r\n"
		"\tSets the damage type for ships collision or debris\r\n"
		"\t1: true = set collision, False = set debris\r\n"
		"\t2: Damage type to set or <none>\r\n"
		"\t3: Set = true/Reset to defualt = false\r\n"
		"\trest: Ships to set\r\n"},

	{ OP_SHIP_SHOCKWAVE_SET_DAMAGE_TYPE, "ship-set-shockwave-damage-type\r\n"
		"\tSets the shockwave damage type for a class of ship.  All ships of that class are changed.\r\n"
		"\t1: Damage type to set or <none>\r\n"
		"\t2: Set = true/Reset to defualt = false\r\n"
		"\trest: Ship classes to set\r\n"},

	{ OP_FIELD_SET_DAMAGE_TYPE, "field-set-damage-type\r\n"
		"\tSets the damage type for asteroid/debris fields\r\n"
		"\t1: Damage type to set or <none>\r\n"
		"\t2: Set = true/Reset to defualt = false\r\n"},

	{ OP_TURRET_SET_TARGET_ORDER, "turret-set-target-order\r\n"
		"\tSets targeting order of a given turret\r\n"
		"\t1: Ship turret is on\r\n"
		"\t2: Turret\r\n"
		"\trest: Target order type (Bombs,ships,asteroids)"},

	{ OP_SHIP_TURRET_TARGET_ORDER, "ship-turret-target-order\r\n"
		"\tSets targeting order of all turrets on a given ship\r\n"
		"\t1: Ship turrets are on\r\n"
		"\trest: Target order type (Bombs,ships,asteroids)"},

	{ OP_TURRET_SUBSYS_TARGET_DISABLE, "turret-subsys-target-disable\r\n"
		"\tPrevents turrets from targeting only the subsystems when targeting large targets\r\n"
		"\t1: Ship to be operated on\r\n"
		"\trest: List of turrets that are affected\r\n"},

	{ OP_TURRET_SUBSYS_TARGET_ENABLE, "turret-subsys-target-enable\r\n"
		"\tSets turret to target the subsystems when targeting large targets\r\n"
		"\t1: Ship to be operated on\r\n"
		"\trest: List of turrets that are affected\r\n"},

	{ OP_ADD_REMOVE_ESCORT, "add-remove-escort\r\n"
		"\tAdds or removes a ship from an escort list.\r\n"
		"\t1: Ship to be added or removed\r\n"
		"\t2: 0 to remove from the list, any positive value will be used as the escort priority\r\n"
		"NOTE : it _IS_ safe to add a ship which may already be on the list or remove\r\n"
		"a ship which is not on the list\r\n"},

	{ OP_AWACS_SET_RADIUS, "awacs-set-radius\r\n"
		"\tSets the awacs radius for a given ship subsystem. NOTE : does not work properly in multiplayer\r\n"
		"\t1: Ship which has the awacs subsystem\r\n"
		"\t2: Awacs subsystem\r\n"
		"\t3: New radius\r\n"},

	// Goober5000
	{ OP_PRIMITIVE_SENSORS_SET_RANGE, "primitive-sensors-set-range\r\n"
		"\tSets the range of the primitive sensors on a ship.  Ships outside of this range will not appear on "
		"sensors.  Has no effect on ships that do not have the \"primitive-sensors\" flag2 set.  Takes 2 arguments...\r\n"
		"\t1: Ship on which to set range\r\n"
		"\t2: Range, in meters\r\n" },

	{ OP_SEND_MESSAGE_LIST, "send-message-list\r\n"
		"\tSends a series of delayed messages. All times are accumulated.\r\n"
		"\t1:\tName of who the message is from.\r\n"
		"\t2:\tPriority of message (\"Low\", \"Normal\" or \"High\").\r\n"
		"\t3:\tName of message (from message editor).\r\n"
		"\t4:\tDelay from previous message in list (if any) in ms\r\n"
		"Use Add-Data for multiple messages.\r\n\r\n"
		"IMPORTANT: Each additional message in the list MUST HAVE four entries; "
		"any message without the four proper fields will be ignored, as will any "
		"successive messages."},

	{ OP_CAP_WAYPOINT_SPEED, "cap-waypoint-speed\r\n"
		"\tSets the maximum speed of a ship while flying waypoints.\r\n"
		"\t1: Ship name\r\n"
		"\t2: Maximum speed while flying waypoints\r\n"
		"\tNOTE: This will only work if the ship is already in the game\r\n"
		"\tNOTE: Set to -1 to reset\r\n"},

	{ OP_TURRET_TAGGED_ONLY_ALL, "turret-tagged-only\r\n"
		"\tMakes turrets target and hence fire strictly at tagged objects\r\n"
		"\t1: Ship name\r\n"
		"\tNOTE: Will not stop a turret already firing at an untagged ship\r\n"},

	{ OP_TURRET_TAGGED_CLEAR_ALL, "turret-tagged-clear\r\n"
		"\tRelaxes restriction on turrets targeting only tagged ships\r\n"
		"\t1: Ship name\r\n"},

	{ OP_PRIMARIES_DEPLETED, "primaries-depleted\r\n"
		"\tReturns true if ship is out of primary weapons\r\n"
		"\t1: Ship name\r\n"},

	{ OP_SECONDARIES_DEPLETED, "secondaries-depleted\r\n"
		"\tReturns true if ship is out of secondary weapons\r\n"
		"\t1: Ship name\r\n"},

	{ OP_SUBSYS_SET_RANDOM, "subsys-set-random\r\n"
		"\tSets ship subsystem strength in a given range\r\n"
		"\t1: Ship name\r\n"
		"\t2: Low range\r\n"
		"\t3: High range\r\n"
		"\t4: List of subsys names not to be randomized\r\n"},

	{ OP_SUPERNOVA_START, "supernova-start\r\n"
		"\t1: Time in seconds until the supernova shockwave hits the player\r\n"},

	{ OP_SUPERNOVA_STOP, "supernova-stop\r\n"
		"\t Stops a supernova in progress.\r\n"
		"\t Note this only works if the camera hasn't cut to the player's death animation yet.\r\n"},

	{ OP_WEAPON_RECHARGE_PCT, "weapon-recharge-pct\r\n"
		"\tReturns a percentage from 0 to 100\r\n"
		"\t1: Ship name\r\n" },

	{ OP_SHIELD_RECHARGE_PCT, "shield-recharge-pct\r\n"
		"\tReturns a percentage from 0 to 100\r\n"
		"\t1: Ship name\r\n" },

	{ OP_ENGINE_RECHARGE_PCT, "engine-recharge-pct\r\n"
		"\tReturns a percentage from 0 to 100\r\n"
		"\t1: Ship name\r\n" },

	{ OP_GET_ETS_VALUE, "get-ets-value\r\n"
		"\tGets one ETS index for a ship\r\n"
		"\t1: ETS index to get, Engine|Shield|Weapon\r\n"
		"\t2: Ship name\r\n"},

	{ OP_SET_ETS_VALUES, "set-ets-values\r\n"
		"\tSets ETS indexes for a ship\r\n"
		"\tUse values retrieved with get-ets-value\r\n"
		"\tIf you use your own values, make sure they add up to 12\r\n"
		"\t1: Engine percent\r\n"
		"\t2: Shields percent\r\n"
		"\t3: Weapons percent\r\n"
		"\t4: Ship name\r\n"},

	{ OP_CARGO_NO_DEPLETE, "cargo-no-deplete\r\n"
		"\tCauses the named ship to have unlimited cargo.\r\n"
		"\tNote:  only applies to BIG or HUGE ships\r\n"
		"Takes 1 or more arguments...\r\n"
		"\t1:\tName of one of the ships.\r\n"
		"\t2:\toptional: 1 disallow depletion, 0 allow depletion." },

	{ OP_SHIELD_QUAD_LOW, "shield-quad-low\r\n"
		"\tReturns true if the specified ship has a shield quadrant below\r\n"
		"\tthe specified threshold percentage\r\n"
		"\t1: Ship name\r\n"
		"\t2: Percentage\r\n" },

	{ OP_PRIMARY_AMMO_PCT, "primary-ammo-pct\r\n"
		"\tReturns the percentage of ammo remaining in the specified ballistic primary bank (0 to 100).  Non-ballistic primary banks return as 100%.\r\n"
		"\t1: Ship name\r\n"
		"\t2: Bank to check (from 0 to N-1, where N is the number of primary banks in the ship; N or higher will return the cumulative average for all banks)" },

	// Karajorma
	{ OP_GET_PRIMARY_AMMO, "get-primary-ammo\r\n"
		"\tReturns the amount of ammo remaining in the specified bank\r\n"
		"\t1: Ship name\r\n"
		"\t2: Bank to check (from 0 to N-1, where N is the number of primary banks in the ship; N or higher will return the cumulative total for all banks)" },

	
	{ OP_SECONDARY_AMMO_PCT, "secondary-ammo-pct\r\n"
		"\tReturns the percentage of ammo remaining in the specified bank (0 to 100)\r\n"
		"\t1: Ship name\r\n"
		"\t2: Bank to check (from 0 to N-1, where N is the number of secondary banks in the ship; N or higher will return the cumulative average for all banks)" },

	// Karajorma
	{ OP_GET_SECONDARY_AMMO, "get-secondary-ammo\r\n"
		"\tReturns the amount of ammo remaining in the specified bank\r\n"
		"\t1: Ship name\r\n"
		"\t2: Bank to check (from 0 to N-1, where N is the number of secondary banks in the ship; N or higher will return the cumulative total for all banks)" },

	// Karajorma
	{ OP_GET_NUM_COUNTERMEASURES, "get-num-countermeasures\r\n"
		"\tReturns the amount of countermeasures remaining\r\n"
		"\t1: Ship name\r\n" },

	{ OP_IS_SECONDARY_SELECTED, "is-secondary-selected\r\n"
		"\tReturns true if the specified bank is selected\r\n"
		"\t1: Ship name\r\n"
		"\t2: Bank to check (This is a zero-based index. The first bank is numbered 0.)\r\n"},

	{ OP_IS_PRIMARY_SELECTED, "is-primary-selected\r\n"
		"\tReturns true if the specified bank is selected\r\n"
		"\t1: Ship name\r\n"
		"\t2: Bank to check (This is a zero-based index. The first bank is numbered 0.)\r\n"},

	{ OP_SPECIAL_WARP_DISTANCE, "special-warp-dist\r\n"
		"\tReturns distance to the plane of the knossos device in percent length of ship\r\n"
		"\t(ie, 100 means front of ship is 1 ship length from plane of knossos device)\r\n"
		"\t1: Ship name\r\n"}, 

	{ OP_SET_SPECIAL_WARPOUT_NAME, "special-warpout-name\r\n"
		"\tSets the name of the knossos device to be used for warpout\r\n"
		"\t1: Ship name to exit\r\n"
		"\t2: Name of knossos device\r\n"},

	{ OP_SHIP_VANISH, "ship-vanish\r\n"
		"\tMakes the named ship vanish (no log and vanish)\r\n"
		"\tSingle Player Only!  Warning: This will cause ship exit not to be logged, so 'has-departed', etc. will not work\r\n"
		"\t1: List of ship names to vanish\r\n"},

	{ OP_DESTROY_INSTANTLY, "destroy-instantly\r\n"
		"\tSelf-destructs the named ship without explosion, death roll, or debris.  That is, the ship is instantly gone from the mission and the only indication of what happened is a mission log entry.\r\n"
		"\tSingle Player Only! Non-player ship only!\r\n"
		"\tAll: List of ship names to destroy.\r\n"},

	{ OP_SHIP_CREATE, "ship-create\r\n"
		"\tCreates a new ship\r\n"
		"\tTakes 5 to 8 arguments...\r\n"
		"\t1: Name of new ship (use \"" SEXP_NONE_STRING "\" for a default name)\r\n"
		"\t2: Class of new ship\r\n"
		"\t3: X position\r\n"
		"\t4: Y position\r\n"
		"\t5: Z position\r\n"
		"\t6: Pitch (optional)\r\n"
		"\t7: Bank (optional)\r\n"
		"\t8: Heading (optional)\r\n"
	},

	// Goober5000
	{ OP_WEAPON_CREATE, "weapon-create\r\n"
		"\tCreates a new weapon\r\n"
		"\tTakes 5 to 10 arguments...\r\n"
		"\t 1: Name of parent ship (or \"" SEXP_NONE_STRING "\" for no parent)\r\n"
		"\t 2: Class of new weapon\r\n"
		"\t 3: X position\r\n"
		"\t 4: Y position\r\n"
		"\t 5: Z position\r\n"
		"\t 6: Pitch (optional)\r\n"
		"\t 7: Bank (optional)\r\n"
		"\t 8: Heading (optional)\r\n"
		"\t 9: Targeted ship (optional)\r\n"
		"\t10: Targeted subsystem (optional)\r\n"
	},

	{ OP_IS_SHIP_VISIBLE, "is-ship-visible\r\n"
		"\tCheck whether ship is visible on Player's radar\r\n"
		"\tSingle Player Only!  Returns 0 - not visible, 1 - partially visible, 2 - fully visible.\r\n"
		"\t1: Name of ship to check\r\n"},

	// Goober5000
	{ OP_IS_SHIP_STEALTHY, "is-ship-stealthy\r\n"
		"\tCheck whether ship is currently stealthy.\r\n"
		"\tTrue if stealth flag set, false otherwise.  Takes 1 argument...\r\n"
		"\t1: Name of ship to check\r\n"},

	// Goober5000
	{ OP_IS_FRIENDLY_STEALTH_VISIBLE, "is-friendly-stealth-visible\r\n"
		"\tCheck whether ship will be visible to radar as a stealth friendly.\r\n"
		"\tTakes 1 argument...\r\n"
		"\t1: Name of ship to check\r\n"},

	{ OP_TEAM_SCORE, "team-score\r\n"
		"\tGet the score of a multi team vs team game.\r\n"
		"\t1: Team index (1 for team 1 and 2 for team 2)\r\n"},

	// phreak
	{ OP_DAMAGED_ESCORT_LIST, "damaged-escort-list\r\n"
		"\tSets the most damaged ship in <ship list> to <priority1>, sets the others to <priority2>.  Don't use this sexp in the same mission as damaged-escort-list-all, or strange results might occur.\r\n"
		"\t1: Priority1\r\n"
		"\t2: Priority2\r\n"
		"\tRest: <ship_list>\r\n\r\n"
	},

	// Goober5000
	{ OP_DAMAGED_ESCORT_LIST_ALL, "damaged-escort-list-all\r\n"
		"\tSets the most damaged ship in the entire existing escort list (even what's not shown onscreen) to <priority1>, the next most damaged to <priority2>, and so on.  "
		"If there are more ships than priorities, the least most damaged ships are all set to the last priority in the list.  Don't use this sexp in the same mission as damaged-escort-list, or strange results might occur.\r\n"
		"\tTakes between 1 and MAX_COMPLETE_ESCORT_LIST (currently 20) arguments...\r\n"
		"\t1: Priority 1\r\n"
		"\tRest: Priorities 2 through 20 (optional)\r\n\r\n"
	},

	// Goober5000
	{ OP_CHANGE_SHIP_CLASS, "change-ship-class\r\n"
		"\tCauses the listed ships' classes to be changed to the specified ship class.  Takes 2 or more arguments...\r\n"
		"\t1: The name of the new ship class\r\n"
		"\tRest: The list of ships to change the classes of"
	},

	// Goober5000
	{ OP_SHIP_COPY_DAMAGE, "ship-copy-damage\r\n"
		"\tCopies the damage (hull, shields, and subsystems) from the first ship in the list to the rest.  The initial ship must be currently "
		"present in the mission, but the target ships may be either in-mission or on the arrival list.  Takes 2 or more arguments...\r\n"
		"\t1: The name of the ship that supplies the damage stats\r\n"
		"\tRest: The list of ships to be modified"
	},

	// Goober5000
	{ OP_SET_SUPPORT_SHIP, "set-support-ship\r\n"
		"\tSets information for all support ships in a mission.  Takes 6 or 7 arguments...\r\n"
		"\t1: Arrival location\r\n"
		"\t2: Arrival anchor\r\n"
		"\t3: Departure location\r\n"
		"\t4: Departure anchor\r\n"
		"\t5: Ship class\r\n"
		"\t6: Maximum number of support ships consecutively in this mission (use a negative number for infinity)\r\n"
		"\t7: Maximum number of support ships concurrently in this mission (optional, default 1)\r\n"
		"\r\n"
		"Note: The support ship will emerge from or depart into hyperspace if the location is set as hyperspace *or* the anchor is set as <no anchor>."
	},

	// Goober5000
	{ OP_SET_ARRIVAL_INFO, "set-arrival-info\r\n"
		"\tSets arrival information for a ship or wing.  Takes 2 to 7 arguments...\r\n"
		"\t1: Ship or wing name\r\n"
		"\t2: Arrival location\r\n"
		"\t3: Arrival anchor (optional; only required for certain locations)\r\n"
		"\t4: Arrival path mask (optional; this is a bitfield where the bits set to 1 correspond to the paths to use; defaults to 0 which is a special case that means all paths can be used)\r\n"
		"\t5: Arrival distance (optional; defaults to 0)\r\n"
		"\t6: Arrival delay (optional; defaults to 0)\r\n"
		"\t7: Whether to show a jump effect if arriving from subspace (optional; defaults to true)\r\n"
	},

	// Goober5000
	{ OP_SET_DEPARTURE_INFO, "set-departure-info\r\n"
		"\tSets departure information for a ship or wing.  Takes 2 to 6 arguments...\r\n"
		"\t1: Ship or wing name\r\n"
		"\t2: Departure location\r\n"
		"\t3: Departure anchor (optional; only required for certain locations)\r\n"
		"\t4: Departure path mask (optional; this is a bitfield where the bits set to 1 correspond to the paths to use; defaults to 0 which is a special case that means all paths can be used)\r\n"
		"\t5: Departure delay (optional; defaults to 0)\r\n"
		"\t6: Whether to show a jump effect if departing to subspace (optional; defaults to true)\r\n"
	},

	// Bobboau
	{ OP_DEACTIVATE_GLOW_POINTS, "deactivate-glow-points\r\n"
		"\tDeactivates all glow points on a ship.  Takes 1 or more arguments...\r\n"
		"\tAll: Name of ship on which to deactivate glow points\r\n"
	},

	// Bobboau
	{ OP_ACTIVATE_GLOW_POINTS, "activate-glow-points\r\n"
		"\tActivates all glow points on a ship.  Takes 1 or more arguments...\r\n"
		"\tAll: Name of ship on which to activate glow points\r\n"
	},

	// Bobboau
	{ OP_DEACTIVATE_GLOW_MAPS, "deactivate-glow-maps\r\n"
		"\tDeactivates the glow maps for a ship.  Takes 1 or more arguments...\r\n"
		"\tAll: Name of ship on which to deactivate glow maps\r\n"
	},

	// Bobboau
	{ OP_ACTIVATE_GLOW_MAPS, "activate-glow-maps\r\n"
		"\tActivates the glow maps for a ship.  Takes 1 or more arguments...\r\n"
		"\tAll: Name of ship on which to activate glow maps\r\n"
	},

	// Bobboau
	{ OP_DEACTIVATE_GLOW_POINT_BANK, "deactivate-glow-point-bank\r\n"
		"\tDeactivates one or more glow point bank(s) on a ship.  Takes 2 or more arguments...\r\n"
		"\t1: Name of ship on which to deactivate glow point bank(s)\r\n"
		"\tRest: Name of glow point bank to deactivate\r\n"
	},

	// Bobboau
	{ OP_ACTIVATE_GLOW_POINT_BANK, "activate-glow-point-bank\r\n"
		"\tActivates one or more glow point bank(s) on a ship.  Takes 2 or more arguments...\r\n"
		"\t1: Name of ship on which to activate glow point bank(s)\r\n"
		"\tRest: Name of glow point bank to activate\r\n"
	},

	//-Sesquipedalian
	{ OP_KAMIKAZE, "kamikaze\r\n"
		"\tTells ships to perform a kamikaze on its current target. Takes 2 or more arguments...\r\n"
		"\t1: Damage dealt when kamikaze is done\r\n"
		"\tRest: Names of ships to perform kamikaze\r\n"
	},
	
	//phreak
	{ OP_TURRET_TAGGED_SPECIFIC, "turret-tagged-specific\r\n"
		"\tSpecific turrets on a ship only fire at tagged targets, as opposed to all turrets doing this using turret-tagged-only\r\n"
		"\tIt is safe to slave turrets already slaved\r\n"
		"\tTakes 2 or more arguments...\r\n"
		"\t1: Name of ship to slave some turrets to target only tagged ships\r\n"
		"\tRest: Turrets to slave\r\n"
	},

	//phreak
	{ OP_TURRET_TAGGED_CLEAR_SPECIFIC, "turret-tagged-clear-specific\r\n"
		"\tSpecific turrets on a ship are free to fire on untagged ships, as opposed to all turrets doing this using turret-tagged-clear\r\n"
		"\tIt is safe to unslave turrets already free\r\n"
		"\tTakes 2 or more arguments...\r\n"
		"\t1: Name of ship to unslave some turrets to target any hostile ship\r\n"
		"\tRest: Turrets to unslave\r\n"
	},

	// Goober5000
	{ OP_LOCK_ROTATING_SUBSYSTEM, "lock-rotating-subsystem\r\n"
		"\tInstantaneously locks a rotating subsystem so that it cannot rotate unless freed by free-rotating-subsystem.  "
		"Takes 2 or more arguments...\r\n"
		"\t1:\tName of the ship housing the subsystem\r\n"
		"\tRest:\tName of the rotating subsystem to lock"
	},

	// Goober5000
	{ OP_FREE_ROTATING_SUBSYSTEM, "free-rotating-subsystem\r\n"
		"\tInstantaneously frees a rotating subsystem previously locked by lock-rotating-subsystem.  "
		"Takes 2 or more arguments...\r\n"
		"\t1:\tName of the ship housing the subsystem\r\n"
		"\tRest:\tName of the rotating subsystem to free"
	},

	// Goober5000
	{ OP_REVERSE_ROTATING_SUBSYSTEM, "reverse-rotating-subsystem\r\n"
		"\tInstantaneously reverses the rotation direction of a rotating subsystem.  "
		"Takes 2 or more arguments...\r\n"
		"\t1:\tName of the ship housing the subsystem\r\n"
		"\tRest:\tName of the rotating subsystem to reverse"
	},

	// Goober5000
	{ OP_ROTATING_SUBSYS_SET_TURN_TIME, "rotating-subsys-set-turn-time\r\n"
		"\tSets the turn time of a rotating subsystem.  "
		"Takes 3 or 4 arguments...\r\n"
		"\t1:\tName of the ship housing the subsystem\r\n"
		"\t2:\tName of the rotating subsystem to configure\r\n"
		"\t3:\tThe time for one complete rotation, in milliseconds (positive is counterclockwise, negative is clockwise)\r\n"
		"\t4:\tThe acceleration (x1000, just as #3 is seconds x1000) to change from the current turn rate to the desired turn rate.  "
		"This is actually the time to complete one rotation that changes in one second, or the reciprocal of what you might expect, "
		"meaning that larger numbers cause slower acceleration.  (FS2 defaults to 2pi/0.5, or about 12.566, which would be 12566 in this sexp.)  "
		"The advantage of this method is so that this argument can be directly compared to the previous argument using a ratio, without worrying about pi.  "
		"Omit this argument if you want an instantaneous change."
	},

	// Goober5000
	{ OP_TRIGGER_SUBMODEL_ANIMATION, "trigger-submodel-animation\r\n"
		"\tActivates a submodel animation trigger for a given ship.  Takes 4 to 6 arguments...\r\n"
		"\t1: The ship on which the animation should run\r\n"
		"\t2: The type of animation (named as one would see them in ships.tbl)\r\n"
		"\t3: The subtype of animation, which is type-dependent.  For docking animations this is the dock index.\r\n"
		"\t4: The animation direction: 1 for forward, or -1 for reverse\r\n"
		"\t5: (Optional) Whether the animation should instantly snap to its final position\r\n"
		"\t6: (Optional) A subsystem, if the animation should trigger on only a specific subsystem as opposed to all applicable subsystems\r\n"
	},

	// Karajorma
	{ OP_SET_PRIMARY_AMMO, "set-primary-ammo\r\n"
		"\tSets the amount of ammo for the specified ballistic bank\r\n"
		"\t1: Ship name\r\n"
		"\t2: Bank to check (0, 1, and 2 are legal banks)\r\n" 
		"\t3: Number to set this bank to (If this is larger than the maximum, bank will be set to maximum).\r\n"
		"\t4: Rearm Limit. Support ships will only supply this number of weapons (If this is larger than the maximum, bank will be set to maximum)"
	},

	// Karajorma
	{ OP_SET_SECONDARY_AMMO, "set-secondary-ammo\r\n"
		"\tSets the amount of ammo for the specified bank\r\n"
		"\t1: Ship name\r\n"
		"\t2: Bank to check (0, 1, 2 and 3 are legal banks)\r\n" 
		"\t3: Number to set this bank to (If this is larger than the maximum, bank will be set to maximum).\r\n"
		"\t4: Rearm Limit. Support ships will only supply this number of weapons (If this is larger than the maximum, bank will be set to maximum)"
	},
	
	// Karajorma
	{ OP_SET_PRIMARY_WEAPON, "set-primary-weapon\r\n"
		"\tSets the weapon for the specified bank\r\n"
		"\t1: Ship name\r\n"
		"\t2: Bank to check (0, 1 and 2 are legal banks)\r\n" 
		"\t3: Name of the primary weapon \r\n"
		"\t4: Number to set ammo of this bank to (If this is larger than the maximum, bank will be set to maximum)\r\n"
		"\t5: Rearm Limit. Support ships will only supply this number of weapons (If this is larger than the maximum, bank will be set to maximum)"
	},
	
	// Karajorma
	{ OP_SET_SECONDARY_WEAPON, "set-secondary-weapon\r\n"
		"\tSets the weapon for the specified bank\r\n"
		"\t1: Ship name\r\n"
		"\t2: Bank to check (0, 1, 2 and 3 are legal banks)\r\n" 
		"\t3: Name of the secondary weapon \r\n"
		"\t4: Number to set ammo of this bank to (If this is larger than the maximum, bank will be set to maximum)\r\n"
		"\t5: Rearm Limit. Support ships will only supply this number of weapons (If this is larger than the maximum, bank will be set to maximum)"
	},


	
	// Karajorma
	{ OP_SET_NUM_COUNTERMEASURES, "set-num-countermeasures\r\n"
		"\tSets the number of countermeasures the ship has\r\n"
		"\tValues greater than the maximum a ship can carry are set to the maximum\r\n"
		"\t1: Ship name\r\n"
		"\t2: Number to set"
	},
	
	// Karajorma
	{ OP_LOCK_PRIMARY_WEAPON, "lock-primary-weapon\r\n"
		"\tLocks the primary banks for the specified ship(s)\r\n"
		"\tTakes 1 or more arguments\r\n"
		"\t(all): Name(s) of ship(s) to lock"
	},

	// Karajorma
	{ OP_UNLOCK_PRIMARY_WEAPON, "unlock-primary-weapon\r\n"
		"\tUnlocks the primary banks for the specified ship(s)\r\n"
		"\tTakes 1 or more arguments\r\n"
		"\t(all): Name(s) of ship(s) to lock"
	},
	
	// Karajorma
	{ OP_LOCK_SECONDARY_WEAPON, "lock-secondary-weapon\r\n"
		"\tLocks the secondary banks for the specified ship(s)\r\n"
		"\tTakes 1 or more arguments\r\n"
		"\t(all): Name(s) of ship(s) to lock"
	},

	// Karajorma
	{ OP_UNLOCK_SECONDARY_WEAPON, "unlock-secondary-weapon\r\n"
		"\tUnlocks the secondary banks for the specified ship(s)\r\n"
		"\tTakes 1 or more arguments\r\n"
		"\t(all): Name(s) of ship(s) to lock"
	},
	
	// KeldorKatarn
	{ OP_LOCK_AFTERBURNER, "lock-afterburner\r\n"
		"\tLocks the afterburners on the specified ship(s)\r\n"
		"\tTakes 1 or more arguments\r\n"
		"\t(all): Name(s) of ship(s) to lock"
	},

	// KeldorKatarn
	{ OP_UNLOCK_AFTERBURNER, "unlock-afterburner\r\n"
		"\tUnlocks the afterburners on the specified ship(s)\r\n"
		"\tTakes 1 or more arguments\r\n"
		"\t(all): Name(s) of ship(s) to lock"
	},

	// Karajorma
	{ OP_SET_AFTERBURNER_ENERGY, "set-afterburner-energy\r\n"
		"\tSets the afterburner energy for the specified ship(s)\r\n"
		"\tTakes 2 or more arguments\r\n"
		"\t1: percentage of maximum afterburner energy.\r\n"
		"\t(rest): Name(s) of ship(s)"
	},

	{ OP_SET_WEAPON_ENERGY, "set-weapon-energy\r\n"
		"\tSets the weapon energy for the specified ship(s)\r\n"
		"\tTakes 2 or more arguments\r\n"
		"\t1: percentage of maximum weapon energy.\r\n"
		"\t(rest): Name(s) of ship(s)"
	},

	{ OP_SET_SHIELD_ENERGY, "set-shield-energy\r\n"
		"\tSets the shield energy for the specified ship(s)\r\n"
		"\tTakes 2 or more arguments\r\n"
		"\t1: percentage of maximum shield energy.\r\n"
		"\t(rest): Name(s) of ship(s)"
	},

	{ OP_SET_AMBIENT_LIGHT, "set-ambient-light\r\n"
		"\tSets the ambient light level for the mission\r\n"
		"\tTakes 3 arguments\r\n"
		"\t1: Red (0 - 255).\r\n"
		"\t2: Green (0 - 255).\r\n"
		"\t3: Blue (0 - 255)."
	},

	{ OP_SET_POST_EFFECT, "set-post-effect\r\n"
		"\tConfigures post-processing effect\r\n"
		"\tTakes 2 arguments\r\n"
		"\t1: Effect type\r\n"
		"\t2: Effect intensity (0 - 100)."
	},

	{ OP_CHANGE_SUBSYSTEM_NAME, "change-subsystem-name\r\n"
		"\tChanges the name of the specified subsystem on the specified ship\r\n"
		"\tTakes 3 or more arguments\r\n"
		"\t1: Name of the ship.\r\n"
		"\t2: New name for the subsystem (names larger than the maximum display size will be truncated\r\n"
		"\t3: Name(s) of subsystem(s) to rename\r\n"
	},

	//phreak
	{ OP_NUM_SHIPS_IN_BATTLE, "num-ships-in-battle\r\n"
		"\tReturns the number of ships in battle or the number of ships in battle out of a list of teams, wings, and ships.  Takes 1 or more arguments...\r\n"
		"\t(all):\tTeams, Wings, and Ships to query (optional)"
	},

	// Karajorma
	{ OP_NUM_SHIPS_IN_WING, "num-ships-in-wing\r\n"
		"\tReturns the number of ships in battle which belong to a given wing.  Takes 1 or more arguments...\r\n"
		"\t(all):\tName of wing(s) to check"
	},

	// Goober5000
	{ OP_HUD_DISABLE, "hud-disable\r\n"
		"\tSets whether the hud is disabled.  Takes 1 argument...\r\n"
		"\t1: Flag (1 to disable, 0 to re-enable)"
	},
	
	// Goober5000
	{ OP_HUD_DISABLE_EXCEPT_MESSAGES, "hud-disable-except-messages\r\n"
		"\tSets whether the hud (except for messages) is disabled.  Takes 1 argument...\r\n"
		"\t1: Flag (1 to disable, 0 to re-enable)"
	},

	// Goober5000
	{ OP_HUD_SET_MAX_TARGETING_RANGE, "hud-set-max-targeting-range\r\n"
		"\tSets the farthest distance at which an object can be targeted.  Takes 1 argument...\r\n"
		"\1: Maximum targeting distance (0 for infinite)\r\n"
	},

	{ OP_HUD_DISPLAY_GAUGE, "hud-display-gauge <milliseconds> <gauge>\r\n"
		"\tCauses specified hud gauge to appear or disappear for so many milliseconds.  Takes 1 argument...\r\n"
		"\t1: Number of milliseconds that the warpout gauge should appear on the HUD."
		" 0 will immediately cause the gauge to disappear.\r\n"
		"\t2: Name of HUD element.  Must be one of:\r\n"
		"\t\t" SEXP_HUD_GAUGE_WARPOUT " - the \"Subspace drive active\" box that appears above the viewscreen.\r\n"
	},

	// Goober5000
	{ OP_PLAYER_USE_AI, "player-use-ai\r\n"
		"\tCauses the player's ship to be controlled by the FreeSpace AI.  Takes 0 arguments.\r\n"
	},

	// Goober5000
	{ OP_PLAYER_NOT_USE_AI, "player-not-use-ai\r\n"
		"\tCauses the player's ship to not be controlled by the FreeSpace AI.  Takes 0 arguments.\r\n"
	},

	// Karajorma
	{ OP_ALLOW_TREASON, "allow-treason\r\n"
		"\tTurns the Allow Traitor switch on or off in mission. Takes 0 arguments.\r\n"
		"\t1:\tTrue/False."
	},

	// Karajorma
	{ OP_SET_PLAYER_ORDERS, "set-player-orders\r\n"
		"\tChanges the orders friendly AI will accept. Takes 3 or more arguments.\r\n"
		"\t1:\tShip Name\r\n"
		"\t2:\tTrue/False as to whether this order is allowed or not\r\n"
		"\tRest:\tOrder"
	},

	//WMC
	{ OP_HUD_SET_TEXT, "hud-set-text\r\n"
		"\tSets the text value of a given HUD gauge. Works for custom and certain retail gauges. Takes 2 arguments...\r\n"
		"\t1:\tHUD gauge to be modified\r\n"
		"\t2:\tText to be set"
	},

	{ OP_HUD_SET_TEXT_NUM, "hud-set-text-num\r\n"
		"\tSets the text value of a given HUD gauge to a number. Works for custom and certain retail gauges. Takes 2 arguments...\r\n"
		"\t1:\tHUD gauge to be modified\r\n"
		"\t2:\tNumber to be set"
	},

	{ OP_HUD_SET_MESSAGE, "hud-set-message\r\n"
		"\tSets the text value of a given HUD gauge to a message from the mission's message list. Works for custom and certain retail gauges. Takes 2 arguments...\r\n"
		"\t1:\tHUD gauge to be modified\r\n"
		"\t2:\tMessage"
	},

	//WMC
	{ OP_HUD_SET_COORDS, "hud-set-coord\r\n"
		"\tSets the coordinates of a given HUD gauge. Works for custom and retail gauges. Takes 3 arguments...\r\n"
		"\t1:\tHUD gauge to be modified\r\n"
		"\t2:\tCoordinate X component\r\n"
		"\t2:\tCoordinate Y component"
	},

	//WMC
	{ OP_HUD_SET_FRAME, "hud-set-frame\r\n"
		"\tSets the frame of a given HUD gauge's associated image. Works for custom and certain retail gauges. Takes 2 arguments...\r\n"
		"\t1:\tHUD gauge to be modified\r\n"
		"\t2:\tFrame number to be changed to"
	},

	//WMC
	{ OP_HUD_SET_COLOR, "hud-set-color\r\n"
		"\tSets the color of a given HUD gauge. Works only for custom gauges Takes 4 arguments...\r\n"
		"\t1:\tHUD gauge to be modified\r\n"
		"\t2:\tRed component (0-255)\r\n"
		"\t3:\tGreen component (0-255)\r\n"
		"\t4:\tBlue component (0-255)"
	},

	//WMC
	{ OP_CURRENT_SPEED, "current-speed\r\n"
		"\tReturns the speed of the given object. Takes 1 argument...\r\n"
		"\t1:\tName of the object"
	},

	// Karajora
	{ OP_PRIMARY_FIRED_SINCE, "primary-fired-since\r\n"
		"\tReturns true if the primary weapon bank specified has been fired within the supplied window of time. Takes 3 arguments...\r\n\r\n"
		"\t1:\tShip name\r\n"
		"\t2:\tWeapon bank number (This is a zero-based index. The first bank is numbered 0.)\r\n"
		"\t3:\tTime period to check if the weapon was fired (in millieconds)\r\n"
	},

	// Karajora
	{ OP_SECONDARY_FIRED_SINCE, "secondary-fired-since\r\n"
		"\tReturns true if the secondary weapon bank specified has been fired within the supplied window of time. Takes 3 arguments...\r\n\r\n"
		"\t1:\tShip name\r\n"
		"\t2:\tWeapon bank number (This is a zero-based index. The first bank is numbered 0.)\r\n"
		"\t3:\tTime period to check if the weapon was fired (in millieconds)\r\n"
	},

	// Karajora
	{ OP_HAS_PRIMARY_WEAPON, "has-primary-weapon\r\n"
		"\tReturns true if the primary weapon bank specified has any of the weapons listed. Takes 3 or more arguments...\r\n\r\n"
		"\t1:\tShip name\r\n"
		"\t2:\tWeapon bank number (This is a zero-based index. The first bank is numbered 0.)\r\n"
		"\tRest:\tWeapon name\r\n"
	},

	// Karajora
	{ OP_HAS_SECONDARY_WEAPON, "has-secondary-weapon\r\n"
		"\tReturns true if the secondary weapon bank specified has any of the weapons listed. Takes 3 or more arguments...\r\n\r\n"
		"\t1:\tShip name\r\n"
		"\t2:\tWeapon bank number (This is a zero-based index. The first bank is numbered 0.)\r\n"
		"\tRest:\tWeapon name\r\n"
	},

	// Karajora
	{ OP_DIRECTIVE_VALUE, "directive-value\r\n"
		"\tCauses a value to appear in the directive count\r\n"
		"\tAlways returns true. Takes 1 or more arguments...\r\n\r\n"
		"\t1:\tValue\r\n"
		"\t2:\t(Optional) Ignore the directive count set by any earlier SEXPs in the event. If set to false it will add instead\r\n"
	},

	//phreak
	{ OP_SCRAMBLE_MESSAGES, "scramble-messages\r\n"
		"\tCauses messages to be sent as if the player has sustained communications subsystem or EMP damage.  This effect can be reversed using unscramble-messages.  Takes zero or more arguments.\r\n"
		"\tAll (Optional):\tName of the ship for which to scramble messages.  If no ships are specified, message scrambling will be turned on for all messages the player receives.\r\n"
	},

	//phreak
	{ OP_UNSCRAMBLE_MESSAGES, "unscramble-messages\r\n"
		"\tUndoes the effects of scramble-messages, causing messages to be sent clearly.  Takes zero or more arguments.\r\n"
		"\tAll (Optional):\tName of the ship for which to scramble messages.  If no ships are specified, message scrambling will be turned on for all messages the player receives.\r\n"
	},

	{ OP_CUTSCENES_SET_CUTSCENE_BARS, "set-cutscene-bars\r\n"
		"\tShows bars at the top and bottom of screen.  "
		"Takes 0 or 1 arguments...\r\n"
		"\t1:\tMilliseconds for bars to slide in\r\n"
	},

	{ OP_CUTSCENES_UNSET_CUTSCENE_BARS, "unset-cutscene-bars\r\n"
		"\tRemoves cutscene bars.  "
		"Takes 0 or 1 arguments...\r\n"
		"\t1:\tMilliseconds for bars to slide out\r\n"
	},

	{ OP_CUTSCENES_FADE_IN, "fade-in\r\n"
		"\tFades in.  "
		"Takes 0 to 4 arguments...\r\n"
		"\t1:\tTime to fade in (in milliseconds)\r\n"
		"\t2:\tColor to fade to (optional).  If arguments 3 and 4 are specified, this is the R component of an RGB color.  Otherwise it is 1 for white, 2 for red, and any other number for black.\r\n"
		"\t3:\tG component of an RGB color (optional)\r\n"
		"\t4:\tB component of an RGB color (optional)\r\n"
	},

	{ OP_CUTSCENES_FADE_OUT, "fade-out\r\n"
		"\tFades out.  "
		"Takes 0 to 4 arguments...\r\n"
		"\t1:\tTime to fade in (in milliseconds)\r\n"
		"\t2:\tColor to fade to (optional).  If arguments 3 and 4 are specified, this is the R component of an RGB color.  Otherwise it is 1 for white, 2 for red, and any other number for black.\r\n"
		"\t3:\tG component of an RGB color (optional)\r\n"
		"\t4:\tB component of an RGB color (optional)\r\n"
	},

	{ OP_CUTSCENES_SET_CAMERA, "set-camera\r\n"
		"\tSets SEXP camera, or another specified cutscene camera.  "
		"Takes 0 to 1 arguments...\r\n"
		"\t(optional)\r\n"
		"\t1:\tCamera name (created if nonexistent)\r\n"
	},

	{ OP_CUTSCENES_SET_CAMERA_FACING, "set-camera-facing\r\n"
		"\tMakes the camera face the given point.  "
		"Takes 3 to 6 arguments...\r\n"
		"\t1:\tX position to face\r\n"
		"\t2:\tY position to face\r\n"
		"\t3:\tZ position to face\r\n"
		"\t(optional)\r\n"
		"\t4:\tTotal turn time (milliseconds)\r\n"
		"\t5:\tTime to spend accelerating/decelerating (milliseconds)\r\n"
		"\t6:\tTime to spend decelerating (milliseconds)\r\n"
	},

	{ OP_CUTSCENES_SET_CAMERA_FACING_OBJECT, "set-camera-facing-object\r\n"
		"\tMakes the camera face the given object.  "
		"Takes 1 to 4 arguments...\r\n"
		"\t1:\tObject to face\r\n"
		"\t(optional)\r\n"
		"\t2:\tTotal turn time (milliseconds)\r\n"
		"\t3:\tTime to spend accelerating/decelerating (milliseconds)\r\n"
		"\t4:\tTime to spend decelerating (milliseconds)\r\n"
	},

	{ OP_CUTSCENES_SET_CAMERA_FOV, "set-camera-fov\r\n"
		"\tSets the camera field of view.  "
		"Takes 1 to 4 arguments...\r\n"
		"\t1:\tNew FOV (degrees)\r\n"
		"\t(optional)\r\n"
		"\t2:\tTotal zoom time (milliseconds)\r\n"
		"\t3:\tTime to spend accelerating/decelerating (milliseconds)\r\n"
		"\t4:\tTime to spend decelerating (milliseconds)\r\n"
	},
	
	{ OP_CUTSCENES_SET_CAMERA_HOST, "set-camera-host\r\n"
		"\tSets the object and subystem camera should view from. Camera position is offset from the host. "
		"If the selected subsystem or one of its children has an eyepoint bound to it it will be used for the camera position and orientation."
		"If the selected subsystem is a turret and has no eyepoint the camera will be at the first firing point and look along the firing direction."
		"If a valid camera target is set the direction to the target will override any other orientation."
		"Takes 1 to 2 arguments...\r\n"
		"\t1:\tShip to mount camera on\r\n"
		"\t(optional)\r\n"
		"\t2:\tSubystem to mount camera on\r\n"
	},

	{ OP_CUTSCENES_SET_CAMERA_POSITION, "set-camera-position\r\n"
		"\tSets the camera position to a spot in mission space.  "
		"Takes 3 to 6 arguments...\r\n"
		"\t1:\tX position\r\n"
		"\t2:\tY position\r\n"
		"\t3:\tZ position\r\n"
		"\t(optional)\r\n"
		"\t4:\tTotal turn time (milliseconds)\r\n"
		"\t5:\tTime to spend accelerating/decelerating (milliseconds)\r\n"
		"\t6:\tTime to spend decelerating (milliseconds)\r\n"
	},

	{ OP_CUTSCENES_SET_CAMERA_ROTATION, "set-camera-rotation\r\n"
		"\tSets the camera rotation.  "
		"Takes 3 to 6 arguments...\r\n"
		"\t1:\tPitch (degrees)\r\n"
		"\t2:\tBank (degrees)\r\n"
		"\t3:\tHeading (degrees)\r\n"
		"\t(optional)\r\n"
		"\t4:\tTotal turn time (milliseconds)\r\n"
		"\t5:\tTime to spend accelerating/decelerating (milliseconds)\r\n"
		"\t6:\tTime to spend decelerating (milliseconds)\r\n"
	},

	{ OP_CUTSCENES_SET_CAMERA_TARGET, "set-camera-target\r\n"
		"\tSets the object and subystem camera should track. Camera orientation is offset from the target.  "
		"Takes 1 to 2 arguments...\r\n"
		"\t1:\tShip to track\r\n"
		"\t(optional)\r\n"
		"\t2:\tSubystem to track\r\n"
	},

	{ OP_CUTSCENES_SET_FOV, "set-fov\r\n"
		"\tSets the field of view - overrides all camera settings.  "
		"Takes 1 argument...\r\n"
		"\t1:\tNew FOV (degrees)\r\n"
	},

	// Echelon9
	{ OP_CUTSCENES_GET_FOV, "get-fov\r\n"
		"\tReturns the current field of view (in degrees) from the Main camera.\r\n\r\n"
		"Returns a numeric value.  Takes no arguments."
	},

	{ OP_CUTSCENES_RESET_FOV, "reset-fov\r\n"
		"\tResets the field of view.  "
	},

	{ OP_CUTSCENES_RESET_CAMERA, "reset-camera\r\n"
		"\tReleases cutscene camera control.  "
		"Takes 1 optional argument...\r\n"
		"\t(optional)\r\n"
		"\t1:\tReset camera data (Position, facing, FOV...) (default: false)"
	},

	{ OP_CUTSCENES_SHOW_SUBTITLE, "show-subtitle (deprecated)\r\n"
		"\tDisplays a subtitle, either an image or a string of text.  As this operator tries to combine two functions into one and does not adjust coordinates for screen formats, it has been deprecated.\r\n"
		"Takes 4 to 13 arguments...\r\n"
		"\t1:\tX position (negative value to be from right of screen)\r\n"
		"\t2:\tY position (negative value to be from bottom of screen)\r\n"
		"\t3:\tText to display\r\n"
		"\t4:\tTime to be displayed, not including fadein/out\r\n"
		"\t5:\tImage name (optional)\r\n"
		"\t6:\tFade in time (optional)\r\n"
		"\t7:\tCenter horizontally? (optional)\r\n"
		"\t8:\tCenter vertically? (optional)\r\n"
		"\t9:\tWidth (optional)\r\n"
		"\t10:\tText red component (0-255) (optional)\r\n"
		"\t11:\tText green component (0-255) (optional)\r\n"
		"\t12:\tText blue component (0-255) (optional)\r\n"
		"\t13:\tDrawn after shading? (optional)"
	},

	{ OP_CUTSCENES_SHOW_SUBTITLE_TEXT, "show-subtitle-text\r\n"
		"\tDisplays a subtitle in the form of text.  Note that because of the constraints of the subtitle system, textual subtitles are currently limited to 255 characters or fewer.\r\n"
		"Takes 6 to 13 arguments...\r\n"
		"\t1:\tText to display, or the name of a message containing text\r\n"
		"\t2:\tX position, from 0 to 100% (positive measures from the left; negative measures from the right)\r\n"
		"\t3:\tY position, from 0 to 100% (positive measures from the top; negative measures from the bottom)\r\n"
		"\t4:\tCenter horizontally? (if true, overrides argument #2)\r\n"
		"\t5:\tCenter vertically? (if true, overrides argument #3)\r\n"
		"\t6:\tTime (in milliseconds) to be displayed, not including fade-in/fade-out\r\n"
		"\t7:\tFade time (in milliseconds) to be used for both fade-in and fade-out (optional)\r\n"
		"\t8:\tParagraph width, from 1 to 100% (optional; 0 uses default 200 pixels)\r\n"
		"\t9:\tText red component (0-255) (optional)\r\n"
		"\t10:\tText green component (0-255) (optional)\r\n"
		"\t11:\tText blue component (0-255) (optional)\r\n"
		"\t12:\tText font (optional)\r\n"
		"\t13:\tDrawn after shading? (optional)"
	},

	{ OP_CUTSCENES_SHOW_SUBTITLE_IMAGE, "show-subtitle-image\r\n"
		"\tDisplays a subtitle in the form of an image.\r\n"
		"Takes 8 to 10 arguments...\r\n"
		"\t1:\tImage to display\r\n"
		"\t2:\tX position, from 0 to 100% (positive measures from the left; negative measures from the right)\r\n"
		"\t3:\tY position, from 0 to 100% (positive measures from the top; negative measures from the bottom)\r\n"
		"\t4:\tCenter horizontally? (if true, overrides argument #2)\r\n"
		"\t5:\tCenter vertically? (if true, overrides argument #3)\r\n"
		"\t6:\tImage width, from 1 to 100% (0 uses original width)\r\n"
		"\t7:\tImage height, from 1 to 100% (0 uses original height)\r\n"
		"\t8:\tTime (in milliseconds) to be displayed, not including fade-in/fade-out\r\n"
		"\t9:\tFade time (in milliseconds) to be used for both fade-in and fade-out (optional)\r\n"
		"\t10:\tDrawn after shading? (optional)"
	},

	{ OP_CUTSCENES_SET_TIME_COMPRESSION, "set-time-compression\r\n"
		"\tSets the time compression and prevents it from being changed by the user.  "
		"Takes 1 to 3 arguments...\r\n"
		"\t1:\tNew time compression (% of 1x)\r\n"
		"\t2:\tTime in ms for change to take\r\n"
		"\t3:\tTime compression to start from\r\n"
	},

	{ OP_CUTSCENES_RESET_TIME_COMPRESSION, "reset-time-compression\r\n"
		"\tResets the time compression - that is to say, time compression is set back to 1x, "
		"and the time compression controls are unlocked.  Always call this when done with set-time-compression.  "
	},

	{ OP_CUTSCENES_FORCE_PERSPECTIVE, "lock-perspective\r\n"
		"\tPrevents or allows the player from changing the view mode.  "
		"Takes 1 or 2 arguments...\r\n"
		"\t1:\tTrue to lock the view mode, false to unlock it\r\n"
		"\t2:\tWhat view mode to lock; 0 for first-person, 1 for chase, 2 for external, 3 for top-down"
	},

	{ OP_SET_CAMERA_SHUDDER, "set-camera-shudder\r\n"
		"\tCauses the camera to shudder.  Currently this will only work if the camera is showing the player's viewpoint (i.e. the HUD).\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1: Time (in milliseconds)\r\n"
		"\t2: Intensity.  For comparison, the Maxim has an intensity of 1440."
	},

	{ OP_JUMP_NODE_SET_JUMPNODE_NAME, "set-jumpnode-name\r\n"
		"\tSets the name of a jump node. Takes 2 arguments...\r\n"
		"\t1: Name of jump node to change name for\r\n"
		"\t2: New name for jump node\r\n\r\n"
		"\tNote: SEXPs referencing the old name will not work after the name change.\r\n"
	},

	{ OP_JUMP_NODE_SET_JUMPNODE_COLOR, "set-jumpnode-color\r\n"
		"\tSets the color of a jump node.  "
		"Takes 5 arguments...\r\n"
		"\t1:\tJump node to change color for\r\n"
		"\t2:\tRed value\r\n"
		"\t3:\tGreen value\r\n"
		"\t4:\tBlue value\r\n"
		"\t5:\tAlpha value\r\n"
	},

	{ OP_JUMP_NODE_SET_JUMPNODE_MODEL, "set-jumpnode-model\r\n"
		"\tSets the model of a jump node.  "
		"Takes 3 arguments...\r\n"
		"\t1:\tJump node to change model for\r\n"
		"\t2:\tModel filename\r\n"
		"\t3:\tShow as normal model. When this is true, the jumpnode will be rendered like a normal model.\r\n"
	},

	{ OP_JUMP_NODE_SHOW_JUMPNODE, "show-jumpnode\r\n"
		"\tSets a jump node to display on the screen.\r\n"
		"\tAny:\tJump node to show\r\n"
	},

	{ OP_JUMP_NODE_HIDE_JUMPNODE, "hide-jumpnode\r\n"
		"\tSets a jump node to not display on the screen.\r\n"
		"\tAny:\tJump node to hide\r\n"
	},

	// taylor, with modifications by niffiwan and MageKing17
	{ OP_SET_SKYBOX_MODEL, "set-skybox-model\r\n"
		"\tSets the current skybox model.  Takes 1-7 arguments\r\n"
		"\t1:\tModel filename (with .pof extension) to switch to\r\n"
		"\t2:\tRestart animated textures, if they exist (optional, defaults to true)\r\n"
		"\t3-8:\tSet or unset the following skyboxes flags (optional)\r\n"
		"\t\t\tadd-lighting, no-transparency, add-zbuffer\r\n"
		"\t\t\tadd-culling, no-glowmaps, force-clamp\r\n\r\n"
		"Note: If the model filename is set to \"default\" with no extension then it will switch to the mission supplied default skybox."
	},

	// Goober5000
	{ OP_SET_SKYBOX_ORIENT, "set-skybox-orientation\r\n"
		"\tSets the current skybox orientation.  Takes 3 arguments...\r\n"
		"\t1:\tPitch\r\n"
		"\t2:\tBank\r\n"
		"\t3:\tHeading\r\n"
	},

	{ OP_ADD_BACKGROUND_BITMAP, "add-background-bitmap\r\n"
		"\tAdds a background bitmap to the sky.  Returns an integer that is stored in a variable so it can be deleted using remove-background-bitmap\r\n\r\n"
		"Takes 8 to 9 arguments...\r\n"
		"\t1:\tBackground bitmap name\r\n"
		"\t2:\tPitch\r\n"
		"\t3:\tBank\r\n"
		"\t4:\tHeading\r\n"
		"\t5:\tX scale (expressed as a percentage of the original size of the bitmap)\r\n"
		"\t6:\tY scale (expressed as a percentage of the original size of the bitmap)\r\n"
		"\t7:\tX divisions.\r\n"
		"\t8:\tY divisions.\r\n"
		"\t9:\tVariable in which to store result (optional)\r\n"
	},

	{ OP_REMOVE_BACKGROUND_BITMAP, "remove-background-bitmap\r\n"
		"\tRemoves the nth background bitmap from the mission\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tZero based bitmap index from the \'Bitmap\' box in the background editor\r\n"
		"\t\t\tYou can also use the result of a previous call to add-background-bitmap to remove that added bitmap\r\n"
	},

	{ OP_ADD_SUN_BITMAP, "add-sun-bitmap\r\n"
		"\tAdds a sun bitmap to the sky.  Returns an integer that is stored in a variable so it can be deleted using remove-sun-bitmap\r\n\r\n"
		"Takes 5 to 6 arguments...\r\n"
		"\t1:\tSun bitmap name\r\n"
		"\t2:\tPitch\r\n"
		"\t3:\tBank\r\n"
		"\t4:\tHeading\r\n"
		"\t5:\tScale (expressed as a percentage of the original size of the bitmap)\r\n"
		"\t6:\tVariable in which to store result (optional)\r\n"
	},

	{ OP_REMOVE_SUN_BITMAP, "remove-sun-bitmap\r\n"
		"\tRemoves the nth sun from the mission\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tZero based sun index from the \'Suns\' box in the background editor\r\n"
		"\t\t\tYou can also use the result of a previous call to add-sun-bitmap to remove that added sun\r\n"
	},

	{ OP_NEBULA_CHANGE_STORM, "nebula-change-storm\r\n"
		"\tChanges the current nebula storm\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tNebula storm to change to\r\n"
	},

	{ OP_NEBULA_TOGGLE_POOF, "nebula-toggle-poof\r\n"
		"\tToggles the state of a nebula poof\r\n\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tName of nebula poof to toggle\r\n"
		"\t2:\tA True boolean expression will toggle this poof on.  A false one will do the opposite."
	},

	{ OP_NEBULA_CHANGE_PATTERN, "nebula-change-pattern\r\n"
	"\tChanges the current nebula background pattern (as defined in nebula.tbl)\r\n\r\n"
		"Takes 1 argument...\r\n"
		"\t1:\tNebula background pattern to change to\r\n"
	},

	{OP_SCRIPT_EVAL_NUM, "script-eval-num\r\n"
		"\tEvaluates script to return a number"
		"Takes 1 argument...\r\n"
		"\t1:\tScript\r\n"
	},

	{ OP_DISABLE_ETS, "disable-ets\r\n"
		"\tSwitches a ships' ETS system off\r\n\r\n"
		"Takes at least 1 argument...\r\n"
		"\tAll:\tList of ships this sexp applies to\r\n"
	},

	{ OP_ENABLE_ETS, "enable-ets\r\n"
		"\tSwitches a ships' ETS system on\r\n\r\n"
		"Takes at least 1 argument...\r\n"
		"\tAll:\tList of ships this sexp applies to\r\n"
	},

	{OP_SCRIPT_EVAL_STRING, "script-eval-string\r\n"
		"\tEvaluates script to return a string\r\n\r\n"
		"Takes a multiple of 2 arguments...\r\n"
		"\t1:\tScript (Without a leading 'return')\r\n"
		"\t2:\tDestination variable\r\n"
	},

	{OP_SCRIPT_EVAL, "script-eval\r\n"
		"\tEvaluates the given script\r\n"
		"Takes at least 1 argument...\r\n"
		"\t1:\tScript to evaluate\r\n"
	},

	{OP_SCRIPT_EVAL_BLOCK, "script-eval-block\r\n"
		"\tEvaluates the concatenation of all arguments as a script\r\n"
		"Takes at least 1 argument...\r\n"
		"\tAll:\tScript to evaluate\r\n"
	},

	{OP_SCRIPT_EVAL_MULTI, "multi-eval\r\n"
		"\tEvaluates script\r\n\r\n"
		"Takes at least 2 arguments...\r\n"
		"\t1:\tScript to evaluate\r\n"
		"\t2:\tTrue/False - Should the script evaluate on the server?\r\n"
		"\t(rest):\tList of players who should evaluate this script. If no player is given, all clients will execute the script\r\n"
	},

	{OP_FORCE_GLIDE, "force-glide\r\n"
		"\tForces a given ship into glide mode, provided it is capable of gliding. Note that the player will not be able to leave glide mode on his own,, and that a ship in glide mode cannot warp out or enter autopilot."
		"Takes 2 Arguments...\r\n"
		"\t1:\tShip to force\r\n"
		"\t2:\tTrue to activate glide, False to deactivate\r\n"
	},

	{OP_HUD_SET_DIRECTIVE, "hud-set-directive\r\n"
		"\tSets the text of a given custom hud gauge to the provided text."
		"Takes 2 Arguments...\r\n"
		"\t1:\tHUD Gauge name\r\n"
		"\t2:\tText that will be displayed. This text will be treated as directive text, meaning that references to mapped keys will be replaced with the user's preferences.\r\n"
	},

	{OP_HUD_GAUGE_SET_ACTIVE, "hud-gauge-set-active (deprecated)\r\n"
		"\tActivates or deactivates a given custom gauge."
		"Takes 2 Arguments...\r\n"
		"\t1:\tHUD Gauge name\r\n"
		"\t2:\tBoolean, whether or not to display this gauge\r\n"
	},

	{OP_HUD_CLEAR_MESSAGES, "hud-clear-messages\r\n"
		"\tClears active messages displayed on the HUD."
		"Takes no arguments\r\n"
	},

	{OP_HUD_ACTIVATE_GAUGE_TYPE, "hud-activate-gauge-type (deprecated)\r\n"
		"\tActivates or deactivates all hud gauges of a given type."
		"Takes 2 Arguments...\r\n"
		"\t1:\tGauge Type\r\n"
		"\t2:\tBoolean, whether or not to display this gauge\r\n"
	},

	{OP_HUD_SET_CUSTOM_GAUGE_ACTIVE, "hud-set-custom-gauge-active\r\n"
		"\tActivates or deactivates a custom hud gauge defined in hud_gauges.tbl."
		"Takes 2 Arguments...\r\n"
		"\t1:\tBoolean, whether or not to display this gauge\r\n"
		"\tRest:\tHUD Gauge name\r\n"
	},

	{OP_HUD_SET_RETAIL_GAUGE_ACTIVE, "hud-set-custom-gauge-active\r\n"
		"\tActivates or deactivates a retail hud gauge grouping."
		"Takes 2 Arguments...\r\n"
		"\t1:\tBoolean, whether or not to display this gauge\r\n"
		"\tRest:\tHUD Gauge Group name\r\n"
	},

	{OP_ADD_TO_COLGROUP, "add-to-collision-group\r\n"
		"\tAdds a ship to the specified collision group(s). Note that there are 32 collision groups,\r"
		"\tand that an object may be in several collision groups at the same time\r\n"
		"Takes 2 or more Arguments...\r\n"
		"\t1:\tObject to add\r\n"
		"\t2+:\tGroup IDs. Valid IDs are 0 through 31 inclusive.\r\n"
	},

	{OP_REMOVE_FROM_COLGROUP, "remove-from-collision-group\r\n"
		"\tRemoves a ship from the specified collision group(s). Note that there are 32 collision groups,\n"
		"\tand that an object may be in several collision groups at the same time\r\n"
		"Takes 2 or more Arguments...\r\n"
		"\t1:\tObject to add\r\n"
		"\t2+:\tGroup IDs. Valid IDs are 0 through 31 inclusive.\r\n"
	},

	{OP_GET_COLGROUP_ID, "get-collision-group\r\n"
		"\tReturns an objects' collision group ID. Note that this ID is a bitfield.\r\n"
		"Takes 1 Argument...\r\n"
		"\t1:\tObject name\r\n"
	},

	//Valathil
	{OP_SHIP_EFFECT, "ship-effect\r\n"
		"\tPlays an animated shader effect on the ship(s) or wing(s).\r\n"
		"Takes 3 or more arguments...\r\n"
		"\t1:\tEffect name (as defined in post_processing.tbl)\r\n"
		"\t2:\tHow long the effect should take in milliseconds\r\n"
		"\tRest:\tShip or wing name\r\n"
	},

	{OP_CLEAR_SUBTITLES, "clear-subtitles\r\n"
		"\tClears the subtitle queue completely.\r\n"
	},

	{OP_SET_THRUSTERS, "set-thrusters-status\r\n"
		"\tManipulates the thrusters on a ship.\r\n"
		"Takes 2 or more arguments...\r\n"
		"\t1:\tBoolean, true sets thrusters to visible, false deactivates them.\r\n"
		"\t2:\tRest: List of ships this sexp will work on.\r\n"
	},

	{OP_SET_PLAYER_THROTTLE_SPEED, "set-player-throttle-speed\r\n"
		"\tSets a player's throttle to a percentage of their maximum speed.\r\n"
		"\tThis SEXP has no effect if used on an AI ship, however it will still work on an AI-controlled player ship.\r\n"
		"Takes 2 arguments...\r\n"
		"\t1:\tThe player ship to set the throttle of.\r\n"
		"\t2:\tThe percentage of the player's maximum speed to set their throttle to.\r\n"
		"\t\tThis is capped to either 0 or 100 if outside the valid range."
	},

	{OP_CHANGE_TEAM_COLOR, "change-team-color\r\n"
		"\tChanges the team color setting for one or several ships.\r\n"
		"\tThis sexp has no effect on ships that don't have team colors enabled for them.\r\n"
		"\tTakes 3 or more arguments...\r\n"
		"\t1:\tThe new team color name. Name must be defined in colors.tbl.\r\n"
		"\t2:\tCrossfade time in milliseconds. During this time, colors will be mixed.\r\n"
		"\t3:\tRest: List of ships this sexp will operate on."
	},

	{OP_CALL_SSM_STRIKE, "call-ssm-strike\r\n"
		"\tCalls a subspace missile strike on the specified ship.\r\n"
		"\tRequires a ssm table (ssm.tbl).\r\n"
		"Takes 3 arguments...\r\n"
		"\t1:\tStrike name.\r\n"
		"\t2:\tCalling team.\r\n"
		"\tRest:\tList of ships the strike will be called on."
	},

	{OP_PLAYER_IS_CHEATING_BASTARD, "player-is-cheating\r\n"
		"\tReturns true if the player is or has been cheating in this mission.\r\n"
	},

	{ OP_SET_MOTION_DEBRIS, "set-motion-debris-override\r\n"
		"\tControls whether or not motion debris should be active.\r\n"
		"\tThis overrides any choice made by the user through the -nomotiondebris commandline flag."
		"Takes 1 argument...\r\n"
		"\t1:\tBoolean: True will disable motion debris, False reenable it.\r\n"
	}
};



op_menu_struct op_menu[] =
{
	{ "Objectives",		OP_CATEGORY_OBJECTIVE },
	{ "Time",			OP_CATEGORY_TIME },
	{ "Logical",		OP_CATEGORY_LOGICAL },
	{ "Arithmetic",		OP_CATEGORY_ARITHMETIC },
	{ "Status",			OP_CATEGORY_STATUS },
	{ "Change",			OP_CATEGORY_CHANGE },
	{ "Conditionals",	OP_CATEGORY_CONDITIONAL },
	{ "Ai goals",		OP_CATEGORY_AI },
	{ "Event/Goals",	OP_CATEGORY_GOAL_EVENT },
	{ "Training",		OP_CATEGORY_TRAINING },
};

// Goober5000's subcategorization of the Change menu (and possibly other menus in the future,
// if people so choose - see sexp.h)
op_menu_struct op_submenu[] =
{
	{	"Messages and Personas",		CHANGE_SUBCATEGORY_MESSAGING						},
	{	"AI Control",					CHANGE_SUBCATEGORY_AI_CONTROL						},
	{	"Ship Status",					CHANGE_SUBCATEGORY_SHIP_STATUS						},
	{	"Weapons, Shields, and Engines",	CHANGE_SUBCATEGORY_SHIELDS_ENGINES_AND_WEAPONS		},
	{	"Subsystems and Health",		CHANGE_SUBCATEGORY_SUBSYSTEMS						},
	{	"Cargo",						CHANGE_SUBCATEGORY_CARGO							},
	{	"Armor and Damage Types",		CHANGE_SUBCATEGORY_ARMOR_AND_DAMAGE_TYPES			},
	{	"Beams and Turrets",			CHANGE_SUBCATEGORY_BEAMS_AND_TURRETS				},
	{	"Models and Textures",			CHANGE_SUBCATEGORY_MODELS_AND_TEXTURES				},
	{	"Coordinate Manipulation",		CHANGE_SUBCATEGORY_COORDINATE_MANIPULATION			},
	{	"Mission and Campaign",			CHANGE_SUBCATEGORY_MISSION_AND_CAMPAIGN				},
	{	"Music and Sound",				CHANGE_SUBCATEGORY_MUSIC_AND_SOUND					},
	{	"HUD",							CHANGE_SUBCATEGORY_HUD								},
	{	"Nav Points",					CHANGE_SUBCATEGORY_NAV								},
	{	"Cutscenes",					CHANGE_SUBCATEGORY_CUTSCENES						},
	{	"Backgrounds and Nebulae",		CHANGE_SUBCATEGORY_BACKGROUND_AND_NEBULA			},
	{	"Jump Nodes",					CHANGE_SUBCATEGORY_JUMP_NODES						},
	{	"Special Effects",				CHANGE_SUBCATEGORY_SPECIAL_EFFECTS					},
	{	"Variables",					CHANGE_SUBCATEGORY_VARIABLES						},
	{	"Other",						CHANGE_SUBCATEGORY_OTHER							},
	{	"Mission",						STATUS_SUBCATEGORY_MISSION							},
	{	"Player",						STATUS_SUBCATEGORY_PLAYER							},
	{	"Multiplayer",						STATUS_SUBCATEGORY_MULTIPLAYER					},
	{	"Ship Status",					STATUS_SUBCATEGORY_SHIP_STATUS						},
	{	"Weapons, Shields, and Engines",	STATUS_SUBCATEGORY_SHIELDS_ENGINES_AND_WEAPONS	},
	{	"Cargo",						STATUS_SUBCATEGORY_CARGO							},
	{	"Damage",						STATUS_SUBCATEGORY_DAMAGE							},
	{	"Distance and Coordinates",		STATUS_SUBCATEGORY_DISTANCE_AND_COORDINATES			},
	{	"Variables",					STATUS_SUBCATEGORY_VARIABLES						},
	{	"Other",						STATUS_SUBCATEGORY_OTHER							},


};
int Num_sexp_help = sizeof(Sexp_help) / sizeof(sexp_help_struct);
int Num_op_menus = sizeof(op_menu) / sizeof(op_menu_struct);
int Num_submenus = sizeof(op_submenu) / sizeof(op_menu_struct);

/**
 * Internal file used by output_sexps, should not be called from output_sexps
 */
static void output_sexp_html(int sexp_idx, FILE *fp)
{
	if(sexp_idx < 0 || sexp_idx > Num_operators)
		return;

	bool printed=false;

	for(int i = 0; i < Num_sexp_help; i++)
	{
		if(Sexp_help[i].id == Operators[sexp_idx].value)
		{
			char* new_buf = new char[2*strlen(Sexp_help[i].help)];
			char* dest_ptr = new_buf;
			char* curr_ptr = Sexp_help[i].help;
			char* end_ptr = curr_ptr + strlen(Sexp_help[i].help);
			while(curr_ptr < end_ptr)
			{
				if(*curr_ptr == '\n')
				{
					strcpy(dest_ptr, "\n<br>");
					dest_ptr+=5;
				}
				else
				{
					*dest_ptr++ = *curr_ptr;
				}
				curr_ptr++;
			}
			*dest_ptr = '\0';

			fprintf(fp, "<dt><b>%s</b></dt>\n<dd>%s</dd>\n", Operators[sexp_idx].text, new_buf);
			delete[] new_buf;

			printed = true;
		}
	}

	if(!printed)
		fprintf(fp, "<dt><b>%s</b></dt>\n<dd>Min arguments: %d, Max arguments: %d</dd>\n", Operators[sexp_idx].text, Operators[sexp_idx].min, Operators[sexp_idx].max);
}

/**
 * Output sexp.html file
 */
bool output_sexps(char *filepath)
{
	FILE *fp = fopen(filepath,"w");

	if(fp == NULL)
	{
		MessageBox(NULL,"Error creating SEXP operator list", "Error", MB_OK);
		return false; 
	}

	//Header
	if (FS_VERSION_BUILD == 0 && FS_VERSION_REVIS == 0) //-V547
	{
		fprintf(fp, "<html>\n<head>\n\t<title>SEXP Output - FSO v%i.%i</title>\n</head>\n", FS_VERSION_MAJOR, FS_VERSION_MINOR);
		fputs("<body>", fp);
		fprintf(fp,"\t<h1>SEXP Output - FSO v%i.%i</h1>\n", FS_VERSION_MAJOR, FS_VERSION_MINOR);
	}
	else if (FS_VERSION_REVIS == 0)
	{
		fprintf(fp, "<html>\n<head>\n\t<title>SEXP Output - FSO v%i.%i.%i</title>\n</head>\n", FS_VERSION_MAJOR, FS_VERSION_MINOR, FS_VERSION_BUILD);
		fputs("<body>", fp);
		fprintf(fp,"\t<h1>SEXP Output - FSO v%i.%i.%i</h1>\n", FS_VERSION_MAJOR, FS_VERSION_MINOR, FS_VERSION_BUILD);
	}
	else
	{
		fprintf(fp, "<html>\n<head>\n\t<title>SEXP Output - FSO v%i.%i.%i.%i</title>\n</head>\n", FS_VERSION_MAJOR, FS_VERSION_MINOR, FS_VERSION_BUILD, FS_VERSION_REVIS);
		fputs("<body>", fp);
		fprintf(fp,"\t<h1>SEXP Output - FSO v%i.%i.%i.%i</h1>\n", FS_VERSION_MAJOR, FS_VERSION_MINOR, FS_VERSION_BUILD, FS_VERSION_REVIS);
	}

	SCP_vector<int> done_sexp_ids;
	int x,y,z;

	//Output an overview
	fputs("<dl>", fp);
	for(x = 0; x < Num_op_menus; x++)
	{
		fprintf(fp, "<dt><a href=\"#%d\">%s</a></dt>", (op_menu[x].id & OP_CATEGORY_MASK), op_menu[x].name);
		for(y = 0; y < Num_submenus; y++)
		{
			if(((op_submenu[y].id & OP_CATEGORY_MASK) == op_menu[x].id))
			{
				fprintf(fp, "<dd><a href=\"#%d\">%s</a></dd>", op_submenu[y].id & (OP_CATEGORY_MASK | SUBCATEGORY_MASK), op_submenu[y].name);
			}
		}
	}
	fputs("</dl>", fp);

	//Output the full descriptions
	fputs("<dl>", fp);
	for(x = 0; x < Num_op_menus; x++)
	{
		fprintf(fp, "<dt id=\"%d\"><h2>%s</h2></dt>\n", (op_menu[x].id & OP_CATEGORY_MASK), op_menu[x].name);
		fputs("<dd>", fp);
		fputs("<dl>", fp);
		for(y = 0; y < Num_submenus; y++)
		{
			if(((op_submenu[y].id & OP_CATEGORY_MASK) == op_menu[x].id))
			{
				fprintf(fp, "<dt id=\"%d\"><h3>%s</h3></dt>\n", op_submenu[y].id & (OP_CATEGORY_MASK | SUBCATEGORY_MASK), op_submenu[y].name);
				fputs("<dd>", fp);
				fputs("<dl>", fp);
				for(z = 0; z < Num_operators; z++)
				{
					if((get_category(Operators[z].value) == op_menu[x].id)
						&& (get_subcategory(Operators[z].value) != -1)
						&& (get_subcategory(Operators[z].value) == op_submenu[y].id))
					{
						output_sexp_html(z, fp);
					}
				}
				fputs("</dl>", fp);
				fputs("</dd>", fp);
			}
		}
		for(z = 0; z < Num_operators; z++)
		{
			if((get_category(Operators[z].value) == op_menu[x].id)
				&& (get_subcategory(Operators[z].value) == -1))
			{
				output_sexp_html(z, fp);
			}
		}
		fputs("</dl>", fp);
		fputs("</dd>", fp);
	}
	for(z = 0; z < Num_operators; z++)
	{
		if(!get_category(Operators[z].value))
		{
			output_sexp_html(z, fp);
		}
	}
	fputs("</dl>", fp);
	fputs("</body>\n</html>\n", fp);

	fclose(fp);

	return true;
}