]> icculus.org git repositories - taylor/freespace2.git/blob - src/parse/sexp.cpp
merge updated graphics code
[taylor/freespace2.git] / src / parse / sexp.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/parse/SEXP.CPP $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * main sexpression generator
16  *
17  * $Log$
18  * Revision 1.5  2003/05/25 02:30:43  taylor
19  * Freespace 1 support
20  *
21  * Revision 1.4  2002/06/17 06:15:25  relnev
22  * ryan's struct patch (and cr removal)
23  *
24  * Revision 1.3  2002/06/09 04:41:25  relnev
25  * added copyright header
26  *
27  * Revision 1.2  2002/05/07 03:16:48  theoddone33
28  * The Great Newline Fix
29  *
30  * Revision 1.1.1.1  2002/05/03 03:28:10  root
31  * Initial import.
32  *
33  * 
34  * 66    9/13/99 11:38a Andsager
35  * Stupid switch for sexp_team_score.  Don't forget *break*
36  * 
37  * 65    9/09/99 11:40p Dave
38  * Handle an SDL_assert() in beam code. Added supernova sounds. Play the right
39  * 2 end movies properly, based upon what the player did in the mission.
40  * 
41  * 64    9/07/99 1:05a Andsager
42  * Added team-score sexp for multi team vs team missions
43  * 
44  * 63    9/06/99 9:46p Jefff
45  * skip mission support
46  * 
47  * 62    8/29/99 2:33p Andsager
48  * Fix bug in sexp_is_ship_visible()
49  * 
50  * 61    8/27/99 9:07p Dave
51  * LOD explosions. Improved beam weapon accuracy.
52  * 
53  * 60    8/27/99 4:07p Andsager
54  * Add is-ship-visible sexp.  Make ship-vanish sexp SINGLE player only
55  * 
56  * 59    8/26/99 4:21p Mikek
57  * Add new special-check for JimB, zeroing front shield quadrant.
58  * 
59  * 58    8/24/99 4:25p Andsager
60  * Add ship-vanish sexp
61  * 
62  * 57    8/23/99 6:05p Johnson
63  * Oops. Self destruct log should also go into the is-destroyed
64  * sexpression.
65  * 
66  * 56    8/23/99 3:23p Johnson
67  * Fix bug in sexp_facing2 when Player_obj does not yet existl
68  * 
69  * 55    8/19/99 3:30p Andsager
70  * Make sexp_special_warp_dist check if ship if facing knossos device
71  * 
72  * 54    8/19/99 9:20a Andsager
73  * Enable flashing for all guages
74  * 
75  * 53    8/19/99 12:31a Andsager
76  * Add support guage as one that can flash
77  * 
78  * 52    8/18/99 12:09p Andsager
79  * Add debug if message has no anim for message.  Make messages come from
80  * wing leader.
81  * 
82  * 51    8/16/99 10:04p Andsager
83  * Add special-warp-dist and special-warpout-name sexp for Knossos device
84  * warpout.
85  * 
86  * 50    8/09/99 3:32p Andsager
87  * Make has_time_elapsed work with arithmatic args.
88  * 
89  * 49    8/09/99 2:00p Dave
90  * 2 new sexpressions.
91  * 
92  * 48    8/02/99 4:26p Dave
93  * Added 2 new sexpressions.
94  * 
95  * 47    7/31/99 2:30p Dave
96  * Added nifty mission message debug viewing keys.
97  * 
98  * 46    7/28/99 1:36p Andsager
99  * Modify cargo1 to include flag CARGO_NO_DEPLETE.  Add sexp
100  * cargo-no-deplete (only for BIG / HUGE).  Modify ship struct to pack
101  * better.
102  * 
103  * 45    7/24/99 4:56p Dave
104  * Added 3 new sexpressions.
105  * 
106  * 44    7/21/99 8:10p Dave
107  * First run of supernova effect.
108  * 
109  * 43    7/20/99 9:19p Andsager
110  * Added facing waypoint sexp
111  * 
112  * 42    7/20/99 9:54a Andsager
113  * Add subsys-set-random sexp
114  * 
115  * 41    7/19/99 12:02p Andsager
116  * Allow AWACS on any ship subsystem. Fix sexp_set_subsystem_strength to
117  * only blow up subsystem if its strength is > 0
118  * 
119  * 40    7/15/99 9:22p Andsager
120  * modify secondaries_depleted sexp to report true only when all
121  * secondaries gone
122  * 
123  * 39    7/13/99 3:37p Andsager
124  * Add secondaries-depleted sexp
125  * 
126  * 38    7/08/99 12:06p Andsager
127  * Add turret-tagged-only and turret-tagged-clear sexp.
128  * 
129  * 37    6/28/99 4:51p Andsager
130  * Add ship-guardian sexp (does not allow ship to be killed)
131  * 
132  * 36    6/25/99 2:51p Andsager
133  * Make event_delay, goal_delay, and subsys strength work with sexp_rand
134  * 
135  * 35    6/23/99 5:51p Andsager
136  * Add waypoint-cap-speed.  Checkin stealth ai - inactive.
137  * 
138  * 34    6/16/99 10:21a Dave
139  * Added send-message-list sexpression.
140  * 
141  * 33    6/15/99 2:53p Andsager
142  * Fixed subsystem checking for AWACS type subsystems.
143  * 
144  * 32    6/01/99 8:35p Dave
145  * Finished lockarm weapons. Added proper supercap weapons/damage. Added
146  * awacs-set-radius sexpression.
147  * 
148  * 31    5/27/99 12:14p Andsager
149  * Some fixes for live debris when more than one subsys on ship with live
150  * debris.  Set subsys strength (when 0) blows off subsystem.
151  * sexp_hits_left_subsystem works for SUBSYSTEM_UNKNOWN.
152  * 
153  * 30    5/24/99 11:28a Dave
154  * Sexpression for adding/removing ships from the hud escort list.
155  * 
156  * 29    4/28/99 9:33a Andsager
157  * Add turret-free and turret-lock (and -all) sexp.  Stargger start time
158  * of beam weapons beam-free and beam-free-all.
159  * 
160  * 28    4/26/99 2:14p Andsager
161  * Add beam-protect-ship and beam-unprotect-ship sexp.
162  * 
163  * 27    4/23/99 12:01p Johnson
164  * Added SIF_HUGE_SHIP
165  * 
166  * 26    4/23/99 9:45a Andsager
167  * Modify rand_sexp to return the same value each time it is called on a
168  * particular node.  This prevents random time delay defaulting to min.
169  * 
170  * 25    4/21/99 6:15p Dave
171  * Did some serious housecleaning in the beam code. Made it ready to go
172  * for anti-fighter "pulse" weapons. Fixed collision pair creation. Added
173  * a handy macro for recalculating collision pairs for a given object.
174  * 
175  * 24    4/19/99 2:28p Johnson
176  * DA:  Use ship_info flags, not ship_flags for ship type.  DOH!!
177  * 
178  * 23    4/19/99 11:46a Johnson
179  * DA: DOH!
180  * 
181  * 22    4/19/99 11:36a Johnson
182  * Don't display multiple warning messges when large ship gets more than 1
183  * cargo transfer.
184  * 
185  * 21    4/02/99 9:55a Dave
186  * Added a few more options in the weapons.tbl for beam weapons. Attempt
187  * at putting "pain" packets into multiplayer.
188  * 
189  * 20    3/31/99 2:22p Johnson
190  * Fix sexp_repair_subsystem() to accept sexp increments
191  * 
192  * 19    3/28/99 5:58p Dave
193  * Added early demo code. Make objects move. Nice and framerate
194  * independant, but not much else. Don't use yet unless you're me :)
195  * 
196  * 18    3/20/99 3:46p Dave
197  * Added support for model-based background nebulae. Added 3 new
198  * sexpressions.
199  * 
200  * 17    3/08/99 7:03p Dave
201  * First run of new object update system. Looks very promising.
202  * 
203  * 16    3/04/99 6:09p Dave
204  * Added in sexpressions for firing beams and checking for if a ship is
205  * tagged.
206  * 
207  * 15    3/04/99 9:22a Andsager
208  * Make escort list work with ship-is-visible.  When not visible, dump,
209  * when becoming visible, maybe add.
210  * 
211  * 14    2/26/99 6:01p Andsager
212  * Add sexp has-been-tagged-delay and cap-subsys-cargo-known-delay
213  * 
214  * 13    2/26/99 4:14p Dave
215  * Put in the ability to have multiple shockwaves for ships.
216  * 
217  * 12    2/11/99 5:22p Andsager
218  * Fixed bugs, generalized block Sexp_variables
219  * 
220  * 11    2/11/99 2:15p Andsager
221  * Add ship explosion modification to FRED
222  * 
223  * 10    1/25/99 4:29p Andsager
224  * Modify sexp_modify_variable() to handle type string. added quick out
225  * for multiplayer_client
226  * 
227  * 9     1/25/99 8:11a Andsager
228  * Add sexp_modify_variable().  Changed syntax checking to allow, adding
229  * operator return type ambiguous
230  * 
231  * 8     1/24/99 11:37p Dave
232  * First full rev of beam weapons. Very customizable. Removed some bogus
233  * Int3()'s in low level net code.
234  * 
235  * 7     1/20/99 9:37a Andsager
236  * 
237  * 6     1/19/99 3:57p Andsager
238  * Round 2 of variables
239  * 
240  * 5     1/07/99 1:52p Andsager
241  * Initial check in of Sexp_variables
242  * 
243  * 4     11/05/98 5:55p Dave
244  * Big pass at reducing #includes
245  * 
246  * 3     10/13/98 9:29a Dave
247  * Started neatening up freespace.h. Many variables renamed and
248  * reorganized. Added AlphaColors.[h,cpp]
249  * 
250  * 2     10/07/98 10:53a Dave
251  * Initial checkin.
252  * 
253  * 1     10/07/98 10:50a Dave
254  * 
255  * 321   9/20/98 7:20p Dave
256  * Added CHANGE_IFF packet. 
257  * 
258  * 320   9/16/98 10:42a Hoffoss
259  * Added sexp node counting to fsm files for end user designers.
260  * 
261  * 319   7/06/98 4:31p Hoffoss
262  * Fixed bug in sexp parsing when formula is ( ).
263  * 
264  * 318   6/09/98 5:15p Lawrance
265  * French/German localization
266  * 
267  * 317   5/26/98 11:54a Allender
268  * fix multiplayer problems and sexpression crash
269  * 
270  * 316   5/23/98 3:16p Allender
271  * work on object update packet optimizations (a new updating system).
272  * Don't allow medals/promotions/badges when playing singple player
273  * missions through the simulator
274  * 
275  * 315   5/20/98 1:34a Allender
276  * fixed observer problems.  Removed some code offending BoundsCheccker.
277  * Fixed medals for multiplayer
278  * 
279  * 314   5/17/98 12:46p Mike
280  * Change special-check functions for cueing rearm suggestion.
281  * 
282  * 313   5/14/98 6:29p Hoffoss
283  * Fixed some warnings a release rebuild all turned up.
284  * 
285  * 312   5/14/98 10:15a Allender
286  * add optional argument to prevous-goal/event operators to specify what
287  * sexpression should return when being played as a single mission
288  * 
289  * 311   5/08/98 10:16a Lawrance
290  * Add new "ship attacking count" gauge
291  * 
292  * 310   4/29/98 11:39p Allender
293  * fixed nasty problem with is-event-false always returning true right
294  * away
295  * 
296  * 
297  */
298
299 //      Parse a symbolic expression.
300 //      These are identical to Lisp functions.
301 //      It uses a very baggy format, allocating 16 characters per token, regardless
302 //      of how many are used.
303
304 #include        <stdio.h>
305 #include <stdlib.h>
306 #include <string.h>
307 #include <ctype.h>
308 #include <assert.h>
309 #include <limits.h>
310
311 #include "parselo.h"
312 #include "sexp.h"
313 #include "ship.h"
314 #include "freespace.h"
315 #include "fix.h"
316 #include "weapon.h"
317 #include "missionlog.h"
318 #include "missionparse.h"               // for p_object definition
319 #include "missionmessage.h"
320 #include "missiontraining.h"
321 #include "vecmat.h"
322 #include "linklist.h"
323 #include "model.h"                              // for subsystem types
324 #include "aigoals.h"
325 #include "missioncampaign.h"
326 #include "missiongoals.h"
327 #include "controlsconfig.h"
328 #include "timer.h"
329 #include "shiphit.h"
330 #include "gamesequence.h"
331 #include "scoring.h"
332 #include "medals.h"
333 #include "player.h"
334 #include "hudmessage.h"
335 #include "hud.h"
336 #include "redalert.h"
337 #include "jumpnode.h"
338 #include "hudshield.h"
339 #include "multi.h"
340 #include "multimsgs.h"
341 #include "multiutil.h"
342 #include "hudescort.h"
343 #include "beam.h"
344 #include "supernova.h"
345 #include "hudets.h"
346 #include "fvi.h"
347 #include "awacs.h"
348 #include "multi_team.h"
349
350 #define TRUE    1
351 #define FALSE   0
352
353 sexp_oper Operators[] = {
354 //   Operator, Identity, Min / Max arguments
355         { "+",          OP_PLUS,                2,      INT_MAX },
356         { "-",          OP_MINUS,       2,      INT_MAX },
357         { "*",          OP_MUL,         2,      INT_MAX },
358         { "/",          OP_DIV,         2,      INT_MAX },
359         { "mod",                OP_MOD,         2,      INT_MAX },
360         { "rand",       OP_RAND,                2,      2                       },
361
362         { "true",                                                       OP_TRUE,                                                        0,      0,                      },
363         { "false",                                                      OP_FALSE,                                               0,      0,                      },
364         { "and",                                                                OP_AND,                                                 2,      INT_MAX,        },
365         { "and-in-sequence",                            OP_AND_IN_SEQUENCE,                     2, INT_MAX, },
366         { "or",                                                         OP_OR,                                                  2,      INT_MAX,        },
367         { "not",                                                                OP_NOT,                                                 1, 1,                   },
368         { "=",                                                          OP_EQUALS,                                              2,      INT_MAX,        },
369         { ">",                                                          OP_GREATER_THAN,                                2,      2,                      },
370         { "<",                                                          OP_LESS_THAN,                                   2,      2,                      },
371         { "is-iff",                                                     OP_IS_IFF,                                              2, INT_MAX,     },
372         { "has-time-elapsed",                   OP_HAS_TIME_ELAPSED,                    1,      1,                      },
373         { "modify-variable",                            OP_MODIFY_VARIABLE,                     2,      2,                      },
374
375         { "is-goal-incomplete",                                 OP_GOAL_INCOMPLETE,                             1, 1,   },
376         { "is-goal-true-delay",                                 OP_GOAL_TRUE_DELAY,                             2, 2,   },
377         { "is-goal-false-delay",                                OP_GOAL_FALSE_DELAY,                            2, 2,   },
378         { "is-event-incomplete",                                OP_EVENT_INCOMPLETE,                            1, 1,   },
379         { "is-event-true-delay",                                OP_EVENT_TRUE_DELAY,                            2, 2,   },
380         { "is-event-false-delay",                               OP_EVENT_FALSE_DELAY,                   2, 2,   },
381         { "is-previous-goal-incomplete",                OP_PREVIOUS_GOAL_INCOMPLETE,    2, 3,   },
382         { "is-previous-goal-true",                              OP_PREVIOUS_GOAL_TRUE,                  2, 3,   },
383         { "is-previous-goal-false",                     OP_PREVIOUS_GOAL_FALSE,                 2, 3,   },
384         { "is-previous-event-incomplete",       OP_PREVIOUS_EVENT_INCOMPLETE,   2, 3,   },
385         { "is-previous-event-true",                     OP_PREVIOUS_EVENT_TRUE,                 2, 3,   },
386         { "is-previous-event-false",                    OP_PREVIOUS_EVENT_FALSE,                2, 3,   },
387
388         { "is-destroyed",                                                       OP_IS_DESTROYED,                                                1,      INT_MAX,        },
389         { "is-subsystem-destroyed",                     OP_IS_SUBSYSTEM_DESTROYED,                      2, 2,                   },
390         { "is-disabled",                                                        OP_IS_DISABLED,                                         1, INT_MAX,     },
391         { "is-disarmed",                                                        OP_IS_DISARMED,                                         1, INT_MAX,     },
392         { "has-docked",                                                 OP_HAS_DOCKED,                                                  3, 3,                   },
393         { "has-undocked",                                                       OP_HAS_UNDOCKED,                                                3, 3,                   },
394         { "has-arrived",                                                        OP_HAS_ARRIVED,                                         1, INT_MAX,     },
395         { "has-departed",                                                       OP_HAS_DEPARTED,                                                1, INT_MAX,     },
396         { "is-destroyed-delay",                                 OP_IS_DESTROYED_DELAY,                          2,      INT_MAX,        },
397         { "is-subsystem-destroyed-delay",       OP_IS_SUBSYSTEM_DESTROYED_DELAY,        3, 3,                   },
398         { "is-disabled-delay",                                  OP_IS_DISABLED_DELAY,                           2, INT_MAX,     },
399         { "is-disarmed-delay",                                  OP_IS_DISARMED_DELAY,                           2, INT_MAX,     },
400         { "has-docked-delay",                                   OP_HAS_DOCKED_DELAY,                                    4, 4,                   },
401         { "has-undocked-delay",                                 OP_HAS_UNDOCKED_DELAY,                          4, 4,                   },
402         { "has-arrived-delay",                                  OP_HAS_ARRIVED_DELAY,                           2, INT_MAX,     },
403         { "has-departed-delay",                                 OP_HAS_DEPARTED_DELAY,                          2, INT_MAX,     },
404         { "are-waypoints-done",                                 OP_WAYPOINTS_DONE,                                      2, 2,                   },
405         { "are-waypoints-done-delay",                   OP_WAYPOINTS_DONE_DELAY,                        3, 3,                   },
406         { "ship-type-destroyed",                                OP_SHIP_TYPE_DESTROYED,                         2, 2,                   },
407         { "is-event-true",                                              OP_EVENT_TRUE,                                                  1, 1,                   },
408         { "is-event-false",                                             OP_EVENT_FALSE,                                         1, 1,                   },
409         { "is-cargo-known",                                             OP_IS_CARGO_KNOWN,                                      1, INT_MAX,     },
410         { "was-promotion-granted",                              OP_WAS_PROMOTION_GRANTED,                       0, 1,                   },
411         { "was-medal-granted",                                  OP_WAS_MEDAL_GRANTED,                           0, 1,                   },
412         { "percent-ships-departed",                     OP_PERCENT_SHIPS_DEPARTED,                      2, INT_MAX      },
413         { "percent-ships-destroyed",                    OP_PERCENT_SHIPS_DESTROYED,             2, INT_MAX      },
414         { "is-cargo-known-delay",                               OP_CARGO_KNOWN_DELAY,                           2, INT_MAX,     },
415         { "cap-subsys-cargo-known-delay",       OP_CAP_SUBSYS_CARGO_KNOWN_DELAY,        3, INT_MAX,     },
416         { "has-been-tagged-delay",                              OP_HAS_BEEN_TAGGED_DELAY,                       2, INT_MAX,     },
417         { "depart-node-delay",                                  OP_DEPART_NODE_DELAY,                           3, INT_MAX, },  
418         { "destroyed-or-departed-delay",                OP_DESTROYED_DEPARTED_DELAY,            2, INT_MAX, },  
419         { "is_tagged",                                                          OP_IS_TAGGED,                                                   1, 1                    },
420         { "num_kills",                                                          OP_NUM_KILLS,                                                   1, 1                    },
421         { "num_type_kills",                                             OP_NUM_TYPE_KILLS,                                      2,      2                       },
422         { "num_class_kills",                                            OP_NUM_CLASS_KILLS,                                     2,      2                       },
423         { "shield-recharge-pct",                                OP_SHIELD_RECHARGE_PCT,                         1, 1                    },
424         { "engine-recharge-pct",                                OP_ENGINE_RECHARGE_PCT,                         1, 1                    },
425         { "weapon-recharge-pct",                                OP_WEAPON_RECHARGE_PCT,                         1, 1                    },
426         { "shield-quad-low",                                            OP_SHIELD_QUAD_LOW,                                     2,      2                       },
427         { "secondary-ammo-pct",                                 OP_SECONDARY_AMMO_PCT,                          2,      2                       },
428         { "is-secondary-selected",                              OP_IS_SECONDARY_SELECTED,                       2,      2                       },
429         { "is-primary-selected",                                OP_IS_PRIMARY_SELECTED,                         2,      2                       },
430
431         { "time-ship-destroyed",        OP_TIME_SHIP_DESTROYED, 1,      1,      },
432         { "time-ship-arrived",          OP_TIME_SHIP_ARRIVED,   1,      1,      },
433         { "time-ship-departed",         OP_TIME_SHIP_DEPARTED,  1,      1,      },
434         { "time-wing-destroyed",        OP_TIME_WING_DESTROYED, 1,      1,      },
435         { "time-wing-arrived",          OP_TIME_WING_ARRIVED,   1,      1,      },
436         { "time-wing-departed",         OP_TIME_WING_DEPARTED,  1,      1,      },
437         { "mission-time",                               OP_MISSION_TIME,                        0, 0,   },
438         { "time-docked",                                OP_TIME_DOCKED,                 3, 3, },
439         { "time-undocked",                      OP_TIME_UNDOCKED,                       3, 3, },
440
441         { "shields-left",                                       OP_SHIELDS_LEFT,                                1, 1, },
442         { "hits-left",                                          OP_HITS_LEFT,                                   1, 1, },
443         { "hits-left-subsystem",                OP_HITS_LEFT_SUBSYSTEM,         2, 2, },
444         { "distance",                                           OP_DISTANCE,                                    2, 2, },
445         { "is-ship-visible",                            OP_IS_SHIP_VISIBLE,                     1, 1, },
446         { "team-score",                                 OP_TEAM_SCORE,                                  1,      1,      }, 
447         { "time-elapsed-last-order",    OP_LAST_ORDER_TIME,                     2, 2, /*INT_MAX*/ },
448         { "skill-level-at-least",               OP_SKILL_LEVEL_AT_LEAST,        1, 1, },
449         { "num-players",                                        OP_NUM_PLAYERS,                         0, 0, },
450         { "special-warp-dist",                  OP_SPECIAL_WARP_DISTANCE,       1, 1,   },
451
452         { "special-warpout-name",               OP_SET_SPECIAL_WARPOUT_NAME,    2, 2 },
453
454         { "do-nothing", OP_NOP, 0, 0,                   },
455         { "when",                       OP_WHEN,        2, INT_MAX, },
456         { "cond",                       OP_COND, 1, INT_MAX, },
457
458         { "add-goal",                                           OP_ADD_GOAL,                                            2, 2,                   },
459         { "add-ship-goal",                              OP_ADD_SHIP_GOAL,                                       2, 2,                   },
460         { "add-wing-goal",                              OP_ADD_WING_GOAL,                                       2, 2,                   },
461         { "clear-goals",                                        OP_CLEAR_GOALS,                                 1, INT_MAX,     },
462         { "clear-ship-goals",                   OP_CLEAR_SHIP_GOALS,                            1, 1,                   },
463         { "clear-wing-goals",                   OP_CLEAR_WING_GOALS,                            1, 1,                   },
464         { "change-iff",                                 OP_CHANGE_IFF,                                          2,      INT_MAX,        },
465         { "protect-ship",                                       OP_PROTECT_SHIP,                                        1, INT_MAX,     },
466         { "unprotect-ship",                             OP_UNPROTECT_SHIP,                              1, INT_MAX,     },
467         { "beam-protect-ship",                  OP_BEAM_PROTECT_SHIP,                   1, INT_MAX,     },
468         { "beam-unprotect-ship",                OP_BEAM_UNPROTECT_SHIP,                 1, INT_MAX,     },
469         { "send-message",                                       OP_SEND_MESSAGE,                                        3, 3,                   },
470         { "self-destruct",                              OP_SELF_DESTRUCT,                                       1, INT_MAX,     },
471         { "next-mission",                                       OP_NEXT_MISSION,                                        1, 1,                   },
472         { "end-campaign",                                       OP_END_CAMPAIGN,                                        0, 0,                   },
473         { "end-of-campaign",                            OP_END_OF_CAMPAIGN,                             0, 0,                   },
474         { "sabotage-subsystem",                 OP_SABOTAGE_SUBSYSTEM,                  3, 3,                   },
475         { "repair-subsystem",                   OP_REPAIR_SUBSYSTEM,                            3, 3,                   },
476         { "set-subsystem-strength",     OP_SET_SUBSYSTEM_STRNGTH,               3, 3,                   },
477         { "invalidate-goal",                            OP_INVALIDATE_GOAL,                             1, INT_MAX,     },
478         { "validate-goal",                              OP_VALIDATE_GOAL,                                       1, INT_MAX,     },
479         { "send-random-message",                OP_SEND_RANDOM_MESSAGE,                 3, INT_MAX,     },
480         { "transfer-cargo",                             OP_TRANSFER_CARGO,                              2, 2,                   },
481         { "exchange-cargo",                             OP_EXCHANGE_CARGO,                              2, 2,                   },
482         { "end-misison-delay",                  OP_END_MISSION_DELAY,                   1, 1,                   },
483         { "good-rearm-time",                            OP_GOOD_REARM_TIME,                             2,      2,                      },
484         { "grant-promotion",                            OP_GRANT_PROMOTION,                             0, 0,                   },
485         { "grant-medal",                                        OP_GRANT_MEDAL,                                 1, 1,                   },
486         { "allow-ship",                                 OP_ALLOW_SHIP,                                          1, 1,                   },
487         { "allow-weapon",                                       OP_ALLOW_WEAPON,                                        1, 1,                   },
488         { "break-warp",                                 OP_WARP_BROKEN,                                 1, INT_MAX,     },
489         { "fix-warp",                                           OP_WARP_NOT_BROKEN,                             1, INT_MAX,     },
490         { "never-warp",                                 OP_WARP_NEVER,                                          1, INT_MAX, },
491         { "allow-warp",                                 OP_WARP_ALLOWED,                                        1, INT_MAX, },
492         { "good-secondary-time",                OP_GOOD_SECONDARY_TIME,                 4, 4,                   },
493         { "ship-invisible",                             OP_SHIP_INVISIBLE,                              1, INT_MAX      },
494         { "ship-visible",                                       OP_SHIP_VISIBLE,                                        1, INT_MAX      },
495         { "ship-invulnerable",                  OP_SHIP_INVULNERABLE,                   1, INT_MAX      },
496         { "ship-vulnerable",                            OP_SHIP_VULNERABLE,                             1, INT_MAX      },
497         { "red-alert",                                          OP_RED_ALERT,                                           0, 0                    },
498         { "tech-add-ships",                             OP_TECH_ADD_SHIP,                                       1, INT_MAX      },
499         { "tech-add-weapons",                   OP_TECH_ADD_WEAPON,                             1, INT_MAX      },
500         { "jettison-cargo-delay",               OP_JETTISON_CARGO,                              2, 2                    },
501         { "fire-beam",                                          OP_BEAM_FIRE,                                           3, 4                    },
502         { "beam-free",                                          OP_BEAM_FREE,                                           2, INT_MAX      },
503         { "beam-free-all",                              OP_BEAM_FREE_ALL,                                       1, 1                    },
504         { "beam-lock",                                          OP_BEAM_LOCK,                                           2, INT_MAX      },
505         { "beam-lock-all",                              OP_BEAM_LOCK_ALL,                                       1, 1                    },
506         { "turret-free",                                        OP_TURRET_FREE,                                 2, INT_MAX      },
507         { "turret-free-all",                            OP_TURRET_FREE_ALL,                             1, 1                    },
508         { "turret-lock",                                        OP_TURRET_LOCK,                                 2, INT_MAX      },
509         { "turret-lock-all",                            OP_TURRET_LOCK_ALL,                             1, 1                    },
510         { "add-remove-escort",                  OP_ADD_REMOVE_ESCORT,                   2, 2                    },
511         { "awacs-set-radius",                   OP_AWACS_SET_RADIUS,                            3,      3                       },
512         { "send-message-list",                  OP_SEND_MESSAGE_LIST,                   4, INT_MAX      },
513         { "cap-waypoint-speed",                 OP_CAP_WAYPOINT_SPEED,                  2, 2                    },
514         { "ship-guardian",                              OP_SHIP_GUARDIAN,                                       1, INT_MAX      },
515         { "ship-no-guardian",                   OP_SHIP_NO_GUARDIAN,                            1, INT_MAX      },
516         { "ship-vanish",                                        OP_SHIP_VANISH,                                 1, INT_MAX      },
517         { "turret-tagged-only",                 OP_TURRET_TAGGED_ONLY_ALL,              1,      1                       },
518         { "turret-tagged-clear",                OP_TURRET_TAGGED_CLEAR_ALL,     1,      1                       },
519         { "subsys-set-random",                  OP_SUBSYS_SET_RANDOM,                   3, INT_MAX      },
520         { "supernova-start",                            OP_SUPERNOVA_START,                             1,      1                       },
521         { "cargo-no-deplete",                   OP_CARGO_NO_DEPLETE,                            1,      2                       },
522
523         { "error",      OP_INT3,        0, 0 },
524
525         { "ai-chase",                                   OP_AI_CHASE,                                    2, 2, },
526         { "ai-chase-wing",                      OP_AI_CHASE_WING,                               2, 2, },
527         { "ai-dock",                                    OP_AI_DOCK,                                             4, 4, },
528         { "ai-undock",                                  OP_AI_UNDOCK,                                   1, 1, },
529         { "ai-warp",                                    OP_AI_WARP,                                             2, 2, },
530         { "ai-warp-out",                                OP_AI_WARP_OUT,                         1, 1, },
531         { "ai-waypoints",                               OP_AI_WAYPOINTS,                                2, 2, },
532         { "ai-waypoints-once",          OP_AI_WAYPOINTS_ONCE,           2, 2, },
533         { "ai-destroy-subsystem",       OP_AI_DESTROY_SUBSYS,           3, 3, },
534         { "ai-disable-ship",                    OP_AI_DISABLE_SHIP,                     2, 2, },
535         { "ai-disarm-ship",                     OP_AI_DISARM_SHIP,                      2, 2, },
536         { "ai-guard",                                   OP_AI_GUARD,                                    2, 2, },
537         { "ai-chase-any",                               OP_AI_CHASE_ANY,                                1, 1, },
538         { "ai-guard-wing",                      OP_AI_GUARD_WING,                               2, 2, },
539         { "ai-evade-ship",                      OP_AI_EVADE_SHIP,                               2, 2,   },
540         { "ai-stay-near-ship",          OP_AI_STAY_NEAR_SHIP,           2, 2, },
541         { "ai-keep-safe-distance",      OP_AI_KEEP_SAFE_DISTANCE,       1, 1, },
542         { "ai-ignore",                                  OP_AI_IGNORE,                                   2, 2, },
543         { "ai-stay-still",                      OP_AI_STAY_STILL,                               2, 2, },
544         { "ai-play-dead",                               OP_AI_PLAY_DEAD,                                1, 1, },
545
546         { "goals",      OP_GOALS_ID,    1, INT_MAX, },
547
548         { "key-pressed",                                OP_KEY_PRESSED,                         1,      2,                      },
549         { "key-reset",                                  OP_KEY_RESET,                                   1, INT_MAX,     },
550         { "targeted",                                   OP_TARGETED,                                    1, 3,                   },
551         { "speed",                                              OP_SPEED,                                               1, 1,                   },
552         { "facing",                                             OP_FACING,                                              2, 2,                   },
553         { "facing-waypoint",                    OP_FACING2,                                             2, 2,                   },
554         { "order",                                              OP_ORDER,                                               2, 2,                   },
555         { "waypoint-missed",                    OP_WAYPOINT_MISSED,                     0, 0,                   },
556         { "waypoint-twice",                     OP_WAYPOINT_TWICE,                      0, 0,                   },
557         { "path-flown",                         OP_PATH_FLOWN,                                  0, 0,                   },
558         { "training-msg",                               OP_TRAINING_MSG,                                1, 4,                   },
559         { "flash-hud-gauge",                    OP_FLASH_HUD_GAUGE,                     1, 1,                   },
560         { "special-check",                      OP_SPECIAL_CHECK,                               1, 1,                   },
561         { "secondaries-depleted",       OP_SECONDARIES_DEPLETED,        1, 1,                   },
562
563         { "set-training-context-fly-path",      OP_SET_TRAINING_CONTEXT_FLY_PATH,       2, 2, },
564         { "set-training-context-speed",         OP_SET_TRAINING_CONTEXT_SPEED,          2, 2, },
565 };
566
567 sexp_ai_goal_link Sexp_ai_goal_links[] = {
568         { AI_GOAL_CHASE, OP_AI_CHASE },
569         { AI_GOAL_CHASE_WING, OP_AI_CHASE_WING },
570         { AI_GOAL_DOCK, OP_AI_DOCK },
571         { AI_GOAL_UNDOCK, OP_AI_UNDOCK },
572         { AI_GOAL_WARP, OP_AI_WARP_OUT },
573         { AI_GOAL_WARP, OP_AI_WARP },
574         { AI_GOAL_WAYPOINTS, OP_AI_WAYPOINTS },
575         { AI_GOAL_WAYPOINTS_ONCE, OP_AI_WAYPOINTS_ONCE },
576         { AI_GOAL_DESTROY_SUBSYSTEM, OP_AI_DESTROY_SUBSYS },
577         { AI_GOAL_DISABLE_SHIP, OP_AI_DISABLE_SHIP },
578         { AI_GOAL_DISARM_SHIP, OP_AI_DISARM_SHIP },
579         { AI_GOAL_GUARD, OP_AI_GUARD },
580         { AI_GOAL_CHASE_ANY, OP_AI_CHASE_ANY },
581         { AI_GOAL_GUARD_WING, OP_AI_GUARD_WING },
582         { AI_GOAL_EVADE_SHIP, OP_AI_EVADE_SHIP },
583         { AI_GOAL_STAY_NEAR_SHIP, OP_AI_STAY_NEAR_SHIP },
584         { AI_GOAL_KEEP_SAFE_DISTANCE, OP_AI_KEEP_SAFE_DISTANCE },
585         { AI_GOAL_IGNORE, OP_AI_IGNORE },
586         { AI_GOAL_STAY_STILL, OP_AI_STAY_STILL },
587         { AI_GOAL_PLAY_DEAD, OP_AI_PLAY_DEAD },
588 };
589
590 const char *HUD_gauge_text[NUM_HUD_GAUGES] = 
591 {
592         "LEAD_INDICATOR",
593         "ORIENTATION_TEE",
594         "HOSTILE_TRIANGLE",
595         "TARGET_TRIANGLE",
596         "MISSION_TIME",
597         "RETICLE_CIRCLE",
598         "THROTTLE_GAUGE",
599         "RADAR",
600         "TARGET_MONITOR",
601         "CENTER_RETICLE",
602         "TARGET_MONITOR_EXTRA_DATA",
603         "TARGET_SHIELD_ICON",
604         "PLAYER_SHIELD_ICON",
605         "ETS_GAUGE",
606         "AUTO_TARGET",
607         "AUTO_SPEED",
608         "WEAPONS_GAUGE",
609         "ESCORT_VIEW",
610         "DIRECTIVES_VIEW",
611         "THREAT_GAUGE",
612         "AFTERBURNER_ENERGY",
613         "WEAPONS_ENERGY",
614         "WEAPON_LINKING_GAUGE",
615         "TARGER_MINI_ICON",
616         "OFFSCREEN_INDICATOR",
617         "TALKING_HEAD",
618         "DAMAGE_GAUGE",
619         "MESSAGE_LINES",
620         "MISSILE_WARNING_ARROW",
621         "CMEASURE_GAUGE",
622         "OBJECTIVES_NOTIFY_GAUGE",
623         "WINGMEN_STATUS",
624         "OFFSCREEN RANGE",
625         "KILLS GAUGE",
626         "ATTACKING TARGET COUNT",
627         "TEXT FLASH",
628         "MESSAGE BOX",
629         "SUPPORT GUAGE",
630         "LAG GUAGE"
631 };
632
633
634 int     Directive_count;
635 int     Sexp_useful_number;  // a variable to pass useful info in from external modules
636 int     Locked_sexp_true, Locked_sexp_false;
637 int     Num_operators = sizeof(Operators) / sizeof(sexp_oper);
638 int     Num_sexp_ai_goal_links = sizeof(Sexp_ai_goal_links) / sizeof(sexp_ai_goal_link);
639 int     Sexp_build_flag;
640 int     Sexp_clipboard = -1;  // used by Fred
641 int     Training_context = 0;
642 int     Training_context_speed_set;
643 int     Training_context_speed_min;
644 int     Training_context_speed_max;
645 int     Training_context_speed_timestamp;
646 int     Training_context_path;
647 int     Training_context_goal_waypoint;
648 int     Training_context_at_waypoint;
649 float   Training_context_distance;
650 char    Sexp_error_text[MAX_SEXP_TEXT];
651 char    *Sexp_string; //[1024] = {0};
652 int Sexp_string_len;
653 sexp_node Sexp_nodes[MAX_SEXP_NODES];
654 sexp_variable Sexp_variables[MAX_SEXP_VARIABLES];
655
656 int Players_target = UNINITIALIZED;
657 ship_subsys *Players_targeted_subsys;
658 int Players_target_timestamp;
659
660 int get_sexp(char *token);
661 int eval_sexp(int cur_node);
662 void build_extended_sexp_string(int cur_node, int level, int mode);
663 void update_sexp_references(char *old_name, char *new_name, int format, int node);
664 int sexp_determine_team(char *subj);
665 int sexp_distance2(int obj1, char *subj);
666 int sexp_distance3(int obj1, int obj2);
667 int extract_sexp_variable_index(int node);
668 void init_sexp_vars();
669 int num_eval(int node);
670
671 void init_sexp()
672 {
673         int i;
674
675         for (i=0; i<MAX_SEXP_NODES; i++) {
676                 if ( !(Sexp_nodes[i].type & SEXP_FLAG_PERSISTENT) ){
677                         Sexp_nodes[i].type = SEXP_NOT_USED;
678                 }
679         }
680
681         init_sexp_vars();
682
683         Locked_sexp_false = Locked_sexp_true = -1;
684         Locked_sexp_false = alloc_sexp("false", SEXP_LIST, SEXP_ATOM_OPERATOR, -1, -1);
685         SDL_assert(Locked_sexp_false != -1);
686         Sexp_nodes[Locked_sexp_false].type = SEXP_ATOM;  // fix bypassing value
687         Locked_sexp_true = alloc_sexp("true", SEXP_LIST, SEXP_ATOM_OPERATOR, -1, -1);
688         SDL_assert(Locked_sexp_true != -1);
689         Sexp_nodes[Locked_sexp_true].type = SEXP_ATOM;  // fix bypassing value
690 }
691
692 // allocates an sexp node.
693 int alloc_sexp(const char *text, int type, int subtype, int first, int rest)
694 {
695         int i;
696
697         i = find_operator(text);
698         if ((i == OP_TRUE) && (type == SEXP_ATOM) &&    (subtype == SEXP_ATOM_OPERATOR)) {
699                 return Locked_sexp_true;
700         } else if ((i == OP_FALSE) && (type == SEXP_ATOM) && (subtype == SEXP_ATOM_OPERATOR)) {
701                 return Locked_sexp_false;
702         }
703
704         i = find_free_sexp();
705         SDL_assert(i != Locked_sexp_true);
706         SDL_assert(i != Locked_sexp_false);
707         if (i == MAX_SEXP_NODES){
708                 return -1;
709         }
710
711         SDL_assert(strlen(text) < TOKEN_LENGTH);
712         SDL_strlcpy(Sexp_nodes[i].text, text, TOKEN_LENGTH);
713         SDL_assert(type >= 0);
714         Sexp_nodes[i].type = type;
715         Sexp_nodes[i].subtype = subtype;
716         Sexp_nodes[i].first = first;
717         Sexp_nodes[i].rest = rest;
718         Sexp_nodes[i].value = SEXP_UNKNOWN;
719         return i;
720 }
721
722 int Sexp_hwm = 0;
723
724 int count_free_sexp_nodes()
725 {
726         int i, f = 0, p = 0;
727
728         for (i=0; i<MAX_SEXP_NODES; i++) {
729                 if (Sexp_nodes[i].type == SEXP_NOT_USED){
730                         f++;
731                 } else if (Sexp_nodes[i].type & SEXP_FLAG_PERSISTENT){
732                         p++;
733                 }
734         }
735
736         if (MAX_SEXP_NODES - f > Sexp_hwm) {
737                 nprintf(("Sexp", "Sexp nodes: Free=%d, Used=%d, Persistent=%d\n", f, MAX_SEXP_NODES - f, p));
738                 Sexp_hwm = MAX_SEXP_NODES - f;
739         }
740
741         return f;
742 }
743
744 // find the next free sexp and return it's index.
745 int find_free_sexp()
746 {
747         int i;
748
749         for (i=0; i<MAX_SEXP_NODES; i++){
750                 if (Sexp_nodes[i].type == SEXP_NOT_USED){
751                         break;
752                 }
753         }
754
755 #ifndef NDEBUG
756         //count_free_sexp_nodes();
757 #endif
758
759         SDL_assert(i != MAX_SEXP_NODES);  // time to raise the limit..
760         if (i == MAX_SEXP_NODES){
761                 return -1;
762         }
763
764         return i;
765 }
766
767 // sexp_mark_persistent() marks a whole sexp tree with the persistent flag so that it won't
768 // get re-used between missions
769 void sexp_mark_persistent( int n )
770 {
771         if (n == -1){
772                 return;
773         }
774
775         // total hack because of the true/false locked sexps -- we should make those persistent as well
776         if ( (n == Locked_sexp_true) || (n == Locked_sexp_false) ){
777                 return;
778         }
779
780         SDL_assert( !(Sexp_nodes[n].type & SEXP_FLAG_PERSISTENT) );
781         Sexp_nodes[n].type |= SEXP_FLAG_PERSISTENT;
782
783         sexp_mark_persistent(Sexp_nodes[n].first);
784         sexp_mark_persistent(Sexp_nodes[n].rest);
785
786 }
787
788 // sexp_unmark_persistent() removes the persistent flag from all nodes in the tree
789 void sexp_unmark_persistent( int n )
790 {
791         if (n == -1){
792                 return;
793         }
794
795         if ( (n == Locked_sexp_true) || (n == Locked_sexp_false) ){
796                 return;
797         }
798
799         SDL_assert( Sexp_nodes[n].type & SEXP_FLAG_PERSISTENT );
800         Sexp_nodes[n].type &= ~SEXP_FLAG_PERSISTENT;
801
802         sexp_unmark_persistent(Sexp_nodes[n].first);
803         sexp_unmark_persistent(Sexp_nodes[n].rest);
804 }
805
806 // just frees up the specified sexp node,  Leaves link chains untouched.
807 int free_one_sexp(int num)
808 {
809         SDL_assert(Sexp_nodes[num].type != SEXP_NOT_USED);  // make sure it is actually used
810         SDL_assert( !(Sexp_nodes[num].type & SEXP_FLAG_PERSISTENT) );
811
812         if ((num == Locked_sexp_true) || (num == Locked_sexp_false)){
813                 return 0;
814         }
815
816         Sexp_nodes[num].type = SEXP_NOT_USED;
817         return 1;
818 }
819
820 // frees a used sexp node, so it can be reused later.  Should only be called on
821 // an atom or a list, and not an operator.  If on a list, the list and everything
822 // in it will be freed (including the operator).
823 int free_sexp(int num)
824 {
825         int i, rest, count = 0;
826
827         SDL_assert(Sexp_nodes[num].type != SEXP_NOT_USED);  // make sure it is actually used
828         SDL_assert( !(Sexp_nodes[num].type & SEXP_FLAG_PERSISTENT) );
829
830         if ((num == Locked_sexp_true) || (num == Locked_sexp_false) || (num == -1) ){
831                 return 0;
832         }
833
834         Sexp_nodes[num].type = SEXP_NOT_USED;
835         count++;
836
837         i = Sexp_nodes[num].first;
838         while (i != -1){
839                 count += free_sexp(i);
840                 i = Sexp_nodes[i].rest;
841         }
842
843         rest = Sexp_nodes[num].rest;
844         for (i=0; i<MAX_SEXP_NODES; i++) {
845                 if (Sexp_nodes[i].first == num){
846                         Sexp_nodes[i].first = rest;
847                 }
848
849                 if (Sexp_nodes[i].rest == num){
850                         Sexp_nodes[i].rest = rest;
851                 }
852         }
853
854         return count;  // total elements freed up.
855 }
856
857 // used to free up an entire sexp tree.  Because the root node is an operator, instead of
858 // a list, we can't simply call free_sexp().  This function should only be called on the
859 // root node of an sexp, otherwise the linking will get screwed up.
860 int free_sexp2(int num)
861 {       
862         int i, count = 0;
863
864         if ((num == -1) || (num == Locked_sexp_true) || (num == Locked_sexp_false)){
865                 return 0;
866         }
867
868         i = Sexp_nodes[num].rest;
869         while (i != -1) {
870                 count += free_sexp(i);
871                 i = Sexp_nodes[i].rest;
872         }
873
874         count += free_sexp(num);
875         return count;
876 }
877
878 // This function resets the status of all the nodes in a tree, forcing them to all be
879 // evaulated again.
880 void flush_sexp_tree(int node)
881 {
882         if (node < 0){
883                 return;
884         }
885
886         Sexp_nodes[node].value = SEXP_UNKNOWN;
887         flush_sexp_tree(Sexp_nodes[node].first);
888         flush_sexp_tree(Sexp_nodes[node].rest);
889 }
890
891 int verify_sexp_tree(int node)
892 {
893         if (node == -1){
894                 return 0;
895         }
896
897         if ((Sexp_nodes[node].type == SEXP_NOT_USED) ||
898                 (Sexp_nodes[node].first == node) ||
899                 (Sexp_nodes[node].rest == node)) {
900                 Error(LOCATION, "Sexp node is corrupt");
901                 return -1;
902         }
903
904         if (Sexp_nodes[node].first != -1){
905                 verify_sexp_tree(Sexp_nodes[node].first);
906         }
907         if (Sexp_nodes[node].rest != -1){
908                 verify_sexp_tree(Sexp_nodes[node].rest);
909         }
910
911         return 0;
912 }
913
914 int dup_sexp_chain(int node)
915 {
916         int cur, first, rest;
917
918         if (node == -1){
919                 return -1;
920         }
921
922         // TODO - CASE OF SEXP VARIABLES - ONLY 1 COPY OF VARIABLE
923         first = dup_sexp_chain(Sexp_nodes[node].first);
924         rest = dup_sexp_chain(Sexp_nodes[node].rest);
925         cur = alloc_sexp(Sexp_nodes[node].text, Sexp_nodes[node].type, Sexp_nodes[node].subtype, first, rest);
926
927         if (cur == -1) {
928                 if (first != -1){
929                         free_sexp(first);
930                 }
931                 if (rest != -1){
932                         free_sexp(rest);
933                 }
934         }
935
936         return cur;
937 }
938
939 // returns 1 if they are the same, 0 if different
940 int cmp_sexp_chains(int node1, int node2)
941 {
942         if ((node1 == -1) && (node2 == -1)){
943                 return 1;
944         }
945
946         if ((node1 == -1) || (node2 == -1)){
947                 return 0;
948         }
949
950         // DA: 1/7/99 Need to check the actual Sexp_node.text, not possible variable, which can be equal
951         if (SDL_strcasecmp(Sexp_nodes[node1].text, Sexp_nodes[node2].text)){
952                 return 0;
953         }
954
955         if (!cmp_sexp_chains(Sexp_nodes[node1].first, Sexp_nodes[node2].first)){
956                 return 0;
957         }
958
959         if (!cmp_sexp_chains(Sexp_nodes[node1].rest, Sexp_nodes[node2].rest)){
960                 return 0;
961         }
962
963         return 1;
964 }
965
966 // determine if an sexp node is within the given sexp chain.
967 int query_node_in_sexp(int node, int sexp)
968 {
969         if (sexp == -1){
970                 return 0;
971         }
972         if (node == sexp){
973                 return 1;
974         }
975
976         if (query_node_in_sexp(node, Sexp_nodes[sexp].first)){
977                 return 1;
978         }
979         if (query_node_in_sexp(node, Sexp_nodes[sexp].rest)){
980                 return 1;
981         }
982
983         return 0;
984 }
985
986 // find the index of the list associated with an operator
987 int find_sexp_list(int num)
988 {
989         int i;
990
991         for (i=0; i<MAX_SEXP_NODES; i++){
992                 if (Sexp_nodes[i].first == num){
993                         return i;
994                 }
995         }
996
997         return -1;
998 }
999
1000 // find index of operator that item is an argument of.
1001 int find_parent_operator(int num)
1002 {
1003         int i;
1004
1005         if (Sexp_nodes[num].subtype == SEXP_ATOM_OPERATOR){
1006                 num = find_sexp_list(num);
1007         }
1008
1009         while (Sexp_nodes[num].subtype != SEXP_ATOM_OPERATOR) {
1010                 for (i=0; i<MAX_SEXP_NODES; i++){
1011                         if (Sexp_nodes[i].rest == num){
1012                                 break;
1013                         }
1014                 }
1015
1016                 if (i == MAX_SEXP_NODES){
1017                         return -1;  // not found, probably at top node already.
1018                 }
1019
1020                 num = i;
1021         }
1022
1023         return num;
1024 }
1025
1026 // function to determine if an sexpression node is the top level node of an sexpression tree.  Top
1027 // level nodes do not have their node id in anyone elses first or rest index
1028 int is_sexp_top_level( int node )
1029 {
1030         int i;
1031
1032         if ( Sexp_nodes[node].type == SEXP_NOT_USED ){
1033                 return 0;
1034         }
1035
1036         for (i = 0; i < MAX_SEXP_NODES; i++ ) {
1037                 if ( (Sexp_nodes[i].type == SEXP_NOT_USED) || ( i == node ) ){                          // don't check myself or unused nodes
1038                         continue;
1039                 }
1040                 if ( (Sexp_nodes[i].first == node) || (Sexp_nodes[i].rest == node) ){
1041                         return 0;
1042                 }
1043         }
1044
1045         return 1;
1046 }
1047
1048 int identify_operator(const char *token)
1049 {
1050         int     i;
1051
1052         for (i=0; i<Num_operators; i++){
1053                 if (!SDL_strcasecmp(token, Operators[i].text)){
1054                         return i;
1055                 }
1056         }
1057
1058         return -1;
1059 }
1060
1061 int find_operator(const char *token)
1062 {
1063         int     i;
1064
1065         for (i=0; i<Num_operators; i++){
1066                 if (!SDL_strcasecmp(token, Operators[i].text)){
1067                         return Operators[i].value;
1068                 }
1069         }
1070
1071         return 0;
1072 }
1073
1074 int query_sexp_args_count(int index)
1075 {
1076         int count = 0;
1077
1078         while (Sexp_nodes[index].rest != -1){
1079                 count++;
1080                 index = Sexp_nodes[index].rest;
1081         }
1082
1083         return count;
1084 }
1085
1086 // returns 0 if ok, negative if there's an error in expression..
1087 // See the returns types in sexp.h
1088
1089 int check_sexp_syntax(int index, int return_type, int recursive, int *bad_index, int mode)
1090 {
1091         int i = 0, z, t, type, argnum = 0, count, op, type2 = 0, op2;
1092         int op_index;
1093
1094         SDL_assert(index >= 0 && index < MAX_SEXP_NODES);
1095         SDL_assert(Sexp_nodes[index].type != SEXP_NOT_USED);
1096         if (Sexp_nodes[index].subtype == SEXP_ATOM_NUMBER && return_type == OPR_BOOL) {
1097                 // special case Mark seems to want supported
1098                 SDL_assert(Sexp_nodes[index].first == -1);  // only lists should have a first pointer
1099                 if (Sexp_nodes[index].rest != -1)  // anything after the number?
1100                         return SEXP_CHECK_NONOP_ARGS; // if so, it's a syntax error
1101
1102                 return 0;
1103         }
1104
1105         op_index = index;               // save the index of the operator since we need to get to other args.
1106         if (bad_index)
1107                 *bad_index = op_index;
1108
1109         if (Sexp_nodes[op_index].subtype != SEXP_ATOM_OPERATOR)
1110                 return SEXP_CHECK_OP_EXPTECTED;  // not an operator, which it should always be
1111
1112         op = identify_operator(CTEXT(op_index));
1113         if (op == -1)
1114                 return SEXP_CHECK_UNKNOWN_OP;  // unrecognized operator
1115
1116         //special case - OPR_AMBIGUOUS matches all
1117         if (return_type != OPR_AMBIGUOUS) {
1118                 if (query_operator_return_type(op) != return_type) {
1119                         return SEXP_CHECK_TYPE_MISMATCH;
1120                 }
1121         } 
1122
1123         count = query_sexp_args_count(op_index);
1124         if (count < Operators[op].min || count > Operators[op].max)
1125                 return SEXP_CHECK_BAD_ARG_COUNT;  // incorrect number of arguments
1126
1127         index = Sexp_nodes[op_index].rest;
1128         while (index != -1) {
1129                 type = query_operator_argument_type(op, argnum);
1130                 SDL_assert(Sexp_nodes[index].type != SEXP_NOT_USED);
1131                 if (bad_index)
1132                         *bad_index = index;
1133
1134                 if (Sexp_nodes[index].subtype == SEXP_ATOM_LIST) {
1135                         i = Sexp_nodes[index].first;
1136                         if (bad_index)
1137                                 *bad_index = i;
1138                         
1139                         // be sure to check to see if this node is a list of stuff and not an actual operator type
1140                         // thing.  (i.e. in the case of a cond statement, the conditional will fall into this if
1141                         // statement.  MORE TO DO HERE!!!!
1142                         if (Sexp_nodes[i].subtype == SEXP_ATOM_LIST)
1143                                 return 0;
1144
1145                         op2 = identify_operator(CTEXT(i));
1146                         if (op2 == -1)
1147                                 return SEXP_CHECK_UNKNOWN_OP;
1148
1149                         type2 = query_operator_return_type(op2);
1150                         if (recursive) {
1151                                 switch (type) {
1152                                         case OPF_NUMBER:
1153                                                 t = OPR_NUMBER;
1154                                                 break;
1155
1156                                         case OPF_POSITIVE:
1157                                                 t = OPR_POSITIVE;
1158                                                 break;
1159
1160                                         case OPF_BOOL:
1161                                                 t = OPR_BOOL;
1162                                                 break;
1163
1164                                         case OPF_NULL:
1165                                                 t = OPR_NULL;
1166                                                 break;
1167
1168                                         case OPF_AI_GOAL:
1169                                                 t = OPR_AI_GOAL;
1170                                                 break;
1171
1172                                         // special case for modify-variable"
1173                                         case OPF_AMBIGUOUS:
1174                                                 t = OPR_AMBIGUOUS;
1175                                                 break;
1176
1177                                         default:
1178                                                 return SEXP_CHECK_UNKNOWN_TYPE;  // no other return types available
1179                                 }
1180
1181                                 if ((z = check_sexp_syntax(i, t, recursive, bad_index)) != 0) {
1182                                         return z;
1183                                 }
1184                         }
1185
1186                 } else if (Sexp_nodes[index].subtype == SEXP_ATOM_NUMBER) {
1187                         char *ptr;
1188
1189                         type2 = OPR_POSITIVE;
1190                         ptr = CTEXT(index);
1191                         if (*ptr == '-') {
1192                                 type2 = OPR_NUMBER;
1193                                 ptr++;
1194                         }
1195
1196                         if (type == OPF_BOOL)  // allow numbers to be used where boolean is required.
1197                                 type2 = OPR_BOOL;
1198
1199                         while (*ptr) {
1200                                 if (!isdigit(*ptr))
1201                                         return SEXP_CHECK_INVALID_NUM;  // not a valid number
1202
1203                                 ptr++;
1204                         }
1205
1206                         i = atoi(CTEXT(index));
1207                         z = find_operator(CTEXT(op_index));
1208                         if ( (z == OP_HAS_DOCKED_DELAY) || (z == OP_HAS_UNDOCKED_DELAY) )
1209                                 if ( (argnum == 2) && (i < 1) )
1210                                         return SEXP_CHECK_NUM_RANGE_INVALID;
1211
1212                         z = identify_operator(CTEXT(op_index));
1213                         if ( (query_operator_return_type(z) == OPR_AI_GOAL) && (argnum == Operators[op].min - 1) )
1214                                 if ( (i < 0) || (i > 89) )
1215                                         return SEXP_CHECK_NUM_RANGE_INVALID;
1216
1217                 } else if (Sexp_nodes[index].subtype == SEXP_ATOM_STRING) {
1218                         type2 = SEXP_ATOM_STRING;
1219
1220                 } else {
1221                         SDL_assert(0);
1222                 }
1223
1224                 switch (type) {
1225                         case OPF_NUMBER:
1226                                 if ((type2 != OPR_NUMBER) && (type2 != OPR_POSITIVE)){
1227                                         return SEXP_CHECK_TYPE_MISMATCH;
1228                                 }
1229
1230                                 break;
1231
1232                         case OPF_POSITIVE:
1233                                 if (type2 == OPR_NUMBER){
1234                                         return SEXP_CHECK_NEGATIVE_NUM;
1235                                 }
1236
1237                                 if (type2 != OPR_POSITIVE){
1238                                         return SEXP_CHECK_TYPE_MISMATCH;
1239                                 }
1240
1241                                 break;
1242
1243                         case OPF_SHIP_NOT_PLAYER:
1244                                 if (type2 != SEXP_ATOM_STRING){
1245                                         return SEXP_CHECK_TYPE_MISMATCH;
1246                                 }
1247
1248                                 if (ship_name_lookup(CTEXT(index), 0) < 0) {
1249                                         if (Fred_running || mission_parse_ship_arrived(CTEXT(index))){  // == 0 when still on arrival list
1250                                                 return SEXP_CHECK_INVALID_SHIP;
1251                                         }
1252                                 }
1253
1254                                 break;
1255
1256                         case OPF_SHIP:
1257                         case OPF_SHIP_POINT:
1258                                 if (type2 != SEXP_ATOM_STRING){
1259                                         return SEXP_CHECK_TYPE_MISMATCH;
1260                                 }
1261
1262                                 if (ship_name_lookup(CTEXT(index), 1) < 0) {
1263                                         if (Fred_running || mission_parse_ship_arrived(CTEXT(index))) {         // == 0 when still on arrival list
1264                                                 if (type == OPF_SHIP){                                                                                                  // return invalid ship if not also looking for point
1265                                                         return SEXP_CHECK_INVALID_SHIP;
1266                                                 }
1267
1268                                                 if (waypoint_lookup(CTEXT(index)) < 0){
1269                                                         if (verify_vector(CTEXT(index))){                                               // verify return non-zero on invalid point
1270                                                                 return SEXP_CHECK_INVALID_POINT;
1271                                                         }
1272                                                 }
1273                                         }
1274                                 }
1275
1276                                 break;
1277
1278                         case OPF_WING:
1279                                 if (type2 != SEXP_ATOM_STRING){
1280                                         return SEXP_CHECK_TYPE_MISMATCH;
1281                                 }
1282
1283                                 if (wing_name_lookup(CTEXT(index), 1) < 0){
1284                                         return SEXP_CHECK_INVALID_WING;
1285                                 }
1286
1287                                 break;
1288
1289                         case OPF_SHIP_WING:
1290                         case OPF_SHIP_WING_POINT:
1291                                 if ( type2 != SEXP_ATOM_STRING ){
1292                                         return SEXP_CHECK_TYPE_MISMATCH;
1293                                 }
1294
1295                                 if ((ship_name_lookup(CTEXT(index), 1) < 0) && (wing_name_lookup(CTEXT(index), 1) < 0)) {
1296                                         if (Fred_running || mission_parse_ship_arrived(CTEXT(index))) {         // == 0 when still on arrival list
1297                                                 if (type != OPF_SHIP_WING_POINT){                                                                       // return invalid if not also looking for point
1298                                                         return SEXP_CHECK_INVALID_SHIP_WING;
1299                                                 }
1300
1301                                                 if (waypoint_lookup(CTEXT(index)) < 0){
1302                                                         if (verify_vector(CTEXT(index))){  // non-zero on verify vector mean invalid!
1303                                                                 if (!sexp_determine_team(CTEXT(index))){
1304                                                                         return SEXP_CHECK_INVALID_POINT;
1305                                                                 }
1306                                                         }
1307                                                 }
1308                                         }
1309                                 }
1310
1311                                 break;
1312
1313                         case OPF_AWACS_SUBSYSTEM:
1314                         case OPF_SUBSYSTEM: {
1315                                 char *shipname;
1316                                 int shipnum,ship_class;
1317                                 int ship_index;                         
1318
1319                                 if (type2 != SEXP_ATOM_STRING){
1320                                         return SEXP_CHECK_TYPE_MISMATCH;
1321                                 }
1322
1323                                 // we must get the model of the ship that is part of this sexpression and find a subsystem
1324                                 // with that name.  This code assumes that the ship *always* preceeds the subsystem in an sexpression.
1325                                 // if this current fact is ever not the case, the next lines of code must be changes to get the correct
1326                                 // shipname.                            
1327                                 switch(Operators[identify_operator(CTEXT(op_index))].value){
1328                                 case OP_CAP_SUBSYS_CARGO_KNOWN_DELAY:
1329                                         ship_index = Sexp_nodes[Sexp_nodes[op_index].rest].rest;
1330                                         break;
1331
1332                                 case OP_BEAM_FIRE:
1333                                         if(argnum == 1){
1334                                                 ship_index = Sexp_nodes[op_index].rest;
1335                                         } else {
1336                                                 ship_index = Sexp_nodes[Sexp_nodes[Sexp_nodes[op_index].rest].rest].rest;
1337                                         }
1338                                         break;
1339                                 
1340                                 default :
1341                                         ship_index = Sexp_nodes[op_index].rest;
1342                                         break;
1343                                 }
1344
1345                                 shipname = CTEXT(ship_index);
1346                                 shipnum = ship_name_lookup(shipname);
1347                                 if (shipnum >= 0){
1348                                         ship_class = Ships[shipnum].ship_info_index;
1349                                 } else {
1350                                         // must try to find the ship in the ship_arrival_list
1351                                         p_object *parse_obj;
1352
1353                                         parse_obj = mission_parse_get_arrival_ship( shipname );
1354                                         if ( parse_obj == NULL ){
1355                                                 return SEXP_CHECK_INVALID_SHIP;
1356                                         }
1357
1358                                         ship_class = parse_obj->ship_class;
1359                                 }
1360
1361                                 // check for the special "hull" value
1362                                 if ( (Operators[op].value == OP_SABOTAGE_SUBSYSTEM) || (Operators[op].value == OP_REPAIR_SUBSYSTEM) || (Operators[op].value == OP_SET_SUBSYSTEM_STRNGTH) ) {
1363                                         if ( !SDL_strcasecmp( CTEXT(index), SEXP_HULL_STRING) ){
1364                                                 break;
1365                                         }
1366                                 }
1367
1368                                 for (i=0; i<Ship_info[ship_class].n_subsystems; i++){
1369                                         if (!SDL_strcasecmp(Ship_info[ship_class].subsystems[i].subobj_name, CTEXT(index))){
1370                                                 break;
1371                                         }
1372                                 }
1373
1374                                 if (i == Ship_info[ship_class].n_subsystems){
1375                                         return SEXP_CHECK_INVALID_SUBSYS;
1376                                 }
1377
1378                                 // if we're checking for an AWACS subsystem and this is not an awacs subsystem
1379                                 if(Fred_running){
1380                                         if((type == OPF_AWACS_SUBSYSTEM) && !(Ship_info[ship_class].subsystems[i].flags & MSS_FLAG_AWACS)){
1381                                                 return SEXP_CHECK_INVALID_SUBSYS;
1382                                         }
1383                                 }
1384
1385                                 break;
1386                         }
1387
1388                         case OPF_POINT:
1389                                 if (waypoint_lookup(CTEXT(index)) < 0){
1390                                         if (verify_vector(CTEXT(index))){
1391                                                 return SEXP_CHECK_INVALID_POINT;
1392                                         }
1393                                 }
1394
1395                                 if (type2 != SEXP_ATOM_STRING){
1396                                         return SEXP_CHECK_TYPE_MISMATCH;
1397                                 }
1398
1399                                 break;
1400
1401                         case OPF_IFF:
1402                                 if (type2 == SEXP_ATOM_STRING){
1403                                         for (i=0; i<Num_team_names; i++){
1404                                                 if (!SDL_strcasecmp(Team_names[i], CTEXT(index))){
1405                                                         break;
1406                                                 }
1407                                         }
1408                                 }
1409
1410                                 if (i == Num_team_names){
1411                                         return SEXP_CHECK_INVALID_IFF;
1412                                 }
1413
1414                                 if (type2 != SEXP_ATOM_STRING){
1415                                         return SEXP_CHECK_TYPE_MISMATCH;
1416                                 }
1417
1418                                 break;
1419
1420                         case OPF_BOOL:
1421                                 if (type2 != OPR_BOOL){
1422                                         return SEXP_CHECK_TYPE_MISMATCH;
1423                                 }
1424
1425                                 break;
1426
1427                         case OPF_NULL:
1428                                 if (type2 != OPR_NULL){
1429                                         return SEXP_CHECK_TYPE_MISMATCH;
1430                                 }
1431
1432                                 break;
1433
1434                         case OPF_AI_ORDER:
1435                                 if ( type2 != SEXP_ATOM_STRING ){
1436                                         return SEXP_CHECK_TYPE_MISMATCH;
1437                                 }
1438
1439                                 break;
1440
1441                         case OPF_AI_GOAL:
1442                                 if (type2 != OPR_AI_GOAL){
1443                                         return SEXP_CHECK_TYPE_MISMATCH;
1444                                 }
1445
1446                                 if (Fred_running) {
1447                                         int ship_num, ship2, w = 0;
1448
1449                                         ship_num = ship_name_lookup(CTEXT(Sexp_nodes[op_index].rest));
1450                                         if (ship_num < 0) {
1451                                                 w = wing_name_lookup(CTEXT(Sexp_nodes[op_index].rest));
1452                                                 if (w < 0) {
1453                                                         if (bad_index){
1454                                                                 *bad_index = Sexp_nodes[op_index].rest;
1455                                                         }
1456
1457                                                         return SEXP_CHECK_INVALID_SHIP;  // should have already been caught earlier, but just in case..
1458                                                 }
1459                                         }
1460
1461                                         SDL_assert(Sexp_nodes[index].subtype == SEXP_ATOM_LIST);
1462                                         z = Sexp_nodes[index].first;
1463                                         SDL_assert(Sexp_nodes[z].subtype != SEXP_ATOM_LIST);
1464                                         z = find_operator(CTEXT(z));
1465                                         if (ship_num >= 0) {
1466                                                 if (!query_sexp_ai_goal_valid(z, ship_num)){
1467                                                         return SEXP_CHECK_ORDER_NOT_ALLOWED;
1468                                                 }
1469
1470                                         } else {
1471                                                 for (i=0; i<Wings[w].wave_count; i++){
1472                                                         if (!query_sexp_ai_goal_valid(z, Wings[w].ship_index[i])){
1473                                                                 return SEXP_CHECK_ORDER_NOT_ALLOWED;
1474                                                         }
1475                                                 }
1476                                         }
1477
1478                                         if ((z == OP_AI_DOCK) && (Sexp_nodes[index].rest >= 0)) {
1479                                                 ship2 = ship_name_lookup(CTEXT(Sexp_nodes[index].rest));
1480                                                 if ((ship_num < 0) || !ship_docking_valid(ship_num, ship2)){
1481                                                         return SEXP_CHECK_DOCKING_NOT_ALLOWED;
1482                                                 }
1483                                         }
1484                                 }
1485
1486                                 // we should check the syntax of the actual goal!!!!
1487                                 z = Sexp_nodes[index].first;
1488                                 if ((z = check_sexp_syntax(z, OPR_AI_GOAL, recursive, bad_index)) != 0){
1489                                         return z;
1490                                 }
1491
1492                                 break;
1493
1494                         case OPF_SHIP_TYPE:
1495                                 if (type2 != SEXP_ATOM_STRING){
1496                                         return SEXP_CHECK_TYPE_MISMATCH;
1497                                 }
1498
1499                                 for (i=0; i<MAX_SHIP_TYPE_COUNTS; i++){
1500                                         if (!SDL_strcasecmp( Ship_type_names[i], CTEXT(index))){
1501                                                 break;
1502                                         }
1503                                 }
1504
1505                                 if (i == MAX_SHIP_TYPE_COUNTS){
1506                                         return SEXP_CHECK_INVALID_SHIP_TYPE;
1507                                 }
1508
1509                                 break;
1510
1511                         case OPF_WAYPOINT_PATH:
1512                                 for (i=0; i<Num_waypoint_lists; i++){
1513                                         if (!SDL_strcasecmp(Waypoint_lists[i].name, CTEXT(index))){
1514                                                 break;
1515                                         }
1516                                 }
1517
1518                                 if (i == Num_waypoint_lists){
1519                                         return SEXP_CHECK_TYPE_MISMATCH;
1520                                 }
1521                                 break;
1522
1523                         case OPF_MESSAGE:
1524                                 // code commented out because of order reversing of arguments to messaging code.  Maybe
1525                                 // I'll comment it back in someday when older missions get fixed.
1526                                 if (type2 != SEXP_ATOM_STRING)
1527                                         return SEXP_CHECK_TYPE_MISMATCH;
1528
1529                                 if (Fred_running) {
1530                                         for (i=0; i<Num_messages; i++)
1531                                                 if (!SDL_strcasecmp(Messages[i].name, CTEXT(index)))
1532                                                         break;
1533
1534                                         if (i == Num_messages)
1535                                                 return SEXP_CHECK_UNKNOWN_MESSAGE;
1536                                 }
1537                                 
1538                                 break;
1539
1540                         case OPF_PRIORITY: {
1541                                 // following code must be removed since I changed the order of the operators in the send-message
1542                                 // function to take priority second.  Maybe someday, I'll require that all designers fix the
1543                                 // old missions.
1544                                 if (type2 != SEXP_ATOM_STRING)
1545                                         return SEXP_CHECK_TYPE_MISMATCH;
1546
1547                                 if (Fred_running) {  // should still check in Fred though..
1548                                         char *name;
1549
1550                                         name = CTEXT(index);
1551                                         if (!SDL_strcasecmp(name, "low") || !SDL_strcasecmp(name, "normal") || !SDL_strcasecmp(name, "high"))
1552                                                 break;
1553
1554                                         return SEXP_CHECK_INVALID_PRIORITY;
1555                                 }
1556
1557                                 break;
1558                         }
1559
1560                         case OPF_MISSION_NAME:
1561                                 if (type2 != SEXP_ATOM_STRING)
1562                                         return SEXP_CHECK_TYPE_MISMATCH;
1563
1564                                 if (Fred_running) {
1565                                         if (mode == SEXP_MODE_CAMPAIGN) {
1566                                                 for (i=0; i<Campaign.num_missions; i++)
1567                                                         if (!SDL_strcasecmp(CTEXT(index), Campaign.missions[i].name)) {
1568                                                                 if ((i != Sexp_useful_number) && (Campaign.missions[i].level >= Campaign.missions[Sexp_useful_number].level))
1569                                                                         return SEXP_CHECK_INVALID_LEVEL;
1570
1571                                                                 break;
1572                                                         }
1573
1574                                                 if (i == Campaign.num_missions)
1575                                                         return SEXP_CHECK_INVALID_MISSION_NAME;
1576
1577                                         } else {
1578                                                 // mwa -- put the following if statement to prevent Fred errors for possibly valid
1579                                                 // conditions.  We should do something else here!!!
1580                                                 if ( (Operators[op].value == OP_PREVIOUS_EVENT_TRUE) || (Operators[op].value == OP_PREVIOUS_EVENT_FALSE) || (Operators[op].value == OP_PREVIOUS_EVENT_INCOMPLETE)
1581                                                         || (Operators[op].value == OP_PREVIOUS_GOAL_TRUE) || (Operators[op].value == OP_PREVIOUS_GOAL_FALSE) || (Operators[op].value == OP_PREVIOUS_GOAL_INCOMPLETE) )
1582                                                         break;
1583
1584                                                 if (!(*Mission_filename) || SDL_strcasecmp(Mission_filename, CTEXT(index)))
1585                                                         return SEXP_CHECK_INVALID_MISSION_NAME;
1586                                         }
1587                                 }
1588
1589                                 break;
1590
1591                         case OPF_GOAL_NAME:
1592                                 if (type2 != SEXP_ATOM_STRING)
1593                                         return SEXP_CHECK_TYPE_MISMATCH;
1594
1595                                 // we only need to check the campaign list if running in Fred and are in campaign mode.
1596                                 // otherwise, check the set of current goals
1597                                 if ( Fred_running && (mode == SEXP_MODE_CAMPAIGN) ) {
1598                                         z = find_parent_operator(index);
1599                                         SDL_assert(z >= 0);
1600                                         z = Sexp_nodes[z].rest;  // first argument of operator should be mission name
1601                                         SDL_assert(z >= 0);
1602                                         for (i=0; i<Campaign.num_missions; i++)
1603                                                 if (!SDL_strcasecmp(CTEXT(z), Campaign.missions[i].name))
1604                                                         break;
1605
1606                                         // read the goal/event list from the mission file if both num_goals and num_events
1607                                         // are < 0
1608                                         if ((Campaign.missions[i].num_goals <= 0) && (Campaign.missions[i].num_events <= 0) )
1609                                                 read_mission_goal_list(i);
1610                                         
1611                                         if (i < Campaign.num_missions) {
1612                                                 for (t=0; t<Campaign.missions[i].num_goals; t++)
1613                                                         if (!SDL_strcasecmp(CTEXT(index), Campaign.missions[i].goals[t].name))
1614                                                                 break;
1615
1616                                                 if (t == Campaign.missions[i].num_goals)
1617                                                         return SEXP_CHECK_INVALID_GOAL_NAME;
1618                                         }
1619                                 } else {
1620                                         // MWA -- short circuit evaluation of these things for now.
1621                                         if ( (Operators[op].value == OP_PREVIOUS_GOAL_TRUE) || (Operators[op].value == OP_PREVIOUS_GOAL_FALSE) || (Operators[op].value == OP_PREVIOUS_GOAL_INCOMPLETE) )
1622                                                 break;
1623
1624                                         for (i=0; i<Num_goals; i++)
1625                                                 if (!SDL_strcasecmp(CTEXT(index), Mission_goals[i].name))
1626                                                         break;
1627
1628                                         if (i == Num_goals)
1629                                                 return SEXP_CHECK_INVALID_GOAL_NAME;
1630                                 }
1631
1632                                 break;
1633
1634                         case OPF_EVENT_NAME:
1635                                 if ( type2 != SEXP_ATOM_STRING )
1636                                         return SEXP_CHECK_TYPE_MISMATCH;
1637
1638                                 // like above checking for goals, check events in the campaign only if in Fred
1639                                 // and only if in campaign mode.  Otherwise, check the current set of events
1640                                 if ( Fred_running && (mode == SEXP_MODE_CAMPAIGN) ) {
1641                                         z = find_parent_operator(index);
1642                                         SDL_assert(z >= 0);
1643                                         z = Sexp_nodes[z].rest;  // first argument of operator should be mission name
1644                                         SDL_assert(z >= 0);
1645                                         for (i=0; i<Campaign.num_missions; i++)
1646                                                 if (!SDL_strcasecmp(CTEXT(z), Campaign.missions[i].name))
1647                                                         break;
1648
1649                                         // read the goal/event list from the mission file if both num_goals and num_events
1650                                         // are < 0
1651                                         if ((Campaign.missions[i].num_goals <= 0) && (Campaign.missions[i].num_events <= 0) )
1652                                                 read_mission_goal_list(i);
1653                                         
1654                                         if (i < Campaign.num_missions) {
1655                                                 for (t=0; t<Campaign.missions[i].num_events; t++)
1656                                                         if (!SDL_strcasecmp(CTEXT(index), Campaign.missions[i].events[t].name))
1657                                                                 break;
1658
1659                                                 if (t == Campaign.missions[i].num_events)
1660                                                         return SEXP_CHECK_INVALID_EVENT_NAME;
1661                                         }
1662                                 } else {
1663                                         // MWA -- short circuit evaluation of these things for now.
1664                                         if ( (Operators[op].value == OP_PREVIOUS_EVENT_TRUE) || (Operators[op].value == OP_PREVIOUS_EVENT_FALSE) || (Operators[op].value == OP_PREVIOUS_EVENT_INCOMPLETE) )
1665                                                 break;
1666
1667                                         for ( i = 0; i < Num_mission_events; i++ ) {
1668                                                 if ( !SDL_strcasecmp(CTEXT(index), Mission_events[i].name) )
1669                                                         break;
1670                                         }
1671                                         if ( i == Num_mission_events )
1672                                                 return SEXP_CHECK_INVALID_EVENT_NAME;
1673                                 }
1674                                 break;
1675
1676                         case OPF_DOCKER_POINT:
1677                                 if (type2 != SEXP_ATOM_STRING)
1678                                         return SEXP_CHECK_TYPE_MISMATCH;
1679
1680                                 if (Fred_running) {
1681                                         int ship_num, model;
1682
1683                                         z = find_parent_operator(op_index);
1684                                         ship_num = ship_name_lookup(CTEXT(Sexp_nodes[z].rest));
1685                                         if (ship_num < 0) {
1686                                                 if (bad_index)
1687                                                         *bad_index = Sexp_nodes[z].rest;
1688
1689                                                 return SEXP_CHECK_INVALID_SHIP;  // should have already been caught earlier, but just in case..
1690                                         }
1691
1692                                         model = Ships[ship_num].modelnum;
1693                                         z = model_get_num_dock_points(model);
1694                                         for (i=0; i<z; i++)
1695                                                 if (!SDL_strcasecmp(CTEXT(index), model_get_dock_name(model, i)))
1696                                                         break;
1697
1698                                         if (i == z)
1699                                                 return SEXP_CHECK_INVALID_DOCKER_POINT;
1700                                 }
1701
1702                                 break;
1703
1704                         case OPF_DOCKEE_POINT:
1705                                 if (type2 != SEXP_ATOM_STRING)
1706                                         return SEXP_CHECK_TYPE_MISMATCH;
1707
1708                                 if (Fred_running) {
1709                                         int ship_num, model;
1710
1711                                         ship_num = ship_name_lookup(CTEXT(Sexp_nodes[op_index].rest));
1712                                         if (ship_num < 0) {
1713                                                 if (bad_index)
1714                                                         *bad_index = Sexp_nodes[op_index].rest;
1715
1716                                                 return SEXP_CHECK_INVALID_SHIP;  // should have already been caught earlier, but just in case..
1717                                         }
1718
1719                                         model = Ships[ship_num].modelnum;
1720                                         z = model_get_num_dock_points(model);
1721                                         for (i=0; i<z; i++)
1722                                                 if (!SDL_strcasecmp(CTEXT(index), model_get_dock_name(model, i)))
1723                                                         break;
1724
1725                                         if (i == z)
1726                                                 return SEXP_CHECK_INVALID_DOCKEE_POINT;
1727                                 }
1728
1729                                 break;
1730
1731                         case OPF_WHO_FROM:
1732                                 if (type2 != SEXP_ATOM_STRING)
1733                                         return SEXP_CHECK_TYPE_MISMATCH;
1734
1735                                 if (*CTEXT(index) != '#') {  // not a manual source?
1736                                         //if ( !SDL_strcasecmp(CTEXT(index), "<any allied>") )
1737                                         //      return SEXP_CHECK_INVALID_MSG_SOURCE;
1738
1739                                         if ( SDL_strcasecmp(CTEXT(index), "<any wingman>"))  // not a special token?
1740                                                 if ((ship_name_lookup(CTEXT(index)) < 0) && (wing_name_lookup(CTEXT(index), 1) < 0))  // is it in the mission?
1741                                                         if (Fred_running || mission_parse_ship_arrived(CTEXT(index)))  // == 0 when still on arrival list
1742                                                                 return SEXP_CHECK_INVALID_MSG_SOURCE;
1743                                 }
1744
1745                                 break;
1746                                 
1747                         case OPF_KEYPRESS:
1748                                 if (type2 != SEXP_ATOM_STRING)
1749                                         return SEXP_CHECK_TYPE_MISMATCH;
1750
1751                                 break;
1752
1753                         case OPF_SKILL_LEVEL:
1754                                 if ( type2 != SEXP_ATOM_STRING )
1755                                         return SEXP_CHECK_TYPE_MISMATCH;
1756
1757                                 for (i = 0; i < NUM_SKILL_LEVELS; i++) {
1758                                         if ( !SDL_strcasecmp(CTEXT(index), Skill_level_names(i, 0)) )
1759                                                 break;
1760                                 }
1761                                 if ( i == NUM_SKILL_LEVELS )
1762                                         return SEXP_CHECK_INVALID_SKILL_LEVEL;
1763                                 break;
1764
1765                         case OPF_MEDAL_NAME:
1766                                 if ( type2 != SEXP_ATOM_STRING)
1767                                         return SEXP_CHECK_TYPE_MISMATCH;
1768
1769                                 for (i = 0; i < NUM_MEDALS; i++) {
1770                                         if ( !SDL_strcasecmp(CTEXT(index), Medals[i].name) )
1771                                                 break;
1772                                 }
1773
1774                                 if ( i == NUM_MEDALS )
1775                                         return SEXP_CHECK_INVALID_MEDAL_NAME;
1776                                 break;
1777
1778                         case OPF_HUGE_WEAPON:
1779                         case OPF_WEAPON_NAME:
1780                                 if ( type2 != SEXP_ATOM_STRING )
1781                                         return SEXP_CHECK_TYPE_MISMATCH;
1782
1783                                 for (i = 0; i < Num_weapon_types; i++ ) {
1784                                         if ( !SDL_strcasecmp(CTEXT(index), Weapon_info[i].name) )
1785                                                 break;
1786                                 }
1787
1788                                 if ( i == Num_weapon_types )
1789                                         return SEXP_CHECK_INVALID_WEAPON_NAME;
1790
1791                                 // we need to be sure that for huge weapons, the WIF_HUGE flag is set
1792                                 if ( type == OPF_HUGE_WEAPON ) {
1793                                         if ( !(Weapon_info[i].wi_flags & WIF_HUGE) )
1794                                                 return SEXP_CHECK_INVALID_WEAPON_NAME;
1795                                 }
1796
1797                                 break;
1798         
1799                         case OPF_SHIP_CLASS_NAME:
1800                                 if ( type2 != SEXP_ATOM_STRING )
1801                                         return SEXP_CHECK_TYPE_MISMATCH;
1802
1803                                 for (i = 0; i < Num_ship_types; i++ ) {
1804                                         if ( !SDL_strcasecmp(CTEXT(index), Ship_info[i].name) )
1805                                                 break;
1806                                 }
1807
1808                                 if ( i == Num_ship_types )
1809                                         return SEXP_CHECK_INVALID_SHIP_CLASS_NAME;
1810                                 break;
1811
1812                         case OPF_HUD_GAUGE_NAME:
1813                                 if ( type2 != SEXP_ATOM_STRING )
1814                                         return SEXP_CHECK_TYPE_MISMATCH;
1815
1816                                 for ( i = 0; i < NUM_HUD_GAUGES; i++ ) {
1817                                         if ( !SDL_strcasecmp(CTEXT(index), HUD_gauge_text[i]) )
1818                                                 break;
1819                                 }
1820
1821                                 // if we reached the end of the list, then the name is invalid
1822                                 if ( i == NUM_HUD_GAUGES )
1823                                         return SEXP_CHECK_INVALID_GAUGE_NAME;
1824                                 
1825                                 break;
1826
1827                         case OPF_JUMP_NODE_NAME:
1828                                 if ( type2 != SEXP_ATOM_STRING )
1829                                         return SEXP_CHECK_TYPE_MISMATCH;
1830
1831                                 for ( i = 0; i < Num_jump_nodes; i++ ) {
1832                                         if ( !SDL_strcasecmp(Jump_nodes[i].name, CTEXT(index)) )
1833                                                 break;
1834                                 }
1835
1836                                 if ( i == Num_jump_nodes )
1837                                         return SEXP_CHECK_INVALID_JUMP_NODE;
1838
1839                                 break;
1840
1841
1842                         case OPF_VARIABLE_NAME:
1843                                 if ( Fred_running ) {
1844                                         if ( get_index_sexp_variable_name(Sexp_nodes[index].text)  == -1) {
1845                                                 return SEXP_CHECK_INVALID_VARIABLE;
1846                                         }
1847                                 }
1848                                 // if Fred not running anything goes
1849                                 break;
1850
1851                         case OPF_AMBIGUOUS:
1852                                 // type checking for modify-variable
1853                                 // string or number -- anything goes
1854                                 break;                                          
1855
1856                         default:
1857                                 Int3();  // currently unhandled argument format (so add it now)
1858                 }
1859
1860                 index = Sexp_nodes[index].rest;
1861                 argnum++;
1862         }
1863
1864         return 0;
1865 }
1866
1867 //      Stuff a string (" chars ") in *str, return length.
1868 //      Updates Mp.
1869 int get_string(char *str)
1870 {
1871         int     len;
1872
1873         len = strcspn(Mp + 1, "\"");
1874         SDL_strlcpy(str, Mp + 1, len+1);
1875
1876         Mp += len + 2;
1877         return len;
1878 }
1879
1880
1881 // get text to stuff into Sexp_node in case of variable
1882 // if Fred_running - stuff Sexp_variables[].variable_name
1883 // otherwise - stuff index into Sexp_variables array.
1884 void get_sexp_text_for_variable(char *text, char *token)
1885 {
1886         int end_index;
1887         int sexp_var_index;
1888         
1889         // get variable name (up to '['
1890         end_index = strcspn(token, "[");
1891         SDL_assert( (end_index != 0) && (end_index < TOKEN_LENGTH-1) );
1892         SDL_strlcpy(text, token, end_index+1);
1893
1894         if ( !Fred_running ) {
1895                 // freespace - get index into Sexp_variables array
1896                 sexp_var_index = get_index_sexp_variable_name(text);
1897                 SDL_assert(sexp_var_index != -1);
1898                 SDL_snprintf(text, TOKEN_LENGTH, "%d", sexp_var_index);
1899         }
1900 }
1901
1902
1903 // returns the first sexp index of data this function allocates. (start of this sexp)
1904 // recursive function - always sets first and then rest
1905 int get_sexp(char *token)
1906 {
1907         int start, node, last, len, op, count;
1908         char variable_text[TOKEN_LENGTH];
1909
1910         // start - the node allocated in first instance of fuction
1911         // node - the node allocated in current instance of function
1912         // count - number of nodes allocated this instance of function [do we set last.rest or first]
1913         // variable - whether string or number is a variable referencing Sexp_variables
1914
1915         // initialization
1916         start = last = -1;
1917         count = 0;
1918
1919         ignore_white_space();
1920         while (*Mp != ')') {
1921                 SDL_assert(*Mp != EOF_CHAR);
1922                 if (*Mp == '(') {
1923                         // Sexp list
1924                         Mp++;
1925                         node = alloc_sexp("", SEXP_LIST, SEXP_ATOM_LIST, get_sexp(token), -1);
1926
1927                 } else if (*Mp == '\"') {
1928                         // Sexp string
1929                         len = strcspn(Mp + 1, "\"");
1930                         
1931                         SDL_assert(Mp[len + 1] == '\"');    // hit EOF first (unterminated string)
1932                         SDL_assert_release(len < TOKEN_LENGTH);  // token is too long.
1933
1934                         // check if string variable
1935                         if ( *(Mp + 1) == SEXP_VARIABLE_CHAR ) {
1936
1937                                 // reduce length by 1 for end \"
1938                                 int length = len - 1;
1939                                 SDL_assert_release(length >= 1);
1940                         //      SDL_assert(length < 2*TOKEN_LENGTH+2);
1941
1942                                 // start copying after skipping 1st char
1943                                 SDL_strlcpy(token, Mp + 2, length+1);
1944
1945                                 get_sexp_text_for_variable(variable_text, token);
1946                                 node = alloc_sexp(variable_text, (SEXP_ATOM | SEXP_FLAG_VARIABLE), SEXP_ATOM_STRING, -1, -1);
1947                         } else {
1948                                 SDL_strlcpy(token, Mp + 1, len+1);
1949
1950                                 node = alloc_sexp(token, SEXP_ATOM, SEXP_ATOM_STRING, -1, -1);
1951                         }
1952
1953                         // bump past closing \" by 1 char
1954                         Mp += len + 2;
1955
1956                 } else {
1957                         // Sexp operator or number
1958                         len = 0;
1959                         bool variable = false;
1960                         while (*Mp != ')' && !is_white_space(*Mp)) {
1961                                 if ( (len == 0) && (*Mp == SEXP_VARIABLE_CHAR) ) {
1962                                         variable = true;
1963                                         Mp++;
1964                                         continue;
1965                                 }
1966                                 SDL_assert(*Mp != EOF_CHAR);
1967                                 SDL_assert(len < TOKEN_LENGTH - 1);
1968                                 token[len++] = *Mp++;
1969                         }
1970
1971                         token[len] = 0;
1972
1973                         op = identify_operator(token);
1974                         if (op != -1) {
1975                                 node = alloc_sexp(token, SEXP_ATOM, SEXP_ATOM_OPERATOR, -1, -1);
1976                         } else {
1977                                 if ( variable ) {
1978                                         // convert token text for variable
1979                                         get_sexp_text_for_variable(variable_text, token);
1980
1981                                         node = alloc_sexp(variable_text, (SEXP_ATOM | SEXP_FLAG_VARIABLE), SEXP_ATOM_NUMBER, -1, -1);
1982                                 } else {
1983                                         node = alloc_sexp(token, SEXP_ATOM, SEXP_ATOM_NUMBER, -1, -1);
1984                                 }
1985                         }
1986                 }
1987
1988                 // update links
1989                 if (count++) {
1990                         SDL_assert(last != -1);
1991                         Sexp_nodes[last].rest = node;
1992                 } else {
1993                         start = node;
1994                 }
1995
1996                 SDL_assert(node != -1);  // ran out of nodes.  Time to raise the MAX!
1997                 last = node;
1998                 ignore_white_space();
1999         }
2000
2001         Mp++;  // skip past the ')'
2002         return start;
2003 }
2004
2005
2006 // Stuffs a list of sexp variables
2007 int stuff_sexp_variable_list()
2008 {       
2009         int count;
2010         char var_name[TOKEN_LENGTH];
2011         char default_value[TOKEN_LENGTH];
2012         char str_type[TOKEN_LENGTH];
2013         int index;
2014         int type;
2015
2016         count = 0;
2017         required_string("$Variables:");
2018         ignore_white_space();
2019
2020         // check for start of list
2021         if (*Mp != '(') {
2022                 error_display(1, "Reading sexp variable list.  Found [%c].  Expecting '('.\n", *Mp);
2023                 throw PARSE_ERROR_INT_LIST;
2024         }
2025
2026         Mp++;
2027         ignore_white_space();
2028
2029         while (*Mp != ')') {
2030                 SDL_assert(count < MAX_SEXP_VARIABLES);
2031
2032                 // get index - for debug
2033                 stuff_int(&index);
2034                 ignore_gray_space();
2035
2036                 // get var_name
2037                 get_string(var_name);
2038                 ignore_gray_space();
2039
2040                 // get default_value;
2041                 get_string(default_value);
2042                 ignore_gray_space();
2043
2044                 // get type
2045                 get_string(str_type);
2046                 ignore_white_space();
2047
2048
2049                 if (!SDL_strcasecmp(str_type, "number")) {
2050                         type = SEXP_VARIABLE_NUMBER;
2051                 } else if (!SDL_strcasecmp(str_type, "string")) {
2052                         type = SEXP_VARIABLE_STRING;
2053                 } else if (!SDL_strcasecmp(str_type, "block")) {
2054                         type = SEXP_VARIABLE_BLOCK | SEXP_VARIABLE_BLOCK_EXP;
2055                 } else {
2056                         type = SEXP_VARIABLE_UNKNOWN;
2057                         Int3();
2058                 }
2059
2060                 count++;
2061
2062                 // check if variable name already exists
2063                 if ( (type == SEXP_VARIABLE_NUMBER) || (type == SEXP_VARIABLE_STRING) ) {
2064                         SDL_assert(get_index_sexp_variable_name(var_name) == -1);
2065                 }
2066
2067                 sexp_add_variable(default_value, var_name, type, index);
2068         }
2069
2070         Mp++;
2071
2072         return count;
2073 }
2074
2075 //
2076 void build_sexp_text_string(char *buffer, const int max_bufsize, int node, int mode)
2077 {
2078         if (Sexp_nodes[node].type & SEXP_FLAG_VARIABLE) {
2079
2080                 int sexp_variables_index = get_index_sexp_variable_name(Sexp_nodes[node].text);
2081                 SDL_assert(sexp_variables_index != -1);
2082                 SDL_assert( (Sexp_variables[sexp_variables_index].type & SEXP_VARIABLE_NUMBER) || (Sexp_variables[sexp_variables_index].type & SEXP_VARIABLE_STRING) );
2083
2084                 // number
2085                 if (Sexp_nodes[node].subtype == SEXP_ATOM_NUMBER) {
2086                         SDL_assert(Sexp_variables[sexp_variables_index].type & SEXP_VARIABLE_NUMBER);
2087                 
2088                         // Error check - can be Fred or Freespace
2089                         if (mode == SEXP_ERROR_CHECK_MODE) {
2090                                 if ( Fred_running ) {
2091                                         SDL_snprintf(buffer, max_bufsize, "%s[%s] ", Sexp_nodes[node].text, Sexp_variables[sexp_variables_index].text);
2092                                 } else {
2093                                         SDL_snprintf(buffer, max_bufsize, "%s[%s] ", Sexp_variables[sexp_variables_index].variable_name, Sexp_variables[sexp_variables_index].text);
2094                                 }
2095                         } else {
2096                                 // Save as string - only  Fred
2097                                 SDL_assert(mode == SEXP_SAVE_MODE);
2098                                 SDL_snprintf(buffer, max_bufsize, "@%s[%s] ", Sexp_nodes[node].text, Sexp_variables[sexp_variables_index].text);
2099                         }
2100                 } else {
2101                         // string
2102                         SDL_assert(Sexp_nodes[node].subtype == SEXP_ATOM_STRING);
2103                         SDL_assert(Sexp_variables[sexp_variables_index].type & SEXP_VARIABLE_STRING);
2104
2105                         // Error check - can be Fred or Freespace
2106                         if (mode == SEXP_ERROR_CHECK_MODE) {
2107                                 if ( Fred_running ) {
2108                                         SDL_snprintf(buffer, max_bufsize, "%s[%s] ", Sexp_variables[sexp_variables_index].variable_name, Sexp_variables[sexp_variables_index].text);
2109                                 } else {
2110                                         SDL_snprintf(buffer, max_bufsize, "%s[%s] ", Sexp_nodes[node].text, Sexp_variables[sexp_variables_index].text);
2111                                 }
2112                         } else {
2113                                 // Save as string - only Fred
2114                                 SDL_assert(mode == SEXP_SAVE_MODE);
2115                                 SDL_snprintf(buffer, max_bufsize, "\"@%s[%s]\" ", Sexp_nodes[node].text, Sexp_variables[sexp_variables_index].text);
2116                         }
2117                 }
2118         } else {
2119                 // not a variable
2120                 if (Sexp_nodes[node].subtype == SEXP_ATOM_STRING) {
2121                         SDL_snprintf(buffer, max_bufsize, "\"%s\" ", CTEXT(node));
2122                 } else {
2123                         SDL_snprintf(buffer, max_bufsize, "%s ", CTEXT(node));
2124                 }
2125         }
2126
2127 }
2128
2129
2130 int build_sexp_string(int cur_node, int level, int mode)
2131 {
2132         char    pstr[128];
2133         int len, offset, node;
2134
2135         Sexp_build_flag = 0;
2136         offset = strlen(Sexp_string);
2137         SDL_strlcat(Sexp_string, "( ", Sexp_string_len);
2138         node = cur_node;
2139         while (node != -1) {
2140                 SDL_assert(node >= 0 && node < MAX_SEXP_NODES);
2141                 if (Sexp_nodes[node].first == -1) {
2142                         // build text to string
2143                         build_sexp_text_string(pstr, SDL_arraysize(pstr), node, mode);
2144                         SDL_strlcat(Sexp_string, pstr, Sexp_string_len);
2145
2146                 } else {
2147                         build_sexp_string(Sexp_nodes[node].first, level + 1, mode);
2148                 }
2149
2150                 node = Sexp_nodes[node].rest;
2151         }
2152
2153         SDL_strlcat(Sexp_string, ") ", Sexp_string_len);
2154         len = strlen(Sexp_string) - offset;
2155         if (len > 40) {
2156                 Sexp_string[offset] = 0;
2157                 build_extended_sexp_string(cur_node, level, mode);
2158                 return 1;
2159         }
2160
2161         return 0;
2162 }
2163
2164 void build_extended_sexp_string(int cur_node, int level, int mode)
2165 {
2166         char pstr[128];
2167         int i, flag = 0, node;
2168
2169         SDL_strlcat(Sexp_string, "( ", Sexp_string_len);
2170         node = cur_node;
2171         while (node != -1) {
2172                 if (flag)  // not the first line?
2173                         for (i=0; i<level + 1; i++)
2174                                 SDL_strlcat(Sexp_string, "   ", Sexp_string_len);
2175
2176                 flag = 1;
2177                 SDL_assert(node >= 0 && node < MAX_SEXP_NODES);
2178                 if (Sexp_nodes[node].first == -1) {
2179                         build_sexp_text_string(pstr, SDL_arraysize(pstr),node, mode);
2180                         SDL_strlcat(Sexp_string, pstr, Sexp_string_len);
2181
2182                 } else {
2183                         build_sexp_string(Sexp_nodes[node].first, level + 1, mode);
2184                 }
2185
2186                 SDL_strlcat(Sexp_string, "\n", Sexp_string_len);
2187                 node = Sexp_nodes[node].rest;
2188         }
2189
2190         for (i=0; i<level; i++)
2191                 SDL_strlcat(Sexp_string, "   ", Sexp_string_len);
2192
2193         SDL_strlcat(Sexp_string, ")", Sexp_string_len);
2194 }
2195
2196 void convert_sexp_to_string(int cur_node, char *outstr, const int outstr_len, int mode)
2197 {
2198         Sexp_string = outstr;
2199         Sexp_string_len = outstr_len;
2200         *outstr = 0;
2201         if (cur_node >= 0)
2202                 build_sexp_string(cur_node, 0, mode);
2203         else
2204                 SDL_strlcpy(Sexp_string, "( )", Sexp_string_len);
2205 }
2206
2207 // determine if the named ship or wing hasn't arrived yet (wing or ship must be on arrival list)
2208 int sexp_query_has_yet_to_arrive(char *name)
2209 {
2210         int i;
2211
2212         if (ship_query_state(name) < 0)
2213                 return 1;
2214
2215         i = wing_name_lookup(name, 1);
2216
2217         // has not arrived yet, and never will arrive
2218         if ((i >= 0) && (Wings[i].num_waves >= 0) && (Wings[i].flags & WF_NEVER_EXISTED)){
2219                 return 1;
2220         }
2221
2222         // has not arrived yet
2223         if ((i >= 0) && (Wings[i].num_waves >= 0) && !Wings[i].total_arrived_count){
2224                 return 1;
2225         }
2226
2227         return 0;
2228 }
2229
2230 // arithmetic functions
2231 int add_sexps(int n)
2232 {
2233         int     sum = 0, val;
2234
2235         if (n != -1) {
2236                 if ( CAR(n) != -1)
2237                         sum = eval_sexp( CAR(n) );
2238                 else
2239                         sum = atoi( CTEXT(n) );
2240
2241                 // be sure to check for the NAN value when doing arithmetic -- this value should
2242                 // get propagated to the next highest function.
2243                 if ( Sexp_nodes[CAR(n)].value == SEXP_NAN )
2244                         return SEXP_NAN;
2245                 else if ( Sexp_nodes[CAR(n)].value == SEXP_NAN_FOREVER )
2246                         return SEXP_NAN_FOREVER;
2247
2248                 while (CDR(n) != -1) {
2249                         val = eval_sexp( CDR(n) );
2250                         // be sure to check for the NAN value when doing arithmetic -- this value should
2251                         // get propagated to the next highest function.
2252                         if ( Sexp_nodes[CDR(n)].value == SEXP_NAN )
2253                                 return SEXP_NAN;
2254                         else if ( Sexp_nodes[CAR(n)].value == SEXP_NAN_FOREVER )
2255                                 return SEXP_NAN_FOREVER;
2256                         sum += val;
2257                         n = CDR(n);
2258                 }
2259         }
2260
2261         return sum;
2262 }
2263
2264 int sub_sexps(int n)
2265 {
2266         int     sum = 0;
2267
2268         if (n != -1) { 
2269                 if (Sexp_nodes[n].first != -1)
2270                         sum = eval_sexp(CAR(n));
2271                 else
2272                         sum = atoi(CTEXT(n));
2273
2274                 while (CDR(n) != -1) {
2275                         sum -= eval_sexp(CDR(n));
2276                         n = CDR(n);
2277                 }
2278         }
2279
2280         return sum;
2281 }
2282
2283 int mul_sexps(int n)
2284 {
2285         int     sum = 0;
2286
2287         if (n != -1) {
2288                 if (Sexp_nodes[n].first != -1)
2289                         sum = eval_sexp(Sexp_nodes[n].first);
2290                 else
2291                         sum = atoi(CTEXT(n));
2292
2293                 while (Sexp_nodes[n].rest != -1) {
2294                         sum *= eval_sexp(Sexp_nodes[n].rest);
2295                         n = Sexp_nodes[n].rest;
2296                 }
2297         }
2298
2299         return sum;
2300 }
2301
2302 int div_sexps(int n)
2303 {
2304         int     sum = 0;
2305
2306         if (n != -1) {
2307                 if (Sexp_nodes[n].first != -1)
2308                         sum = eval_sexp(Sexp_nodes[n].first);
2309                 else
2310                         sum = atoi(CTEXT(n));
2311
2312                 while (Sexp_nodes[n].rest != -1) {
2313                         sum /= eval_sexp(Sexp_nodes[n].rest);
2314                         n = Sexp_nodes[n].rest;
2315                 }
2316         }
2317
2318         return sum;
2319 }
2320
2321 int mod_sexps(int n)
2322 {
2323         int     sum = 0;
2324
2325         if (n != -1) {
2326                 if (Sexp_nodes[n].first != -1)
2327                         sum = eval_sexp(Sexp_nodes[n].first);
2328                 else
2329                         sum = atoi(CTEXT(n));
2330
2331                 while (Sexp_nodes[n].rest != -1) {
2332                         sum = sum % eval_sexp(Sexp_nodes[n].rest);
2333                         n = Sexp_nodes[n].rest;
2334                 }
2335         }
2336
2337         return sum;
2338 }
2339
2340 int rand_internal(int low, int high)
2341 {
2342         int diff;
2343
2344         // get diff - don't allow negative or zero
2345         diff = high - low;
2346         if (diff < 0) {
2347                 diff = 0;
2348         }
2349
2350         return (low + myrand() % (diff + 1));
2351 }
2352
2353
2354 int rand_sexp(int n, int multiple=0)
2355 {
2356         int low = 0;
2357         int high = 0;
2358         int rand_num = 0;
2359
2360         if (n != -1) {
2361                 if (Sexp_nodes[n].value == SEXP_NUM_EVAL) {
2362                         // don't regenerate new random number
2363                         rand_num = atoi(CTEXT(n));
2364                 } else {
2365                         // get low
2366 //                      if (Sexp_nodes[n].first != -1) {
2367 //                              low = eval_sexp(Sexp_nodes[n].first);
2368 //                      } else {
2369 //                              low = atoi(CTEXT(n));
2370 //                      }
2371                         low = num_eval(n);
2372
2373                         // get high
2374                         high = num_eval(CDR(n));
2375
2376                         // get the random number
2377                         rand_num = rand_internal(low, high);
2378
2379                         if (!multiple) {
2380                                 // set .value and .text so random number is generated only once.
2381                                 Sexp_nodes[n].value = SEXP_NUM_EVAL;
2382                                 SDL_snprintf(Sexp_nodes[n].text, TOKEN_LENGTH, "%d", rand_num);
2383                         }
2384                 }
2385         }
2386
2387         return rand_num;
2388 }
2389
2390 // boolean evaluation functions.  Evaluate all sexpressions in the 'or' operator.  Needed to mark
2391 // entries in the mission log as essential so when pruning the log, we know which entries we might
2392 // need to keep.
2393 int sexp_or(int n)
2394 {
2395         int all_false, result;
2396
2397         all_false = 1;
2398         result = 0;
2399         if (n != -1) {
2400                 if (Sexp_nodes[n].first != -1) {
2401                         result |= eval_sexp(Sexp_nodes[n].first);
2402                         if ( Sexp_nodes[Sexp_nodes[n].first].value == SEXP_KNOWN_TRUE )
2403                                 return SEXP_KNOWN_TRUE;                                                                                                                 // if one of the OR clauses is TRUE, whole clause is true
2404                         if ( Sexp_nodes[Sexp_nodes[n].first].value != SEXP_KNOWN_FALSE )                // if the value is still unknown, they all can't be false
2405                                 all_false = 0;
2406                 } else
2407                         result |= atoi(CTEXT(n));
2408
2409                 // don't return on true value -- keep evaluating for mission log purposes
2410                 //if ( result )
2411                 //      return result;
2412
2413                 while (Sexp_nodes[n].rest != -1) {
2414                         result |= eval_sexp(Sexp_nodes[n].rest);
2415                         if ( Sexp_nodes[Sexp_nodes[n].rest].value == SEXP_KNOWN_TRUE )
2416                                 return SEXP_KNOWN_TRUE;                                                                                                                 // if one of the OR clauses is TRUE, whole clause is true
2417                         if ( Sexp_nodes[Sexp_nodes[n].rest].value != SEXP_KNOWN_FALSE )         // if the value is still unknown, they all can't be false
2418                                 all_false = 0;
2419                         n = Sexp_nodes[n].rest;
2420                         // don't return on true value -- keep evaluating for mission log purposes
2421                         //if ( result )
2422                         //      return result;
2423                 }
2424         }
2425
2426         if ( all_false )
2427                 return SEXP_KNOWN_FALSE;
2428
2429         return result;
2430 }
2431
2432 // this function does the 'and' operator.  It will short circuit evaluation  *but* it will still
2433 // evaluate other members of the and construct.  I do this because I need events in the mission log
2434 // to get marked as essential for goal purposes, and evaluation is pretty much the only way
2435 int sexp_and(int n)
2436 {
2437         int all_true, result;
2438
2439         result = -1;
2440         all_true = 1;
2441         if (n != -1) {
2442                 if (Sexp_nodes[n].first != -1) {
2443                         result &= eval_sexp( CAR(n) );
2444                         if ( Sexp_nodes[Sexp_nodes[n].first].value == SEXP_KNOWN_FALSE )
2445                                 return SEXP_KNOWN_FALSE;                                                                                                                // if one of the AND clauses is FALSE, whole clause is false
2446                         if ( Sexp_nodes[Sexp_nodes[n].first].value != SEXP_KNOWN_TRUE )         // if the value is still unknown, they all can't be true
2447                                 all_true = 0;
2448                 } else
2449                         result &= atoi(CTEXT(n));
2450
2451                 // don't short circuit -- evaluate everything for purposes of marking mission log
2452                 //if ( !result )
2453                 //      return result;
2454
2455                 while (Sexp_nodes[n].rest != -1) {
2456                         int new_result;
2457
2458                         new_result = eval_sexp( CDR(n) );
2459                         result &= new_result;
2460                         if ( Sexp_nodes[Sexp_nodes[n].rest].value == SEXP_KNOWN_FALSE )
2461                                 return SEXP_KNOWN_FALSE;                                                                                                                        // if one of the OR clauses is TRUE, whole clause is true
2462                         if ( Sexp_nodes[Sexp_nodes[n].rest].value != SEXP_KNOWN_TRUE )                          // if the value is still unknown, they all can't be false
2463                                 all_true = 0;
2464                         // don't short circuit -- evaluate everything for purposes of marking mission log
2465                         //if ( !result )
2466                                 //return result;
2467
2468                         n = Sexp_nodes[n].rest;
2469                 }
2470         }
2471
2472         if ( all_true )
2473                 return SEXP_KNOWN_TRUE;
2474
2475         return result;
2476 }
2477
2478 // this version of the 'and' operator determines whether or not it's arguments become true
2479 // in the order in which they are specified in the when statement.  Should be a simple matter of 
2480 // seeing if anything evaluates to true later than something that evalueated to false
2481 int sexp_and_in_sequence(int n)
2482 {
2483         int result = -1;
2484         int all_true;
2485
2486         all_true = 1;                                                                                   // represents whether or not all nodes we have seen so far are true
2487         if (n != -1) {
2488                 if (Sexp_nodes[n].first != -1) {
2489                         result &= eval_sexp( CAR(n) );
2490                         if ( Sexp_nodes[Sexp_nodes[n].first].value == SEXP_KNOWN_FALSE )
2491                                 return SEXP_KNOWN_FALSE;                                                                                                                // if one of the AND clauses is FALSE, whole clause is false
2492                         if ( Sexp_nodes[Sexp_nodes[n].first].value != SEXP_KNOWN_TRUE )         // if value is true, mark our all_true variable for later checking
2493                                 all_true = 0;
2494                 } else
2495                         result &= atoi(CTEXT(n));
2496
2497                 // a little test -- if the previous sexpressions was true, then mark the node itself as always
2498                 // true.  I did this because of the distance function.  It might become true, then when waiting for
2499                 // the second evalation, it might become false, rendering this function false.  So, when one becomes
2500                 // true -- mark it true forever.
2501                 if ( result )
2502                         Sexp_nodes[Sexp_nodes[n].first].value = SEXP_KNOWN_TRUE;
2503
2504                 while (Sexp_nodes[n].rest != -1) {
2505                         int next_result;
2506
2507                         next_result = eval_sexp( CDR(n) );
2508                         if ( next_result && !result )                           // if current result is true, and our running result is false, thngs didn't become true in order
2509                                 return SEXP_KNOWN_FALSE;
2510                         result &= next_result;
2511                         if ( Sexp_nodes[Sexp_nodes[n].rest].value == SEXP_KNOWN_FALSE )
2512                                 return SEXP_KNOWN_FALSE;                                                                                                                        // if one of the OR clauses is TRUE, whole clause is true
2513                         if ( Sexp_nodes[Sexp_nodes[n].rest].value != SEXP_KNOWN_TRUE )                          // if the value is still unknown, they all can't be false
2514                                 all_true = 0;
2515                         // see comment above for explanation of next lines
2516                         if ( result )
2517                                 Sexp_nodes[Sexp_nodes[n].rest].value = SEXP_KNOWN_TRUE;
2518                         n = Sexp_nodes[n].rest;
2519                 }
2520         }
2521
2522         if ( all_true )
2523                 return SEXP_KNOWN_TRUE;
2524
2525         return result;
2526 }
2527
2528 // for these four basic boolean operations (not, <, >, and =), we have special cases that we must deal
2529 // with.  We have sexpressions operators that might return a NAN type return value (such as the distance
2530 // between two ships when one of the ships is destroyed or departed).  These operations need to check for
2531 // this special NAN value and adjust their return types accordingly.  NAN values represent false return values
2532 int sexp_not( int n )
2533 {
2534         int result = 0;
2535
2536         if (n != -1) {
2537                 if (Sexp_nodes[n].first != -1) {
2538                         result = eval_sexp( CAR(n) );
2539                         if ( Sexp_nodes[CAR(n)].value == SEXP_KNOWN_FALSE )
2540                                 return SEXP_KNOWN_TRUE;                                                                                         // not KNOWN_FALSE == KNOWN_TRUE;
2541                         else if ( Sexp_nodes[CAR(n)].value == SEXP_KNOWN_TRUE )         // not KNOWN_TRUE == KNOWN_FALSE
2542                                 return SEXP_KNOWN_FALSE;
2543                         else if ( Sexp_nodes[CAR(n)].value == SEXP_NAN )                                // not NAN == TRUE (I think)
2544                                 return 1;
2545                         else if ( Sexp_nodes[CAR(n)].value == SEXP_NAN_FOREVER )
2546                                 return 1;
2547                 } else
2548                         result = atoi(CTEXT(n));
2549         }
2550
2551         return !result;
2552 }
2553
2554 int sexp_gt(int n)
2555 {
2556         int exp1, exp2;
2557
2558         exp1 = eval_sexp( n );
2559         exp2 = eval_sexp( CDR(n) );
2560         
2561         // check for the NAN value
2562         if ( ( Sexp_nodes[CAR(n)].value == SEXP_NAN ) || ( Sexp_nodes[CDR(n)].value == SEXP_NAN ) )
2563                 return 0;
2564         else if ( ( Sexp_nodes[CAR(n)].value == SEXP_NAN_FOREVER ) || ( Sexp_nodes[CDR(n)].value == SEXP_NAN_FOREVER ) )
2565                 return SEXP_KNOWN_FALSE;
2566
2567         if ( exp1 > exp2 )
2568                 return 1;
2569         return 0;
2570 }
2571
2572 int sexp_lt(int n)
2573 {
2574         int exp1, exp2;
2575
2576         exp1 = eval_sexp( n );
2577         exp2 = eval_sexp( CDR(n) );
2578
2579                 // check for the NAN value
2580         if ( ( Sexp_nodes[CAR(n)].value == SEXP_NAN ) || ( Sexp_nodes[CDR(n)].value == SEXP_NAN ) )
2581                 return 0;
2582         else if ( ( Sexp_nodes[CAR(n)].value == SEXP_NAN_FOREVER ) || ( Sexp_nodes[CDR(n)].value == SEXP_NAN_FOREVER ) )
2583                 return SEXP_KNOWN_FALSE;
2584
2585         if ( exp1 < exp2 )
2586                 return 1;
2587         return 0;
2588 }
2589
2590 int sexp_equal(int n)
2591 {
2592         int exp1, exp2;
2593
2594         exp1 = eval_sexp( n );
2595         exp2 = eval_sexp( CDR(n) );
2596
2597                 // check for the NAN value
2598         if ( ( Sexp_nodes[CAR(n)].value == SEXP_NAN ) || ( Sexp_nodes[CDR(n)].value == SEXP_NAN ) )
2599                 return 0;
2600         else if ( ( Sexp_nodes[CAR(n)].value == SEXP_NAN_FOREVER ) || ( Sexp_nodes[CDR(n)].value == SEXP_NAN_FOREVER ) )
2601                 return SEXP_KNOWN_FALSE;
2602
2603         if ( exp1 == exp2 )
2604                 return 1;
2605         return 0;
2606 }
2607
2608 // Evaluate if given ship is destroyed.
2609 //      Return true if the ship in the expression has been destroyed.
2610 int sexp_is_destroyed(int n, fix *latest_time)
2611 {
2612         char    *name;
2613         int     count, num_destroyed, wing_index;
2614         fix     time;
2615
2616         SDL_assert ( n != -1 );
2617
2618         count = 0;
2619         num_destroyed = 0;
2620         wing_index = -1;
2621         while (n != -1) {
2622                 count++;
2623                 name = CTEXT(n);
2624
2625                 if (sexp_query_has_yet_to_arrive(name))
2626                         return SEXP_CANT_EVAL;
2627
2628                 // check to see if this ship/wing has departed.  If so, then function is known false
2629                 if ( mission_log_get_time (LOG_SHIP_DEPART, name, NULL, NULL) || mission_log_get_time (LOG_WING_DEPART, name, NULL, NULL) )
2630                         return SEXP_KNOWN_FALSE;
2631
2632                 // check the mission log.  If ship/wing not destroyed, immediately return 0.
2633                 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_DESTRUCT, name, NULL, &time)) {
2634                         num_destroyed++;
2635                         if ( latest_time && (time > *latest_time) )
2636                                 *latest_time = time;
2637                 } else {
2638                         // ship or wing isn't destroyed -- add to directive count
2639                         if ( (wing_index = wing_name_lookup( name, 1 )) >= 0 ) {
2640                                 Directive_count += Wings[wing_index].current_count;
2641                         } else
2642                                 Directive_count++;
2643                 }
2644
2645                 // move to next ship/wing in list
2646                 n = CDR(n);
2647         }
2648
2649         // special case to mark a directive for destroy wing objectives true after a short amount
2650         // of time when there are more waves for this wing.
2651         if ( (count == 1) && (wing_index >= 0) && (Directive_count == 0) ) {
2652                 if ( Wings[wing_index].current_wave < Wings[wing_index].num_waves )
2653                         Directive_count =       DIRECTIVE_WING_ZERO;
2654         }
2655
2656         if ( count == num_destroyed )
2657                 return SEXP_KNOWN_TRUE;
2658         else
2659                 return 0;
2660 }
2661
2662
2663 // return true if the subsystem of the given ship has been destroyed or not
2664 int sexp_is_subsystem_destroyed(int n)
2665 {
2666         char *ship_name, *subsys_name;
2667
2668         SDL_assert( n != -1 );
2669         
2670         ship_name = CTEXT(n);
2671         subsys_name = CTEXT(CDR(n));
2672
2673         if (sexp_query_has_yet_to_arrive(ship_name))
2674                 return SEXP_CANT_EVAL;
2675
2676         // if the ship has departed, no way to destroy it's subsystem.
2677         if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL ))
2678                 return SEXP_KNOWN_FALSE;
2679         
2680         if ( mission_log_get_time(LOG_SHIP_SUBSYS_DESTROYED, ship_name, subsys_name, NULL) )
2681                 return SEXP_KNOWN_TRUE;
2682
2683         return 0;
2684
2685 }
2686
2687 // determines if a ship has docked
2688 int sexp_has_docked(int n)
2689 {
2690         char *docker = CTEXT(n);
2691         char *dockee = CTEXT(CDR(n));
2692         int count = atoi(CTEXT(CDR(CDR(n))));           // count of times that we should look for
2693
2694         if (sexp_query_has_yet_to_arrive(docker))
2695                 return SEXP_CANT_EVAL;
2696
2697         if (sexp_query_has_yet_to_arrive(dockee))
2698                 return SEXP_CANT_EVAL;
2699
2700         SDL_assert ( count > 0 );
2701         if ( mission_log_get_time(LOG_SHIP_DESTROYED, docker, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, dockee, NULL, NULL) )
2702                 return SEXP_KNOWN_FALSE;
2703
2704         if ( !mission_log_get_time_indexed(LOG_SHIP_DOCK, docker, dockee, count, NULL) )
2705                 return 0;
2706
2707         return SEXP_KNOWN_TRUE;
2708 }
2709
2710 // determines if a ship has undocked
2711 int sexp_has_undocked(int n)
2712 {
2713         char *docker = CTEXT(n);
2714         char *dockee = CTEXT(CDR(n));
2715         int count = atoi(CTEXT(CDR(CDR(n))));
2716
2717         if (sexp_query_has_yet_to_arrive(docker))
2718                 return SEXP_CANT_EVAL;
2719
2720         if (sexp_query_has_yet_to_arrive(dockee))
2721                 return SEXP_CANT_EVAL;
2722
2723         SDL_assert ( count > 0 );
2724         if ( !mission_log_get_time_indexed(LOG_SHIP_UNDOCK, docker, dockee, count, NULL) ) {
2725                 // if either ship destroyed before they dock, then sexp is known false
2726                 if ( mission_log_get_time(LOG_SHIP_DESTROYED, docker, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, dockee, NULL, NULL) )
2727                         return SEXP_KNOWN_FALSE;
2728                 else
2729                         return 0;
2730         }
2731
2732         return SEXP_KNOWN_TRUE;
2733 }
2734
2735 // determines if a ship has arrived onto the scene
2736 int sexp_has_arrived(int n, fix *latest_time)
2737 {
2738         char *name;
2739         int     count, num_arrived;
2740         fix     time;
2741
2742         count = 0;
2743         num_arrived = 0;
2744         while ( n != -1 ) {
2745                 count++;
2746                 name = CTEXT(n);
2747                 // if there is no log entry for this ship/wing for arrival, sexpression is false
2748                 if ( mission_log_get_time(LOG_SHIP_ARRIVE, name, NULL, &time) || mission_log_get_time(LOG_WING_ARRIVE, name, NULL, &time) ) {
2749                         num_arrived++;
2750                         if ( latest_time && (time > *latest_time) )
2751                                 *latest_time = time;
2752                 }
2753                 n = CDR(n);
2754         }
2755
2756         if ( count == num_arrived )
2757                 return SEXP_KNOWN_TRUE;
2758         else
2759                 return 0;
2760 }
2761
2762 // determines if a ship/wing has departed
2763 int sexp_has_departed(int n, fix *latest_time)
2764 {
2765         char *name;
2766         int count, num_departed;
2767         fix time;
2768
2769         count = 0;
2770         num_departed = 0;
2771         while ( n != -1 ) {
2772                 count++;
2773                 name = CTEXT(n);
2774
2775                 if (sexp_query_has_yet_to_arrive(name))
2776                         return SEXP_CANT_EVAL;
2777
2778                 // if ship/wing destroyed, sexpression is known false.  Also, if there is no departure log entry, then
2779                 // the sexpression is not true.
2780                 if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, NULL) || mission_log_get_time(LOG_WING_DESTROYED, name, NULL, NULL))
2781                         return SEXP_KNOWN_FALSE;
2782                 else if ( mission_log_get_time(LOG_SHIP_DEPART, name, NULL, &time) || mission_log_get_time(LOG_WING_DEPART, name, NULL, &time) ) {
2783                         num_departed++;
2784                         if ( latest_time && (time > *latest_time) )
2785                                 *latest_time = time;
2786                 }
2787                 n = CDR(n);
2788         }
2789
2790         if ( count == num_departed )
2791                 return SEXP_KNOWN_TRUE;
2792         else
2793                 return 0;
2794 }
2795
2796 // determines if ships are disabled
2797 int sexp_is_disabled( int n, fix *latest_time )
2798 {
2799         char *name;
2800         int count, num_disabled;
2801         fix time;
2802
2803         count = 0;
2804         num_disabled = 0;
2805         while ( n != -1 ) {
2806                 count++;
2807                 name = CTEXT(n);
2808
2809                 if (sexp_query_has_yet_to_arrive(name))
2810                         return SEXP_CANT_EVAL;
2811
2812                 // if ship/wing destroyed, sexpression is known false.  Also, if there is no disable log entry, then
2813                 // the sexpression is not true.
2814                 if ( mission_log_get_time(LOG_SHIP_DEPART, name, NULL, &time) || mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, &time) )
2815                         return SEXP_KNOWN_FALSE;
2816                 else if ( mission_log_get_time(LOG_SHIP_DISABLED, name, NULL, &time) ) {
2817                         num_disabled++;
2818                         if ( latest_time && (time > *latest_time) )
2819                                 *latest_time = time;
2820                 }
2821                 n = CDR(n);
2822         }
2823
2824         if ( count == num_disabled )
2825                 return SEXP_KNOWN_TRUE;
2826         else
2827                 return 0;
2828 }
2829
2830 // function to determine if a ship is done flying waypoints
2831 int sexp_are_waypoints_done( int n )
2832 {
2833         char *ship_name, *waypoint_name;
2834
2835         ship_name = CTEXT(n);
2836         waypoint_name = CTEXT(CDR(n));
2837
2838         if (sexp_query_has_yet_to_arrive(ship_name))
2839                 return SEXP_CANT_EVAL;
2840
2841         // a destroyed or departed ship will never reach their goal -- return known false
2842         if ( mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) )
2843                 return SEXP_KNOWN_FALSE;
2844         else if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL) )
2845                 return SEXP_KNOWN_FALSE;
2846
2847         // now check the log for the waypoints done entry
2848         if ( mission_log_get_time(LOG_WAYPOINTS_DONE, ship_name, waypoint_name, NULL) )
2849                 return SEXP_KNOWN_TRUE;
2850
2851         return 0;
2852 }
2853
2854
2855 // determines if ships are disarmed
2856 int sexp_is_disarmed( int n, fix *latest_time )
2857 {
2858         char *name;
2859         int count, num_disarmed;
2860         fix time;
2861
2862         count = 0;
2863         num_disarmed = 0;
2864         while ( n != -1 ) {
2865                 count++;
2866                 name = CTEXT(n);
2867
2868                 if (sexp_query_has_yet_to_arrive(name))
2869                         return SEXP_CANT_EVAL;
2870
2871                 // if ship/wing destroyed, sexpression is known false.  Also, if there is no disarm log entry, then
2872                 // the sexpression is not true.
2873                 if ( mission_log_get_time(LOG_SHIP_DEPART, name, NULL, &time) || mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, &time) )
2874                         return SEXP_KNOWN_FALSE;
2875                 else if ( mission_log_get_time(LOG_SHIP_DISARMED, name, NULL, &time) ) {
2876                         num_disarmed++;
2877                         if ( latest_time && (time > *latest_time) )
2878                                 *latest_time = time;
2879                 }
2880                 n = CDR(n);
2881         }
2882
2883         if ( count == num_disarmed )
2884                 return SEXP_KNOWN_TRUE;
2885         else
2886                 return 0;
2887 }
2888
2889 // the following functions are similar to the above objective functions but return true/false
2890 // if N seconds have elasped after the corresponding function is true.
2891 int sexp_is_destroyed_delay(int n)
2892 {
2893         fix delay, time;
2894         int val;
2895
2896         SDL_assert ( n >= 0 );
2897
2898         time = 0;
2899
2900         delay = i2f(num_eval(n));
2901
2902         // check value of is_destroyed function.  KNOWN_FALSE should be returned immediately
2903         val = sexp_is_destroyed( CDR(n), &time );
2904         if ( val == SEXP_KNOWN_FALSE )
2905                 return val;
2906
2907         if ( val == SEXP_CANT_EVAL )
2908                 return SEXP_CANT_EVAL;
2909
2910         if ( val ) {
2911
2912                 if ( (Missiontime - time) >= delay )
2913                         return SEXP_KNOWN_TRUE;
2914         }
2915
2916         return 0;
2917 }
2918
2919 int sexp_is_subsystem_destroyed_delay( int n )
2920 {
2921         char *ship_name, *subsys_name;
2922         fix delay, time;
2923
2924         SDL_assert( n != -1 );
2925         
2926         ship_name = CTEXT(n);
2927         subsys_name = CTEXT(CDR(n));
2928         delay = i2f(atoi(CTEXT(CDR(CDR(n)))));
2929
2930         if (sexp_query_has_yet_to_arrive(ship_name))
2931                 return SEXP_CANT_EVAL;
2932
2933         // if the ship has departed, no way to destroy it's subsystem.
2934         if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL ))
2935                 return SEXP_KNOWN_FALSE;
2936
2937         if ( mission_log_get_time(LOG_SHIP_SUBSYS_DESTROYED, ship_name, subsys_name, &time) ) {
2938                 if ( (Missiontime - time) >= delay )
2939                         return SEXP_KNOWN_TRUE;
2940         }
2941
2942         return 0;
2943 }
2944
2945 int sexp_is_disabled_delay( int n )
2946 {
2947         fix delay, time;
2948         int val;
2949
2950         SDL_assert ( n >= 0 );
2951
2952         time = 0;
2953         delay = i2f(atoi(CTEXT(n)));
2954
2955         // check value of is_disable for known false and return immediately if it is.
2956         val = sexp_is_disabled( CDR(n), &time );
2957         if ( val == SEXP_KNOWN_FALSE )
2958                 return val;
2959
2960         if ( val == SEXP_CANT_EVAL )
2961                 return SEXP_CANT_EVAL;
2962
2963         if ( val ) {
2964                 if ( (Missiontime - time) >= delay )
2965                         return SEXP_KNOWN_TRUE;
2966         }
2967
2968         return 0;
2969 }
2970
2971 int sexp_is_disarmed_delay( int n )
2972 {
2973         fix delay, time;
2974         int val;
2975
2976         SDL_assert ( n >= 0 );
2977
2978         time = 0;
2979         delay = i2f(atoi(CTEXT(n)));
2980         
2981         // check value of is_disarmed for a known false value and return that immediately if it is
2982         val = sexp_is_disarmed( CDR(n), &time );
2983         if ( val == SEXP_KNOWN_FALSE )
2984                 return val;
2985
2986         if ( val == SEXP_CANT_EVAL )
2987                 return SEXP_CANT_EVAL;
2988
2989         if ( val ) {
2990                 if ( (Missiontime - time) >= delay )
2991                         return SEXP_KNOWN_TRUE;
2992         }
2993
2994         return 0;
2995 }
2996
2997 int sexp_has_docked_delay( int n )
2998 {
2999         char *docker = CTEXT(n);
3000         char *dockee = CTEXT(CDR(n));
3001         int count = atoi(CTEXT(CDR(CDR(n))));           // count of times that we should look for
3002         fix delay = i2f(atoi(CTEXT(CDR(CDR(CDR(n))))));
3003         fix time;
3004
3005         SDL_assert ( count > 0 );
3006         if ( mission_log_get_time(LOG_SHIP_DESTROYED, docker, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, dockee, NULL, NULL) )
3007                 return SEXP_KNOWN_FALSE;
3008
3009         if (sexp_query_has_yet_to_arrive(docker))
3010                 return SEXP_CANT_EVAL;
3011
3012         if (sexp_query_has_yet_to_arrive(dockee))
3013                 return SEXP_CANT_EVAL;
3014
3015         if ( !mission_log_get_time_indexed(LOG_SHIP_DOCK, docker, dockee, count, &time) )
3016                 return 0;
3017
3018         if ( (Missiontime - time) >= delay )
3019                 return SEXP_KNOWN_TRUE;
3020         else
3021                 return 0;
3022 }
3023
3024 int sexp_has_undocked_delay( int n )
3025 {
3026         char *docker = CTEXT(n);
3027         char *dockee = CTEXT(CDR(n));
3028         int count = atoi(CTEXT(CDR(CDR(n))));
3029         fix delay = i2f(atoi(CTEXT(CDR(CDR(CDR(n))))));
3030         fix time;
3031
3032         if (sexp_query_has_yet_to_arrive(docker))
3033                 return SEXP_CANT_EVAL;
3034
3035         if (sexp_query_has_yet_to_arrive(dockee))
3036                 return SEXP_CANT_EVAL;
3037
3038         SDL_assert ( count > 0 );
3039         if ( !mission_log_get_time_indexed(LOG_SHIP_UNDOCK, docker, dockee, count, &time) ) {
3040                 // if either ship destroyed before they dock, then sexp is known false
3041                 if ( mission_log_get_time(LOG_SHIP_DESTROYED, docker, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, dockee, NULL, NULL) )
3042                         return SEXP_KNOWN_FALSE;
3043                 else
3044                         return 0;
3045         }
3046
3047         if ( (Missiontime - time) >= delay )
3048                 return SEXP_KNOWN_TRUE;
3049         else
3050                 return 0;
3051 }
3052
3053 int sexp_has_arrived_delay( int n )
3054 {
3055         fix delay, time;
3056         int val;
3057
3058         SDL_assert ( n >= 0 );
3059
3060         time = 0;
3061         delay = i2f(atoi(CTEXT(n)));
3062
3063         // check return value from arrived function.  if can never arrive, then return that value here as well
3064         val = sexp_has_arrived( CDR(n), &time );
3065         if ( val == SEXP_KNOWN_FALSE )
3066                 return val;
3067
3068         if ( val == SEXP_CANT_EVAL )
3069                 return SEXP_CANT_EVAL;
3070
3071         if ( val ) {
3072                 if ( (Missiontime - time) >= delay )
3073                         return SEXP_KNOWN_TRUE;
3074         }
3075
3076         return 0;
3077 }
3078
3079 int sexp_has_departed_delay( int n )
3080 {
3081         fix delay, time;
3082         int val;
3083
3084         SDL_assert ( n >= 0 );
3085
3086         time = 0;
3087         delay = i2f(atoi(CTEXT(n)));
3088
3089         // must first check to see if the departed function could ever be true/false or is true or false.
3090         // if it can never be true, return that value
3091         val = sexp_has_departed( CDR(n), &time);
3092         if ( val == SEXP_KNOWN_FALSE )
3093                 return val;
3094
3095         if ( val == SEXP_CANT_EVAL )
3096                 return SEXP_CANT_EVAL;
3097
3098         if ( val ) {
3099                 if ( (Missiontime - time) >= delay )
3100                         return SEXP_KNOWN_TRUE;
3101         }
3102
3103         return 0;
3104 }
3105
3106 // function to determine if a ship is done flying waypoints after N seconds
3107 int sexp_are_waypoints_done_delay( int n )
3108 {
3109         char *ship_name, *waypoint_name;
3110         fix time, delay;
3111
3112         ship_name = CTEXT(n);
3113         waypoint_name = CTEXT(CDR(n));
3114         delay = i2f(atoi(CTEXT(CDR(CDR(n)))));
3115
3116         if (sexp_query_has_yet_to_arrive(ship_name))
3117                 return SEXP_CANT_EVAL;
3118
3119         // a destroyed or departed ship will never reach their goal -- return known false
3120         // 
3121         // Not checking the entries below.  Ships which warp out after reaching their goal (or getting
3122         // destroyed after their goal), but after reaching their waypoints, may have this goal incorrectly
3123         // marked false!!!!
3124
3125         // now check the log for the waypoints done entry
3126         if ( mission_log_get_time(LOG_WAYPOINTS_DONE, ship_name, waypoint_name, &time) ) {
3127                 if ( (Missiontime - time) >= delay )
3128                         return SEXP_KNOWN_TRUE;
3129         } else {
3130                 if ( mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) )
3131                         return SEXP_KNOWN_FALSE;
3132                 else if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL) )
3133                         return SEXP_KNOWN_FALSE;
3134         }
3135
3136         return 0;
3137 }
3138
3139 // function to determine is all of a given ship type are destroyed
3140 int sexp_ship_type_destroyed( int n )
3141 {
3142         int percent, type;
3143         char *shiptype;
3144
3145         percent = atoi(CTEXT(n));
3146         shiptype = CTEXT(CDR(n));
3147
3148         for ( type = 0; type < MAX_SHIP_TYPE_COUNTS; type++ ) {
3149                 if ( !SDL_strcasecmp( Ship_type_names[type], shiptype) )
3150                         break;
3151         }
3152
3153         // bogus if we reach the end of this array!!!!
3154         if ( type == MAX_SHIP_TYPE_COUNTS ) {
3155                 Int3();
3156                 return 0;
3157         }
3158
3159         if ( Ship_counts[type].total == 0 )
3160                 return 0;
3161
3162         // determine if the percentage of killed/total is >= percentage given in the expression
3163         if ( (Ship_counts[type].killed * 100 / Ship_counts[type].total) >= percent)
3164                 return SEXP_KNOWN_TRUE;
3165         
3166         return 0;
3167 }
3168
3169
3170 // following are time based functions
3171 int sexp_has_time_elapsed(int n)
3172 {
3173         int time = num_eval(n);
3174
3175         if ( f2i(Missiontime) >= time )
3176                 return SEXP_KNOWN_TRUE;
3177
3178         return 0;
3179 }
3180
3181 // next function returns the time into the mission
3182 int sexp_mission_time()
3183 {
3184         return f2i(Missiontime);
3185 }
3186
3187 // returns percent of length of distance to special warpout plane
3188 int sexp_special_warp_dist( int n)
3189 {
3190         char *ship_name;
3191         int shipnum;
3192
3193         // get shipname
3194         ship_name = CTEXT(n);
3195
3196         // check to see if either ship was destroyed or departed.  If so, then make this node known
3197         // false
3198         if ( mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPART, ship_name, NULL, NULL) ) {
3199                 return SEXP_NAN_FOREVER;
3200         }
3201
3202         // get ship name
3203         shipnum = ship_name_lookup(ship_name);
3204         if (shipnum < 0) {
3205                 return SEXP_NAN;
3206         }
3207
3208         // check that ship has warpout_objnum
3209         if (Ships[shipnum].special_warp_objnum == -1) {
3210                 return SEXP_NAN;
3211         }
3212         
3213         SDL_assert( (Ships[shipnum].special_warp_objnum >= 0) && (Ships[shipnum].special_warp_objnum < MAX_OBJECTS));
3214         if ( (Ships[shipnum].special_warp_objnum < 0) && (Ships[shipnum].special_warp_objnum >= MAX_OBJECTS) ) {
3215                 return SEXP_NAN;
3216         }
3217
3218         // check the special warpout device is valid
3219         int valid = FALSE;
3220         object *ship_objp = &Objects[Ships[shipnum].objnum];
3221         object *warp_objp = &Objects[Ships[shipnum].special_warp_objnum];
3222         if (warp_objp->type == OBJ_SHIP) {
3223                 if (Ship_info[Ships[warp_objp->instance].ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
3224                         valid = TRUE;
3225                 }
3226         }
3227
3228         if (!valid) {
3229                 return SEXP_NAN;
3230         }
3231
3232         // check if within 45 degree half-angle cone of facing 
3233         float dot = fl_abs(vm_vec_dotprod(&warp_objp->orient.v.fvec, &ship_objp->orient.v.fvec));
3234         if (dot < 0.707f) {
3235                 return SEXP_NAN;
3236         }
3237
3238         // get distance
3239         vector hit_pt;
3240         float dist = fvi_ray_plane(&hit_pt, &warp_objp->pos, &warp_objp->orient.v.fvec, &ship_objp->pos, &ship_objp->orient.v.fvec, 0.0f);
3241         polymodel *pm = model_get(Ships[shipnum].modelnum);
3242         dist += pm->mins.xyz.z;
3243
3244         // return as a percent of length
3245         return (int) (100.0f * dist / ship_get_length(&Ships[shipnum]));
3246 }
3247
3248
3249 int sexp_time_destroyed(int n)
3250 {
3251         fix time;
3252
3253         if ( !mission_log_get_time( LOG_SHIP_DESTROYED, CTEXT(n), NULL, &time) ){               // returns 0 when not found
3254                 return SEXP_NAN;
3255         }
3256         
3257         return f2i(time);
3258 }
3259
3260 int sexp_time_wing_destroyed(int n)
3261 {
3262         fix time;
3263
3264         if ( !mission_log_get_time( LOG_WING_DESTROYED, CTEXT(n), NULL, &time) ){
3265                 return SEXP_NAN;
3266         }
3267         
3268         return f2i(time);
3269 }
3270
3271 int sexp_time_docked(int n)
3272 {
3273         fix time;
3274         char *docker = CTEXT(n);
3275         char *dockee = CTEXT(CDR(n));
3276         int count = atoi(CTEXT(CDR(CDR(n))));
3277
3278         SDL_assert ( count > 0 );
3279         if ( !mission_log_get_time_indexed(LOG_SHIP_DOCK, docker, dockee, count, &time) ){
3280                 return SEXP_NAN;
3281         }
3282
3283         return f2i(time);
3284 }
3285
3286 int sexp_time_undocked(int n)
3287 {
3288         fix time;
3289         char *docker = CTEXT(n);
3290         char *dockee = CTEXT(CDR(n));
3291         int count = atoi(CTEXT(CDR(CDR(n))));
3292
3293         SDL_assert ( count > 0 );
3294         if ( !mission_log_get_time_indexed(LOG_SHIP_UNDOCK, docker, dockee, count, &time) ){
3295                 return SEXP_NAN;
3296         }
3297
3298         return f2i(time);
3299 }
3300
3301 int sexp_time_ship_arrived(int n)
3302 {
3303         fix time;
3304
3305         SDL_assert( n != -1 );
3306         if ( !mission_log_get_time( LOG_SHIP_ARRIVE, CTEXT(n), NULL, &time ) ){
3307                 return SEXP_NAN;
3308         }
3309
3310         return f2i(time);
3311 }
3312
3313 int sexp_time_wing_arrived(int n)
3314 {
3315         fix time;
3316
3317         SDL_assert( n != -1 );
3318         if ( !mission_log_get_time( LOG_WING_ARRIVE, CTEXT(n), NULL, &time ) ){
3319                 return SEXP_NAN;
3320         }
3321
3322         return f2i(time);
3323 }
3324
3325 int sexp_time_ship_departed(int n)
3326 {
3327         fix time;
3328
3329         SDL_assert( n != -1 );
3330         if ( !mission_log_get_time( LOG_SHIP_DEPART, CTEXT(n), NULL, &time ) ){
3331                 return SEXP_NAN;
3332         }
3333
3334         return f2i(time);
3335 }
3336
3337 int sexp_time_wing_departed(int n)
3338 {
3339         fix time;
3340
3341         SDL_assert( n != -1 );
3342         if ( !mission_log_get_time( LOG_WING_DEPART, CTEXT(n), NULL, &time ) ){
3343                 return SEXP_NAN;
3344         }
3345
3346         return f2i(time);
3347 }
3348
3349 // function to return the remaining shields as a percentage of the given ship.
3350 int sexp_shields_left(int n)
3351 {
3352         int shipnum, percent;
3353         char *shipname;
3354
3355         shipname = CTEXT(n);
3356         
3357         // if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
3358         if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPART, shipname, NULL, NULL) ){
3359                 return SEXP_NAN_FOREVER;
3360         }
3361
3362         shipnum = ship_name_lookup( shipname );
3363         if ( shipnum == -1 ){                                   // hmm.. if true, must not have arrived yet
3364                 return SEXP_NAN;
3365         }
3366
3367         // now return the amount of shields left as a percentage of the whole.
3368         percent = (int)(get_shield_strength(&Objects[Ships[shipnum].objnum]) / Ship_info[Ships[shipnum].ship_info_index].shields * 100.0f);
3369         return percent;
3370 }
3371
3372 // function to return the remaining hits left as a percentage of the whole.  This hit amount counts for
3373 // all hits on the ship (hull + subsystems).  Use hits_left_hull to find hull hits remaining.
3374 int sexp_hits_left(int n)
3375 {
3376         int shipnum, percent;
3377         char *shipname;
3378
3379         shipname = CTEXT(n);
3380         
3381         // if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
3382         if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPART, shipname, NULL, NULL) ){
3383                 return SEXP_NAN_FOREVER;
3384         }
3385
3386         shipnum = ship_name_lookup( shipname );
3387         if ( shipnum == -1 ){                                   // hmm.. if true, must not have arrived yet
3388                 return SEXP_NAN;
3389         }
3390
3391         // now return the amount of hits left as a percentage of the whole.  Subtract the percentage from 100
3392         // since we are working with total hit points taken, not total remaining.
3393         ship            *shipp = &Ships[shipnum];
3394         ship_info *sip  = &Ship_info[shipp->ship_info_index];
3395         object  *objp = &Objects[shipp->objnum];
3396         percent = (int) (100.0f * objp->hull_strength / sip->initial_hull_strength);
3397         return percent;
3398 }
3399
3400 // is ship visible on radar
3401 // returns 0 - not visible
3402 // returns 1 - marginally targetable (jiggly on radar)
3403 // returns 2 - fully targetable
3404 int sexp_is_ship_visible(int n)
3405 {
3406         char *shipname;
3407         int shipnum;
3408         int ship_is_visible = 0;
3409
3410         // if multiplayer, bail
3411         if (Game_mode & GM_MULTIPLAYER) {
3412                 return SEXP_NAN_FOREVER;
3413         }
3414
3415         shipname = CTEXT(n);
3416         
3417         // if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
3418         if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPART, shipname, NULL, NULL) ){
3419                 return SEXP_NAN_FOREVER;
3420         }
3421
3422         shipnum = ship_name_lookup( shipname );
3423         if ( shipnum == -1 ){                                   // hmm.. if true, must not have arrived yet
3424                 return SEXP_NAN;
3425         }
3426
3427         // get ship's *radar* visiblity
3428         if (Player_ship != NULL) {
3429                 if (ship_is_visible_by_team(shipnum, Player_ship->team)) {
3430                         ship_is_visible = 2;
3431                 }
3432         }
3433
3434         // only check awacs level if ship is not visible by team
3435         if (Player_ship != NULL && !ship_is_visible) {
3436                 float awacs_level = awacs_get_level(&Objects[Ships[shipnum].objnum], Player_ship);
3437                 if (awacs_level >= 1.0f) {
3438                         ship_is_visible = 2;
3439                 } else if (awacs_level > 0) {
3440                         ship_is_visible = 1;
3441                 }
3442         }
3443
3444         return ship_is_visible;
3445 }
3446
3447 // get multi team v team score
3448 // if not multi team v team return 0
3449 // if invalid team return 0
3450 int sexp_team_score(int node)
3451 {
3452         // if multi t vs t
3453         if (Game_mode & GM_MULTIPLAYER) {
3454                 if (Netgame.type_flags & NG_TYPE_TEAM) {
3455
3456                         int team = atoi(CTEXT(node));
3457
3458                         if (team == 1) {
3459                                 return Multi_team0_score;
3460                         } else if (team == 2) {
3461                                 return Multi_team1_score;
3462                         } else {
3463                                 // invalid team index
3464                                 Int3();
3465                                 return 0;
3466                         }
3467                 }
3468         }
3469
3470         return 0;
3471 }
3472
3473
3474 // function to return the remaining hits left on a subsystem as a percentage of thw whole.
3475 int sexp_hits_left_subsystem(int n)
3476 {
3477         int shipnum, percent, type;
3478         char *shipname;
3479         char *subsys_name;
3480
3481         shipname = CTEXT(n);
3482         
3483         // if ship is gone or departed, cannot ever evaluate properly.  Return NAN_FOREVER
3484         if ( mission_log_get_time(LOG_SHIP_DESTROYED, shipname, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPART, shipname, NULL, NULL) ){
3485                 return SEXP_NAN_FOREVER;
3486         }
3487
3488         shipnum = ship_name_lookup( shipname );
3489         if ( shipnum == -1 ){                                   // hmm.. if true, must not have arrived yet
3490                 return SEXP_NAN;
3491         }
3492
3493         subsys_name = CTEXT(CDR(n));
3494         type = ai_get_subsystem_type( subsys_name );
3495         if ( (type >= 0) && (type < SUBSYSTEM_MAX) ) {
3496                 // return as a percentage the hits remaining on the subsystem as a whole (i.e. for 3 engines,
3497                 // we are returning the sum of the hits on the 3 engines)
3498                 if (type == SUBSYSTEM_UNKNOWN) {
3499                         // find the ship subsystem by searching ship's subsys_list
3500                         ship_subsys *ss;
3501                         ss = GET_FIRST( &Ships[shipnum].subsys_list );
3502                         while ( ss != END_OF_LIST( &Ships[shipnum].subsys_list ) ) {
3503
3504                                 if ( !SDL_strcasecmp(ss->system_info->subobj_name, subsys_name)) {
3505                                         percent = (int) (ss->current_hits / ss->system_info->max_hits * 100.0f);
3506                                         return percent;
3507                                 }
3508
3509                                 ss = GET_NEXT( ss );
3510                         }
3511                         // we reached end of ship subsys list without finding subsys_name
3512                         Int3();
3513
3514                 } else {
3515                         percent = (int)(ship_get_subsystem_strength(&Ships[shipnum],type) * 100.0f);
3516                         return percent;
3517                 }
3518         }
3519         return SEXP_NAN;                        // if for some strange reason, the type field of the subsystem is bogus
3520 }
3521
3522 int sexp_determine_team(char *subj)
3523 {
3524         int team = 0;
3525
3526         if (!SDL_strcasecmp(subj, "<any friendly>")){
3527                 team = TEAM_FRIENDLY;
3528         } else if (!SDL_strcasecmp(subj, "<any hostile>")){
3529                 team = TEAM_HOSTILE;
3530         } else if (!SDL_strcasecmp(subj, "<any neutral>")){
3531                 team = TEAM_NEUTRAL;
3532         } else if (!SDL_strcasecmp(subj, "<any unknown>")){
3533                 team = TEAM_UNKNOWN;
3534         } else if (!SDL_strcasecmp(subj, "<any traitor>")){
3535                 team = TEAM_TRAITOR;
3536         }
3537
3538         return team;
3539 }
3540
3541 // returns the distance between two objects.  If a wing is specificed as one (or both) or the arguments
3542 // to this function, we are looking for the closest distance
3543 int sexp_distance(int n)
3544 {
3545         int i, team, obj, dist, dist_min = 0, inited = 0;
3546         char *sname1, *sname2;
3547         wing *wingp;
3548         ship_obj *so;
3549
3550         sname1 = CTEXT(n);
3551         sname2 = CTEXT(CDR(n));
3552
3553         // check to see if either ship was destroyed or departed.  If so, then make this node known
3554         // false
3555         if ( mission_log_get_time(LOG_SHIP_DESTROYED, sname1, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPART, sname1, NULL, NULL) ||
3556                   mission_log_get_time(LOG_SHIP_DESTROYED, sname2, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPART, sname2, NULL, NULL) ) 
3557                 return SEXP_NAN_FOREVER;
3558
3559         // one of the names might be the name of a wing.  Check to see if the wing is detroyed or departed
3560         if ( mission_log_get_time(LOG_WING_DESTROYED, sname1, NULL, NULL) || mission_log_get_time( LOG_WING_DEPART, sname1, NULL, NULL) ||
3561                   mission_log_get_time(LOG_WING_DESTROYED, sname2, NULL, NULL) || mission_log_get_time( LOG_WING_DEPART, sname2, NULL, NULL) ) 
3562                 return SEXP_NAN_FOREVER;
3563
3564         team = sexp_determine_team(sname1);
3565         if (team) {  // we have a team type, so check all ships of that type
3566                 so = GET_FIRST(&Ship_obj_list);
3567                 while (so != END_OF_LIST(&Ship_obj_list)) {
3568                         if (Ships[Objects[so->objnum].instance].team == team) {
3569                                 obj = so->objnum;
3570                                 dist = sexp_distance2(obj, sname2);
3571                                 if (dist != SEXP_NAN) {
3572                                         if (!inited || (dist < dist_min)) {
3573                                                 dist_min = dist;
3574                                                 inited = 1;
3575                                         }
3576                                 }
3577                         }
3578
3579                         so = GET_NEXT(so);
3580                 }
3581
3582                 if (!inited)  // no objects were checked
3583                         return SEXP_NAN;
3584
3585                 return dist_min;
3586         }
3587
3588         // at this point, we must have a wing, ship or point for a subj
3589         obj = ship_name_lookup(sname1);
3590         if (obj >= 0)
3591                 return sexp_distance2(Ships[obj].objnum, sname2);
3592
3593         // at this point, we must have a wing or point for a subj
3594         obj = waypoint_lookup(sname1);
3595         if (obj >= 0)
3596                 return sexp_distance2(obj, sname2);
3597                 
3598         // at this point, we must have a wing for a subj
3599         obj = wing_name_lookup(sname1);
3600         if (obj < 0)
3601                 return SEXP_NAN;  // we apparently don't have anything legal
3602
3603         wingp = &Wings[obj];
3604         for (i=0; i<wingp->current_count; i++) {
3605                 obj = Ships[wingp->ship_index[i]].objnum;
3606                 dist = sexp_distance2(obj, sname2);
3607                 if (dist != SEXP_NAN) {
3608                         if (!inited || (dist < dist_min)) {
3609                                 dist_min = dist;
3610                                 inited = 1;
3611                         }
3612                 }
3613         }
3614
3615         if (!inited)  // no objects were checked
3616                 return SEXP_NAN;
3617
3618         return dist_min;
3619 }
3620
3621 // check distance between a given ship and a given subject (ship, wing, any <team>).
3622 int sexp_distance2(int obj1, char *subj)
3623 {
3624         int i, team, obj2, dist, dist_min = 0, inited = 0;
3625         wing *wingp;
3626         ship_obj        *so;
3627         
3628         team = sexp_determine_team(subj);
3629         if (team) {  // we have a team type, so check all ships of that type
3630                 so = GET_FIRST(&Ship_obj_list);
3631                 while (so != END_OF_LIST(&Ship_obj_list)) {
3632                         if (Ships[Objects[so->objnum].instance].team == team) {
3633                                 obj2 = so->objnum;
3634                                 dist = sexp_distance3(obj1, obj2);
3635                                 if (dist != SEXP_NAN) {
3636                                         if (!inited || (dist < dist_min)) {
3637                                                 dist_min = dist;
3638                                                 inited = 1;
3639                                         }
3640                                 }
3641                         }
3642
3643                         so = GET_NEXT(so);
3644                 }
3645
3646                 if (!inited)  // no objects were checked
3647                         return SEXP_NAN;
3648
3649                 return dist_min;
3650         }
3651
3652         // at this point, we must have a wing, ship or point for a subj
3653         obj2 = ship_name_lookup(subj);
3654         if (obj2 >= 0)
3655                 return sexp_distance3(obj1, Ships[obj2].objnum);
3656
3657         // at this point, we must have a wing or point for a subj
3658         obj2 = waypoint_lookup(subj);
3659         if (obj2 >= 0)
3660                 return sexp_distance3(obj1, obj2);
3661                 
3662         // at this point, we must have a wing for a subj
3663         obj2 = wing_name_lookup(subj);
3664         if (obj2 < 0)
3665                 return SEXP_NAN;  // we apparently don't have anything legal
3666
3667         wingp = &Wings[obj2];
3668         for (i=0; i<wingp->current_count; i++) {
3669                 obj2 = Ships[wingp->ship_index[i]].objnum;
3670                 dist = sexp_distance3(obj1, obj2);
3671                 if (dist != SEXP_NAN) {
3672                         if (!inited || (dist < dist_min)) {
3673                                 dist_min = dist;
3674                                 inited = 1;
3675                         }
3676                 }
3677         }
3678
3679         if (!inited)  // no objects were checked
3680                 return SEXP_NAN;
3681
3682         return dist_min;
3683 }
3684
3685 // check distance between two given objects
3686 int sexp_distance3(int obj1, int obj2)
3687 {
3688         if ( (obj1 == -1) || (obj2 == -1) )                             // if either object isn't present in the mission now
3689                 return SEXP_NAN;                                                                        // return a really small number
3690
3691         if ( (Objects[obj1].type == OBJ_SHIP) && (Objects[obj2].type == OBJ_SHIP) ) {
3692                 if (OBJ_INDEX(Player_obj) == obj1)
3693                         return (int) hud_find_target_distance( &Objects[obj2], &Objects[obj1] );
3694                 else
3695                         return (int) hud_find_target_distance( &Objects[obj1], &Objects[obj2] );
3696
3697         } else {
3698                 return (int) vm_vec_dist_quick( &Objects[obj1].pos, &Objects[obj2].pos );
3699         }
3700 }
3701
3702 // funciton to determine when the last meaningful order was given to one or more ships.  Returns
3703 // true or false depending on whether or not a meaningful order was received
3704 int sexp_last_order_time( int n )
3705 {
3706         int instance, i;
3707         fix time;
3708         char *name;
3709         ai_goals *aigp;
3710
3711         time = i2f(atoi(CTEXT(n)));
3712         SDL_assert ( time >= 0 );
3713
3714         n = CDR(n);
3715         while ( n != -1 ) {
3716                 name = CTEXT(n);
3717                 instance = ship_name_lookup(name);
3718                 if ( instance != -1 ) {
3719                         aigp = Ai_info[Ships[instance].ai_index].goals;
3720                 } else {
3721                         instance = wing_name_lookup(name);
3722                         if ( instance == -1 )                                           // if we cannot find ship or wing, return 0
3723                                 return 0;
3724                         aigp = Wings[instance].ai_goals;
3725                 }
3726
3727                 // with the ship, check the ai_goals structure for this ship and determine if there are any
3728                 // orders which are < time seconds since current mission time
3729                 for ( i = 0; i < MAX_AI_GOALS; i++ ) {
3730                         int mode;
3731
3732                         mode = aigp->ai_mode;
3733                         if ( (mode  != AI_GOAL_NONE) && (mode != AI_GOAL_WARP) )
3734                                 if ( (aigp->time + time) > Missiontime )
3735                                         break;
3736                         aigp++;
3737                 }
3738                 if ( i == MAX_AI_GOALS )
3739                         return 1;
3740
3741                 n = CDR(n);
3742         }
3743
3744         return 0;
3745 }
3746
3747 // sexpression to return the number of players in the mission
3748 int sexp_num_players()
3749 {
3750         int count;
3751         object *objp;
3752
3753         count = 0;
3754         for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
3755                 if ( (objp->type == OBJ_SHIP) && (objp->flags & OF_PLAYER_SHIP) )
3756                         count++;
3757         }
3758
3759         return count;
3760 }
3761
3762 // expression to determine if the current skill level of the game is at least
3763 // the skill level given in the sexpression
3764 int sexp_skill_level_at_least( int n )
3765 {
3766         int i;
3767         char *level_name;
3768
3769         level_name = CTEXT(n);
3770         for (i = 0; i < NUM_SKILL_LEVELS; i++ ) {
3771                 if ( !SDL_strcasecmp(level_name, Skill_level_names(i, 0)) ) {
3772                         if ( Game_skill_level >= i ){
3773                                 return 1;
3774                         } else {
3775                                 return 0;
3776                         }
3777                 }
3778         }
3779
3780         // return 0 if not found!!!
3781         return 0;
3782 }
3783
3784 int sexp_was_promotion_granted(int n)
3785 {
3786         if (Player->flags & PLAYER_FLAGS_PROMOTED)
3787                 return 1;
3788
3789         return 0;
3790 }
3791
3792 int sexp_was_medal_granted(int n)
3793 {
3794         int i;
3795         char *medal_name;
3796
3797         if (n < 0) {
3798                 if (Player->stats.m_medal_earned >= 0)
3799                         return 1;
3800
3801                 return 0;
3802         }
3803
3804         medal_name = CTEXT(n);
3805         for (i=0; i<NUM_MEDALS; i++) {
3806                 if (!SDL_strcasecmp(medal_name, Medals[i].name))
3807                         break;
3808         }
3809
3810         if ( (i < NUM_MEDALS) && (Player->stats.m_medal_earned == i) )
3811                 return 1;
3812
3813         return 0;
3814 }
3815
3816 // function which returns true if the percentage of ships (and ships in wings) departed is at
3817 // least the percentage given.  what determine if we should check destroyed or departed status
3818 int sexp_percent_ships_depart_destroy(int n, int what)
3819 {
3820         int percent;
3821         int total, count;
3822         char *name;
3823
3824         percent = atoi(CTEXT(n));
3825
3826         total = 0;
3827         count = 0;
3828         // iterate through the rest of the ships/wings in the list and tally the departures and the
3829         // total
3830         for ( n = CDR(n); n != -1; n = CDR(n) ) {
3831                 int wingnum;
3832
3833                 name = CTEXT(n);
3834
3835                 wingnum = wing_name_lookup( name, 1 );
3836                 if ( wingnum != -1 ) {
3837                         // for wings, we can increment the total by the total number of ships that we expect for
3838                         // this wing, and the departures by the number of departures stored for this wing
3839                         total += (Wings[wingnum].wave_count * Wings[wingnum].num_waves);
3840                         if ( what == OP_PERCENT_SHIPS_DEPARTED )
3841                                 count += Wings[wingnum].total_departed;
3842                         else if ( what == OP_PERCENT_SHIPS_DESTROYED )
3843                                 count += Wings[wingnum].total_destroyed;
3844                         else
3845                                 Int3();                 // this would be very bogus!
3846                 } else {
3847                         // must be a ship, so increment the total by 1, then determine if this ship has departed
3848                         total++;
3849                         if ( what == OP_PERCENT_SHIPS_DEPARTED ) {
3850                                 if ( mission_log_get_time(LOG_SHIP_DEPART, name, NULL, NULL) )
3851                                         count++;
3852                         } else if ( what == OP_PERCENT_SHIPS_DESTROYED ) {
3853                                 if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, NULL) )
3854                                         count++;
3855                         } else
3856                                 Int3();                 // this would be very bogus as well.
3857
3858                 }
3859         }
3860
3861         // now, look at the percentage
3862         if ( (total > 0) && (((count * 100) / total) >= percent) )
3863                 return SEXP_KNOWN_TRUE;
3864         else
3865                 return 0;
3866 }
3867
3868 // function to tell is a list of ships has departed from within a radius of a given jump node.
3869 // returns true N seconds after the list of ships have departed
3870 int sexp_depart_node_delay( int n )
3871 {
3872         int delay, count, num_departed;
3873         char *jump_node_name, *name;
3874         fix latest_time, this_time;
3875
3876         delay = atoi( CTEXT(n) );
3877         n = CDR(n);
3878         jump_node_name = CTEXT(n);
3879
3880         // iterate through the list of ships
3881         n = CDR(n);
3882         latest_time = 0;
3883         count = 0;
3884         num_departed = 0;
3885         while ( n != -1 ) {
3886                 count++;
3887                 name = CTEXT(n);
3888
3889                 if (sexp_query_has_yet_to_arrive(name))
3890                         return SEXP_CANT_EVAL;
3891
3892                 // if ship/wing destroyed, sexpression is known false.  Also, if there is no departure log entry, then
3893                 // the sexpression is not true.
3894                 if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, NULL) )
3895                         return SEXP_KNOWN_FALSE;
3896                 else if ( mission_log_get_time(LOG_SHIP_DEPART, name, jump_node_name, &this_time) ) {
3897                         num_departed++;
3898                         if ( this_time > latest_time )
3899                                 latest_time = this_time;
3900                 }
3901                 n = CDR(n);
3902         }
3903
3904         if ( (count == num_departed) && ((Missiontime - latest_time) >= delay) )
3905                 return SEXP_KNOWN_TRUE;
3906         else
3907                 return 0;
3908 }
3909
3910 // sexpression which returns true when the listed ships/wings have all been destroyed or
3911 // have departed.
3912 int sexp_destroyed_departed_delay( int n )
3913 {
3914         int count, total;
3915         fix delay, latest_time;
3916         char *name;
3917
3918         // get the delay
3919         delay = i2f(atoi(CTEXT(n)));
3920         n = CDR(n);
3921
3922         count = 0;                                      // number destroyed or departed
3923         total = 0;                                      // total number of ships/wings to check
3924         latest_time = 0;
3925         while ( n != -1 ) {
3926                 int wingnum;
3927                 fix time_gone = 0;
3928
3929                 total++;
3930                 name = CTEXT(n);
3931
3932                 // for wings, check the WF_GONE flag to see if there are no more ships in this wing to arrive.
3933                 wingnum = wing_name_lookup(name, 1);
3934                 if ( wingnum != -1 ) {
3935                         if ( Wings[wingnum].flags & WF_WING_GONE ) {
3936                                 // be sure to get the latest time of one of these 
3937                                 if ( Wings[wingnum].time_gone > latest_time ){
3938                                         time_gone = Wings[wingnum].time_gone;
3939                                 }
3940                                 count++;
3941                         }
3942                 } else if ( mission_log_get_time(LOG_SHIP_DEPART, name, NULL, &time_gone) ) {
3943                         count++;
3944                 } else if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, &time_gone) ) {
3945                         count++;
3946                 }
3947
3948                 // check our latest time
3949                 if ( time_gone > latest_time ){
3950                         latest_time = time_gone;
3951                 }
3952
3953                 n = CDR(n);
3954         }
3955
3956         if ( (count == total) && (Missiontime > (latest_time + delay)) )
3957                 return SEXP_KNOWN_TRUE;
3958         else
3959                 return 0;
3960 }
3961
3962 int sexp_special_warpout_name( int node )
3963 {
3964         int shipnum, knossos_num;
3965         char *ship_name, *knossos;
3966
3967         ship_name = CTEXT(node);
3968         knossos = CTEXT(CDR(node));
3969
3970         // check to see if either ship was destroyed or departed.  If so, then make this node known
3971         // false
3972         if ( mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPART, ship_name, NULL, NULL) ||
3973                   mission_log_get_time(LOG_SHIP_DESTROYED, knossos, NULL, NULL) || mission_log_get_time( LOG_SHIP_DEPART, knossos, NULL, NULL) ) 
3974                 return SEXP_NAN_FOREVER;
3975
3976         // get ship name
3977         shipnum = ship_name_lookup(ship_name);
3978         if (shipnum < 0) {
3979                 return SEXP_NAN;
3980         }
3981
3982         // get knossos ship
3983         knossos_num = ship_name_lookup(knossos);
3984         if (knossos_num < 0) {
3985                 return SEXP_NAN;
3986         }
3987
3988         // set special warpout objnum
3989         Ships[shipnum].special_warp_objnum = knossos_num;
3990         return 0;
3991 }
3992
3993
3994 // function which determines if N seconds have elpased since all discovery of all cargo
3995 // of given ships
3996 int sexp_is_cargo_known( int n, int check_delay )
3997 {
3998         int count, shipnum, num_known, delay;
3999         char *name;
4000
4001         SDL_assert ( n >= 0 );
4002
4003         count = 0;
4004         num_known = 0;
4005
4006         // get the delay value (if there is one)
4007         delay = 0;
4008         if ( check_delay ) {
4009                 delay = atoi(CTEXT(n) );
4010                 n = CDR(n);
4011         }
4012
4013         while ( n != -1 ) {
4014                 fix time_known;
4015                 int is_known;
4016
4017                 is_known = 0;
4018
4019                 count++;
4020
4021                 // see if we have already checked this entry
4022                 if ( Sexp_nodes[n].value == SEXP_KNOWN_TRUE ) {
4023                         num_known++;
4024                 } else {
4025                         int exited_index;
4026
4027                         name = CTEXT(n);
4028
4029                         // see if the ship has already exited the mission (either through departure or destruction).  If so,
4030                         // grab the status of whether the cargo is known from this list
4031                         exited_index = ship_find_exited_ship_by_name( name );
4032                         if (exited_index != -1 ) {
4033                                 if ( !(Ships_exited[exited_index].flags & SEF_CARGO_KNOWN) )
4034                                         return SEXP_KNOWN_FALSE;
4035
4036                                 // check the delay of when we found out.  We use the ship died time which isn't entirely accurate
4037                                 // but won't cause huge delays.
4038                                 time_known = Missiontime - Ships_exited[exited_index].time;
4039                                 if ( f2i(time_known) >= delay )
4040                                         is_known = 1;
4041                         } else {
4042
4043                                 // otherwise, ship should still be in the mission.  If ship_name_lookup returns -1, then ship
4044                                 // is yet to arrive.
4045                                 shipnum = ship_name_lookup( name );
4046                                 if ( shipnum != -1 ) {
4047                                         if ( Ships[shipnum].flags & SF_CARGO_REVEALED ) {
4048                                                 time_known = Missiontime - Ships[shipnum].time_cargo_revealed;
4049                                                 if ( f2i(time_known) >= delay )
4050                                                         is_known = 1;
4051                                         }
4052                                 }
4053                         }
4054                 }
4055
4056                 // if cargo is known, mark our variable and this sexpression.
4057                 if ( is_known ) {
4058                         num_known++;
4059                         Sexp_nodes[n].value = SEXP_KNOWN_TRUE;
4060                 }
4061
4062                 n = CDR(n);
4063         }
4064
4065         Directive_count += count - num_known;
4066         if ( count == num_known )
4067                 return SEXP_KNOWN_TRUE;
4068         else
4069                 return 0;
4070 }
4071
4072 int sexp_has_been_tagged_delay(int n)
4073 {
4074         int count, shipnum, num_known, delay;
4075         char *name;
4076
4077         SDL_assert ( n >= 0 );
4078
4079         count = 0;
4080         num_known = 0;
4081
4082         // get the delay value
4083         delay = atoi(CTEXT(n) );
4084
4085         n = CDR(n);
4086
4087         while ( n != -1 ) {
4088                 fix time_known;
4089                 int is_known;
4090
4091                 is_known = 0;
4092
4093                 count++;
4094
4095                 // see if we have already checked this entry
4096                 if ( Sexp_nodes[n].value == SEXP_KNOWN_TRUE ) {
4097                         num_known++;
4098                 } else {
4099                         int exited_index;
4100
4101                         name = CTEXT(n);
4102
4103                         // see if the ship has already exited the mission (either through departure or destruction).  If so,
4104                         // grab the status of whether the cargo is known from this list
4105                         exited_index = ship_find_exited_ship_by_name( name );
4106                         if (exited_index != -1 ) {
4107                                 if ( !(Ships_exited[exited_index].flags & SEF_BEEN_TAGGED) )
4108                                         return SEXP_KNOWN_FALSE;
4109
4110                                 // check the delay of when we found out.  We use the ship died time which isn't entirely accurate
4111                                 // but won't cause huge delays.
4112                                 time_known = Missiontime - Ships_exited[exited_index].time;
4113                                 if ( f2i(time_known) >= delay )
4114                                         is_known = 1;
4115                         } else {
4116
4117                                 // otherwise, ship should still be in the mission.  If ship_name_lookup returns -1, then ship
4118                                 // is yet to arrive.
4119                                 shipnum = ship_name_lookup( name );
4120                                 if ( shipnum != -1 ) {
4121                                         if ( Ships[shipnum].time_first_tagged != 0 ) {
4122                                                 time_known = Missiontime - Ships[shipnum].time_first_tagged;
4123                                                 if ( f2i(time_known) >= delay )
4124                                                         is_known = 1;
4125                                         }
4126                                 }
4127                         }
4128                 }
4129
4130                 // if cargo is known, mark our variable and this sexpression.
4131                 if ( is_known ) {
4132                         num_known++;
4133                         Sexp_nodes[n].value = SEXP_KNOWN_TRUE;
4134                 }
4135
4136                 n = CDR(n);
4137         }
4138
4139         Directive_count += count - num_known;
4140         if ( count == num_known )
4141                 return SEXP_KNOWN_TRUE;
4142         else
4143                 return 0;
4144 }
4145
4146 int sexp_cap_subsys_cargo_known_delay(int n)
4147 {
4148         int delay, count, delta_time, num_known;
4149         char *ship_name, *subsys_name;
4150
4151         num_known = 0;
4152         count = 0;
4153
4154         // get delay
4155         delay = atoi(CTEXT(n));
4156         n = CDR(n);
4157
4158         // get shipname
4159         ship_name = CTEXT(n);
4160         n = CDR(n);
4161
4162         while ( n != -1 ) {
4163                 fix time_known;
4164                 int is_known;
4165                 int logged = 0;
4166
4167                 is_known = 0;
4168                 count++;
4169
4170                 // see if we have already checked this entry
4171                 if ( Sexp_nodes[n].value == SEXP_KNOWN_TRUE ) {
4172                         num_known++;
4173                 } else {
4174                         // get subsys name
4175                         subsys_name = CTEXT(n);
4176
4177                         logged = mission_log_get_time(LOG_CAP_SUBSYS_CARGO_REVEALED, ship_name, subsys_name, &time_known);
4178                         if (logged) {
4179                                 delta_time = f2i(Missiontime - time_known);
4180                                 if (delta_time >= delay) {
4181                                         is_known = 1;
4182                                 }
4183                         }
4184
4185                         // if (exited or destroyed) and not logged, known false
4186                         // otherwise, still out there and cargo not yet known
4187                         if ( (mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL ) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL )) && !logged ) {
4188                                 return SEXP_KNOWN_FALSE;
4189                         }
4190                 }
4191
4192                 if (is_known) {
4193                         num_known++;
4194                         Sexp_nodes[n].value = SEXP_KNOWN_TRUE;
4195                 }
4196
4197                 n = CDR(n);
4198         }
4199
4200         Directive_count += count - num_known;
4201         if ( count == num_known )
4202                 return SEXP_KNOWN_TRUE;
4203         else
4204                 return 0;
4205 }
4206
4207
4208 // return object index of waypoint or -1 if no such waypoint
4209 int waypoint_lookup(char *name)
4210 {
4211         char buf[128];
4212         int i;
4213         object *ptr;
4214
4215         ptr = GET_FIRST(&obj_used_list);
4216         while (ptr != END_OF_LIST(&obj_used_list)) {
4217                 if (ptr->type == OBJ_WAYPOINT) {
4218                         i = ptr->instance;
4219                         SDL_snprintf(buf, SDL_arraysize(buf), "%s:%d", Waypoint_lists[i / 65536].name, (i & 0xffff) + 1);
4220                         if ( !SDL_strcasecmp(buf, name) )
4221                                 return OBJ_INDEX(ptr);
4222                 }
4223
4224                 ptr = GET_NEXT(ptr);
4225         }
4226
4227         return -1;
4228 }
4229
4230 // conditional sexpressions follow
4231         
4232 // eval_when evaluates the when conditional
4233 int eval_when(int n)
4234 {
4235         int cond, val;
4236
4237         SDL_assert( n >= 0 );                           // must have valid sexp index
4238
4239         cond = CAR(n);
4240         val = eval_sexp(cond);          // get the value of the the conditional
4241         if ( val ) {                                    // if the value is true, perform the actions is the 'then' part of the if
4242                 int actions, exp;
4243
4244                 actions = CDR(n);
4245                 while ( actions != -1 ) {
4246                         exp = CAR(actions);
4247                         if ( exp != -1 )
4248                                 val = eval_sexp(exp);                                                           // these sexp evaled only for side effects
4249                         actions = CDR(actions);
4250                 }
4251         }
4252
4253         if (Sexp_nodes[cond].value == SEXP_KNOWN_FALSE)
4254                 return SEXP_KNOWN_FALSE;  // no need to waste time on this anymore
4255
4256         if (val == SEXP_KNOWN_FALSE)
4257                 return 0;  // can't return known false, as this would bypass future actions under the when
4258
4259         return val;
4260 }
4261
4262 // eval_cond() evaluates the cond conditional
4263 int eval_cond( int n )
4264 {
4265         int cond = 0, node, val = 0;
4266
4267         SDL_assert (n >= 0);
4268         while (n >= 0) {
4269                 node = CAR(n);
4270                 cond = CAR(node);
4271                 val = eval_sexp(cond);
4272
4273                 // if the conditional evaluated to true, then we must evaluate the rest of the expression returning
4274                 // the value of this evaluation
4275                 if (val) {
4276                         int actions, exp;
4277
4278                         val = 0;
4279                         actions = CDR(node);
4280                         while (actions >= 0) {
4281                                 exp = CAR(actions);
4282                                 if (exp >= -1)
4283                                         val = eval_sexp(exp);                                                           // these sexp evaled only for side effects
4284
4285                                 actions = CDR(actions);
4286                         }
4287
4288                         break;
4289                 }
4290
4291                 // move onto the next cond clause
4292                 n = CDR(n);
4293         }
4294
4295         return val;
4296 }
4297
4298 int sexp_is_iff( int n )
4299 {
4300         char *ship_name, *iff;
4301         int num, team;
4302
4303         SDL_assert ( n >= 0 );
4304
4305         // iff value is the first parameter, second is a list of one or more ships to check to see if the
4306         // iff value matches
4307         iff = CTEXT(n);
4308         if ( !SDL_strcasecmp(iff, "friendly") )
4309                 team = TEAM_FRIENDLY;
4310         else if ( !SDL_strcasecmp(iff, "hostile") )
4311                 team = TEAM_HOSTILE;
4312         else if ( !SDL_strcasecmp(iff, "neutral") )
4313                 team = TEAM_NEUTRAL;
4314         else if ( !SDL_strcasecmp(iff, "unknown") )
4315                 team = TEAM_UNKNOWN;
4316         else if ( !SDL_strcasecmp(iff, "traitor") )
4317                 team = TEAM_TRAITOR;
4318         else {
4319                 Int3();
4320                 mprintf(("Warning: Team %s no longer supported.  Just Friendly and Hostile.\n", iff));
4321                 team = TEAM_HOSTILE;
4322         }
4323
4324         n = CDR(n);
4325         while ( n != -1 ) {
4326                 ship_name = CTEXT(n);
4327                 // find the ship and check to be sure that it is still around.
4328                 num = ship_name_lookup(ship_name);
4329                 if ( num < 0 )                  // if the ship is gone, can't check it's iff.
4330                         continue;
4331
4332                 // if the team doesn't match the team specified, return 0 immediately
4333                 if ( Ships[num].team != team)
4334                         return 0;
4335
4336                 n = CDR(n);
4337         }
4338
4339         return 1;
4340 }
4341
4342 void sexp_change_iff( int n )
4343 {
4344         char *ship_name, *new_iff;
4345         int num, new_team;
4346
4347         SDL_assert ( n >= 0 );
4348         new_iff = CTEXT(n);
4349         if ( !SDL_strcasecmp(new_iff, "friendly") )
4350                 new_team = TEAM_FRIENDLY;
4351         else if ( !SDL_strcasecmp(new_iff, "hostile") )
4352                 new_team = TEAM_HOSTILE;
4353         else if ( !SDL_strcasecmp(new_iff, "neutral") )
4354                 new_team = TEAM_NEUTRAL;
4355         else if ( !SDL_strcasecmp(new_iff, "unknown") )
4356                 new_team = TEAM_UNKNOWN;
4357         else if ( !SDL_strcasecmp(new_iff, "traitor") )
4358                 new_team = TEAM_TRAITOR;
4359         else {
4360                 mprintf(("Warning: Team %s no longer supported.  Just Friendly and Hostile.\n", new_iff));
4361                 new_team = TEAM_HOSTILE;
4362                 Int3();
4363         }
4364
4365         n = CDR(n);
4366         while ( n != -1 ) {
4367                 ship_name = CTEXT(n);
4368
4369                 // find the ship and check to be sure that it is still around.
4370                 num = ship_name_lookup(ship_name);
4371                 if ( num >= 0 ) {                                       // only change iff if we found the ship
4372                         Ships[num].team = new_team;
4373
4374                         // send a network packet if we need to
4375                         if((Game_mode & GM_MULTIPLAYER) && (Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (Ships[num].objnum >= 0)){
4376                                 send_change_iff_packet(Objects[Ships[num].objnum].net_signature, new_team);
4377                         }
4378                 }
4379
4380                 n = CDR(n);
4381         }
4382         
4383 }
4384
4385 // following routine adds an ai goal to a ship structure.  The sexpression index
4386 // passed in should be an ai-goal of the proper form.  The code in MissionGoal should
4387 // check the syntax.
4388
4389 void sexp_add_ship_goal( int n )
4390 {
4391         int num, sindex;
4392         char *ship_name;
4393
4394         SDL_assert ( n >= 0 );
4395         ship_name = CTEXT(n);
4396         num = ship_name_lookup(ship_name);
4397         if ( num < 0 )                                                                  // ship not around anymore???? then forget it!
4398                 return;
4399
4400         sindex = CDR(n);
4401         ai_add_ship_goal_sexp( sindex, AIG_TYPE_EVENT_SHIP, &(Ai_info[Ships[num].ai_index]) );
4402 }
4403
4404 // identical to above, except add a wing
4405 void sexp_add_wing_goal( int n )
4406 {
4407         int num, sindex;
4408         char *wing_name;
4409
4410         SDL_assert ( n >= 0 );
4411         wing_name = CTEXT(n);
4412         num = wing_name_lookup(wing_name);
4413         if ( num < 0 )                                                                  // ship not around anymore???? then forget it!
4414                 return;
4415
4416         sindex = CDR(n);
4417         ai_add_wing_goal_sexp( sindex, AIG_TYPE_EVENT_WING, num );
4418 }
4419
4420 // sexp_add_goal adds a goal to the specified entiry (ships and wings have unique names between
4421 // the two sets).
4422 void sexp_add_goal( int n )
4423 {
4424         int num, sindex;
4425         char *name;
4426
4427         SDL_assert ( n >= 0 );
4428         name = CTEXT(n);
4429         sindex = CDR(n);
4430
4431         // first, look for ship name -- if found, then add ship goal.  else look for wing name -- if
4432         // found, add wing goal
4433         if ( (num = ship_name_lookup(name)) != -1 )
4434                 ai_add_ship_goal_sexp( sindex, AIG_TYPE_EVENT_SHIP, &(Ai_info[Ships[num].ai_index]) );
4435         else if ( (num = wing_name_lookup(name)) != -1 )
4436                 ai_add_wing_goal_sexp( sindex, AIG_TYPE_EVENT_WING, num );
4437 }
4438
4439 // clears out all ai goals for a ship
4440 void sexp_clear_ship_goals( int n )
4441 {
4442         int num;
4443         char *ship_name;
4444
4445         SDL_assert ( n >= 0 );
4446         ship_name = CTEXT(n);
4447         num = ship_name_lookup(ship_name);
4448         ai_clear_ship_goals( &(Ai_info[Ships[num].ai_index]) );
4449 }
4450
4451 // clears out ai goals for a wing
4452 void sexp_clear_wing_goals( int n )
4453 {
4454         int num;
4455         char *wing_name;
4456
4457         SDL_assert ( n >= 0 );
4458         wing_name = CTEXT(n);
4459         num = wing_name_lookup(wing_name);
4460         if ( num < 0 )
4461                 return;
4462         ai_clear_wing_goals( num );
4463 }
4464
4465 // this function clears all ai goals for the given ship or wing
4466 void sexp_clear_goals( int n )
4467 {
4468         int num;
4469         char *name;
4470
4471         SDL_assert ( n >= 0 );
4472         while ( n != -1 ) {
4473                 name = CTEXT(n);
4474                 if ( (num = ship_name_lookup(name)) != -1 )
4475                         ai_clear_ship_goals( &(Ai_info[Ships[num].ai_index]) );
4476                 else if ( (num = wing_name_lookup(name)) != -1 )
4477                         ai_clear_wing_goals( num );
4478
4479                 n = CDR(n);
4480         }
4481 }
4482
4483 // this function get called by send-message or send-message random with the name of the message, sender,
4484 // and priority.
4485 void sexp_send_one_message( char *name, char *who_from, char *priority, int group, int delay )
4486 {
4487         int ipriority, num, ship_index, source;
4488         ship *shipp;
4489
4490         if(physics_paused){
4491                 return;
4492         }
4493
4494         // determine the priority of the message
4495         if ( !SDL_strcasecmp(priority, "low") )
4496                 ipriority = MESSAGE_PRIORITY_LOW;
4497         else if ( !SDL_strcasecmp(priority, "normal") )
4498                 ipriority = MESSAGE_PRIORITY_NORMAL;
4499         else if ( !SDL_strcasecmp(priority, "high") )
4500                 ipriority = MESSAGE_PRIORITY_HIGH;
4501         else {
4502                 Int3();
4503                 ipriority = MESSAGE_PRIORITY_NORMAL;
4504         }
4505
4506         // check to see if the 'who_from' string is a ship that had been destroyed or departed.  If so,
4507         // then don't send the message.  We must look at 'who_from' to determine what to look for.  who_from
4508         // may be any allied person, any wingman, a wingman from a specific wing, or a specific ship
4509         ship_index = -1;
4510         shipp = NULL;
4511         source = MESSAGE_SOURCE_COMMAND;
4512         if ( who_from[0] == '#' ) {
4513                 message_send_unique_to_player( name, &(who_from[1]), MESSAGE_SOURCE_SPECIAL, ipriority, group, delay );
4514                 return;
4515         } else if (!SDL_strcasecmp(who_from, "<any allied>")) {
4516                 //Int3();                       // no longer supported
4517                 return;
4518         } else if ( (num = wing_name_lookup(who_from)) != -1 ) {
4519                 // message from a wing
4520                 // this will be an invalid case soon
4521                 // Int3();
4522                 // choose wing leader to speak for wing (hence "1" at end of ship_get_random_ship_in_wing)
4523                 ship_index = ship_get_random_ship_in_wing( num, SHIP_GET_NO_PLAYERS, 1 );
4524                 if ( ship_index == -1 ) {
4525                         if ( ipriority != MESSAGE_PRIORITY_HIGH )
4526                                 return;
4527                 }
4528
4529         } else if ( mission_log_get_time(LOG_SHIP_DESTROYED, who_from, NULL, NULL) || mission_log_get_time(LOG_SHIP_DEPART, who_from, NULL, NULL) 
4530                 || mission_log_get_time(LOG_WING_DESTROYED, who_from, NULL, NULL) || mission_log_get_time(LOG_WING_DEPART, who_from, NULL, NULL) ) {
4531                 // getting into this if statement means that the ship or wing (sender) is no longer in the mission
4532                 // if message is high priority, make it come from Terran Command
4533                 if ( ipriority != MESSAGE_PRIORITY_HIGH )
4534                         return;
4535                 
4536                 source = MESSAGE_SOURCE_COMMAND;
4537
4538         } else if ( !SDL_strcasecmp(who_from, "<any wingman>") || (wing_name_lookup(who_from) != -1) ) {
4539                 source = MESSAGE_SOURCE_WINGMAN;
4540         } else {
4541                 // Message from a apecific ship
4542                 // bail if not high priority, otherwise reroute to command
4543                 source = MESSAGE_SOURCE_SHIP;
4544                 ship_index = ship_name_lookup(who_from);
4545                 if ( ship_index == -1 ) {
4546                         if ( ipriority != MESSAGE_PRIORITY_HIGH )
4547                                 return;
4548                         source = MESSAGE_SOURCE_COMMAND;
4549                 }
4550         }
4551
4552         if ( ship_index == -1 ){
4553                 shipp = NULL;
4554         } else {
4555                 shipp = &Ships[ship_index];
4556         }
4557
4558         message_send_unique_to_player( name, shipp, source, ipriority, group, delay );
4559 }
4560
4561 void sexp_send_message( int n )
4562 {
4563         char *name, *who_from, *priority, *tmp;
4564
4565         if(physics_paused){
4566                 return;
4567         }
4568
4569         SDL_assert ( n != -1 );
4570         who_from = CTEXT(n);
4571         priority = CTEXT(CDR(n));
4572         name = CTEXT(CDR(CDR(n)));
4573
4574         // a temporary check to see if the name field matched a priority since I am in the process
4575         // of reordering the arguments
4576         if ( !SDL_strcasecmp(name, "low") || !SDL_strcasecmp(name, "normal") || !SDL_strcasecmp(name, "high") ) {
4577                 tmp = name;
4578                 name = priority;
4579                 priority = tmp;
4580         }
4581
4582         sexp_send_one_message( name, who_from, priority, 0, 0 );
4583 }
4584
4585 void sexp_send_message_list( int n )
4586 {
4587         char *name, *who_from, *priority;
4588         int delay;
4589
4590         if(physics_paused){
4591                 return;
4592         }
4593
4594         // send a bunch of messages
4595         delay = 0;
4596         while(n != -1){
4597                 who_from = CTEXT(n);
4598
4599                 // next node
4600                 n = CDR(n);
4601                 if(n == -1){
4602                         Warning(LOCATION, "Detected incomplete parameter list in sexp-send-message-list");
4603                         return;
4604                 }
4605                 priority = CTEXT(n);
4606
4607                 // next node
4608                 n = CDR(n);
4609                 if(n == -1){
4610                         Warning(LOCATION, "Detected incomplete parameter list in sexp-send-message-list");
4611                         return;
4612                 }
4613                 name = CTEXT(n);
4614
4615                 // next node
4616                 n = CDR(n);
4617                 if(n == -1){
4618                         Warning(LOCATION, "Detected incomplete parameter list in sexp-send-message-list");
4619                         return;
4620                 }
4621                 delay += atoi(CTEXT(n));
4622
4623                 // send the message
4624                 sexp_send_one_message(name, who_from, priority, 1, delay);
4625
4626                 // next node
4627                 n = CDR(n);
4628         }
4629 }
4630
4631 void sexp_send_random_message( int n )
4632 {
4633         char *name, *who_from, *priority;
4634         int temp, num_messages, message_num;
4635
4636         SDL_assert ( n != -1 );
4637         who_from = CTEXT(n);
4638         priority = CTEXT(CDR(n));
4639
4640         if(physics_paused){
4641                 return;
4642         }
4643
4644         // count the number of messages that we have
4645         n = CDR(CDR(n));
4646         temp = n;
4647         num_messages = 0;
4648         while ( n != -1 ) {
4649                 n = CDR(n);
4650                 num_messages++;
4651         }
4652
4653         if (num_messages == 0) {
4654                 Int3();
4655                 return;
4656         }
4657
4658         // get a random message, and pass the parameters to send_one_message
4659         message_num = myrand() % num_messages;
4660         n = temp;
4661         while ( n != -1 ) {
4662                 if ( message_num == 0 )
4663                         break;
4664                 message_num--;
4665                 n = CDR(n);
4666         }
4667         SDL_assert (n != -1);           // should have found the message!!!
4668         name = CTEXT(n);
4669
4670         sexp_send_one_message( name, who_from, priority, 0, 0 );
4671 }
4672
4673 void sexp_self_destruct( int n )
4674 {
4675         char *ship_name;
4676         int shipnum;
4677
4678         while ( n != -1 ) {
4679                 // get the ship name and be sure that it is still in the mission.  Destroy it if we find it
4680                 ship_name = CTEXT(n);
4681                 shipnum = ship_name_lookup( ship_name );
4682                 if ( shipnum == -1 )
4683                         return;
4684                 ship_self_destruct( &Objects[Ships[shipnum].objnum] );
4685
4686                 n = CDR(n);
4687         }
4688 }
4689
4690 void sexp_next_mission( int n )
4691 {
4692         char *mission_name;
4693         int i;
4694
4695         mission_name = CTEXT(n);
4696         for (i = 0; i < Campaign.num_missions; i++) {
4697                 if ( !SDL_strcasecmp(Campaign.missions[i].name, mission_name) ) {
4698                         Campaign.next_mission = i;
4699                         return;
4700                 }
4701         }
4702         Error(LOCATION, "Mission name %s not found in campaign file for next-mission command", mission_name);
4703 }
4704
4705 // function to deal with the end-of-campaign sexpression.  
4706 void sexp_end_of_campaign( int n )
4707 {
4708         // this is really a do-nothing sexpression.  It is pretty much a placeholder to allow
4709         // campaigns to have repeat-mission branches at the end of the campaign.  By not setting
4710         // anything in this function, the higher level campaign code will see this as end-of-campaign
4711         // since next_mission isn't set to anything.  (To be safe, we'll set to -1).
4712         Campaign.next_mission = -1;     
4713 }
4714
4715 // sexpression to end everything.  One parameter is the movie to play when this is over.
4716 void sexp_end_campaign( int n )
4717 {
4718         // post and event to move us to the end-of-campaign state.  There we will play a movie, then
4719         // go to debriefing.
4720 #ifdef MAKE_FS1
4721         // needed to actually end the game
4722         gameseq_post_event( GS_EVENT_END_CAMPAIGN );
4723 #else
4724         // in FS2 our ending is a bit wacky. we'll just flag the mission as having ended the campaign   
4725         Campaign_ended_in_mission = 1;
4726 #endif
4727 }
4728
4729 // sabotage subsystem reduces the strength of a subsystem by the given percentage.  If it is reduced to
4730 // below 0%, then the hits of the subsystem are set to 0
4731 void sexp_sabotage_subsystem( int n )
4732 {
4733         char *shipname, *subsystem;
4734         int     percentage, shipnum, index;
4735         float sabotage_hits;
4736         ship    *shipp;
4737         ship_subsys *ss;
4738
4739         shipname = CTEXT(n);
4740         subsystem = CTEXT(CDR(n));
4741         percentage = atoi(CTEXT(CDR(CDR(n))));
4742
4743         shipnum = ship_name_lookup(shipname);
4744         
4745         // if no ship, then return immediately.
4746         if ( shipnum == -1 )
4747                 return;
4748         shipp = &Ships[shipnum];
4749
4750         // see if we are dealing with the HULL
4751         if ( !SDL_strcasecmp( subsystem, SEXP_HULL_STRING) ) {
4752                 float ihs;
4753                 object *objp;
4754
4755                 ihs = Ship_info[shipp->ship_info_index].initial_hull_strength;
4756                 sabotage_hits = ihs * ((float)percentage / 100.0f);
4757                 objp = &Objects[shipp->objnum];
4758                 objp->hull_strength -= sabotage_hits;
4759
4760                 // self destruct the ship if <= 0.
4761                 if ( objp->hull_strength <= 0.0f )
4762                         ship_self_destruct( objp );
4763                 return;
4764         }
4765
4766         // now find the given subsystem on the ship.  The subsystem should be an actual subsystem name
4767         // and not a generic type (generic type meaning SUBSYSTEM_ENGINE, etc).
4768
4769         index = ship_get_subsys_index(shipp, subsystem);
4770         if ( index == -1 ) {
4771                 nprintf(("Warning", "Couldn't find subsystem %s on ship %s for sabotage subsystem\n", subsystem, shipp->ship_name));
4772                 return;
4773         }
4774
4775         // get the pointer to the subsystem.  Check it's current hits against it's max hits, and
4776         // set the strength to the given percentage if current strength is > given percentage
4777         ss = ship_get_indexed_subsys( shipp, index );
4778         sabotage_hits = ss->system_info->max_hits * ((float)percentage / 100.0f);
4779         ss->current_hits -= sabotage_hits;
4780         if ( ss->current_hits < 0.0f )
4781                 ss->current_hits = 0.0f;
4782         ship_recalc_subsys_strength( shipp );
4783 }
4784
4785 // repair_subsystem adds some percentage of hits to a subsystem.  Anything repaired about 100% is
4786 // set to max hits
4787 void sexp_repair_subsystem( int n )
4788 {
4789         char *shipname, *subsystem;
4790         int     percentage, shipnum, index;
4791         float repair_hits;
4792         ship *shipp;
4793         ship_subsys *ss;
4794
4795         shipname = CTEXT(n);
4796         subsystem = CTEXT(CDR(n));
4797         shipnum = ship_name_lookup(shipname);
4798         
4799         // if no ship, then return immediately.
4800         if ( shipnum == -1 ) {
4801                 return;
4802         }
4803         shipp = &Ships[shipnum];
4804         
4805         // check if we've got a number or an op
4806         if ( CAR(CDR(CDR(n))) != -1) {
4807                 percentage = eval_sexp( CAR(CDR(CDR(n))) );
4808         } else {
4809                 percentage = atoi(CTEXT(CDR(CDR(n))));
4810         }
4811
4812         // see if we are dealing with the HULL
4813         if ( !SDL_strcasecmp( subsystem, SEXP_HULL_STRING) ) {
4814                 float ihs;
4815                 object *objp;
4816
4817                 ihs = Ship_info[shipp->ship_info_index].initial_hull_strength;
4818                 repair_hits = ihs * ((float)percentage / 100.0f);
4819                 objp = &Objects[shipp->objnum];
4820                 objp->hull_strength += repair_hits;
4821                 if ( objp->hull_strength > ihs )
4822                         objp->hull_strength = ihs;
4823                 return;
4824         }
4825
4826         // now find the given subsystem on the ship.  The subsystem should be an actual subsystem name
4827         // and not a generic type (generic type meaning SUBSYSTEM_ENGINE, etc).
4828
4829         index = ship_get_subsys_index(shipp, subsystem);
4830         if ( index == -1 ) {
4831                 nprintf(("Warning", "Couldn't find subsystem %s on ship %s for repair subsystem\n", subsystem, shipp->ship_name));
4832                 return;
4833         }
4834
4835         // get the pointer to the subsystem.  Check it's current hits against it's max hits, and
4836         // set the strength to the given percentage if current strength is < given percentage
4837         ss = ship_get_indexed_subsys( shipp, index );
4838         repair_hits = ss->system_info->max_hits * ((float)percentage / 100.0f);
4839         ss->current_hits += repair_hits;
4840         if ( ss->current_hits > ss->system_info->max_hits )
4841                 ss->current_hits = ss->system_info->max_hits;
4842         ship_recalc_subsys_strength( shipp );
4843 }
4844
4845 // sexpression code to set a subsystem of a ship at a specific percentage
4846 void sexp_set_subsystem_strength( int n )
4847 {
4848         char *shipname, *subsystem;
4849         int     percentage, shipnum, index;
4850         ship *shipp;
4851         ship_subsys *ss;
4852
4853         shipname = CTEXT(n);
4854         subsystem = CTEXT(CDR(n));
4855         percentage = num_eval(CDR(CDR(n)));
4856
4857         shipnum = ship_name_lookup(shipname);
4858         
4859         // if no ship, then return immediately.
4860         if ( shipnum == -1 )
4861                 return;
4862         shipp = &Ships[shipnum];
4863
4864         if ( percentage > 100 ) {
4865                 nprintf(("Warning", "percentage for set_subsystem_strength > 100 -- setting to 100\n"));
4866                 percentage = 100;
4867         } else if ( percentage < 0 ) {
4868                 nprintf(("Werning", "percantage for set_subsystem_strength < 0 -- setting to 0\n"));
4869                 percentage = 0;
4870         }
4871
4872         // see if we are dealing with the HULL
4873         if ( !SDL_strcasecmp( subsystem, SEXP_HULL_STRING) ) {
4874                 float ihs;
4875                 object *objp;
4876
4877                 objp = &Objects[shipp->objnum];
4878
4879                 // destroy the ship if percentage is 0
4880                 if ( percentage == 0 ) {
4881                         ship_self_destruct( objp );
4882                 } else {
4883                         ihs = Ship_info[shipp->ship_info_index].initial_hull_strength;
4884                         objp->hull_strength = ihs * ((float)percentage / 100.0f);
4885                 }
4886
4887                 return;
4888         }
4889
4890         // now find the given subsystem on the ship.  The subsystem should be an actual subsystem name
4891         // and not a generic type (generic type meaning SUBSYSTEM_ENGINE, etc).
4892
4893         index = ship_get_subsys_index(shipp, subsystem);
4894         if ( index == -1 ) {
4895                 nprintf(("Warning", "Couldn't find subsystem %s on ship %s for repair subsystem\n", subsystem, shipp->ship_name));
4896                 return;
4897         }
4898
4899         // get the pointer to the subsystem.  Check it's current hits against it's max hits, and
4900         // set the strength to the given percentage if current strength is < given percentage
4901         ss = ship_get_indexed_subsys( shipp, index );
4902
4903         // maybe blow up subsys
4904         if (ss->current_hits > 0) {
4905                 if (percentage < 1) {
4906                         do_subobj_destroyed_stuff(shipp, ss, NULL);
4907                 }
4908         }
4909
4910         // set hit points
4911         ss->current_hits = ss->system_info->max_hits * ((float)percentage / 100.0f);
4912
4913         ship_recalc_subsys_strength( shipp );
4914 }
4915
4916 // function which changes the validity of a goal.  The flag paramater tells us whether to mark the goals
4917 // as valid or invalid
4918 void sexp_change_goal_validity( int n, int flag )
4919 {
4920         char *name;
4921
4922         while ( n != -1 ) {
4923                 name = CTEXT(n);
4924                 if ( flag )
4925                         mission_goal_mark_valid( name );
4926                 else
4927                         mission_goal_mark_invalid( name );
4928
4929                 n = CDR(n);
4930         }
4931 }
4932
4933 // function to transfer cargo from one ship to another
4934 void sexp_transfer_cargo( int n )
4935 {
4936         char *shipname1, *shipname2;
4937         int shipnum1, shipnum2, i;
4938         object *objp;
4939
4940         shipname1 = CTEXT(n);
4941         shipname2 = CTEXT(CDR(n));
4942
4943         // find the ships -- if neither in the mission, the abort
4944         shipnum1 = ship_name_lookup(shipname1);
4945         shipnum2 = ship_name_lookup(shipname2);
4946         if ( (shipnum1 == -1) || (shipnum2 == -1) )
4947                 return;
4948
4949         // we must be sure that these two objects are indeed docked
4950         objp = ai_find_docked_object( &Objects[Ships[shipnum1].objnum] );
4951         if ( objp != &Objects[Ships[shipnum2].objnum] ) {
4952                 Int3();                 // you are trying to transfer cargo between two ships not docked
4953                 return;
4954         }
4955
4956         if ( !SDL_strcasecmp(Cargo_names[Ships[shipnum1].cargo1 & CARGO_INDEX_MASK], "nothing") ) {
4957                 Int3();                 // you are transfering no cargo!!!!
4958                 return;
4959         }
4960
4961         // transfer cargo from ship1 to ship2
4962 #ifndef NDEBUG
4963         // Don't give warning for large ships (cruiser on up) 
4964         if (! (Ship_info[Ships[shipnum2].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) ) {
4965                 if ( SDL_strcasecmp(Cargo_names[Ships[shipnum2].cargo1 & CARGO_INDEX_MASK], "nothing") ) {
4966                         Warning(LOCATION, "Transfering cargo to %s which already\nhas cargo %s.\nCargo will be replaced", Ships[shipnum2].ship_name, Cargo_names[Ships[shipnum2].cargo1 & CARGO_INDEX_MASK] );
4967                 }
4968         }
4969 #endif
4970         Ships[shipnum2].cargo1 = char(Ships[shipnum1].cargo1 & CARGO_INDEX_MASK);
4971
4972         if ( !(Ships[shipnum1].cargo1 & CARGO_NO_DEPLETE) ) {
4973                 // need to set ship1's cargo to nothing.  scan the cargo_names array looking for the string nothing.
4974                 // add it if not found
4975                 for (i = 0; i < Num_cargo; i++ ) {
4976                         if ( !SDL_strcasecmp(Cargo_names[i], "nothing") ) {
4977                                 Ships[shipnum1].cargo1 = char(i);
4978                                 return;
4979                         }
4980                 }
4981                 SDL_strlcpy(Cargo_names[i], "Nothing", NAME_LENGTH);
4982                 Num_cargo++;
4983         }
4984 }
4985
4986 // this function exchanges cargo between two ships
4987 void sexp_exchange_cargo( int n )
4988 {
4989         char *shipname1, *shipname2;
4990         int shipnum1, shipnum2, temp;
4991         object *objp;
4992
4993         shipname1 = CTEXT(n);
4994         shipname2 = CTEXT(CDR(n));
4995
4996         // find the ships -- if neither in the mission, the abort
4997         shipnum1 = ship_name_lookup(shipname1);
4998         shipnum2 = ship_name_lookup(shipname2);
4999         if ( (shipnum1 == -1) || (shipnum2 == -1) )
5000                 return;
5001
5002         // we must be sure that these two objects are indeed docked
5003         objp = ai_find_docked_object( &Objects[Ships[shipnum1].objnum] );
5004         if ( objp != &Objects[Ships[shipnum2].objnum] ) {
5005                 Int3();                 // you are trying to transfer cargo between two ships not docked
5006                 return;
5007         }
5008
5009         temp = (Ships[shipnum1].cargo1 & CARGO_INDEX_MASK);
5010         Ships[shipnum1].cargo1 = char(Ships[shipnum2].cargo1 & CARGO_INDEX_MASK);
5011         Ships[shipnum2].cargo1 = char(temp);
5012 }
5013
5014 void sexp_cap_waypont_speed(int n)
5015 {
5016         char *shipname;
5017         int shipnum;
5018         int speed;
5019
5020         shipname = CTEXT(n);
5021         speed = atoi(CTEXT(CDR(n)));
5022
5023         shipnum = ship_name_lookup(shipname);
5024
5025         if (shipnum == -1) {
5026                 Int3(); // trying to set waypoint speed of ship not already in game
5027                 return;
5028         }
5029
5030         // cap speed to range (-1, 127) to store within char
5031         if (speed < 0) {
5032                 speed = -1;
5033         }
5034
5035         if (speed > 127) {
5036                 speed = 127;
5037         }
5038
5039         Ai_info[Ships[shipnum].ai_index].waypoint_speed_cap = (char) speed;
5040 }
5041
5042 // this function causes a ship to jettison its cargo
5043 void sexp_jettison_cargo( int n )
5044 {
5045         char *shipname;
5046         int ship_index;//, jettison_delay;
5047
5048         // get some data
5049         shipname = CTEXT(n);
5050 //      jettison_delay = atoi(CTEXT(CDR(n)));
5051
5052         // lookup the ship
5053         ship_index = ship_name_lookup(shipname);
5054         if(ship_index < 0){
5055                 return;
5056         }
5057         
5058         // jettison cargo
5059         ship_jettison_cargo(&Ships[ship_index]);
5060 }
5061
5062 void sexp_cargo_no_deplete( int n )
5063 {
5064         char *shipname;
5065         int ship_index, no_deplete = 1;
5066
5067         // get some data
5068         shipname = CTEXT(n);
5069
5070         // lookup the ship
5071         ship_index = ship_name_lookup(shipname);
5072         if(ship_index < 0){
5073                 return;
5074         }
5075
5076         if ( !(Ship_info[Ships[ship_index].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) ) {
5077                 Warning(LOCATION, "Trying to make non BIG or HUGE ship %s with non-depletable cargo.\n", Ships[ship_index].ship_name);
5078                 return;
5079         }
5080
5081         if (CDR(n) != -1) {
5082                 no_deplete = atoi(CTEXT(CDR(n)));
5083                 SDL_assert((no_deplete == 0) || (no_deplete == 1));
5084                 if ( (no_deplete != 0) && (no_deplete != 1) ) {
5085                         no_deplete = 1;
5086                 }
5087         }
5088
5089         if (no_deplete) {
5090                 Ships[ship_index].cargo1 |= CARGO_NO_DEPLETE;
5091         } else {
5092                 Ships[ship_index].cargo1 &= (~CARGO_NO_DEPLETE);
5093         }
5094
5095 }
5096
5097 // sexpression to end the mission after N seconds!
5098 void sexp_end_mission_delay( int n )
5099 {
5100         //int delay;
5101
5102         //delay = atoi(CTEXT(n));
5103         //mission_parse_set_end_time( delay );
5104         mprintf(("Not ending mission -- end-mission sexpression no longer works!\n"));
5105 }
5106
5107 // funciton to toggle the status bit for the AI code which tells the AI if it is a good time
5108 // to rearm.  The status being set means good time.  Status not being set (unset), means bad time.
5109 // designers must implement this.
5110 void sexp_good_time_to_rearm( int n )
5111 {
5112         int i, time;
5113         char *team_name;
5114
5115         team_name = CTEXT(n);
5116         time = atoi(CTEXT(CDR(n)));                                             // this is the time for how long a good rearm is active -- in seconds
5117         for ( i = 0; i < Num_team_names; i++ ) {
5118                 if ( !SDL_strcasecmp(team_name, Team_names[i]) ) {
5119                         int team;
5120
5121                         team = 1 << i;
5122                         ai_set_rearm_status( team, time );
5123                 }
5124         }
5125 }
5126
5127 // function which grants promotion to the player
5128 void sexp_grant_promotion()
5129 {
5130         // short circuit multiplayer for now until we figure out what to do.
5131         if ( Game_mode & GM_MULTIPLAYER )
5132                 return;
5133
5134         // set a bit to tell player should get promoted at the end of the mission.  I suppose the other
5135         // thing that we could do would be to set the players score to at least the amount of
5136         // points for the next level, but this way is better I think.
5137         if ( Game_mode & GM_CAMPAIGN_MODE ) {
5138                 Player->flags |= PLAYER_FLAGS_PROMOTED;
5139         }
5140 }
5141
5142 // function which gives the named medal to the players in the mission
5143 void sexp_grant_medal( int n )
5144 {
5145         int i, j;
5146         char *medal_name;
5147
5148         // don't give medals in normal gameplay when not in campaign mode
5149         if ( (Game_mode & GM_NORMAL) && !(Game_mode & GM_CAMPAIGN_MODE) )
5150                 return;
5151
5152         SDL_assert(Player->stats.m_medal_earned < 0);  // Mission has problems.  Tried to grant 2 medals in 1 mission.
5153         medal_name = CTEXT(n);
5154         for (i = 0; i < NUM_MEDALS; i++ ) {
5155                 if ( !SDL_strcasecmp(medal_name, Medals[i].name) )
5156                         break;
5157         }
5158
5159         if ( i < NUM_MEDALS ) {
5160                 Player->stats.m_medal_earned = i;
5161                 if ( Game_mode & GM_MULTIPLAYER ) {
5162                         for ( j = 0; j < MAX_PLAYERS; j++ ) {
5163                                 if ( MULTI_CONNECTED(Net_players[j]) ) {
5164                                         Net_players[j].player->stats.m_medal_earned = i;
5165                                 }
5166                         }
5167                 }
5168         }
5169 }
5170
5171 void sexp_tech_add_ship(int node)
5172 {
5173         int i;
5174         char *name;
5175
5176         SDL_assert(node >= 0);
5177         // this function doesn't mean anything when not in campaign mode
5178         if ( !(Game_mode & GM_CAMPAIGN_MODE) )
5179                 return;
5180
5181         while (node >= 0) {
5182                 name = CTEXT(node);
5183                 i = ship_info_lookup(name);
5184                 if (i >= 0)
5185                         Ship_info[i].flags |= SIF_IN_TECH_DATABASE;
5186                 else
5187                         Error(LOCATION, "Ship class \"%s\" invalid", name);
5188
5189                 node = CDR(node);
5190         }
5191 }
5192
5193 void sexp_tech_add_weapon(int node)
5194 {
5195         int i;
5196         char *name;
5197
5198         SDL_assert(node >= 0);
5199         // this function doesn't mean anything when not in campaign mode
5200         if ( !(Game_mode & GM_CAMPAIGN_MODE) )
5201                 return;
5202
5203         while (node >= 0) {
5204                 name = CTEXT(node);
5205                 i = weapon_info_lookup(name);
5206                 if (i >= 0)
5207                         Weapon_info[i].wi_flags |= WIF_IN_TECH_DATABASE;
5208                 else
5209                         Error(LOCATION, "Ship class \"%s\" invalid", name);
5210
5211                 node = CDR(node);
5212         }
5213 }
5214
5215 // function to set variables needed to grant a new ship/weapon to the player during the course
5216 // of a mission
5217 void sexp_allow_ship( int n )
5218 {
5219         int sindex;
5220         char *name;
5221
5222         // this function doesn't mean anything when not in campaign mode
5223         if ( !(Game_mode & GM_CAMPAIGN_MODE) )
5224                 return;
5225
5226         // get the name of the ship and lookup up the ship_info index for it
5227         name = CTEXT(n);
5228         sindex = ship_info_lookup( name );
5229         if ( sindex == -1 )
5230                 return;
5231
5232         // now we have a valid index --
5233         mission_campaign_save_persistent( CAMPAIGN_PERSISTENT_SHIP, sindex );
5234 }
5235
5236 void sexp_allow_weapon( int n )
5237 {
5238         int sindex;
5239         char *name;
5240
5241         // this function doesn't mean anything when not in campaign mode
5242         if ( !(Game_mode & GM_CAMPAIGN_MODE) )
5243                 return;
5244
5245         // get the name of the weapon and lookup up the weapon_info index for it
5246         name = CTEXT(n);
5247         sindex = weapon_info_lookup( name );
5248         if ( sindex == -1 )
5249                 return;
5250
5251         // now we have a valid index --
5252         mission_campaign_save_persistent( CAMPAIGN_PERSISTENT_WEAPON, sindex );
5253 }
5254
5255 // functions to deal with breaking/fixing the warp engines on ships/wings.  should_break is true when
5256 // we are breaking the warp drive (can be repaired). The parameter is 0 when is getting broken (i.e.
5257 // can be fixed by repair).  The repair parameter tells us whether we are clearing the destroyed or broken
5258 // flag (1), or setting them (0).
5259 void sexp_deal_with_warp( int n, int should_break, int nix )
5260 {
5261         int index, flag;
5262         char *name;
5263
5264         for ( ; n != -1; n = CDR(n) ) {
5265                 name = CTEXT(n);
5266                 index = ship_name_lookup(name);
5267
5268                 // check to see if ship destroyed or departed.  In either case, do nothing.
5269                 if ( mission_log_get_time(LOG_SHIP_DEPART, name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, NULL) )
5270                         continue;
5271
5272                 // we can only operate on ships which are in the mission
5273                 if ( index != -1 ) {
5274
5275                         // set the flag value accoring to whether we are destroying the warp or just breaking it
5276                         if ( should_break )
5277                                 flag = SF_WARP_BROKEN;
5278                         else
5279                                 flag = SF_WARP_NEVER;
5280
5281                         if ( nix )
5282                                 Ships[index].flags |= flag;
5283                         else
5284                                 Ships[index].flags &= ~flag;
5285
5286                 } else {
5287                         // maybe this ship has yet to arrive.  Get a possible parse object and set the flag if found
5288                         p_object *pobjp;
5289
5290                         pobjp = mission_parse_get_arrival_ship( name );
5291 #ifndef NDEBUG
5292                         if ( pobjp == NULL ) {
5293                                 Int3();                         // warning, find allender -- should be impossible
5294                                 continue;
5295                         }
5296 #endif
5297                         if ( should_break )
5298                                 flag = P_SF_WARP_BROKEN;
5299                         else
5300                                 flag = P_SF_WARP_BROKEN;
5301
5302                         if ( nix )
5303                                 pobjp->flags |= flag;
5304                         else
5305                                 pobjp->flags &= ~flag;
5306
5307                 }
5308         }
5309 }
5310
5311 // function which is used to tell the AI when it is okay to fire certain secondary
5312 // weapons at other ships.
5313 void sexp_good_secondary_time( int n )
5314 {
5315         char *team_name, *weapon_name, *ship_name;
5316         int num_weapons, weapon_index, team, i;
5317
5318         team_name = CTEXT(n);
5319         num_weapons = atoi(CTEXT(CDR(n)));
5320         weapon_name = CTEXT(CDR(CDR(n)));
5321         ship_name = CTEXT(CDR(CDR(CDR(n))));
5322
5323         weapon_index = weapon_info_lookup(weapon_name);
5324         if ( weapon_index == -1 ) {
5325                 nprintf(("Warning", "couldn't find weapon %s for good-secondary-time\n", weapon_name));
5326                 return;
5327         }
5328
5329         // get the team type from the team_name
5330         for ( i = 0; i < Num_team_names; i++ ) {
5331                 if ( !SDL_strcasecmp(Team_names[i], team_name) )
5332                         break;
5333         }
5334         if ( i == Num_team_names ) {
5335                 nprintf(("Warning", "couldn't find team %s for good-secondary-time\n", team_name ));
5336                 return;
5337         }
5338         team = (1<<i);                  // this is the magic formula to get to a team type.
5339
5340         // see if the ship has departed or has been destroyed.  If so, then we don't need to set up the
5341         // AI stuff
5342         if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) )
5343                 return;
5344
5345         ai_good_secondary_time( team, weapon_index, num_weapons, ship_name );
5346 }
5347
5348
5349 // function to deal with getting status of goals for previous missions (in the current campaign).
5350 // the status parameter is used to tell this function if we are looking for a goal_satisfied, goal_failed,
5351 // or goal incomplete event
5352 int sexp_previous_goal_status( int n, int status )
5353 {
5354         char rval = 0, *mission_name;
5355         char *goal_name;
5356         int i, mission_num, default_value = 0, use_defaults = 1;
5357
5358         mission_name = CTEXT(n);
5359         goal_name = CTEXT(CDR(n));
5360
5361         // check for possible next optional argument
5362         n = CDR(CDR(n));
5363         if ( n != -1 ) {
5364                 default_value = eval_sexp(n);
5365         }
5366
5367         // try to find the given mission name in the current list of missions in the campaign.
5368         if ( Game_mode & GM_CAMPAIGN_MODE ) {
5369                 i = mission_campaign_find_mission( mission_name );
5370
5371                 if ( i == -1 ) {
5372                         // if mission not found, assume that goal was false (so previous-goal-false returns true)
5373                         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"));
5374                         if ( status == GOAL_COMPLETE )
5375                                 rval = SEXP_KNOWN_FALSE;
5376                         else
5377                                 rval = SEXP_KNOWN_TRUE;
5378
5379                         use_defaults = 0;
5380                 } else if (Campaign.missions[i].flags & CMISSION_FLAG_SKIPPED) {
5381                         use_defaults = 1;
5382                 } else {
5383                         // now try and find the goal this mission
5384                         mission_num = i;
5385                         for (i = 0; i < Campaign.missions[mission_num].num_goals; i++) {
5386                                 if ( !SDL_strcasecmp(Campaign.missions[mission_num].goals[i].name, goal_name) )
5387                                         break;
5388                         }
5389
5390                         if ( i == Campaign.missions[mission_num].num_goals ) {
5391                                 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");
5392                                 if ( status == GOAL_COMPLETE )
5393                                         rval = SEXP_KNOWN_FALSE;
5394                                 else
5395                                         rval = SEXP_KNOWN_TRUE;
5396
5397                         } else {
5398                                 // now return KNOWN_TRUE or KNOWN_FALSE based on the status field in the goal structure
5399                                 if ( Campaign.missions[mission_num].goals[i].status == status )
5400                                         rval = SEXP_KNOWN_TRUE;
5401                                 else
5402                                         rval = SEXP_KNOWN_FALSE;
5403                         }
5404
5405                         use_defaults = 0;
5406                 }
5407         }
5408
5409         if (use_defaults) {
5410                 // when not in campaign mode, always return KNOWN_TRUE when looking for goal complete, and KNOWN_FALSE
5411                 // otherwise
5412                 if ( n != -1 ) {
5413                         if ( default_value )
5414                                 rval = SEXP_KNOWN_TRUE;
5415                         else
5416                                 rval = SEXP_KNOWN_FALSE;
5417                 } else {
5418                         if ( status == GOAL_COMPLETE )
5419                                 rval = SEXP_KNOWN_TRUE;
5420                         else
5421                                 rval = SEXP_KNOWN_FALSE;
5422                 }
5423         }
5424
5425         return rval;
5426 }
5427
5428 // sexpression which gets the status of an event from a previous mission.  Like the above function but
5429 // dealing with events instead of goals.  Again, the status parameter tells the code if we are looking
5430 // for an event_true, event_false, or event_incomplete status
5431 int sexp_previous_event_status( int n, int status )
5432 {
5433         char rval = 0, *mission_name;
5434         char *name;
5435         int i, mission_num, default_value = 0, use_defaults = 1;
5436
5437         mission_name = CTEXT(n);
5438         name = CTEXT(CDR(n));
5439
5440         // check for possible optional parameter
5441         n = CDR(CDR(n));
5442         if ( n != -1 ){
5443                 default_value = eval_sexp(n);
5444         }
5445
5446         if ( Game_mode & GM_CAMPAIGN_MODE ) {
5447                 // following function returns -1 when mission isn't found.
5448                 i = mission_campaign_find_mission( mission_name );
5449
5450                 // if the mission name wasn't found -- make this return FALSE for the event status.
5451                 if ( i == -1 ) {
5452                         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"));
5453                         if ( status == EVENT_SATISFIED ) {
5454                                 rval = SEXP_KNOWN_FALSE;
5455                         } else {
5456                                 rval = SEXP_KNOWN_TRUE;
5457                         }
5458
5459                         use_defaults = 0;
5460                 } else if (Campaign.missions[i].flags & CMISSION_FLAG_SKIPPED) {
5461                         use_defaults = 1;
5462                 } else {
5463                         // now try and find the goal this mission
5464                         mission_num = i;
5465                         for (i = 0; i < Campaign.missions[mission_num].num_events; i++) {
5466                                 if ( !SDL_strcasecmp(Campaign.missions[mission_num].events[i].name, name) )
5467                                         break;
5468                         }
5469
5470                         if ( i == Campaign.missions[mission_num].num_events ) {
5471                                 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");
5472                                 if ( status == EVENT_SATISFIED )
5473                                         rval = SEXP_KNOWN_FALSE;
5474                                 else
5475                                         rval = SEXP_KNOWN_TRUE;
5476
5477                         } else {
5478                                 // now return KNOWN_TRUE or KNOWN_FALSE based on the status field in the goal structure
5479                                 if ( Campaign.missions[mission_num].events[i].status == status )
5480                                         rval = SEXP_KNOWN_TRUE;
5481                                 else
5482                                         rval = SEXP_KNOWN_FALSE;
5483                         }
5484
5485                         use_defaults = 0;
5486                 }
5487         } 
5488
5489         if (use_defaults) {
5490                 if ( n != -1 ) {
5491                         if ( default_value )
5492                                 rval = SEXP_KNOWN_TRUE;
5493                         else
5494                                 rval = SEXP_KNOWN_FALSE;
5495                 } else {
5496                         if ( status == EVENT_SATISFIED )
5497                                 rval = SEXP_KNOWN_TRUE;
5498                         else
5499                                 rval = SEXP_KNOWN_FALSE;
5500                 }
5501         }
5502
5503         return rval;
5504 }
5505
5506 // function to return the status of an event in the current mission.  The passed parameter indicates
5507 // if we are checking whether the event is true or the event is false.
5508 int sexp_event_status( int n, int want_true )
5509 {
5510         char *name;
5511         int i, result;
5512
5513         name = CTEXT(n);
5514         for (i = 0; i < Num_mission_events; i++ ) {
5515                 // look for the event name, check it's status.  If formula is gone, we know the state won't ever change.
5516                 if ( !SDL_strcasecmp(Mission_events[i].name, name) ) {
5517                         result = Mission_events[i].result;
5518                         if (Mission_events[i].formula < 0) {
5519                                 if ( (want_true && result) || (!want_true && !result) )
5520                                         return SEXP_KNOWN_TRUE;
5521                                 else
5522                                         return SEXP_KNOWN_FALSE;
5523
5524                         } else {
5525                                 if ( (want_true && result) || (!want_true && !result) )
5526                                         return SEXP_TRUE;
5527                                 else
5528                                         return SEXP_FALSE;
5529                         }
5530                 }
5531         }
5532
5533         return 0;
5534 }
5535
5536 // function to return the status of an event N seconds after the event is true or false.  Similar
5537 // to above function but waits N seconds before returning true
5538 int sexp_event_delay_status( int n, int want_true )
5539 {
5540         char *name;
5541         int i, result;
5542         fix delay;
5543
5544         name = CTEXT(n);
5545         delay = i2f(num_eval(CDR(n)));
5546         for (i = 0; i < Num_mission_events; i++ ) {
5547                 // look for the event name, check it's status.  If formula is gone, we know the state won't ever change.
5548                 if ( !SDL_strcasecmp(Mission_events[i].name, name) ) {
5549                         if ( (fix) Mission_events[i].timestamp + delay >= Missiontime )
5550                                 return SEXP_FALSE;
5551
5552                         result = Mission_events[i].result;
5553                         if (Mission_events[i].formula < 0) {
5554                                 if ( (want_true && result) || (!want_true && !result) )
5555                                         return SEXP_KNOWN_TRUE;
5556                                 else
5557                                         return SEXP_KNOWN_FALSE;
5558
5559                         } else {
5560                                 if ( want_true && result )  //) || (!want_true && !result) )
5561                                         return SEXP_TRUE;
5562                                 else
5563                                         return SEXP_FALSE;
5564                         }
5565                 }
5566         }
5567
5568         return 0;
5569 }
5570
5571 // function which returns true if the given event is still incomplete
5572 int sexp_event_incomplete( int n )
5573 {
5574         char *name;
5575         int i;
5576
5577         name = CTEXT(n);
5578
5579         for (i = 0; i < Num_mission_events; i++ ) {
5580                 if ( !SDL_strcasecmp(Mission_events[i].name, name ) ) {
5581                         // if the formula is still >= 0 (meaning it is still getting eval'ed), then
5582                         // the event is incomplete
5583                         if ( Mission_events[i].formula != -1 )
5584                                 return SEXP_TRUE;
5585                         else
5586                                 return SEXP_KNOWN_FALSE;
5587                 }
5588         }
5589
5590         return 0;
5591 }
5592
5593 // function to return the status of an goal N seconds after the goal is true or false.  Similar
5594 // to above function but operates on goals instead of events
5595 int sexp_goal_delay_status( int n, int want_true )
5596 {
5597         char *name;
5598         fix delay, time;
5599
5600         name = CTEXT(n);
5601         delay = i2f(num_eval(CDR(n)));
5602         
5603         if ( want_true ) {
5604                 // if we are looking for a goal true entry and we find a false, then return known false here
5605                 if ( mission_log_get_time(LOG_GOAL_FAILED, name, NULL, NULL) )
5606                         return SEXP_KNOWN_FALSE;
5607                 else if ( mission_log_get_time(LOG_GOAL_SATISFIED, name, NULL, &time) ) {
5608                         if ( (Missiontime - time) >= delay )
5609                                 return SEXP_KNOWN_TRUE;
5610                 }
5611         } else {
5612                 // if we are looking for a goal false entry and we find a true, then return known false here
5613                 if ( mission_log_get_time(LOG_GOAL_SATISFIED, name, NULL, NULL) )
5614                         return SEXP_KNOWN_FALSE;
5615                 else if ( mission_log_get_time(LOG_GOAL_FAILED, name, NULL, &time) ) {
5616                         if ( (Missiontime - time) >= delay )
5617                                 return SEXP_KNOWN_TRUE;
5618                 }
5619         }
5620
5621         return 0;
5622 }
5623
5624 // function which returns true if the given goal is still incomplete
5625 int sexp_goal_incomplete( int n )
5626 {
5627         char *name;
5628
5629         name = CTEXT(n);
5630
5631         if ( mission_log_get_time( LOG_GOAL_SATISFIED, name, NULL, NULL) || mission_log_get_time( LOG_GOAL_FAILED, name, NULL, NULL) )
5632                 return SEXP_KNOWN_FALSE;
5633         else
5634                 return SEXP_TRUE;
5635 }
5636
5637
5638 // protects/unprotects a ship.  The flag tells us whether or not the protect bit should be set (flag==1)
5639 // or cleared (flag==0)
5640 void sexp_protect_ships( int n, int flag )
5641 {
5642         char *ship_name;
5643         int num;
5644
5645         while ( n != -1 ) {
5646                 ship_name = CTEXT(n);
5647
5648                 // check to see if ship destroyed or departed.  In either case, do nothing.
5649                 if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) )
5650                         return;
5651
5652                 // get the ship num.  If we get a -1 for the number here, ship has yet to arrive.  Store this ship
5653                 // in a list until created
5654                 num = ship_name_lookup(ship_name);
5655                 if ( num >= 0 ) {
5656                         if ( flag )
5657                                 Objects[Ships[num].objnum].flags |= OF_PROTECTED;
5658                         else
5659                                 Objects[Ships[num].objnum].flags &= ~OF_PROTECTED;
5660                 } else {
5661                         p_object *parse_obj;
5662
5663                         parse_obj = mission_parse_get_arrival_ship( ship_name );
5664                         if ( parse_obj ) {
5665                                 if ( flag )
5666                                         parse_obj->flags |= P_OF_PROTECTED;
5667                                 else
5668                                         parse_obj->flags &= ~P_OF_PROTECTED;
5669                                 break;
5670         #ifndef NDEBUG
5671                         } else {
5672                                 Int3(); // get allender -- could be a potential problem here
5673         #endif
5674                         }
5675                 }
5676
5677                 n = CDR(n);
5678         }
5679 }
5680
5681 // protects/unprotects a ship.  The flag tells us whether or not the protect bit should be set (flag==1)
5682 // or cleared (flag==0)
5683 void sexp_beam_protect_ships( int n, int flag )
5684 {
5685         char *ship_name;
5686         int num;
5687
5688         while ( n != -1 ) {
5689                 ship_name = CTEXT(n);
5690
5691                 // check to see if ship destroyed or departed.  In either case, do nothing.
5692                 if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) )
5693                         return;
5694
5695                 // get the ship num.  If we get a -1 for the number here, ship has yet to arrive.  Store this ship
5696                 // in a list until created
5697                 num = ship_name_lookup(ship_name);
5698                 if ( num >= 0 ) {
5699                         if ( flag )
5700                                 Objects[Ships[num].objnum].flags |= OF_BEAM_PROTECTED;
5701                         else
5702                                 Objects[Ships[num].objnum].flags &= ~OF_BEAM_PROTECTED;
5703                 } else {
5704                         p_object *parse_obj;
5705
5706                         parse_obj = mission_parse_get_arrival_ship( ship_name );
5707                         if ( parse_obj ) {
5708                                 if ( flag )
5709                                         parse_obj->flags |= P_OF_BEAM_PROTECTED;
5710                                 else
5711                                         parse_obj->flags &= ~P_OF_BEAM_PROTECTED;
5712                                 break;
5713         #ifndef NDEBUG
5714                         } else {
5715                                 Int3(); // get allender -- could be a potential problem here
5716         #endif
5717                         }
5718                 }
5719
5720                 n = CDR(n);
5721         }
5722 }
5723
5724 // sexpression to make ships "visible" and "invisible" to sensors.  The visible parameter is true
5725 // when making ships visible, false otherwise
5726 void sexp_ships_visible( int n, int visible )
5727 {
5728         char *ship_name;
5729         int num;
5730
5731         for ( ; n != -1; n = CDR(n) ) {
5732                 ship_name = CTEXT(n);
5733
5734                 // check to see if ship destroyed or departed.  In either case, do nothing.
5735                 if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) )
5736                         continue;;
5737
5738                 // get the ship num.  If we get a -1 for the number here, ship has yet to arrive.  Store this ship
5739                 // in a list until created
5740                 num = ship_name_lookup(ship_name);
5741                 if ( num != -1 ) {
5742                         if ( !visible ) {
5743                                 Ships[num].flags |= SF_HIDDEN_FROM_SENSORS;
5744                         } else {
5745                                 Ships[num].flags &= ~SF_HIDDEN_FROM_SENSORS;
5746                                 if (Ships[num].flags & SF_ESCORT) {
5747                                         // SEND add escort request
5748                                         hud_add_ship_to_escort(Ships[num].objnum, 1);
5749                                 }
5750                         }
5751
5752                 } else {
5753                         p_object *parse_obj;
5754
5755                         parse_obj = mission_parse_get_arrival_ship( ship_name );
5756                         if ( parse_obj ) {
5757                                 if ( !visible )
5758                                         parse_obj->flags |= P_SF_HIDDEN_FROM_SENSORS;
5759                                 else
5760                                         parse_obj->flags &= ~P_SF_HIDDEN_FROM_SENSORS;
5761                                 break;
5762         #ifndef NDEBUG
5763                         } else {
5764                                 Int3(); // get allender -- could be a potential problem here
5765         #endif
5766                         }
5767                 }
5768         }
5769 }
5770
5771 // sexpression to toggle invulnerability flag of ships.
5772 void sexp_ships_invulnerable( int n, int invulnerable )
5773 {
5774         char *ship_name;
5775         object *objp;
5776         int num;
5777
5778         for ( ; n != -1; n = CDR(n) ) {
5779                 ship_name = CTEXT(n);
5780
5781                 // check to see if ship destroyed or departed.  In either case, do nothing.
5782                 if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) )
5783                         continue;
5784
5785                 // get the ship num.  If we get a -1 for the number here, ship has yet to arrive.  Store this ship
5786                 // in a list until created
5787                 num = ship_name_lookup(ship_name);
5788                 if ( num != -1 ) {
5789                         objp = &Objects[Ships[num].objnum];
5790                         if ( invulnerable )
5791                                 objp->flags |= OF_INVULNERABLE;
5792                         else
5793                                 objp->flags &= ~OF_INVULNERABLE;
5794                 } else {
5795                         p_object *parse_obj;
5796
5797                         parse_obj = mission_parse_get_arrival_ship( ship_name );
5798                         if ( parse_obj ) {
5799                                 if ( invulnerable )
5800                                         parse_obj->flags |= P_SF_INVULNERABLE;
5801                                 else
5802                                         parse_obj->flags &= ~P_SF_INVULNERABLE;
5803                                 break;
5804         #ifndef NDEBUG
5805                         } else {
5806                                 Int3(); // get allender -- could be a potential problem here
5807         #endif
5808                         }
5809                 }
5810         }
5811 }
5812
5813 // sexpression to toggle KEEP ALIVE flag of ship object
5814 void sexp_ships_guardian( int n, int guardian )
5815 {
5816         char *ship_name;
5817         object *objp;
5818         int num;
5819
5820         for ( ; n != -1; n = CDR(n) ) {
5821                 ship_name = CTEXT(n);
5822
5823                 // check to see if ship destroyed or departed.  In either case, do nothing.
5824                 if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) )
5825                         continue;
5826
5827                 // get the ship num.  If we get a -1 for the number here, ship has yet to arrive.  Store this ship
5828                 // in a list until created
5829                 num = ship_name_lookup(ship_name);
5830                 if ( num != -1 ) {
5831                         objp = &Objects[Ships[num].objnum];
5832                         if ( guardian )
5833                                 objp->flags |= OF_GUARDIAN;
5834                         else
5835                                 objp->flags &= ~OF_GUARDIAN;
5836                 } else {
5837                         p_object *parse_obj;
5838
5839                         parse_obj = mission_parse_get_arrival_ship( ship_name );
5840                         if ( parse_obj ) {
5841                                 if ( guardian )
5842                                         parse_obj->flags |= P_SF_GUARDIAN;
5843                                 else
5844                                         parse_obj->flags &= ~P_SF_GUARDIAN;
5845                                 break;
5846         #ifndef NDEBUG
5847                         } else {
5848                                 Int3(); // get allender -- could be a potential problem here
5849         #endif
5850                         }
5851                 }
5852         }
5853 }
5854
5855 // make ship vanish without a trace (and what its docked to)
5856 void ship_vanished(int);
5857 void sexp_ship_vanish( int n )
5858 {
5859         char *ship_name;
5860         object *objp, *docked_objp;
5861         int num;
5862
5863         // if MULTIPLAYER bail
5864         if (Game_mode & GM_MULTIPLAYER) {
5865                 return;
5866         }
5867
5868         for ( ; n != -1; n = CDR(n) ) {
5869                 ship_name = CTEXT(n);
5870
5871                 // check to see if ship destroyed or departed.  In either case, do nothing.
5872                 if ( mission_log_get_time(LOG_SHIP_DEPART, ship_name, NULL, NULL) || mission_log_get_time(LOG_SHIP_DESTROYED, ship_name, NULL, NULL) )
5873                         continue;
5874
5875                 // get the ship num.  If we get a -1 for the number here, ship has yet to arrive.  Store this ship
5876                 // in a list until created
5877                 num = ship_name_lookup(ship_name);
5878                 if ( num != -1 ) {
5879                         objp = &Objects[Ships[num].objnum];
5880
5881                         // check if docked
5882                         docked_objp = ai_find_docked_object( objp );
5883
5884                         // kill
5885                         objp->flags |= OF_SHOULD_BE_DEAD;
5886
5887                         // make vanish
5888                         ship_vanished(num);
5889
5890                         if (docked_objp) {
5891                                 // kill
5892                                 docked_objp->flags |= OF_SHOULD_BE_DEAD;
5893
5894                                 // vanish
5895                                 ship_vanished(docked_objp->instance);
5896                         }
5897                 }
5898         }
5899 }
5900
5901 int sexp_key_pressed(int node)
5902 {
5903         int z, t;
5904
5905         SDL_assert(node != -1);
5906         z = translate_key_to_index(CTEXT(node));
5907         if (z < 0){
5908                 return 0;
5909         }
5910
5911         if (!Control_config[z].used){
5912                 return 0;
5913         }
5914
5915         if (CDR(node) < 0){
5916                 return 1;
5917         }
5918
5919         t = atoi(CTEXT(CDR(node)));
5920         return timestamp_has_time_elapsed(Control_config[z].used, t * 1000);
5921 }
5922
5923 void sexp_key_reset(int node)
5924 {
5925         int z;
5926
5927         SDL_assert(node != -1);
5928         z = translate_key_to_index(CTEXT(node));
5929         if (z >= 0)
5930                 Control_config[z].used = 0;
5931 }
5932
5933 int sexp_targeted(int node)
5934 {
5935         int z;
5936         ship_subsys *ptr;
5937
5938         z = ship_query_state(CTEXT(node));
5939         if (z == 1){
5940                 return SEXP_KNOWN_FALSE;  // ship isn't around, nor will it ever be
5941         } else if (z == -1) {
5942                 return SEXP_CANT_EVAL;
5943         }
5944
5945         z = ship_name_lookup(CTEXT(node), 1);
5946         if ((z < 0) || !Player_ai || (Ships[z].objnum != Player_ai->target_objnum)){
5947                 return 0;
5948         }
5949
5950         if (CDR(node) >= 0) {
5951                 z = atoi(CTEXT(CDR(node))) * 1000;
5952                 if (!timestamp_has_time_elapsed(Players_target_timestamp, z)){
5953                         return 0;
5954                 }
5955
5956                 if (CDR(CDR(node)) >= 0) {
5957                         ptr = Player_ai->targeted_subsys;
5958                         if (!ptr || SDL_strcasecmp(ptr->system_info->subobj_name, CTEXT(CDR(CDR(node))))){
5959                                 return 0;
5960                         }
5961                 }
5962         }
5963
5964         return 1;
5965 }
5966
5967 int sexp_speed(int node)
5968 {
5969         if (Training_context & TRAINING_CONTEXT_SPEED) {
5970                 if (Training_context_speed_set){
5971                         if (timestamp_has_time_elapsed(Training_context_speed_timestamp, atoi(CTEXT(node)) * 1000)){
5972                                 return SEXP_KNOWN_TRUE;
5973                         }
5974                 }
5975         }
5976
5977         return 0;
5978 }
5979
5980 int sexp_secondaries_depleted(int node)
5981 {
5982         int sindex, num_banks, num_depleted_banks;
5983         ship *shipp;
5984
5985         // get ship
5986         sindex = ship_name_lookup(CTEXT(node));
5987         if (sindex < 0) {
5988                 return 0;
5989         }
5990
5991         shipp = &Ships[sindex];
5992         if (shipp->objnum < 0) {
5993                 return 0;
5994         }
5995
5996         // get num secondary banks
5997         num_banks = shipp->weapons.num_secondary_banks;
5998         num_depleted_banks = 0;
5999
6000         // get number of depleted banks
6001         for (int idx=0; idx<num_banks; idx++) {
6002                 if (shipp->weapons.secondary_bank_ammo[idx] == 0) {
6003                         num_depleted_banks++;
6004                 }
6005         }
6006
6007         // are they all depleted?
6008         return (num_depleted_banks == num_banks);
6009 }
6010
6011 int sexp_facing(int node)
6012 {
6013         int obj, sh;
6014         float a1, a2;
6015         vector v1, v2;
6016
6017         if (ship_query_state(CTEXT(node)) < 0){
6018                 return SEXP_KNOWN_FALSE;
6019         }
6020
6021         sh = ship_name_lookup(CTEXT(node));
6022         if ((sh < 0) || !Player_obj){
6023                 return 0;
6024         }
6025
6026         obj = Ships[sh].objnum;
6027         v1 = Player_obj->orient.v.fvec;
6028         vm_vec_normalize(&v1);
6029         vm_vec_sub(&v2, &Objects[obj].pos, &Player_obj->pos);
6030         vm_vec_normalize(&v2);
6031         a1 = vm_vec_dotprod(&v1, &v2);
6032         a2 = (float) cos(ANG_TO_RAD(atof(CTEXT(CDR(node)))));
6033         if (a1 >= a2){
6034                 return 1;
6035         }
6036
6037         return 0;
6038 }
6039
6040 // is ship facing first waypoint in waypoint path
6041 int sexp_facing2(int node)
6042 {
6043         int i;
6044         float a1, a2;
6045         vector v1, v2;
6046
6047         // bail if Player_obj is not good
6048         if (!Player_obj) {
6049                 return SEXP_CANT_EVAL;
6050         }
6051
6052         // get player fvec
6053         v1 = Player_obj->orient.v.fvec;
6054         vm_vec_normalize(&v1);
6055
6056         // get waypoint name
6057         char *waypoint_name = CTEXT(node);
6058
6059         // get position of first waypoint
6060         int wp_index = -1;
6061         for (i=0; i<Num_waypoint_lists; i++) {
6062                 if (!SDL_strcasecmp(waypoint_name, Waypoint_lists[i].name)) {
6063                         wp_index = i;
6064                         break;
6065                 }
6066         }
6067
6068         if (wp_index == -1) {
6069                 return SEXP_CANT_EVAL;
6070         }
6071
6072         // Waypoint_lists[wp_index].waypoints[0]
6073
6074         vm_vec_sub(&v2, &Waypoint_lists[wp_index].waypoints[0], &Player_obj->pos);
6075         vm_vec_normalize(&v2);
6076         a1 = vm_vec_dotprod(&v1, &v2);
6077         a2 = (float) cos(ANG_TO_RAD(atof(CTEXT(CDR(node)))));
6078         if (a1 >= a2){
6079                 return 1;
6080         }
6081
6082         return 0;
6083 }
6084
6085 int sexp_order(int node)
6086 {
6087         return 0;
6088 }
6089
6090 int sexp_waypoint_missed()
6091 {
6092         if (Training_context & TRAINING_CONTEXT_FLY_PATH) {
6093                 if (Training_context_at_waypoint > Training_context_goal_waypoint){
6094                         return 1;
6095                 }
6096         }
6097
6098         return 0;
6099 }
6100
6101 int sexp_waypoint_twice()
6102 {
6103         if (Training_context & TRAINING_CONTEXT_FLY_PATH) {
6104                 if (Training_context_at_waypoint < Training_context_goal_waypoint - 1){
6105                         return 1;
6106                 }
6107         }
6108
6109         return 0;
6110 }
6111
6112 int sexp_path_flown()
6113 {
6114         if (Training_context & TRAINING_CONTEXT_FLY_PATH) {
6115                 if (Training_context_goal_waypoint == Waypoint_lists[Training_context_path].count){
6116                         return 1;
6117                 }
6118         }
6119
6120         return 0;
6121 }
6122
6123 void sexp_send_training_message(int node)
6124 {
6125         int t = -1, delay = 0;
6126
6127         if(physics_paused){
6128                 return;
6129         }
6130
6131         SDL_assert(node >= 0);
6132         SDL_assert(Event_index >= 0);
6133
6134         if ((CDR(node) >= 0) && (CDR(CDR(node)) >= 0)) {
6135                 delay = atoi(CTEXT(CDR(CDR(node)))) * 1000;
6136                 t = CDR(CDR(CDR(node)));
6137                 if (t >= 0){
6138                         t = atoi(CTEXT(t));
6139                 }
6140         }
6141
6142         if ((Mission_events[Event_index].repeat_count > 1) || (CDR(node) < 0)){
6143                 message_training_que(CTEXT(node), timestamp(delay), t);
6144         } else {
6145                 message_training_que(CTEXT(CDR(node)), timestamp(delay), t);
6146         }
6147
6148 //      if (Training_msg_method)
6149 //              gameseq_post_event(GS_EVENT_TRAINING_PAUSE);
6150 }
6151
6152 int sexp_shield_recharge_pct(int node)
6153 {
6154         int sindex;
6155
6156         // get the firing ship
6157         sindex = ship_name_lookup(CTEXT(node));
6158         if(sindex < 0){
6159                 return 0;
6160         }
6161         if(Ships[sindex].objnum < 0){
6162                 return 0;
6163         }
6164
6165         // shield recharge pct
6166         return (int)(100.0f * Energy_levels[Ships[sindex].shield_recharge_index]);
6167 }
6168
6169 int sexp_engine_recharge_pct(int node)
6170 {
6171         int sindex;
6172
6173         // get the firing ship
6174         sindex = ship_name_lookup(CTEXT(node));
6175         if(sindex < 0){
6176                 return 0;
6177         }
6178         if(Ships[sindex].objnum < 0){
6179                 return 0;
6180         }
6181
6182         // shield recharge pct
6183         return (int)(100.0f * Energy_levels[Ships[sindex].engine_recharge_index]);
6184 }
6185
6186 int sexp_weapon_recharge_pct(int node)
6187 {
6188         int sindex;
6189
6190         // get the firing ship
6191         sindex = ship_name_lookup(CTEXT(node));
6192         if(sindex < 0){
6193                 return 0;
6194         }
6195         if(Ships[sindex].objnum < 0){
6196                 return 0;
6197         }
6198
6199         // shield recharge pct
6200         return (int)(100.0f * Energy_levels[Ships[sindex].weapon_recharge_index]);
6201 }
6202
6203 int sexp_shield_quad_low(int node)
6204 {
6205         int sindex, idx;        
6206         float max_quad, check;
6207         ship_info *sip;
6208         object *objp;
6209
6210         // get the ship
6211         sindex = ship_name_lookup(CTEXT(node));
6212         if(sindex < 0){
6213                 return 0;
6214         }
6215         if((Ships[sindex].objnum < 0) || (Ships[sindex].objnum >= MAX_OBJECTS)){
6216                 return 0;
6217         }
6218         if((Ships[sindex].ship_info_index < 0) || (Ships[sindex].ship_info_index >= Num_ship_types)){
6219                 return 0;
6220         }
6221         objp = &Objects[Ships[sindex].objnum];
6222         sip = &Ship_info[Ships[sindex].ship_info_index];
6223         if(!(sip->flags & SIF_SMALL_SHIP)){
6224                 return 0;
6225         }
6226         max_quad = sip->shields / (float)MAX_SHIELD_SECTIONS;   
6227
6228         // shield pct
6229         check = (float)atoi(CTEXT(CDR(node)));
6230
6231         // check his quadrants
6232         for(idx=0; idx<MAX_SHIELD_SECTIONS; idx++){
6233                 if( ((objp->shields[idx] / max_quad) * 100.0f) <= check ){
6234                         return 1;
6235                 }
6236         }
6237
6238         // all good
6239         return 0;       
6240 }
6241
6242 int sexp_secondary_ammo_pct(int node)
6243 {
6244         ship *shipp;
6245         int sindex;
6246         int check, idx;
6247         int ret_sum[4];
6248         int ret = 0;
6249
6250         // get the ship
6251         sindex = ship_name_lookup(CTEXT(node));
6252         if(sindex < 0){
6253                 return 0;
6254         }
6255         if((Ships[sindex].objnum < 0) || (Ships[sindex].objnum >= MAX_OBJECTS)){
6256                 return 0;
6257         }
6258         shipp = &Ships[sindex];
6259         
6260         // bank to check
6261         check = atoi(CTEXT(CDR(node)));
6262
6263         // bogus check? (3 == cumulative sum of all banks)
6264         if((check != 3) && (check > shipp->weapons.num_secondary_banks)){
6265                 return 0;
6266         }
6267
6268         // cumulative sum?
6269         if(check == 3){
6270                 for(idx=0; idx<shipp->weapons.num_secondary_banks; idx++){
6271                         ret_sum[idx] = (int)(((float)shipp->weapons.secondary_bank_ammo[idx] / (float)shipp->weapons.secondary_bank_start_ammo[idx]) * 100.0f);
6272                 }
6273
6274                 // add it up
6275                 ret = 0;
6276                 for(idx=0; idx<shipp->weapons.num_secondary_banks; idx++){
6277                         ret += ret_sum[idx];
6278                 }
6279                 ret = (int)((float)ret / (float)shipp->weapons.num_secondary_banks);
6280         } else {
6281                 ret = (int)(((float)shipp->weapons.secondary_bank_ammo[check] / (float)shipp->weapons.secondary_bank_start_ammo[check]) * 100.0f);
6282         }       
6283
6284         // return
6285         return ret;
6286 }
6287
6288 void sexp_beam_fire(int node)
6289 {
6290         int sindex;
6291         beam_fire_info fire_info;               
6292         int idx;        
6293
6294         // zero stuff out
6295         memset(&fire_info, 0, sizeof(beam_fire_info));
6296         fire_info.accuracy = 0.000001f;                                                 // this will guarantee a hit
6297
6298         // get the firing ship
6299         sindex = ship_name_lookup(CTEXT(node));
6300         if(sindex < 0){
6301                 return;
6302         }
6303         if(Ships[sindex].objnum < 0){
6304                 return;
6305         }
6306         fire_info.shooter = &Objects[Ships[sindex].objnum];
6307
6308         // get the subsystem
6309         fire_info.turret = ship_get_subsys(&Ships[sindex], CTEXT(CDR(node)));
6310         if(fire_info.turret == NULL){
6311                 return;
6312         }
6313
6314         // get the target
6315         sindex = ship_name_lookup(CTEXT(CDR(CDR(node))));
6316         if(sindex < 0){
6317                 return;
6318         }
6319         if(Ships[sindex].objnum < 0){
6320                 return;
6321         }
6322         fire_info.target = &Objects[Ships[sindex].objnum];
6323
6324         // see if the optional subsystem can be found   
6325         fire_info.target_subsys = NULL;
6326         fire_info.target_subsys = ship_get_subsys(&Ships[sindex], CTEXT(CDR(CDR(CDR(node)))));  
6327
6328         // if it has no primary weapons
6329         if(fire_info.turret->weapons.num_primary_banks <= 0){
6330                 Int3();
6331                 return;
6332         }
6333
6334         // if the turret is destroyed
6335         if(fire_info.turret->current_hits <= 0.0f){
6336                 return;
6337         }
6338
6339         // hmm, this could be wacky. Let's just simply select the first beam weapon in the turret
6340         fire_info.beam_info_index = -1; 
6341         for(idx=0; idx<fire_info.turret->weapons.num_primary_banks; idx++){
6342                 // store the weapon info index
6343                 if(Weapon_info[fire_info.turret->weapons.primary_bank_weapons[idx]].wi_flags & WIF_BEAM){
6344                         fire_info.beam_info_index = fire_info.turret->weapons.primary_bank_weapons[idx];
6345                 }
6346         }
6347
6348         // fire the beam
6349         if(fire_info.beam_info_index != -1){            
6350                 beam_fire(&fire_info);
6351         } else {
6352                 // it would appear the turret doesn't have any beam weapons, dumbass
6353                 Int3();
6354         }
6355 }       
6356
6357 void sexp_beam_free(int node)
6358 {
6359         int sindex;
6360         ship_subsys *turret = NULL;     
6361
6362         // get the firing ship
6363         sindex = ship_name_lookup(CTEXT(node));
6364         if(sindex < 0){
6365                 return;
6366         }
6367         if(Ships[sindex].objnum < 0){
6368                 return;
6369         }
6370
6371         node = CDR(node);
6372         while(node != -1){
6373                 // get the subsystem
6374                 turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
6375                 if(turret == NULL){
6376                         return;
6377                 }
6378
6379                 // flag it as beam free :)
6380                 turret->weapons.flags |= SW_FLAG_BEAM_FREE;
6381                 turret->turret_next_fire_stamp = timestamp((int) frand_range(50.0f, 4000.0f));
6382
6383                 // next
6384                 node = CDR(node);
6385         }
6386 }
6387
6388 void sexp_beam_free_all(int node)
6389 {
6390         ship_subsys *subsys;
6391         int sindex;
6392
6393         // get the firing ship
6394         sindex = ship_name_lookup(CTEXT(node));
6395         if(sindex < 0){
6396                 return;
6397         }
6398         if(Ships[sindex].objnum < 0){
6399                 return;
6400         }
6401
6402         // free all beam weapons
6403         subsys = GET_FIRST(&Ships[sindex].subsys_list);
6404         while(subsys != END_OF_LIST(&Ships[sindex].subsys_list)){
6405                 // just mark all turrets as beam free
6406                 if(subsys->system_info->type == SUBSYSTEM_TURRET){
6407                         subsys->weapons.flags |= SW_FLAG_BEAM_FREE;
6408                         subsys->turret_next_fire_stamp = timestamp((int) frand_range(50.0f, 4000.0f));
6409                 }
6410
6411                 // next item
6412                 subsys = GET_NEXT(subsys);
6413         }
6414 }
6415
6416 void sexp_beam_lock(int node)
6417 {       
6418         int sindex;
6419         ship_subsys *turret = NULL;     
6420
6421         // get the firing ship
6422         sindex = ship_name_lookup(CTEXT(node));
6423         if(sindex < 0){
6424                 return;
6425         }
6426         if(Ships[sindex].objnum < 0){
6427                 return;
6428         }
6429
6430         node = CDR(node);
6431         while(node != -1){
6432                 // get the subsystem
6433                 turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
6434                 if(turret == NULL){
6435                         return;
6436                 }
6437
6438                 // flag it as not beam free
6439                 turret->weapons.flags &= ~(SW_FLAG_BEAM_FREE);
6440
6441                 // next
6442                 node = CDR(node);
6443         }
6444 }
6445
6446 void sexp_beam_lock_all(int node)
6447 {
6448         ship_subsys *subsys;
6449         int sindex;
6450
6451         // get the firing ship
6452         sindex = ship_name_lookup(CTEXT(node));
6453         if(sindex < 0){
6454                 return;
6455         }
6456         if(Ships[sindex].objnum < 0){
6457                 return;
6458         }
6459
6460         // free all beam weapons
6461         subsys = GET_FIRST(&Ships[sindex].subsys_list);
6462         while(subsys != END_OF_LIST(&Ships[sindex].subsys_list)){
6463                 // just mark all turrets as not beam free
6464                 if(subsys->system_info->type == SUBSYSTEM_TURRET){
6465                         subsys->weapons.flags &= ~(SW_FLAG_BEAM_FREE);
6466                 }
6467
6468                 // next item
6469                 subsys = GET_NEXT(subsys);
6470         }
6471 }
6472
6473 void sexp_turret_free(int node)
6474 {
6475         int sindex;
6476         ship_subsys *turret = NULL;     
6477
6478         // get the firing ship
6479         sindex = ship_name_lookup(CTEXT(node));
6480         if(sindex < 0){
6481                 return;
6482         }
6483         if(Ships[sindex].objnum < 0){
6484                 return;
6485         }
6486
6487         node = CDR(node);
6488         while(node != -1){
6489                 // get the subsystem
6490                 turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
6491                 if(turret == NULL){
6492                         return;
6493                 }
6494
6495                 // flag turret as no longer locked :)
6496                 turret->weapons.flags &= (~SW_FLAG_TURRET_LOCK);
6497                 turret->turret_next_fire_stamp = timestamp((int) frand_range(50.0f, 4000.0f));
6498
6499                 // next
6500                 node = CDR(node);
6501         }
6502 }
6503
6504 void sexp_turret_free_all(int node)
6505 {
6506         ship_subsys *subsys;
6507         int sindex;
6508
6509         // get the firing ship
6510         sindex = ship_name_lookup(CTEXT(node));
6511         if(sindex < 0){
6512                 return;
6513         }
6514         if(Ships[sindex].objnum < 0){
6515                 return;
6516         }
6517
6518         // free all turrets
6519         subsys = GET_FIRST(&Ships[sindex].subsys_list);
6520         while(subsys != END_OF_LIST(&Ships[sindex].subsys_list)){
6521                 // just mark all turrets as free
6522                 if(subsys->system_info->type == SUBSYSTEM_TURRET){
6523                         subsys->weapons.flags &= (~SW_FLAG_TURRET_LOCK);
6524                         subsys->turret_next_fire_stamp = timestamp((int) frand_range(50.0f, 4000.0f));
6525                 }
6526
6527                 // next item
6528                 subsys = GET_NEXT(subsys);
6529         }
6530 }
6531
6532 void sexp_turret_lock(int node)
6533 {       
6534         int sindex;
6535         ship_subsys *turret = NULL;     
6536
6537         // get the firing ship
6538         sindex = ship_name_lookup(CTEXT(node));
6539         if(sindex < 0){
6540                 return;
6541         }
6542         if(Ships[sindex].objnum < 0){
6543                 return;
6544         }
6545
6546         node = CDR(node);
6547         while(node != -1){
6548                 // get the subsystem
6549                 turret = ship_get_subsys(&Ships[sindex], CTEXT(node));
6550                 if(turret == NULL){
6551                         return;
6552                 }
6553
6554                 // flag turret as locked
6555                 turret->weapons.flags |= SW_FLAG_TURRET_LOCK;
6556
6557                 // next
6558                 node = CDR(node);
6559         }
6560 }
6561
6562 void sexp_turret_lock_all(int node)
6563 {
6564         ship_subsys *subsys;
6565         int sindex;
6566
6567         // get the firing ship
6568         sindex = ship_name_lookup(CTEXT(node));
6569         if(sindex < 0){
6570                 return;
6571         }
6572         if(Ships[sindex].objnum < 0){
6573                 return;
6574         }
6575
6576         // lcck all turrets
6577         subsys = GET_FIRST(&Ships[sindex].subsys_list);
6578         while(subsys != END_OF_LIST(&Ships[sindex].subsys_list)){
6579                 // just mark all turrets as locked
6580                 if(subsys->system_info->type == SUBSYSTEM_TURRET){
6581                         subsys->weapons.flags |= SW_FLAG_TURRET_LOCK;
6582                 }
6583
6584                 // next item
6585                 subsys = GET_NEXT(subsys);
6586         }
6587 }
6588
6589 void sexp_turret_tagged_only_all(int node)
6590 {
6591         ship_subsys *subsys;
6592         int sindex;
6593
6594         // get the firing ship
6595         sindex = ship_name_lookup(CTEXT(node));
6596         if(sindex < 0){
6597                 return;
6598         }
6599         if(Ships[sindex].objnum < 0){
6600                 return;
6601         }
6602
6603         // mark all turrets to only target tagged ships
6604         subsys = GET_FIRST(&Ships[sindex].subsys_list);
6605         while(subsys != END_OF_LIST(&Ships[sindex].subsys_list)){
6606                 // just mark all turrets as locked
6607                 if(subsys->system_info->type == SUBSYSTEM_TURRET){
6608                         subsys->weapons.flags |= SW_FLAG_TAGGED_ONLY;
6609                 }
6610
6611                 // next item
6612                 subsys = GET_NEXT(subsys);
6613         }
6614 }
6615
6616 void sexp_turret_tagged_clear_all(int node)
6617 {
6618         ship_subsys *subsys;
6619         int sindex;
6620
6621         // get the firing ship
6622         sindex = ship_name_lookup(CTEXT(node));
6623         if(sindex < 0){
6624                 return;
6625         }
6626         if(Ships[sindex].objnum < 0){
6627                 return;
6628         }
6629
6630         // mark all turrets so not restricted to only tagged ships
6631         subsys = GET_FIRST(&Ships[sindex].subsys_list);
6632         while(subsys != END_OF_LIST(&Ships[sindex].subsys_list)){
6633                 // just mark all turrets as locked
6634                 if(subsys->system_info->type == SUBSYSTEM_TURRET){
6635                         subsys->weapons.flags &= (~SW_FLAG_TAGGED_ONLY);
6636                 }
6637
6638                 // next item
6639                 subsys = GET_NEXT(subsys);
6640         }
6641 }
6642
6643 void sexp_add_remove_escort(int node)
6644 {
6645         int sindex;
6646         int flag;
6647
6648         // get the firing ship
6649         sindex = ship_name_lookup(CTEXT(node));
6650         if(sindex < 0){
6651                 return;
6652         }
6653         if(Ships[sindex].objnum < 0){
6654                 return;
6655         }
6656
6657         // determine whether to add or remove it
6658         flag = atoi(CTEXT(CDR(node)));
6659
6660         // add/remove
6661         if(flag){       
6662                 hud_add_ship_to_escort(Ships[sindex].objnum, 1);
6663         } else {
6664                 hud_remove_ship_from_escort(Ships[sindex].objnum);
6665         }
6666 }
6667
6668 void sexp_awacs_set_radius(int node)
6669 {
6670         int sindex;             
6671         ship_subsys *awacs;
6672
6673         // get the firing ship
6674         sindex = ship_name_lookup(CTEXT(node));
6675         if(sindex < 0){
6676                 return;
6677         }
6678         if(Ships[sindex].objnum < 0){
6679                 return;
6680         }       
6681
6682         // get the awacs subsystem
6683         awacs = ship_get_subsys(&Ships[sindex], CTEXT(CDR(node)));
6684         if(awacs == NULL){
6685                 return;
6686         }
6687
6688         // make sure this _is_ an awacs subsystem
6689         SDL_assert(awacs->system_info->flags & MSS_FLAG_AWACS);
6690         if(awacs->system_info->flags & MSS_FLAG_AWACS){
6691                 return;
6692         }
6693
6694         // set the new awacs radius
6695         awacs->awacs_radius = (float)atoi(CTEXT(CDR(CDR(node))));       
6696 }
6697
6698 int sexp_is_tagged(int node)
6699 {
6700         int sindex;
6701
6702         // get the firing ship
6703         sindex = ship_name_lookup(CTEXT(node));
6704         if(sindex < 0){
6705                 return 0;
6706         }
6707         if(Ships[sindex].objnum < 0){
6708                 return 0;
6709         }
6710         if(Ships[sindex].tag_left > 0.0f){
6711                 return 1;
6712         }
6713
6714         // not tagged
6715         return 0;
6716 }
6717
6718 int sexp_num_kills(int node)
6719 {
6720         int sindex, np_index;
6721         player *p = NULL;
6722
6723         // get the ship we're interested in
6724         sindex = ship_name_lookup(CTEXT(node));
6725         if(sindex < 0){
6726                 return 0;
6727         }
6728         if(Ships[sindex].objnum < 0){
6729                 return 0;
6730         }
6731         
6732         // in multiplayer, search through all players
6733         if(Game_mode & GM_MULTIPLAYER){
6734                 // try and find the player
6735                 np_index = multi_find_player_by_object(&Objects[Ships[sindex].objnum]);
6736                 if((np_index >= 0) && (np_index < MAX_PLAYERS)){
6737                         p = Net_players[np_index].player;
6738                 }
6739         }
6740         // if we're in single player, we're only concerned with ourself
6741         else {
6742                 // me
6743                 if(Player_obj == &Objects[Ships[sindex].objnum]){
6744                         p = Player;
6745                 }
6746         }
6747
6748         // now, if we have a valid player, return his kills
6749         if(p != NULL){
6750                 return p->stats.m_kill_count_ok;
6751         }
6752
6753         // bad
6754         return 0;
6755 }
6756
6757 int sexp_num_type_kills(int node)
6758 {
6759         int sindex, np_index, st_index;
6760         int idx, total;
6761         player *p = NULL;
6762
6763         // get the ship we're interested in
6764         sindex = ship_name_lookup(CTEXT(node));
6765         if(sindex < 0){
6766                 return 0;
6767         }
6768         if(Ships[sindex].objnum < 0){
6769                 return 0;
6770         }
6771         
6772         // in multiplayer, search through all players
6773         if(Game_mode & GM_MULTIPLAYER){
6774                 // try and find the player
6775                 np_index = multi_find_player_by_object(&Objects[Ships[sindex].objnum]);
6776                 if((np_index >= 0) && (np_index < MAX_PLAYERS)){
6777                         p = Net_players[np_index].player;
6778                 }
6779         }
6780         // if we're in single player, we're only concerned with ourself
6781         else {
6782                 // me
6783                 if(Player_obj == &Objects[Ships[sindex].objnum]){
6784                         p = Player;
6785                 }
6786         }
6787
6788         // bad
6789         if(p == NULL){
6790                 return 0;
6791         }
6792
6793         // lookup ship type name
6794         st_index = ship_type_name_lookup(CTEXT(CDR(node)));
6795         if(st_index < 0){
6796                 return 0;
6797         }
6798
6799         // look stuff up        
6800         total = 0;
6801         for(idx=0; idx<Num_ship_types; idx++){
6802                 if((p->stats.m_okKills[idx] > 0) && (Ship_info[idx].flags & Ship_type_flags[st_index])){
6803                         total += p->stats.m_okKills[idx];
6804                 }
6805         }
6806
6807         // total
6808         return total;
6809 }
6810
6811 int sexp_num_class_kills(int node)
6812 {
6813         int sindex, np_index, si_index;
6814         player *p = NULL;
6815
6816         // get the ship we're interested in
6817         sindex = ship_name_lookup(CTEXT(node));
6818         if(sindex < 0){
6819                 return 0;
6820         }
6821         if(Ships[sindex].objnum < 0){
6822                 return 0;
6823         }
6824         
6825         // in multiplayer, search through all players
6826         if(Game_mode & GM_MULTIPLAYER){
6827                 // try and find the player
6828                 np_index = multi_find_player_by_object(&Objects[Ships[sindex].objnum]);
6829                 if((np_index >= 0) && (np_index < MAX_PLAYERS)){
6830                         p = Net_players[np_index].player;
6831                 }
6832         }
6833         // if we're in single player, we're only concerned with ourself
6834         else {
6835                 // me
6836                 if(Player_obj == &Objects[Ships[sindex].objnum]){
6837                         p = Player;
6838                 }
6839         }
6840
6841         // bad
6842         if(p == NULL){
6843                 return 0;
6844         }
6845
6846         // get the ship type we're looking for
6847         si_index = ship_info_lookup(CTEXT(CDR(node)));
6848         if((si_index < 0) || (si_index > Num_ship_types)){
6849                 return 0;
6850         }
6851
6852         // return the count     
6853         return p->stats.m_okKills[si_index];
6854 }
6855
6856 void sexp_subsys_set_random(int node)
6857 {
6858         int sindex, low, high, n, idx, rand, exclusion_list[MAX_MODEL_SUBSYSTEMS];              
6859         ship_subsys *subsys;
6860         ship *shipp;
6861
6862         // get ship
6863         sindex = ship_name_lookup(CTEXT(node));
6864         if(sindex < 0){
6865                 return;
6866         }
6867         if(Ships[sindex].objnum < 0){
6868                 return;
6869         }
6870         shipp = &Ships[sindex];
6871
6872         // get low
6873         low = num_eval(CDR(node));
6874         if (low < 0) {
6875                 low = 0;
6876         }
6877
6878         // get high
6879         high = num_eval(CDR(CDR(node)));
6880         if (high > 100) {
6881                 high = 100;
6882         }
6883
6884         if (low > high) {
6885                 Int3();
6886                 return;
6887         }
6888
6889         n = CDR(CDR(CDR(node)));
6890
6891         // init exclusion list
6892         memset(exclusion_list, 0, sizeof(int) * Ship_info[shipp->ship_info_index].n_subsystems);
6893
6894         // get exclusion list
6895         while( n != -1) {
6896                 int exclude_index = ship_get_subsys_index(shipp, CTEXT(n), 0);
6897                 if (exclude_index >= 0) {
6898                         exclusion_list[exclude_index] = 1;
6899                 }
6900
6901                 n = CDR(n);
6902         }
6903
6904         // apply to all others
6905         for (idx=0; idx<Ship_info[shipp->ship_info_index].n_subsystems; idx++) {
6906                 if ( exclusion_list[idx] == 0 ) {
6907                         // get non excluded subsystem
6908                         subsys = ship_get_indexed_subsys(shipp, idx, NULL);
6909
6910                         // randomize its hit points
6911                         rand = rand_internal(low, high);
6912                         subsys->current_hits = 0.01f * rand * subsys->system_info->max_hits;
6913                 }
6914         }
6915 }
6916
6917 void sexp_supernova_start(int node)
6918 {
6919         supernova_start(atoi(CTEXT(node)));
6920 }
6921
6922 int sexp_is_secondary_selected(int node)
6923 {
6924         int sindex;
6925         int bank;
6926         ship *shipp;
6927
6928         // lookup ship
6929         sindex = ship_name_lookup(CTEXT(node));
6930         if(sindex < 0){
6931                 return 0;
6932         }
6933         if(Ships[sindex].objnum < 0){
6934                 return 0;
6935         }
6936         shipp = &Ships[sindex];
6937
6938         // bogus value?
6939         bank = atoi(CTEXT(CDR(node)));
6940         if(bank >= shipp->weapons.num_secondary_banks){
6941                 return 0;
6942         }
6943
6944         // is this the bank currently selected
6945         if(bank == shipp->weapons.current_secondary_bank){
6946                 return 1;
6947         }
6948
6949         // nope
6950         return 0;
6951 }
6952
6953 int sexp_is_primary_selected(int node)
6954 {
6955         int sindex;
6956         int bank;
6957         ship *shipp;
6958
6959         // lookup ship
6960         sindex = ship_name_lookup(CTEXT(node));
6961         if(sindex < 0){
6962                 return 0;
6963         }
6964         if(Ships[sindex].objnum < 0){
6965                 return 0;
6966         }
6967         shipp = &Ships[sindex];
6968
6969         // bogus value?
6970         bank = atoi(CTEXT(CDR(node)));
6971         if(bank >= shipp->weapons.num_primary_banks){
6972                 return 0;
6973         }
6974
6975         // is this the bank currently selected
6976         if(bank == shipp->weapons.current_primary_bank){
6977                 return 1;
6978         }
6979
6980         // nope
6981         return 0;
6982 }
6983
6984 #define RIGHT_QUAD      0
6985 #define FRONT_QUAD      1
6986 #define LEFT_QUAD       3
6987 #define REAR_QUAD       2
6988
6989 //      Return SEXP_TRUE if quadrant quadnum is near max.
6990 int shield_quad_near_max(int quadnum)
6991 {
6992         float   remaining = 0.0f;
6993         for (int i=0; i<MAX_SHIELD_SECTIONS; i++) {
6994                 if (i == quadnum){
6995                         continue;
6996                 }
6997                 remaining += Player_obj->shields[i];
6998         }
6999
7000         if ((remaining < 2.0f) || (Player_obj->shields[quadnum] > Ship_info[Player_ship->ship_info_index].shields/MAX_SHIELD_SECTIONS - 5.0f)) {
7001                 return SEXP_TRUE;
7002         } else {
7003                 return SEXP_FALSE;
7004         }
7005 }
7006
7007 //      Return truth value for special SEXP.
7008 //      Used in training#5, perhaps in other missions.
7009 int process_special_sexps(int index)
7010 {
7011         switch (index) {
7012         case 0: //      Ship "Freighter 1" is aspect locked by player.
7013                 if (Player_ai->target_objnum != -1) {
7014                         if (!(SDL_strcasecmp(Ships[Objects[Player_ai->target_objnum].instance].ship_name, "Freighter 1"))) {
7015                                 if (Player_ai->current_target_is_locked)
7016                                         return SEXP_TRUE;
7017                         }
7018                 }
7019                 return SEXP_FALSE;
7020                 break;
7021         case 1: //      Fired Interceptors
7022                 object  *objp;
7023                 for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
7024                         if (objp->type == OBJ_WEAPON) {
7025                                 if (!SDL_strcasecmp(Weapon_info[Weapons[objp->instance].weapon_info_index].name, "Interceptor#weak")) {
7026                                         int target = Weapons[objp->instance].target_num;
7027                                         if (target != -1) {
7028                                                 if (Objects[target].type == OBJ_SHIP) {
7029                                                         if (!(SDL_strcasecmp(Ships[Objects[target].instance].ship_name, "Freighter 1")))
7030                                                                 return SEXP_TRUE;
7031                                                 }
7032                                         }
7033                                 }
7034                         }
7035                 }
7036                 return SEXP_FALSE;
7037         case 2: //      Ship "Freighter 1", subsystem "Weapons" is aspect locked by player.
7038                 if (Player_ai->target_objnum != -1) {
7039                         if (!(SDL_strcasecmp(Ships[Objects[Player_ai->target_objnum].instance].ship_name, "Freighter 1"))) {
7040                                 if (!(SDL_strcasecmp(Player_ai->targeted_subsys->system_info->name, "Weapons"))) {
7041                                         if (Player_ai->current_target_is_locked){
7042                                                 return SEXP_TRUE;
7043                                         }
7044                                 }
7045                         }
7046                 }
7047                 return SEXP_FALSE;
7048                 break;
7049         case 3: //      Player ship suffering shield damage on front.
7050                 apply_damage_to_shield(Player_obj, FRONT_QUAD, 10.0f);
7051                 hud_shield_quadrant_hit(Player_obj, FRONT_QUAD);
7052                 return SEXP_TRUE;
7053                 break;
7054         case 4: //      Player ship suffering much damage.
7055                 nprintf(("AI", "Frame %i\n", Framecount));
7056                 apply_damage_to_shield(Player_obj, FRONT_QUAD, 10.0f);
7057                 hud_shield_quadrant_hit(Player_obj, FRONT_QUAD);
7058                 if (Player_obj->shields[FRONT_QUAD] < 2.0f)
7059                         return SEXP_TRUE;
7060                 else
7061                         return SEXP_FALSE;
7062                 break;
7063         case 5: //      Player's shield is quick repaired
7064                 nprintf(("AI", "Frame %i, recharged to %7.3f\n", Framecount, Player_obj->shields[FRONT_QUAD]));
7065
7066                 apply_damage_to_shield(Player_obj, FRONT_QUAD, -flFrametime*200.0f);
7067
7068                 if (Player_obj->shields[FRONT_QUAD] > Ship_info[Player_ship->ship_info_index].shields/4.0f)
7069                         Player_obj->shields[FRONT_QUAD] = Ship_info[Player_ship->ship_info_index].shields/4.0f;
7070
7071                 //hud_shield_quadrant_hit(Player_obj, FRONT_QUAD);
7072                 if (Player_obj->shields[FRONT_QUAD] > Player_obj->shields[(FRONT_QUAD+1)%4] - 2.0f)
7073                         return SEXP_TRUE;
7074                 else
7075                         return SEXP_FALSE;
7076                 break;
7077         case 6: //      3 of player's shield quadrants are reduced to 0.
7078                 Player_obj->shields[1] = 1.0f;
7079                 Player_obj->shields[2] = 1.0f;
7080                 Player_obj->shields[3] = 1.0f;
7081                 //apply_damage_to_shield(Player_obj, FRONT_QUAD, 1.0f);
7082                 hud_shield_quadrant_hit(Player_obj, FRONT_QUAD);
7083                 return SEXP_TRUE;
7084         case 7: //      Make sure front quadrant has been maximized, or close to it.
7085                 if (shield_quad_near_max(FRONT_QUAD)) return SEXP_TRUE; else return SEXP_FALSE;
7086                 break;
7087
7088         case 8: //      Make sure rear quadrant has been maximized, or close to it.
7089                 if (shield_quad_near_max(REAR_QUAD)) return SEXP_TRUE; else return SEXP_FALSE;
7090                 break;
7091         
7092         case 9: //      Zero left and right quadrants in preparation for maximizing rear quadrant.
7093                 Player_obj->shields[LEFT_QUAD] = 0.0f;
7094                 Player_obj->shields[RIGHT_QUAD] = 0.0f;
7095                 hud_shield_quadrant_hit(Player_obj, LEFT_QUAD);
7096                 return SEXP_TRUE;
7097                 break;
7098
7099         case 10:        //      Return true if player is low on Interceptors.
7100                 if (Player_ship->weapons.secondary_bank_ammo[0] + Player_ship->weapons.secondary_bank_ammo[1] < 8)
7101                         return SEXP_TRUE;
7102                 else
7103                         return SEXP_FALSE;
7104                 break;
7105
7106         case 11:        //      Return true if player has plenty of Interceptors.
7107                 if (Player_ship->weapons.secondary_bank_ammo[0] + Player_ship->weapons.secondary_bank_ammo[1] >= 8)
7108                         return SEXP_TRUE;
7109                 else
7110                         return SEXP_FALSE;
7111                 break;
7112
7113         case 12:        //      Return true if player is low on Interceptors.
7114                 if (Player_ship->weapons.secondary_bank_ammo[0] + Player_ship->weapons.secondary_bank_ammo[1] < 4)
7115                         return SEXP_TRUE;
7116                 else
7117                         return SEXP_FALSE;
7118                 break;
7119
7120         case 13:        // Zero front shield quadrant.  Added for Jim Boone on August 26, 1999 by MK.
7121                 Player_obj->shields[FRONT_QUAD] = 0.0f;
7122                 hud_shield_quadrant_hit(Player_obj, FRONT_QUAD);
7123                 return SEXP_TRUE;
7124                 break;
7125
7126         case 100:       //      Return true if player is out of countermeasures.
7127                 if (Player_ship->cmeasure_count <= 0)
7128                         return SEXP_TRUE;
7129                 else
7130                         return SEXP_FALSE;
7131
7132         default:
7133                 Int3(); //      Unsupported node type.
7134         }
7135
7136         return SEXP_FALSE;
7137 }
7138
7139 // custom sexp operator for handling misc training stuff
7140 int sexp_special_training_check(int node)
7141 {
7142         int num, rtn;
7143
7144         num = atoi(CTEXT(node));
7145         if (num == SPECIAL_CHECK_TRAINING_FAILURE)
7146                 return Training_failure ? SEXP_TRUE : SEXP_FALSE;
7147
7148         // To MK: do whatever you want with this number here.
7149         rtn = process_special_sexps(atoi(CTEXT(node)));
7150
7151         return rtn;
7152 }
7153
7154 // sexpression to flash a hud gauge.  gauge name is text valud of node
7155 void sexp_flash_hud_gauge( int node )
7156 {
7157         char *name;
7158         int i;
7159
7160         name = CTEXT(node);
7161         for (i = 0; i < NUM_HUD_GAUGES; i++ ) {
7162                 if ( !SDL_strcasecmp(HUD_gauge_text[i], name) ) {
7163                         hud_gauge_start_flash(i);       // call HUD function to flash gauge
7164                         break;
7165                 }
7166         }
7167 }
7168
7169 void sexp_set_training_context_fly_path(int node)
7170 {
7171         int i;
7172
7173         for (i=0; i<Num_waypoint_lists; i++)
7174                 if (!SDL_strcasecmp(CTEXT(node), Waypoint_lists[i].name))
7175                         break;
7176
7177         if (i < Num_waypoint_lists) {
7178                 Training_context |= TRAINING_CONTEXT_FLY_PATH;
7179                 Training_context_path = i;
7180                 Training_context_distance = (float) atof(CTEXT(CDR(node)));
7181                 Training_context_goal_waypoint = 0;
7182                 Training_context_at_waypoint = -1;
7183         }
7184 }
7185
7186 void sexp_set_training_context_speed(int node)
7187 {
7188         Training_context |= TRAINING_CONTEXT_SPEED;
7189         Training_context_speed_min = atoi(CTEXT(node));
7190         Training_context_speed_max = atoi(CTEXT(CDR(node)));
7191         Training_context_speed_set = 0;
7192 }
7193
7194 // high-level sexpression evaluator
7195 int eval_sexp(int cur_node)
7196 {
7197         int node, sexp_val = UNINITIALIZED;
7198         if (cur_node == -1)  // empty list, i.e. sexp: ( )
7199                 return FALSE;
7200
7201         SDL_assert(cur_node >= 0);                      // we have special sexp nodes <= -1!!!  MWA
7202                                                                         // which should be intercepted before we get here.  HOFFOSS
7203
7204         SDL_assert( (SEXP_NODE_TYPE(cur_node) == SEXP_LIST) || (SEXP_NODE_TYPE(cur_node) == SEXP_ATOM) );
7205
7206         // trap known true and known false sexpressions.  We don't trap on SEXP_NAN sexpressions since
7207         // they may yet evaluate to true or false.
7208
7209         if (Sexp_nodes[cur_node].value == SEXP_KNOWN_TRUE)
7210                 return 1;
7211         else if (Sexp_nodes[cur_node].value == SEXP_KNOWN_FALSE)
7212                 return 0;
7213
7214         if (Sexp_nodes[cur_node].first != -1) {
7215                 node = CAR(cur_node);
7216                 sexp_val = eval_sexp(node);
7217                 Sexp_nodes[cur_node].value = Sexp_nodes[node].value;    // higher level node gets node value
7218                 return sexp_val;
7219
7220         } else {
7221                 int op_num;
7222
7223                 node = CDR(cur_node);           // makes reading the next bit of code a little easier.
7224
7225                 op_num = find_operator(CTEXT(cur_node)); 
7226                 switch ( op_num ) {
7227                 // arithmetic operators will always return just their value
7228                         case OP_PLUS:
7229                                 sexp_val = add_sexps( node );
7230                                 break;
7231
7232                         case OP_MINUS:
7233                                 sexp_val = sub_sexps( node );
7234                                 break;
7235
7236                         case OP_MUL:
7237                                 sexp_val = mul_sexps( node );
7238                                 break;
7239
7240                         case OP_MOD:
7241                                 sexp_val = mod_sexps( node );
7242                                 break;
7243
7244                         case OP_DIV:
7245                                 sexp_val = div_sexps( node );
7246                                 break;
7247
7248                         case OP_RAND:
7249                                 sexp_val = rand_sexp( node );
7250                                 break;
7251
7252                 // boolean operators can have one of the special sexp values (known true, known false, unknown)
7253                         case OP_TRUE:
7254                                 sexp_val = SEXP_KNOWN_TRUE;
7255                                 break;
7256
7257                         case OP_FALSE:
7258                                 sexp_val = SEXP_KNOWN_FALSE;
7259                                 break;
7260
7261                         case OP_OR:
7262                                 sexp_val = sexp_or( node );
7263                                 break;
7264
7265                         case OP_AND:
7266                                 sexp_val = sexp_and( node );
7267                                 break;
7268
7269                         case OP_AND_IN_SEQUENCE:
7270                                 sexp_val = sexp_and_in_sequence( node );
7271                                 break;
7272
7273                         case OP_GREATER_THAN:
7274                                 sexp_val = sexp_gt( node );
7275                                 break;
7276                                 
7277                         case OP_LESS_THAN:
7278                                 sexp_val = sexp_lt( node );
7279                                 break;
7280
7281                         case OP_EQUALS:
7282                                 sexp_val = sexp_equal( node );
7283                                 break;
7284
7285                         case OP_IS_IFF:
7286                                 sexp_val = sexp_is_iff( node );
7287                                 break;
7288
7289                         case OP_NOT:
7290                                 sexp_val = sexp_not( node );
7291                                 break;
7292
7293                         case OP_PREVIOUS_GOAL_TRUE:
7294                                 sexp_val = sexp_previous_goal_status( node, GOAL_COMPLETE );
7295                                 break;
7296
7297                         case OP_PREVIOUS_GOAL_FALSE:
7298                                 sexp_val = sexp_previous_goal_status( node, GOAL_FAILED );
7299                                 break;
7300
7301                         case OP_PREVIOUS_GOAL_INCOMPLETE:
7302                                 sexp_val = sexp_previous_goal_status( node, GOAL_INCOMPLETE );
7303                                 break;
7304
7305                         case OP_PREVIOUS_EVENT_TRUE:
7306                                 sexp_val = sexp_previous_event_status( node, EVENT_SATISFIED );
7307                                 break;
7308
7309                         case OP_PREVIOUS_EVENT_FALSE:
7310                                 sexp_val = sexp_previous_event_status( node, EVENT_FAILED );
7311                                 break;
7312
7313                         case OP_PREVIOUS_EVENT_INCOMPLETE:
7314                                 sexp_val = sexp_previous_event_status( node, EVENT_INCOMPLETE );
7315                                 break;
7316
7317                         case OP_EVENT_TRUE:
7318                         case OP_EVENT_FALSE:
7319                                 sexp_val = sexp_event_status( node, (op_num == OP_EVENT_TRUE?1:0) );
7320                                 if ((sexp_val != SEXP_TRUE) && (sexp_val != SEXP_KNOWN_TRUE))
7321                                         Sexp_useful_number = 0;  // indicate sexp isn't current yet
7322
7323                                 break;
7324
7325                         case OP_EVENT_TRUE_DELAY:
7326                         case OP_EVENT_FALSE_DELAY:
7327                                 sexp_val = sexp_event_delay_status( node, (op_num == OP_EVENT_TRUE_DELAY?1:0) );
7328                                 if ((sexp_val != SEXP_TRUE) && (sexp_val != SEXP_KNOWN_TRUE))
7329                                         Sexp_useful_number = 0;  // indicate sexp isn't current yet
7330                                 break;
7331
7332                         case OP_GOAL_TRUE_DELAY:
7333                         case OP_GOAL_FALSE_DELAY:
7334                                 sexp_val = sexp_goal_delay_status( node, (op_num == OP_GOAL_TRUE_DELAY?1:0) );
7335                                 break;
7336
7337                         case OP_EVENT_INCOMPLETE:
7338                                 sexp_val = sexp_event_incomplete( node );
7339                                 if ((sexp_val != SEXP_TRUE) && (sexp_val != SEXP_KNOWN_TRUE))
7340                                         Sexp_useful_number = 0;  // indicate sexp isn't current yet
7341                                 break;
7342
7343                         case OP_GOAL_INCOMPLETE:
7344                                 sexp_val = sexp_goal_incomplete( node );
7345                                 break;
7346
7347                         // destroy type sexpressions
7348                         case OP_IS_DESTROYED:
7349                                 sexp_val = sexp_is_destroyed( node, NULL );
7350                                 break;
7351
7352                         case OP_IS_SUBSYSTEM_DESTROYED:
7353                                 sexp_val = sexp_is_subsystem_destroyed( node );
7354                                 break;
7355
7356                         case OP_HAS_DOCKED:
7357                                 sexp_val = sexp_has_docked( node );
7358                                 break;
7359
7360                         case OP_HAS_ARRIVED:
7361                                 sexp_val = sexp_has_arrived( node, NULL );
7362                                 break;
7363
7364                         case OP_HAS_DEPARTED:
7365                                 sexp_val = sexp_has_departed( node, NULL );
7366                                 break;
7367
7368                         case OP_HAS_UNDOCKED:
7369                                 sexp_val = sexp_has_undocked( node );
7370                                 break;
7371
7372                         case OP_IS_DISABLED:
7373                                 sexp_val = sexp_is_disabled( node, NULL );
7374                                 break;
7375
7376                         case OP_IS_DISARMED:
7377                                 sexp_val = sexp_is_disarmed( node, NULL );
7378                                 break;
7379
7380                         case OP_WAYPOINTS_DONE:
7381                                 sexp_val = sexp_are_waypoints_done( node );
7382                                 break;
7383
7384                         // objective operators that use a delay
7385                         case OP_IS_DESTROYED_DELAY:
7386                                 sexp_val = sexp_is_destroyed_delay( node );
7387                                 break;
7388
7389                         case OP_IS_SUBSYSTEM_DESTROYED_DELAY:
7390                                 sexp_val = sexp_is_subsystem_destroyed_delay( node );
7391                                 break;
7392
7393                         case OP_HAS_DOCKED_DELAY:
7394                                 sexp_val = sexp_has_docked_delay( node );
7395                                 break;
7396
7397                         case OP_HAS_ARRIVED_DELAY:
7398                                 sexp_val = sexp_has_arrived_delay( node );
7399                                 break;
7400
7401                         case OP_HAS_DEPARTED_DELAY:
7402                                 sexp_val = sexp_has_departed_delay( node );
7403                                 break;
7404
7405                         case OP_HAS_UNDOCKED_DELAY:
7406                                 sexp_val = sexp_has_undocked_delay( node );
7407                                 break;
7408
7409                         case OP_IS_DISABLED_DELAY:
7410                                 sexp_val = sexp_is_disabled_delay( node );
7411                                 break;
7412
7413                         case OP_IS_DISARMED_DELAY:
7414                                 sexp_val = sexp_is_disarmed_delay( node );
7415                                 break;
7416
7417                         case OP_WAYPOINTS_DONE_DELAY:
7418                                 sexp_val = sexp_are_waypoints_done_delay( node );
7419                                 break;
7420
7421                         case OP_SHIP_TYPE_DESTROYED:
7422                                 sexp_val = sexp_ship_type_destroyed( node );
7423                                 break;
7424
7425                         // time based sexpressions
7426                         case OP_HAS_TIME_ELAPSED:
7427                                 sexp_val = sexp_has_time_elapsed( node );
7428                                 break;
7429
7430                         case OP_MODIFY_VARIABLE:
7431                                 sexp_modify_variable( node );
7432                                 sexp_val = 1;   // 1 means only do once.
7433                                 break;
7434
7435                         case OP_TIME_SHIP_DESTROYED:
7436                                 sexp_val = sexp_time_destroyed( node );
7437                                 break;
7438                         
7439                         case OP_TIME_WING_DESTROYED:
7440                                 sexp_val = sexp_time_wing_destroyed( node );
7441                                 break;
7442                         
7443                         case OP_TIME_SHIP_ARRIVED:
7444                                 sexp_val = sexp_time_ship_arrived( node );
7445                                 break;
7446                         
7447                         case OP_TIME_WING_ARRIVED:
7448                                 sexp_val = sexp_time_wing_arrived( node );
7449                                 break;
7450                         
7451                         case OP_TIME_SHIP_DEPARTED:
7452                                 sexp_val = sexp_time_ship_departed( node );
7453                                 break;
7454                         
7455                         case OP_TIME_WING_DEPARTED:
7456                                 sexp_val = sexp_time_wing_departed( node );
7457                                 break;
7458
7459                         case OP_MISSION_TIME:
7460                                 sexp_val = sexp_mission_time();
7461                                 break;
7462
7463                         case OP_TIME_DOCKED:
7464                                 sexp_val = sexp_time_docked( node );
7465                                 break;
7466
7467                         case OP_TIME_UNDOCKED:
7468                                 sexp_val = sexp_time_undocked( node );
7469                                 break;
7470
7471                         // info based sexpressions (like shields, hits
7472                         case OP_SHIELDS_LEFT:
7473                                 sexp_val = sexp_shields_left( node );
7474                                 break;
7475
7476                         case OP_HITS_LEFT:
7477                                 sexp_val = sexp_hits_left( node );
7478                                 break;
7479
7480                         case OP_SPECIAL_WARP_DISTANCE:
7481                                 sexp_val = sexp_special_warp_dist( node );
7482                                 break;
7483
7484                         case OP_HITS_LEFT_SUBSYSTEM:
7485                                 sexp_val = sexp_hits_left_subsystem( node );
7486                                 break;
7487
7488                         case OP_DISTANCE:
7489                                 sexp_val = sexp_distance( node );
7490                                 break;
7491
7492                         case OP_IS_SHIP_VISIBLE:
7493                                 sexp_val = sexp_is_ship_visible( node );
7494                                 break;
7495
7496                         case OP_TEAM_SCORE:
7497                                 sexp_val = sexp_team_score( node );
7498                                 break;
7499
7500                         case OP_LAST_ORDER_TIME:
7501                                 sexp_val = sexp_last_order_time( node );
7502                                 break;
7503
7504                         case OP_NUM_PLAYERS:
7505                                 sexp_val = sexp_num_players();
7506                                 break;
7507
7508                         case OP_SKILL_LEVEL_AT_LEAST:
7509                                 sexp_val = sexp_skill_level_at_least( node );
7510                                 break;
7511
7512                         case OP_IS_CARGO_KNOWN:
7513                         case OP_CARGO_KNOWN_DELAY:
7514                                 sexp_val = sexp_is_cargo_known( node, (op_num==OP_IS_CARGO_KNOWN)?0:1 );
7515                                 break;
7516
7517                         case OP_HAS_BEEN_TAGGED_DELAY:
7518                                 sexp_val = sexp_has_been_tagged_delay(node);
7519                                 break;
7520
7521                         case OP_CAP_SUBSYS_CARGO_KNOWN_DELAY:
7522                                 sexp_val = sexp_cap_subsys_cargo_known_delay(node);
7523                                 break;
7524
7525                         case OP_WAS_PROMOTION_GRANTED:
7526                                 sexp_val = sexp_was_promotion_granted(node);
7527                                 break;
7528
7529                         case OP_WAS_MEDAL_GRANTED:
7530                                 sexp_val = sexp_was_medal_granted(node);
7531                                 break;
7532
7533                         case OP_PERCENT_SHIPS_DEPARTED:
7534                         case OP_PERCENT_SHIPS_DESTROYED:
7535                                 sexp_val = sexp_percent_ships_depart_destroy(node, op_num);
7536                                 break;
7537
7538                         case OP_DEPART_NODE_DELAY:
7539                                 sexp_val = sexp_depart_node_delay( node );
7540                                 break;
7541
7542                         case OP_DESTROYED_DEPARTED_DELAY:
7543                                 sexp_val = sexp_destroyed_departed_delay( node );
7544                                 break;
7545
7546                         // conditional sexpressions
7547                         case OP_WHEN:
7548                                 sexp_val = eval_when( node );
7549                                 break;
7550
7551                         case OP_COND:
7552                                 sexp_val = eval_cond( node );
7553                                 break;
7554
7555                         // sexpressions with side effects
7556                         case OP_CHANGE_IFF:
7557                                 sexp_change_iff( node );
7558                                 sexp_val = 1;
7559                                 break;
7560
7561                         case OP_ADD_SHIP_GOAL:
7562                                 sexp_add_ship_goal( node );
7563                                 sexp_val = 1;
7564                                 break;
7565
7566                         case OP_ADD_WING_GOAL:
7567                                 sexp_add_wing_goal( node );
7568                                 sexp_val = 1;
7569                                 break;
7570
7571                         case OP_ADD_GOAL:
7572                                 sexp_add_goal( node );
7573                                 sexp_val = 1;
7574                                 break;
7575
7576                         case OP_CLEAR_SHIP_GOALS:
7577                                 sexp_clear_ship_goals( node );
7578                                 sexp_val = 1;
7579                                 break;
7580
7581                         case OP_CLEAR_WING_GOALS:
7582                                 sexp_clear_wing_goals( node );
7583                                 sexp_val = 1;
7584                                 break;
7585
7586                         case OP_CLEAR_GOALS:
7587                                 sexp_clear_goals( node );
7588                                 sexp_val = 1;
7589                                 break;
7590
7591                         case OP_PROTECT_SHIP:
7592                         case OP_UNPROTECT_SHIP:
7593                                 sexp_protect_ships( node, (op_num==OP_PROTECT_SHIP?1:0) );
7594                                 sexp_val = 1;
7595                                 break;
7596
7597                         case OP_BEAM_PROTECT_SHIP:
7598                         case OP_BEAM_UNPROTECT_SHIP:
7599                                 sexp_beam_protect_ships( node, (op_num==OP_BEAM_PROTECT_SHIP?1:0) );
7600                                 sexp_val = 1;
7601                                 break;
7602
7603                         case OP_SHIP_INVISIBLE:
7604                         case OP_SHIP_VISIBLE:
7605                                 sexp_ships_visible( node, (op_num==OP_SHIP_VISIBLE?1:0) );
7606                                 sexp_val = 1;
7607                                 break;
7608
7609                         case OP_SHIP_VULNERABLE:
7610                         case OP_SHIP_INVULNERABLE:
7611                                 sexp_ships_invulnerable( node, (op_num==OP_SHIP_INVULNERABLE?1:0) );
7612                                 sexp_val = 1;
7613                                 break;
7614
7615                         case OP_SHIP_GUARDIAN:
7616                         case OP_SHIP_NO_GUARDIAN:
7617                                 sexp_ships_guardian( node, (op_num==OP_SHIP_GUARDIAN?1:0) );
7618                                 sexp_val = 1;
7619                                 break;
7620
7621                         case OP_SHIP_VANISH:
7622                                 sexp_ship_vanish( node );
7623                                 sexp_val = 1;
7624                                 break;
7625
7626                         case OP_SEND_MESSAGE:
7627                                 sexp_send_message( node );
7628                                 sexp_val = 1;
7629                                 break;
7630
7631                         case OP_SEND_MESSAGE_LIST:
7632                                 sexp_send_message_list( node );
7633                                 sexp_val = 1;
7634                                 break;
7635
7636                         case OP_SEND_RANDOM_MESSAGE:
7637                                 sexp_send_random_message( node );
7638                                 sexp_val = 1;
7639                                 break;
7640
7641                         case OP_SELF_DESTRUCT:
7642                                 sexp_self_destruct( node );
7643                                 sexp_val = 1;
7644                                 break;
7645
7646                         case OP_NEXT_MISSION:
7647                                 sexp_next_mission( node );
7648                                 sexp_val = 1;
7649                                 break;
7650                                 
7651                         case OP_END_OF_CAMPAIGN:
7652                                 sexp_end_of_campaign( node );
7653                                 sexp_val = 1;
7654                                 break;
7655
7656                         case OP_END_CAMPAIGN:
7657                                 sexp_end_campaign( node );
7658                                 sexp_val = 1;
7659                                 break;
7660
7661                         case OP_SABOTAGE_SUBSYSTEM:
7662                                 sexp_sabotage_subsystem( node );
7663                                 sexp_val = 1;
7664                                 break;
7665
7666                         case OP_REPAIR_SUBSYSTEM:
7667                                 sexp_repair_subsystem( node );
7668                                 sexp_val = 1;
7669                                 break;
7670
7671                         case OP_SET_SUBSYSTEM_STRNGTH:
7672                                 sexp_set_subsystem_strength( node );
7673                                 sexp_val = 1;
7674                                 break;
7675
7676                         case OP_INVALIDATE_GOAL:
7677                         case OP_VALIDATE_GOAL:
7678                                 sexp_change_goal_validity( node, (op_num==OP_INVALIDATE_GOAL?0:1) );
7679                                 sexp_val = 1;
7680                                 break;
7681
7682                         case OP_TRANSFER_CARGO:
7683                                 sexp_transfer_cargo( node );
7684                                 sexp_val = 1;
7685                                 break;
7686
7687                         case OP_EXCHANGE_CARGO:
7688                                 sexp_exchange_cargo( node );
7689                                 sexp_val = 1;
7690                                 break;
7691
7692
7693                         case OP_JETTISON_CARGO:
7694                                 sexp_jettison_cargo( node );
7695                                 sexp_val = 1;
7696                                 break;
7697
7698                         case OP_CARGO_NO_DEPLETE:
7699                                         sexp_cargo_no_deplete( node );
7700                                         sexp_val = 1;
7701                                         break;
7702
7703                         case OP_SET_SPECIAL_WARPOUT_NAME:
7704                                 sexp_special_warpout_name( node );
7705                                 sexp_val = 1;
7706                                 break;
7707
7708                         case OP_END_MISSION_DELAY:
7709                                 sexp_end_mission_delay( node );
7710                                 sexp_val = 1;
7711                                 break;
7712
7713                                 // sexpressions for setting flag for good/bad time for someone to reasm
7714                         case OP_GOOD_REARM_TIME:
7715                                 sexp_good_time_to_rearm( node );
7716                                 sexp_val = 1;
7717                                 break;
7718
7719                         case OP_GRANT_PROMOTION:
7720                                 sexp_grant_promotion();
7721                                 sexp_val = 1;
7722                                 break;
7723
7724                         case OP_GRANT_MEDAL:
7725                                 sexp_grant_medal( node );
7726                                 sexp_val = 1;
7727                                 break;
7728
7729                         case OP_WARP_BROKEN:
7730                         case OP_WARP_NOT_BROKEN:
7731                                 sexp_deal_with_warp( node, 0, op_num==OP_WARP_BROKEN?1:0 );
7732                                 sexp_val = 1;
7733                                 break;
7734
7735                         case OP_WARP_NEVER:
7736                         case OP_WARP_ALLOWED:
7737                                 sexp_deal_with_warp( node, 1, op_num==OP_WARP_NEVER?1:0 );
7738                                 sexp_val = 1;
7739                                 break;
7740
7741                         case OP_GOOD_SECONDARY_TIME:
7742                                 sexp_good_secondary_time( node );
7743                                 sexp_val = 1;
7744                                 break;
7745
7746                         // sexpressions to allow shpis/weapons during the course of a mission
7747                         case OP_ALLOW_SHIP:
7748                                 sexp_allow_ship( node );
7749                                 sexp_val = 1;
7750                                 break;
7751
7752                         case OP_ALLOW_WEAPON:
7753                                 sexp_allow_weapon( node );
7754                                 sexp_val = 1;
7755                                 break;
7756
7757                         case OP_TECH_ADD_SHIP:
7758                                 sexp_tech_add_ship(node);
7759                                 sexp_val = 1;
7760                                 break;
7761
7762                         case OP_TECH_ADD_WEAPON:
7763                                 sexp_tech_add_weapon(node);
7764                                 sexp_val = 1;
7765                                 break;
7766
7767                                 // in the case of a red_alert mission, simply call the red alert function to close
7768                                 // the current campaign's mission and move forward to the next mission
7769                         case OP_RED_ALERT:
7770                                 red_alert_start_mission();
7771                                 sexp_val = 1;
7772                                 break;
7773
7774                         // training operators
7775                         case OP_KEY_PRESSED:
7776                                 sexp_val = sexp_key_pressed(node);
7777                                 break;
7778
7779                         case OP_SPECIAL_CHECK:
7780                                 sexp_val = sexp_special_training_check(node);
7781                                 break;
7782
7783                         case OP_KEY_RESET:
7784                                 sexp_key_reset(node);
7785                                 sexp_val = SEXP_KNOWN_TRUE;  // only do it first time in repeating events.
7786                                 break;
7787
7788                         case OP_TARGETED:
7789                                 sexp_val = sexp_targeted(node);
7790                                 break;
7791
7792                         case OP_SPEED:
7793                                 sexp_val = sexp_speed(node);
7794                                 break;
7795
7796                         case OP_SECONDARIES_DEPLETED:
7797                                 sexp_val = sexp_secondaries_depleted(node);
7798                                 break;
7799
7800                         case OP_FACING:
7801                                 sexp_val = sexp_facing(node);
7802                                 break;
7803
7804                         case OP_FACING2:
7805                                 sexp_val = sexp_facing2(node);
7806                                 break;
7807
7808                         case OP_ORDER:
7809                                 sexp_val = sexp_order(node);
7810                                 break;
7811
7812                         case OP_WAYPOINT_MISSED:
7813                                 sexp_val = sexp_waypoint_missed();
7814                                 break;
7815
7816                         case OP_WAYPOINT_TWICE:
7817                                 sexp_val = sexp_waypoint_twice();
7818                                 break;
7819
7820                         case OP_PATH_FLOWN:
7821                                 sexp_val = sexp_path_flown();
7822                                 break;
7823
7824                         case OP_TRAINING_MSG:
7825                                 sexp_send_training_message(node);
7826                                 sexp_val = 1;
7827                                 break;
7828
7829                         case OP_FLASH_HUD_GAUGE:
7830                                 sexp_flash_hud_gauge(node);
7831                                 sexp_val = 1;
7832                                 break;
7833
7834                         case OP_SET_TRAINING_CONTEXT_FLY_PATH:
7835                                 sexp_set_training_context_fly_path(node);
7836                                 sexp_val = 1;
7837                                 break;
7838
7839                         case OP_SET_TRAINING_CONTEXT_SPEED:
7840                                 sexp_set_training_context_speed(node);
7841                                 sexp_val = 1;
7842                                 break;
7843
7844                         // debugging operators
7845                         case OP_INT3:
7846                                 Int3();
7847                                 sexp_val = 0;
7848                                 break;
7849
7850                         case 0: // zero represents a non-operator
7851                                 return atoi(CTEXT(cur_node));
7852
7853                         case OP_NOP:
7854                                 sexp_val = 1;
7855                                 break;
7856
7857                         case OP_BEAM_FIRE:
7858                                 sexp_beam_fire(node);
7859                                 sexp_val = 1;
7860                                 break;
7861
7862                         case OP_IS_TAGGED:
7863                                 sexp_val = sexp_is_tagged(node);
7864                                 break;
7865
7866                         case OP_NUM_KILLS:
7867                                 sexp_val = sexp_num_kills(node);
7868                                 break;
7869
7870                         case OP_NUM_TYPE_KILLS:
7871                                 sexp_val = sexp_num_type_kills(node);
7872                                 break;
7873
7874                         case OP_NUM_CLASS_KILLS:
7875                                 sexp_val = sexp_num_class_kills(node);
7876                                 break;
7877
7878                         case OP_BEAM_FREE:
7879                                 sexp_val = 1;
7880                                 sexp_beam_free(node);
7881                                 break;
7882
7883                         case OP_BEAM_FREE_ALL:
7884                                 sexp_val = 1;
7885                                 sexp_beam_free_all(node);
7886                                 break;
7887
7888                         case OP_BEAM_LOCK:
7889                                 sexp_val = 1;
7890                                 sexp_beam_lock(node);
7891                                 break;
7892
7893                         case OP_BEAM_LOCK_ALL:
7894                                 sexp_val = 1;
7895                                 sexp_beam_lock_all(node);
7896                                 break;
7897
7898                         case OP_TURRET_FREE:
7899                                 sexp_val = 1;
7900                                 sexp_turret_free(node);
7901                                 break;
7902
7903                         case OP_TURRET_FREE_ALL:
7904                                 sexp_val = 1;
7905                                 sexp_turret_free_all(node);
7906                                 break;
7907
7908                         case OP_TURRET_LOCK:
7909                                 sexp_val = 1;
7910                                 sexp_turret_lock(node);
7911                                 break;
7912
7913                         case OP_TURRET_LOCK_ALL:
7914                                 sexp_val = 1;
7915                                 sexp_turret_lock_all(node);
7916                                 break;
7917
7918                         case OP_ADD_REMOVE_ESCORT:
7919                                 sexp_val = 1;
7920                                 sexp_add_remove_escort(node);
7921                                 break;
7922
7923                         case OP_AWACS_SET_RADIUS:
7924                                 sexp_val = 1;
7925                                 sexp_awacs_set_radius(node);
7926                                 break;
7927
7928                         case OP_CAP_WAYPOINT_SPEED:
7929                                 sexp_val = 1;
7930                                 sexp_cap_waypont_speed(node);
7931                                 break;
7932
7933                         case OP_TURRET_TAGGED_ONLY_ALL:
7934                                 sexp_val = 1;
7935                                 sexp_turret_tagged_only_all(node);
7936                                 break;
7937
7938                         case OP_TURRET_TAGGED_CLEAR_ALL:
7939                                 sexp_val = 1;
7940                                 sexp_turret_tagged_clear_all(node);
7941                                 break;
7942
7943                         case OP_SUBSYS_SET_RANDOM:
7944                                 sexp_val = 1;
7945                                 sexp_subsys_set_random(node);
7946                                 break;
7947
7948                         case OP_SUPERNOVA_START:
7949                                 sexp_val = 1;
7950                                 sexp_supernova_start(node);
7951                                 break;
7952
7953                         case OP_SHIELD_RECHARGE_PCT:
7954                                 sexp_val = sexp_shield_recharge_pct(node);
7955                                 break;
7956
7957                         case OP_ENGINE_RECHARGE_PCT:
7958                                 sexp_val = sexp_engine_recharge_pct(node);
7959                                 break;
7960
7961                         case OP_WEAPON_RECHARGE_PCT:
7962                                 sexp_val = sexp_weapon_recharge_pct(node);
7963                                 break;
7964
7965                         case OP_SHIELD_QUAD_LOW:
7966                                 sexp_val = sexp_shield_quad_low(node);
7967                                 break;
7968
7969                         case OP_SECONDARY_AMMO_PCT:
7970                                 sexp_val = sexp_secondary_ammo_pct(node);
7971                                 break;
7972
7973                         case OP_IS_SECONDARY_SELECTED:
7974                                 sexp_val = sexp_is_secondary_selected(node);
7975                                 break;
7976
7977                         case OP_IS_PRIMARY_SELECTED:
7978                                 sexp_val = sexp_is_primary_selected(node);
7979                                 break;
7980
7981                         default:
7982                                 Error(LOCATION, "Looking for SEXP operator, found '%s'.\n", CTEXT(cur_node));
7983                                 break;
7984                 }
7985
7986                 SDL_assert(sexp_val != UNINITIALIZED);
7987
7988                 // if we haven't returned, check the sexp value of the sexpression evaluation.  A special
7989                 // value of known true or known false means that we should set the sexp.value field for
7990                 // short circuit eval (and return that special value as well).
7991                 if (sexp_val == SEXP_KNOWN_TRUE) {
7992                         Sexp_nodes[cur_node].value = SEXP_KNOWN_TRUE;
7993                         return 1;
7994                 }
7995
7996                 if (sexp_val == SEXP_KNOWN_FALSE) {
7997                         Sexp_nodes[cur_node].value = SEXP_KNOWN_FALSE;
7998                         return 0;
7999                 }
8000
8001                 if ( sexp_val == SEXP_NAN ) {
8002                         Sexp_nodes[cur_node].value = SEXP_NAN;                  // not a number values are false I would suspect
8003                         return 0;
8004                 }
8005
8006                 if ( sexp_val == SEXP_NAN_FOREVER ) {
8007                         Sexp_nodes[cur_node].value = SEXP_NAN_FOREVER;
8008                         return sexp_val;
8009                 }
8010
8011                 if ( sexp_val == SEXP_CANT_EVAL ) {
8012                         Sexp_nodes[cur_node].value = SEXP_CANT_EVAL;
8013                         Sexp_useful_number = 0;  // indicate sexp isn't current yet
8014                         return 0;
8015                 }
8016
8017                 if ( Sexp_nodes[cur_node].value == SEXP_NAN ) { // if we had a nan, but now don't, reset the value
8018                         Sexp_nodes[cur_node].value = SEXP_UNKNOWN;
8019                         return sexp_val;
8020                 }
8021
8022                 if ( sexp_val ){
8023                         Sexp_nodes[cur_node].value = SEXP_TRUE;
8024                 } else {
8025                         Sexp_nodes[cur_node].value = SEXP_FALSE;
8026                 }
8027
8028                 return sexp_val;
8029         }
8030 }
8031
8032 //      Still a debug-level system.
8033 //      get_sexp_main reads and builds the internal representation for a
8034 //      symbolic expression.
8035 //      On entry:
8036 //              Mp points at first character in expression.
8037 //      The symbolic expression is built in Sexp_nodes beginning at node 0.
8038 int get_sexp_main()
8039 {
8040         int     start_node, op;
8041         char    token[TOKEN_LENGTH];
8042         char  *savep, ch;
8043
8044         ignore_white_space();
8045
8046         savep = Mp;
8047         if (!strncmp(Mp, "( )", 3))
8048                 savep++;
8049
8050         SDL_assert(*Mp == '(');
8051         Mp++;
8052         start_node = get_sexp(token);
8053         // only need to check syntax if we have a operator
8054         if ( /*Sexp_nodes[start_node].subtype != SEXP_ATOM_OPERATOR  ||*/ Fred_running || (start_node == -1))
8055                 return start_node;
8056
8057         ch = *Mp;
8058         *Mp = '\0';
8059
8060         op = identify_operator(CTEXT(start_node));
8061         if (op == -1)
8062                 Error (LOCATION, "Can't find operator %s in operator list\n.", CTEXT(start_node) );
8063
8064         *Mp = ch;
8065
8066         return start_node;
8067 }
8068
8069 void test_sexps()
8070 {
8071         Mp = Mission_text;
8072         while (*Mp != '#') {
8073                 get_sexp_main();
8074                 diag_printf("\n----------------\n");
8075                 ignore_white_space();
8076         }
8077         exit(0);
8078 }
8079
8080 // returns the data type returned by an operator
8081 int query_operator_return_type(int op)
8082 {
8083         if (op < FIRST_OP)
8084         {
8085                 SDL_assert(op >= 0 && op < Num_operators);
8086                 op = Operators[op].value;
8087         }
8088
8089         switch (op)
8090         {
8091                 case OP_TRUE:
8092                 case OP_FALSE:
8093                 case OP_AND:
8094                 case OP_AND_IN_SEQUENCE:
8095                 case OP_OR:
8096                 case OP_NOT:
8097                 case OP_EQUALS:
8098                 case OP_GREATER_THAN:
8099                 case OP_LESS_THAN:
8100                 case OP_IS_DESTROYED:
8101                 case OP_IS_SUBSYSTEM_DESTROYED:
8102                 case OP_IS_DISABLED:
8103                 case OP_IS_DISARMED:
8104                 case OP_HAS_DOCKED:
8105                 case OP_HAS_UNDOCKED:
8106                 case OP_HAS_ARRIVED:
8107                 case OP_HAS_DEPARTED:
8108                 case OP_IS_DESTROYED_DELAY:
8109                 case OP_IS_SUBSYSTEM_DESTROYED_DELAY:
8110                 case OP_IS_DISABLED_DELAY:
8111                 case OP_IS_DISARMED_DELAY:
8112                 case OP_HAS_DOCKED_DELAY:
8113                 case OP_HAS_UNDOCKED_DELAY:
8114                 case OP_HAS_ARRIVED_DELAY:
8115                 case OP_HAS_DEPARTED_DELAY:
8116                 case OP_IS_IFF:
8117                 case OP_HAS_TIME_ELAPSED:
8118                 case OP_GOAL_INCOMPLETE:
8119                 case OP_GOAL_TRUE_DELAY:
8120                 case OP_GOAL_FALSE_DELAY:
8121                 case OP_EVENT_INCOMPLETE:
8122                 case OP_EVENT_TRUE_DELAY:
8123                 case OP_EVENT_FALSE_DELAY:
8124                 case OP_PREVIOUS_EVENT_TRUE:
8125                 case OP_PREVIOUS_EVENT_FALSE:
8126                 case OP_PREVIOUS_EVENT_INCOMPLETE:
8127                 case OP_PREVIOUS_GOAL_TRUE:
8128                 case OP_PREVIOUS_GOAL_FALSE:
8129                 case OP_PREVIOUS_GOAL_INCOMPLETE:
8130                 case OP_WAYPOINTS_DONE:
8131                 case OP_WAYPOINTS_DONE_DELAY:
8132                 case OP_SHIP_TYPE_DESTROYED:
8133                 case OP_LAST_ORDER_TIME:
8134                 case OP_KEY_PRESSED:
8135                 case OP_TARGETED:
8136                 case OP_SPEED:
8137                 case OP_FACING:
8138                 case OP_FACING2:
8139                 case OP_ORDER:
8140                 case OP_WAYPOINT_MISSED:
8141                 case OP_WAYPOINT_TWICE:
8142                 case OP_PATH_FLOWN:
8143                 case OP_EVENT_TRUE:
8144                 case OP_EVENT_FALSE:
8145                 case OP_SKILL_LEVEL_AT_LEAST:
8146                 case OP_IS_CARGO_KNOWN:
8147                 case OP_HAS_BEEN_TAGGED_DELAY:
8148                 case OP_CAP_SUBSYS_CARGO_KNOWN_DELAY:
8149                 case OP_CARGO_KNOWN_DELAY:
8150                 case OP_WAS_PROMOTION_GRANTED:
8151                 case OP_WAS_MEDAL_GRANTED:
8152                 case OP_PERCENT_SHIPS_DEPARTED:
8153                 case OP_PERCENT_SHIPS_DESTROYED:
8154                 case OP_DEPART_NODE_DELAY:
8155                 case OP_DESTROYED_DEPARTED_DELAY:
8156                 case OP_SPECIAL_CHECK:
8157                 case OP_IS_TAGGED:
8158                 case OP_SECONDARIES_DEPLETED:
8159                 case OP_SHIELD_QUAD_LOW:
8160                 case OP_IS_SECONDARY_SELECTED:
8161                 case OP_IS_PRIMARY_SELECTED:
8162                         return OPR_BOOL;
8163
8164                 case OP_PLUS:
8165                 case OP_MINUS:
8166                 case OP_MOD:
8167                 case OP_MUL:
8168                 case OP_DIV:
8169                 case OP_RAND:
8170                 case OP_TIME_SHIP_DESTROYED:
8171                 case OP_TIME_SHIP_ARRIVED:
8172                 case OP_TIME_SHIP_DEPARTED:
8173                 case OP_TIME_WING_DESTROYED:
8174                 case OP_TIME_WING_ARRIVED:
8175                 case OP_TIME_WING_DEPARTED:
8176                 case OP_MISSION_TIME:
8177                 case OP_TIME_DOCKED:
8178                 case OP_TIME_UNDOCKED:
8179                 case OP_SHIELDS_LEFT:
8180                 case OP_HITS_LEFT:
8181                 case OP_HITS_LEFT_SUBSYSTEM:
8182                 case OP_DISTANCE:
8183                 case OP_NUM_PLAYERS:
8184                 case OP_NUM_KILLS:
8185                 case OP_NUM_TYPE_KILLS:
8186                 case OP_NUM_CLASS_KILLS:
8187                 case OP_SHIELD_RECHARGE_PCT:
8188                 case OP_ENGINE_RECHARGE_PCT:
8189                 case OP_WEAPON_RECHARGE_PCT:
8190                 case OP_SECONDARY_AMMO_PCT:
8191                 case OP_SPECIAL_WARP_DISTANCE:
8192                 case OP_IS_SHIP_VISIBLE:
8193                 case OP_TEAM_SCORE:
8194                         return OPR_POSITIVE;
8195
8196                 case OP_COND:
8197                 case OP_WHEN:
8198                 case OP_CHANGE_IFF:
8199                 case OP_CLEAR_SHIP_GOALS:
8200                 case OP_CLEAR_WING_GOALS:
8201                 case OP_CLEAR_GOALS:
8202                 case OP_ADD_SHIP_GOAL:
8203                 case OP_ADD_WING_GOAL:
8204                 case OP_ADD_GOAL:
8205                 case OP_PROTECT_SHIP:
8206                 case OP_UNPROTECT_SHIP:
8207                 case OP_BEAM_PROTECT_SHIP:
8208                 case OP_BEAM_UNPROTECT_SHIP:
8209                 case OP_INT3:
8210                 case OP_NOP:
8211                 case OP_GOALS_ID:
8212                 case OP_SEND_MESSAGE:
8213                 case OP_SELF_DESTRUCT:
8214                 case OP_NEXT_MISSION:
8215                 case OP_END_CAMPAIGN:
8216                 case OP_END_OF_CAMPAIGN:
8217                 case OP_SABOTAGE_SUBSYSTEM:
8218                 case OP_REPAIR_SUBSYSTEM:
8219                 case OP_INVALIDATE_GOAL:
8220                 case OP_VALIDATE_GOAL:
8221                 case OP_SEND_RANDOM_MESSAGE:
8222                 case OP_TRANSFER_CARGO:
8223                 case OP_EXCHANGE_CARGO:
8224                 case OP_JETTISON_CARGO:
8225                 case OP_CARGO_NO_DEPLETE:
8226                 case OP_KEY_RESET:
8227                 case OP_TRAINING_MSG:
8228                 case OP_SET_TRAINING_CONTEXT_FLY_PATH:
8229                 case OP_SET_TRAINING_CONTEXT_SPEED:
8230                 case OP_END_MISSION_DELAY:
8231                 case OP_SET_SUBSYSTEM_STRNGTH:
8232                 case OP_GOOD_REARM_TIME:
8233                 case OP_GRANT_PROMOTION:
8234                 case OP_GRANT_MEDAL:
8235                 case OP_ALLOW_SHIP:
8236                 case OP_ALLOW_WEAPON:
8237                 case OP_TECH_ADD_SHIP:
8238                 case OP_TECH_ADD_WEAPON:
8239                 case OP_WARP_BROKEN:
8240                 case OP_WARP_NOT_BROKEN:
8241                 case OP_WARP_NEVER:
8242                 case OP_WARP_ALLOWED:
8243                 case OP_FLASH_HUD_GAUGE:
8244                 case OP_GOOD_SECONDARY_TIME:
8245                 case OP_SHIP_VISIBLE:
8246                 case OP_SHIP_INVISIBLE:
8247                 case OP_SHIP_VULNERABLE:
8248                 case OP_SHIP_INVULNERABLE:
8249                 case OP_SHIP_GUARDIAN:
8250                 case OP_SHIP_VANISH:
8251                 case OP_SHIP_NO_GUARDIAN:
8252                 case OP_RED_ALERT:
8253                 case OP_MODIFY_VARIABLE:
8254                 case OP_BEAM_FIRE:
8255                 case OP_BEAM_FREE:
8256                 case OP_BEAM_FREE_ALL:
8257                 case OP_BEAM_LOCK:
8258                 case OP_BEAM_LOCK_ALL:
8259                 case OP_TURRET_FREE:
8260                 case OP_TURRET_FREE_ALL:
8261                 case OP_TURRET_LOCK:
8262                 case OP_TURRET_LOCK_ALL:
8263                 case OP_ADD_REMOVE_ESCORT:
8264                 case OP_AWACS_SET_RADIUS:
8265                 case OP_SEND_MESSAGE_LIST:
8266                 case OP_CAP_WAYPOINT_SPEED:
8267                 case OP_TURRET_TAGGED_ONLY_ALL:
8268                 case OP_TURRET_TAGGED_CLEAR_ALL:
8269                 case OP_SUBSYS_SET_RANDOM:
8270                 case OP_SUPERNOVA_START:
8271                 case OP_SET_SPECIAL_WARPOUT_NAME:
8272                         return OPR_NULL;
8273
8274                 case OP_AI_CHASE:
8275                 case OP_AI_DOCK:
8276                 case OP_AI_UNDOCK:
8277                 case OP_AI_WARP:                                                // this particular operator is obsolete
8278                 case OP_AI_WARP_OUT:
8279                 case OP_AI_WAYPOINTS:
8280                 case OP_AI_WAYPOINTS_ONCE:
8281                 case OP_AI_DESTROY_SUBSYS:
8282                 case OP_AI_CHASE_WING:
8283                 case OP_AI_DISABLE_SHIP:
8284                 case OP_AI_DISARM_SHIP:
8285                 case OP_AI_GUARD:
8286                 case OP_AI_GUARD_WING:
8287                 case OP_AI_CHASE_ANY:
8288                 case OP_AI_EVADE_SHIP:
8289                 case OP_AI_STAY_NEAR_SHIP:
8290                 case OP_AI_KEEP_SAFE_DISTANCE:
8291                 case OP_AI_IGNORE:
8292                 case OP_AI_STAY_STILL:
8293                 case OP_AI_PLAY_DEAD:
8294                         return OPR_AI_GOAL;
8295
8296                 default:
8297                         Int3();
8298         }
8299
8300         return 0;
8301 }
8302
8303 // returns the data type of a specified argument to an operator.  Argnum is 0 indexed.
8304 int query_operator_argument_type(int op, int argnum)
8305 {
8306         int index = op;
8307
8308         if (op < FIRST_OP)
8309         {
8310                 SDL_assert(index >= 0 && index < Num_operators);
8311                 op = Operators[index].value;
8312
8313         } else {
8314                 for (index=0; index<Num_operators; index++)
8315                         if (Operators[index].value == op)
8316                                 break;
8317
8318                 SDL_assert(index < Num_operators);
8319         }
8320
8321         if (argnum >= Operators[index].max)
8322                 return OPF_NONE;
8323
8324         switch (op) {
8325                 case OP_TRUE:
8326                 case OP_FALSE:
8327                 case OP_MISSION_TIME:
8328                 case OP_INT3:
8329                 case OP_NOP:
8330                 case OP_WAYPOINT_MISSED:
8331                 case OP_WAYPOINT_TWICE:
8332                 case OP_PATH_FLOWN:
8333                 case OP_GRANT_PROMOTION:
8334                 case OP_WAS_PROMOTION_GRANTED:
8335                 case OP_RED_ALERT:
8336                         return OPF_NONE;
8337
8338                 case OP_AND:
8339                 case OP_AND_IN_SEQUENCE:
8340                 case OP_OR:
8341                 case OP_NOT:
8342                         return OPF_BOOL;
8343
8344                 case OP_PLUS:
8345                 case OP_MINUS:
8346                 case OP_MOD:
8347                 case OP_MUL:
8348                 case OP_DIV:
8349                 case OP_RAND:
8350                 case OP_EQUALS:
8351                 case OP_GREATER_THAN:
8352                 case OP_LESS_THAN:
8353                 case OP_HAS_TIME_ELAPSED:
8354                 case OP_SPEED:
8355                 case OP_SET_TRAINING_CONTEXT_SPEED:
8356                 case OP_END_MISSION_DELAY:
8357                 case OP_SPECIAL_CHECK:
8358                 case OP_AI_WARP_OUT:
8359                 case OP_TEAM_SCORE:
8360                         return OPF_POSITIVE;
8361
8362                 case OP_AI_WARP:                                                                // this operator is obsolete
8363                 case OP_SET_TRAINING_CONTEXT_FLY_PATH:
8364                         if ( !argnum )
8365                                 return OPF_WAYPOINT_PATH;
8366                         else
8367                                 return OPF_NUMBER;
8368                 
8369                 case OP_AI_WAYPOINTS:
8370                 case OP_AI_WAYPOINTS_ONCE:
8371                         if ( argnum == 0 )
8372                                 return OPF_WAYPOINT_PATH;
8373                         else
8374                                 return OPF_POSITIVE;
8375
8376                 case OP_IS_DISABLED:
8377                 case OP_IS_DISARMED:
8378                 case OP_TIME_SHIP_DESTROYED:
8379                 case OP_TIME_SHIP_ARRIVED:
8380                 case OP_TIME_SHIP_DEPARTED:
8381                 case OP_SHIELDS_LEFT:
8382                 case OP_HITS_LEFT:
8383                 case OP_CLEAR_SHIP_GOALS:
8384                 case OP_PROTECT_SHIP:
8385                 case OP_UNPROTECT_SHIP:
8386                 case OP_BEAM_PROTECT_SHIP:
8387                 case OP_BEAM_UNPROTECT_SHIP:
8388                 case OP_TRANSFER_CARGO:
8389                 case OP_EXCHANGE_CARGO:
8390                 case OP_SHIP_INVISIBLE:
8391                 case OP_SHIP_VISIBLE:
8392                 case OP_SHIP_INVULNERABLE:
8393                 case OP_SHIP_VULNERABLE:
8394                 case OP_SHIP_GUARDIAN:
8395                 case OP_SHIP_VANISH:
8396                 case OP_SHIP_NO_GUARDIAN:
8397                 case OP_SECONDARIES_DEPLETED:
8398                 case OP_SPECIAL_WARP_DISTANCE:
8399                 case OP_SET_SPECIAL_WARPOUT_NAME:
8400                 case OP_IS_SHIP_VISIBLE:
8401                         return OPF_SHIP;
8402
8403                 case OP_IS_DESTROYED:
8404                 case OP_HAS_ARRIVED:
8405                 case OP_HAS_DEPARTED:
8406                 case OP_CLEAR_GOALS:
8407                         return OPF_SHIP_WING;
8408
8409                 case OP_IS_DISABLED_DELAY:
8410                 case OP_IS_DISARMED_DELAY:
8411                         if ( argnum == 0 )
8412                                 return OPF_POSITIVE;
8413                         else
8414                                 return OPF_SHIP;
8415
8416                 case OP_FACING:
8417                         if (argnum == 0)
8418                                 return OPF_SHIP;
8419                         else
8420                                 return OPF_POSITIVE;
8421
8422                 case OP_FACING2:
8423                         if (argnum == 0) {
8424                                 return OPF_WAYPOINT_PATH;
8425                         } else {
8426                                 return OPF_POSITIVE;
8427                         }
8428
8429                 case OP_ORDER:
8430                         if (argnum == 1)
8431                                 return OPF_AI_ORDER;
8432                         else
8433                                 return OPF_SHIP_WING;
8434
8435                 case OP_IS_DESTROYED_DELAY:
8436                 case OP_HAS_ARRIVED_DELAY:
8437                 case OP_HAS_DEPARTED_DELAY:
8438                 case OP_LAST_ORDER_TIME:
8439                         if ( argnum == 0 )
8440                                 return OPF_POSITIVE;
8441                         else
8442                                 return OPF_SHIP_WING;
8443
8444                 case OP_DISTANCE:
8445                         return OPF_SHIP_WING_POINT;
8446
8447                 case OP_MODIFY_VARIABLE:
8448                         if (argnum == 0) {
8449                                 return OPF_VARIABLE_NAME;
8450                         } else {
8451                                 return OPF_AMBIGUOUS; 
8452                         }
8453
8454                 case OP_HAS_DOCKED:
8455                 case OP_HAS_UNDOCKED:
8456                 case OP_HAS_DOCKED_DELAY:
8457                 case OP_HAS_UNDOCKED_DELAY:
8458                 case OP_TIME_DOCKED:
8459                 case OP_TIME_UNDOCKED:
8460                         if ( argnum < 2 )
8461                                 return OPF_SHIP;
8462                         else
8463                                 return OPF_POSITIVE;
8464
8465                 case OP_TIME_WING_DESTROYED:
8466                 case OP_TIME_WING_ARRIVED:
8467                 case OP_TIME_WING_DEPARTED:
8468                 case OP_CLEAR_WING_GOALS:
8469                         return OPF_WING;
8470
8471                 case OP_IS_SUBSYSTEM_DESTROYED:
8472                 case OP_HITS_LEFT_SUBSYSTEM:
8473                         if (!argnum)
8474                                 return OPF_SHIP;
8475                         else
8476                                 return OPF_SUBSYSTEM;
8477
8478                 case OP_TARGETED:
8479                         if (!argnum)
8480                                 return OPF_SHIP;
8481                         else if (argnum == 1)
8482                                 return OPF_POSITIVE;
8483                         else
8484                                 return OPF_SUBSYSTEM;
8485
8486                 case OP_IS_SUBSYSTEM_DESTROYED_DELAY:
8487                         if ( argnum == 0 )
8488                                 return OPF_SHIP;
8489                         else if ( argnum == 1 )
8490                                 return OPF_SUBSYSTEM;
8491                         else
8492                                 return OPF_POSITIVE;
8493
8494                 case OP_IS_IFF:
8495                 case OP_CHANGE_IFF:
8496                         if (!argnum)
8497                                 return OPF_IFF;
8498                         else
8499                                 return OPF_SHIP;
8500
8501                 case OP_ADD_SHIP_GOAL:
8502                         if (!argnum)
8503                                 return OPF_SHIP;
8504                         else
8505                                 return OPF_AI_GOAL;
8506
8507                 case OP_ADD_WING_GOAL:
8508                         if (!argnum)
8509                                 return OPF_WING;
8510                         else
8511                                 return OPF_AI_GOAL;
8512
8513                 case OP_ADD_GOAL:
8514                         if ( argnum == 0 )
8515                                 return OPF_SHIP_WING;
8516                         else
8517                                 return OPF_AI_GOAL;
8518
8519                 case OP_WHEN:
8520                 case OP_COND:
8521                         if (!argnum)
8522                                 return OPF_BOOL;
8523                         else
8524                                 return OPF_NULL;
8525
8526                 case OP_AI_DISABLE_SHIP:
8527                 case OP_AI_DISARM_SHIP:
8528                 case OP_AI_EVADE_SHIP:
8529                 case OP_AI_STAY_NEAR_SHIP:
8530                 case OP_AI_IGNORE:
8531                         if (!argnum)
8532                                 return OPF_SHIP;
8533                         else
8534                                 return OPF_POSITIVE;
8535
8536                 case OP_AI_CHASE:
8537                 case OP_AI_GUARD:
8538                         if (!argnum)
8539                                 return OPF_SHIP_WING;
8540                         else
8541                                 return OPF_POSITIVE;
8542
8543                 case OP_AI_UNDOCK:
8544                 case OP_AI_KEEP_SAFE_DISTANCE:
8545                         return OPF_POSITIVE;
8546
8547                 case OP_AI_DOCK:
8548                         if (!argnum)
8549                                 return OPF_SHIP;
8550                         else if (argnum == 1)
8551                                 return OPF_DOCKER_POINT;
8552                         else if (argnum == 2)
8553                                 return OPF_DOCKEE_POINT;
8554                         else
8555                                 return OPF_POSITIVE;
8556
8557                 case OP_AI_CHASE_WING:
8558                 case OP_AI_GUARD_WING:
8559                         if (!argnum)
8560                                 return OPF_WING;
8561                         else
8562                                 return OPF_POSITIVE;
8563
8564                 case OP_AI_DESTROY_SUBSYS:
8565                         if (!argnum)
8566                                 return OPF_SHIP;
8567                         else if (argnum == 1)
8568                                 return OPF_SUBSYSTEM;
8569                         else
8570                                 return OPF_POSITIVE;
8571                         
8572                 case OP_GOALS_ID:
8573                         return OPF_AI_GOAL;
8574
8575                 case OP_SEND_MESSAGE:
8576                 case OP_SEND_RANDOM_MESSAGE:
8577                         if ( argnum == 0 )
8578                                 return OPF_WHO_FROM;
8579                         else if ( argnum == 1 )
8580                                 return OPF_PRIORITY;
8581                         else
8582                                 return OPF_MESSAGE;
8583
8584                 case OP_SEND_MESSAGE_LIST:
8585                         int a_mod;
8586
8587                         // every four, the value repeats
8588                         a_mod = argnum % 4;                     
8589
8590                         // who from
8591                         if(a_mod == 0)
8592                                 return OPF_WHO_FROM;
8593                         else if(a_mod == 1)
8594                                 return OPF_PRIORITY;
8595                         else if(a_mod == 2)
8596                                 return OPF_MESSAGE;
8597                         else if(a_mod == 3)
8598                                 return OPF_POSITIVE;
8599
8600                 case OP_TRAINING_MSG:
8601                         if (argnum < 2)
8602                                 return OPF_MESSAGE;
8603                         else
8604                                 return OPF_POSITIVE;
8605
8606                 case OP_SELF_DESTRUCT:
8607                         return OPF_SHIP;
8608
8609                 case OP_NEXT_MISSION:
8610                         return OPF_MISSION_NAME;
8611
8612                 case OP_END_CAMPAIGN:
8613                 case OP_END_OF_CAMPAIGN:
8614                         return OPF_NONE;
8615
8616                 case OP_PREVIOUS_GOAL_TRUE:
8617                 case OP_PREVIOUS_GOAL_FALSE:
8618                         if ( argnum == 0 )
8619                                 return OPF_MISSION_NAME;
8620                         else if (argnum == 1 )
8621                                 return OPF_GOAL_NAME;
8622                         else
8623                                 return OPF_BOOL;
8624
8625                 case OP_PREVIOUS_GOAL_INCOMPLETE:
8626                         return OPF_GOAL_NAME;
8627
8628                 case OP_PREVIOUS_EVENT_TRUE:
8629                 case OP_PREVIOUS_EVENT_FALSE:
8630                 case OP_PREVIOUS_EVENT_INCOMPLETE:
8631                         if (!argnum)
8632                                 return OPF_MISSION_NAME;
8633                         else if ( argnum == 1 )
8634                                 return OPF_EVENT_NAME;
8635                         else
8636                                 return OPF_BOOL;
8637
8638                 case OP_SABOTAGE_SUBSYSTEM:
8639                 case OP_REPAIR_SUBSYSTEM:
8640                 case OP_SET_SUBSYSTEM_STRNGTH:
8641                         if (!argnum)
8642                                 return OPF_SHIP_NOT_PLAYER;
8643                         else if (argnum == 1 )
8644                                 return OPF_SUBSYSTEM;
8645                         else
8646                                 return OPF_POSITIVE;
8647
8648                 case OP_WAYPOINTS_DONE:
8649                         if ( argnum == 0 )
8650                                 return OPF_SHIP_WING;
8651                         else
8652                                 return OPF_WAYPOINT_PATH;
8653
8654                 case OP_WAYPOINTS_DONE_DELAY:
8655                         if ( argnum == 0 )
8656                                 return OPF_SHIP_WING;
8657                         else if ( argnum == 1 )
8658                                 return OPF_WAYPOINT_PATH;
8659                         else
8660                                 return OPF_POSITIVE;
8661
8662                 case OP_INVALIDATE_GOAL:
8663                 case OP_VALIDATE_GOAL:
8664                         return OPF_GOAL_NAME;
8665
8666                 case OP_SHIP_TYPE_DESTROYED:
8667                         if ( argnum == 0 )
8668                                 return OPF_POSITIVE;
8669                         else
8670                                 return OPF_SHIP_TYPE;
8671
8672                 case OP_KEY_PRESSED:
8673                         if (!argnum)
8674                                 return OPF_KEYPRESS;
8675                         else
8676                                 return OPF_POSITIVE;
8677
8678                 case OP_KEY_RESET:
8679                         return OPF_KEYPRESS;
8680
8681                 case OP_EVENT_TRUE:
8682                 case OP_EVENT_FALSE:
8683                         return OPF_EVENT_NAME;
8684
8685                 case OP_EVENT_INCOMPLETE:
8686                 case OP_EVENT_TRUE_DELAY:
8687                 case OP_EVENT_FALSE_DELAY:
8688                         if (!argnum)
8689                                 return OPF_EVENT_NAME;
8690                         else
8691                                 return OPF_POSITIVE;
8692
8693                 case OP_GOAL_INCOMPLETE:
8694                 case OP_GOAL_TRUE_DELAY:
8695                 case OP_GOAL_FALSE_DELAY:
8696                         if (!argnum)
8697                                 return OPF_GOAL_NAME;
8698                         else
8699                                 return OPF_POSITIVE;
8700
8701                 case OP_AI_PLAY_DEAD:
8702                 case OP_AI_CHASE_ANY:
8703                         return OPF_POSITIVE;
8704
8705                 case OP_AI_STAY_STILL:
8706                         if (!argnum)
8707                                 return OPF_SHIP_POINT;
8708                         else
8709                                 return OPF_POSITIVE;
8710
8711                 case OP_GOOD_REARM_TIME:
8712                         if ( argnum == 0 )
8713                                 return OPF_IFF;
8714                         else
8715                                 return OPF_POSITIVE;
8716
8717                 case OP_NUM_PLAYERS:
8718                         return OPF_POSITIVE;
8719
8720                 case OP_SKILL_LEVEL_AT_LEAST:
8721                         return OPF_SKILL_LEVEL;
8722
8723                 case OP_GRANT_MEDAL:
8724                 case OP_WAS_MEDAL_GRANTED:
8725                         return OPF_MEDAL_NAME;
8726
8727                 case OP_IS_CARGO_KNOWN:
8728                         return OPF_SHIP;
8729
8730                 case OP_CARGO_KNOWN_DELAY:
8731                         if ( argnum == 0 )
8732                                 return OPF_POSITIVE;
8733                         else
8734                                 return OPF_SHIP;
8735
8736                 case OP_HAS_BEEN_TAGGED_DELAY:
8737                         if ( argnum == 0 ) {
8738                                 return OPF_POSITIVE;
8739                         } else {
8740                                 return OPF_SHIP;
8741                         }
8742
8743                 case OP_CAP_SUBSYS_CARGO_KNOWN_DELAY:
8744                         if ( argnum == 0 ) {
8745                                 return OPF_POSITIVE;
8746                         } else if ( argnum == 1 ) {
8747                                 return OPF_SHIP;
8748                         } else {
8749                                 return OPF_SUBSYSTEM;
8750                         }
8751
8752                 case OP_ALLOW_SHIP:
8753                 case OP_TECH_ADD_SHIP:
8754                         return OPF_SHIP_CLASS_NAME;
8755
8756                 case OP_ALLOW_WEAPON:
8757                 case OP_TECH_ADD_WEAPON:
8758                         return OPF_WEAPON_NAME;
8759
8760                 case OP_WARP_BROKEN:
8761                 case OP_WARP_NOT_BROKEN:
8762                 case OP_WARP_NEVER:
8763                 case OP_WARP_ALLOWED:
8764                         return OPF_SHIP;
8765
8766                 case OP_FLASH_HUD_GAUGE:
8767                         return OPF_HUD_GAUGE_NAME;
8768
8769                 case OP_GOOD_SECONDARY_TIME:
8770                         if ( argnum == 0 )
8771                                 return OPF_IFF;
8772                         else if ( argnum == 1 )
8773                                 return OPF_POSITIVE;
8774                         else if ( argnum == 2 )
8775                                 return OPF_HUGE_WEAPON;
8776                         else
8777                                 return OPF_SHIP;
8778
8779                 case OP_PERCENT_SHIPS_DEPARTED:
8780                 case OP_PERCENT_SHIPS_DESTROYED:
8781                         if ( argnum == 0 ){
8782                                 return OPF_POSITIVE;
8783                         } else {
8784                                 return OPF_SHIP_WING;
8785                         }
8786                         break;
8787
8788                 case OP_DEPART_NODE_DELAY:      
8789                         if ( argnum == 0 ){
8790                                 return OPF_POSITIVE;
8791                         } else if ( argnum == 1 ){
8792                                 return OPF_JUMP_NODE_NAME;
8793                         } else {
8794                                 return OPF_SHIP;
8795                         }
8796
8797                 case OP_DESTROYED_DEPARTED_DELAY:
8798                         if ( argnum == 0 ){
8799                                 return OPF_POSITIVE;
8800                         } else {
8801                                 return OPF_SHIP_WING;
8802                         }
8803
8804                 case OP_JETTISON_CARGO:
8805                         if(argnum == 0){
8806                                 return OPF_SHIP;
8807                         } else {
8808                                 return OPF_POSITIVE;
8809                         }
8810
8811                 case OP_CARGO_NO_DEPLETE:
8812                         if (argnum == 0) {
8813                                 return OPF_SHIP;
8814                         } else {
8815                                 return OPF_NUMBER;
8816                         }
8817
8818                 case OP_BEAM_FIRE:
8819                         switch(argnum){
8820                         case 0:
8821                                 return OPF_SHIP;
8822                         case 1:
8823                                 return OPF_SUBSYSTEM;
8824                         case 2:
8825                                 return OPF_SHIP;
8826                         case 3:
8827                                 return OPF_SUBSYSTEM;
8828                         }
8829
8830                 case OP_IS_TAGGED:
8831                         return OPF_SHIP;
8832
8833                 case OP_NUM_KILLS:
8834                         return OPF_SHIP;
8835
8836                 case OP_NUM_TYPE_KILLS:
8837                         if(argnum == 0){
8838                                 return OPF_SHIP;
8839                         } else {
8840                                 return OPF_SHIP_TYPE;
8841                         }
8842
8843                 case OP_NUM_CLASS_KILLS:
8844                         if(argnum == 0){
8845                                 return OPF_SHIP;
8846                         } else {
8847                                 return OPF_SHIP_CLASS_NAME;
8848                         }
8849
8850                 case OP_BEAM_FREE:
8851                 case OP_BEAM_LOCK:
8852                 case OP_TURRET_FREE:
8853                 case OP_TURRET_LOCK:
8854                         if(argnum == 0){
8855                                 return OPF_SHIP;
8856                         } else {
8857                                 return OPF_SUBSYSTEM;
8858                         }
8859
8860                 case OP_BEAM_FREE_ALL:
8861                 case OP_BEAM_LOCK_ALL:
8862                 case OP_TURRET_FREE_ALL:
8863                 case OP_TURRET_LOCK_ALL:
8864                 case OP_TURRET_TAGGED_ONLY_ALL:
8865                 case OP_TURRET_TAGGED_CLEAR_ALL:
8866                         return OPF_SHIP;
8867
8868                 case OP_ADD_REMOVE_ESCORT:
8869                         if(argnum == 0){
8870                                 return OPF_SHIP;
8871                         } else {
8872                                 return OPF_NUMBER;
8873                         }
8874
8875                 case OP_AWACS_SET_RADIUS:
8876                         if(argnum == 0){
8877                                 return OPF_SHIP;
8878                         } else if(argnum == 1){
8879                                 return OPF_AWACS_SUBSYSTEM;
8880                         } else {
8881                                 return OPF_NUMBER;
8882                         }
8883
8884                 case OP_CAP_WAYPOINT_SPEED:
8885                         if (argnum == 0) {
8886                                 return OPF_SHIP;
8887                         } else {
8888                                 return OPF_NUMBER;
8889                         }
8890
8891                 case OP_SUBSYS_SET_RANDOM:
8892                         if (argnum == 0) {
8893                                 return OPF_SHIP;
8894                         } else if (argnum == 1 || argnum == 2) {
8895                                 return OPF_NUMBER;
8896                         } else {
8897                                 return OPF_SUBSYSTEM;
8898                         }
8899
8900                 case OP_SUPERNOVA_START:
8901                         return OPF_NUMBER;
8902
8903                 case OP_SHIELD_RECHARGE_PCT:
8904                 case OP_WEAPON_RECHARGE_PCT:
8905                 case OP_ENGINE_RECHARGE_PCT:
8906                         return OPF_SHIP;                        
8907
8908                 case OP_SHIELD_QUAD_LOW:
8909                         if(argnum == 0){
8910                                 return OPF_SHIP;
8911                         } else {
8912                                 return OPF_NUMBER;
8913                         }
8914
8915                 case OP_SECONDARY_AMMO_PCT:
8916                         if(argnum == 0){
8917                                 return OPF_SHIP;
8918                         } else {
8919                                 return OPF_NUMBER;
8920                         }
8921
8922                 case OP_IS_SECONDARY_SELECTED:
8923                 case OP_IS_PRIMARY_SELECTED:
8924                         if(argnum == 0){
8925                                 return OPF_SHIP;
8926                         } else {
8927                                 return OPF_NUMBER;
8928                         }
8929
8930                 default:
8931                         Int3();
8932         }
8933
8934         return 0;
8935 }
8936
8937 void update_block_names(const char *old_name, const char *new_name)
8938 {
8939         int i;
8940
8941         for (i=0; i<MAX_SEXP_VARIABLES; i++) {
8942                 if (Sexp_variables[i].type & SEXP_VARIABLE_BLOCK) {
8943                         if ( !SDL_strcasecmp(old_name, Sexp_variables[i].variable_name) ) {
8944                                 SDL_strlcpy(Sexp_variables[i].variable_name, new_name, TOKEN_LENGTH);
8945                         }
8946                 }
8947         }
8948 }
8949
8950 // DA: 1/7/99  Used to rename ships and waypoints, not variables
8951 // Strictly used in FRED
8952 void update_sexp_references(char *old_name, char *new_name)
8953 {
8954         int i;
8955
8956         // update_block_names
8957         update_block_names(old_name, new_name);
8958
8959         SDL_assert(strlen(new_name) < TOKEN_LENGTH);
8960         for (i=0; i<MAX_SEXP_NODES; i++){
8961                 if ((SEXP_NODE_TYPE(i) == SEXP_ATOM) && (Sexp_nodes[i].subtype == SEXP_ATOM_STRING)){
8962                         if (!SDL_strcasecmp(CTEXT(i), old_name)){
8963                                 SDL_strlcpy(CTEXT(i), new_name, TOKEN_LENGTH);
8964                         }
8965                 }
8966         }
8967 }
8968
8969 // DA: 1/7/99  Used to rename event names, goal names, not variables
8970 // Strictly used in FRED
8971 void update_sexp_references(char *old_name, char *new_name, int format)
8972 {
8973         int i;
8974
8975         SDL_assert(strlen(new_name) < TOKEN_LENGTH);
8976         for (i=0; i<MAX_SEXP_NODES; i++){
8977                 if (is_sexp_top_level(i)){
8978                         update_sexp_references(old_name, new_name, format, i);
8979                 }
8980         }
8981 }
8982
8983 // DA: 1/7/99  Used to rename event names, goal names, not variables
8984 // recursive function to update references to a certain type of data
8985 void update_sexp_references(char *old_name, char *new_name, int format, int node)
8986 {
8987         int i, n, op;
8988
8989         if (node < 0){
8990                 return;
8991         }
8992
8993         if ((SEXP_NODE_TYPE(node) == SEXP_LIST) && (Sexp_nodes[node].subtype == SEXP_ATOM_LIST)) {
8994                 if (Sexp_nodes[node].first){
8995                         update_sexp_references(old_name, new_name, format, Sexp_nodes[node].first);
8996                 }
8997                 if (Sexp_nodes[node].rest){
8998                         update_sexp_references(old_name, new_name, format, Sexp_nodes[node].rest);
8999                 }
9000
9001                 return;
9002         }
9003
9004         if (SEXP_NODE_TYPE(node) != SEXP_ATOM){
9005                 return;
9006         }
9007
9008         if (Sexp_nodes[node].subtype != SEXP_ATOM_OPERATOR){
9009                 return;
9010         }
9011
9012         op = identify_operator(CTEXT(node));
9013         SDL_assert(Sexp_nodes[node].first < 0);
9014         n = Sexp_nodes[node].rest;
9015         i = 0;
9016         while (n >= 0) {
9017                 if (SEXP_NODE_TYPE(n) == SEXP_LIST){
9018                         update_sexp_references(old_name, new_name, format, Sexp_nodes[n].first);
9019                 } else {
9020                         SDL_assert((SEXP_NODE_TYPE(n) == SEXP_ATOM) && ((Sexp_nodes[n].subtype == SEXP_ATOM_NUMBER) || (Sexp_nodes[n].subtype == SEXP_ATOM_STRING)));
9021                         if (query_operator_argument_type(op, i) == format) {
9022                                 if (!SDL_strcasecmp(CTEXT(n), old_name)){
9023                                         SDL_strlcpy(CTEXT(n), new_name, TOKEN_LENGTH);
9024                                 }
9025                         }
9026                 }
9027
9028                 n = Sexp_nodes[n].rest;
9029                 i++;
9030         }
9031 }
9032
9033 int query_referenced_in_sexp(int mode, char *name, int *node)
9034 {
9035         int i, n, j;
9036
9037         for (n=0; n<MAX_SEXP_NODES; n++){
9038                 if ((SEXP_NODE_TYPE(n) == SEXP_ATOM) && (Sexp_nodes[n].subtype == SEXP_ATOM_STRING)){
9039                         if (!SDL_strcasecmp(CTEXT(n), name)){
9040                                 break;
9041                         }
9042                 }
9043         }
9044
9045         if (n == MAX_SEXP_NODES){
9046                 return 0;
9047         }
9048
9049         if (node){
9050                 *node = n;
9051         }
9052
9053         // so we know it's being used somewhere..  Time to find out where..
9054         for (i=0; i<MAX_SHIPS; i++)
9055                 if (Ships[i].objnum >= 0) {
9056                         if (query_node_in_sexp(n, Ships[i].arrival_cue)){
9057                                 return i | SRC_SHIP_ARRIVAL;
9058                         }
9059                         if (query_node_in_sexp(n, Ships[i].departure_cue)){
9060                                 return i | SRC_SHIP_DEPARTURE;
9061                         }
9062                 }
9063
9064         for (i=0; i<MAX_WINGS; i++){
9065                 if (Wings[i].wave_count) {
9066                         if (query_node_in_sexp(n, Wings[i].arrival_cue)){
9067                                 return i | SRC_WING_ARRIVAL;
9068                         }
9069                         if (query_node_in_sexp(n, Wings[i].departure_cue)){
9070                                 return i | SRC_WING_DEPARTURE;
9071                         }
9072                 }
9073         }
9074
9075         for (i=0; i<Num_mission_events; i++){
9076                 if (query_node_in_sexp(n, Mission_events[i].formula)){
9077                         return i | SRC_EVENT;
9078                 }
9079         }
9080
9081         for (i=0; i<Num_goals; i++){
9082                 if (query_node_in_sexp(n, Mission_goals[i].formula)){
9083                         return i | SRC_MISSION_GOAL;
9084                 }
9085         }
9086
9087         for (j=0; j<Num_teams; j++) {
9088                 for (i=0; i<Debriefings[j].num_stages; i++) {
9089                         if (query_node_in_sexp(n, Debriefings[j].stages[i].formula)){
9090                                 return i | SRC_DEBRIEFING;
9091                         }
9092                 }
9093         }
9094
9095         for (j=0; j<Num_teams; j++) {
9096                 for (i=0; i<Briefings[j].num_stages; i++) {
9097                         if (query_node_in_sexp(n, Briefings[j].stages[i].formula)){
9098                                 return i | SRC_BRIEFING;
9099                         }
9100                 }
9101         }
9102
9103         return SRC_UNKNOWN;
9104 }
9105
9106 int verify_vector(char *text)
9107 {
9108         char *str;
9109         int i, z, len = 0;
9110
9111         for (i=0; i<Num_waypoint_lists; i++) {
9112                 len = strlen(str = Waypoint_lists[i].name);
9113                 if (!SDL_strncasecmp(str, text, len)){
9114                         if (!text[len] || text[len] == ':'){
9115                                 break;
9116                         }
9117                 }
9118         }
9119
9120         if (i < Num_waypoint_lists) {
9121                 if (!text[len]){
9122                         return 0;  // a valid waypoint path
9123                 }
9124
9125                 str = &text[len + 1];
9126                 while (*str){
9127                         if (!isdigit(*str++)){
9128                                 return -1;  // not a valid number
9129                         }
9130                 }
9131
9132                 z = atoi(&text[len + 1]);
9133                 if (z < 1 || z > Waypoint_lists[i].count){
9134                         return -1;  // out of range
9135                 }
9136
9137                 return 0;  // a valid waypoint
9138         }
9139
9140         len = strlen(text);
9141         if (text[0] != '(' || text[len - 1] != ')'){
9142                 return -1;
9143         }
9144
9145         str = &text[0];
9146         skip_white(&str);
9147         if (*str != '('){
9148                 return -1;
9149         }
9150
9151         str++;
9152         skip_white(&str);
9153         if (validate_float(&str)){
9154                 return -1;
9155         }
9156
9157         skip_white(&str);
9158         if (validate_float(&str)){
9159                 return -1;
9160         }
9161
9162         skip_white(&str);
9163         if (validate_float(&str)){
9164                 return -1;
9165         }
9166
9167         skip_white(&str);
9168         if (*str != ')'){
9169                 return -1;
9170         }
9171
9172         str++;
9173         skip_white(&str);
9174         if (*str){
9175                 return -1;
9176         }
9177
9178         return 0;
9179 }
9180
9181 void skip_white(char **str)
9182 {
9183         if ((**str == ' ') || (**str == '\t')){
9184                 (*str)++;
9185         }
9186 }
9187
9188 int validate_float(char **str)
9189 {
9190         int count = 0, dot = 0;
9191
9192         while (isdigit(**str) || **str == '.') {
9193                 if (**str == '.') {
9194                         if (dot){
9195                                 return -1;
9196                         }
9197
9198                         dot = 1;
9199                 }
9200
9201                 (*str)++;
9202                 count++;
9203         }
9204
9205         if (!count){
9206                 return -1;
9207         }
9208
9209         return 0;
9210 }
9211
9212 // check if operator return type opr is a valid match for operator argument type opf
9213 int sexp_query_type_match(int opf, int opr)
9214 {
9215         switch (opf) {
9216                 case OPF_NUMBER:
9217                         return ((opr == OPR_NUMBER) || (opr == OPR_POSITIVE));
9218
9219                 case OPF_POSITIVE:
9220                         return (opr == OPR_POSITIVE);
9221
9222                 case OPF_BOOL:
9223                         return (opr == OPR_BOOL);
9224
9225                 case OPF_NULL:
9226                         return (opr == OPR_NULL);
9227
9228                 case OPF_AI_GOAL:
9229                         return (opr == OPR_AI_GOAL);
9230         }
9231
9232         return 0;
9233 }
9234
9235 const char *sexp_error_message(int num)
9236 {
9237         switch (num) {
9238                 case SEXP_CHECK_NONOP_ARGS:
9239                         return "Data shouldn't have arguments";
9240
9241                 case SEXP_CHECK_OP_EXPTECTED:
9242                         return "Operator expected instead of data";
9243
9244                 case SEXP_CHECK_UNKNOWN_OP:
9245                         return "Unrecognized operator";
9246
9247                 case SEXP_CHECK_TYPE_MISMATCH:
9248                         return "Argument type mismatch";
9249
9250                 case SEXP_CHECK_BAD_ARG_COUNT:
9251                         return "Argument count is illegal";
9252
9253                 case SEXP_CHECK_UNKNOWN_TYPE:
9254                         return "Unknown operator argument type";
9255
9256                 case SEXP_CHECK_INVALID_NUM:
9257                         return "Not a number";
9258
9259                 case SEXP_CHECK_INVALID_SHIP:
9260                         return "Invalid ship name";
9261
9262                 case SEXP_CHECK_INVALID_WING:
9263                         return "Invalid wing name";
9264
9265                 case SEXP_CHECK_INVALID_SUBSYS:
9266                         return "Invalid subsystem name";
9267
9268                 case SEXP_CHECK_INVALID_IFF:
9269                         return "Invalid team name";
9270
9271                 case SEXP_CHECK_INVALID_POINT:
9272                         return "Invalid point";
9273
9274                 case SEXP_CHECK_NEGATIVE_NUM:
9275                         return "Negative number not allowed";
9276
9277                 case SEXP_CHECK_INVALID_SHIP_WING:
9278                         return "Invalid ship/wing name";
9279
9280                 case SEXP_CHECK_INVALID_SHIP_TYPE:
9281                         return "Invalid ship type";
9282
9283                 case SEXP_CHECK_UNKNOWN_MESSAGE:
9284                         return "Invalid message name";
9285
9286                 case SEXP_CHECK_INVALID_PRIORITY:
9287                         return "Invalid priority";
9288
9289                 case SEXP_CHECK_INVALID_MISSION_NAME:
9290                         return "Invalid mission filename";
9291
9292                 case SEXP_CHECK_INVALID_GOAL_NAME:
9293                         return "Invalid goal name";
9294
9295                 case SEXP_CHECK_INVALID_LEVEL:
9296                         return "Mission level too low in tree";
9297
9298                 case SEXP_CHECK_INVALID_MSG_SOURCE:
9299                         return "Invalid message source";
9300
9301                 case SEXP_CHECK_INVALID_DOCKER_POINT:
9302                         return "Invalid docker point";
9303
9304                 case SEXP_CHECK_INVALID_DOCKEE_POINT:
9305                         return "Invalid dockee point";
9306
9307                 case SEXP_CHECK_ORDER_NOT_ALLOWED:
9308                         return "Ship not allowed to have this order";
9309
9310                 case SEXP_CHECK_DOCKING_NOT_ALLOWED:
9311                         return "Ship can't dock with target ship";
9312
9313                 case SEXP_CHECK_NUM_RANGE_INVALID:
9314                         return "Number is out of range";
9315
9316                 case SEXP_CHECK_INVALID_EVENT_NAME:
9317                         return "Event name is invalid (not known)";
9318
9319                 case SEXP_CHECK_INVALID_SKILL_LEVEL:
9320                         return "Skill level name is invalid (not known)";
9321
9322                 case SEXP_CHECK_INVALID_MEDAL_NAME:
9323                         return "Invalid medal name";
9324
9325                 case SEXP_CHECK_INVALID_WEAPON_NAME:
9326                         return "Invalid weapon name";
9327
9328                 case SEXP_CHECK_INVALID_SHIP_CLASS_NAME:
9329                         return "Invalid ship class name";
9330
9331                 case SEXP_CHECK_INVALID_GAUGE_NAME:
9332                         return "Invalid HUD gauges name";
9333
9334                 case SEXP_CHECK_INVALID_JUMP_NODE:
9335                         return "Invalid Jump Node name";
9336         }
9337
9338         SDL_snprintf(Sexp_error_text, SDL_arraysize(Sexp_error_text), "Sexp error code %d", num);
9339         return Sexp_error_text;
9340 }
9341
9342 int query_sexp_ai_goal_valid(int sexp_ai_goal, int ship)
9343 {
9344         int i, op;
9345
9346         for (op=0; op<Num_operators; op++)
9347                 if (Operators[op].value == sexp_ai_goal)
9348                         break;
9349
9350         SDL_assert(op < Num_operators);
9351         for (i=0; i<Num_sexp_ai_goal_links; i++)
9352                 if (Sexp_ai_goal_links[i].op_code == sexp_ai_goal)
9353                         break;
9354
9355         SDL_assert(i < Num_sexp_ai_goal_links);
9356         return ai_query_goal_valid(ship, Sexp_ai_goal_links[i].ai_goal);
9357 }
9358
9359 // Takes an Sexp_node.text pointing to a variable (of form "Sexp_variables[xx]=string" or "Sexp_variables[xx]=number")
9360 // and returns the index into the Sexp_variables array of the actual value 
9361 int extract_sexp_variable_index(int node)
9362 {
9363         char *text = Sexp_nodes[node].text;
9364         char char_index[8];
9365         char *start_index;
9366         int variable_index;
9367
9368         // get past the '['
9369         start_index = text + 15;
9370         SDL_assert(isdigit(*start_index));
9371
9372         int len = 0;
9373
9374         while ( *start_index != ']' ) {
9375                 char_index[len++] = *(start_index++);
9376                 SDL_assert(len < 3);
9377         }
9378
9379         SDL_assert(len > 0);
9380         char_index[len] = 0;    // append null termination to string
9381
9382         variable_index = atoi(char_index);
9383         SDL_assert( (variable_index >= 0) && (variable_index < MAX_SEXP_VARIABLES) );
9384
9385         return variable_index;
9386 }
9387
9388
9389 // wrapper around Sexp_node[xx].text for normal and variable
9390 char *CTEXT(int n)
9391 {
9392         if (Sexp_nodes[n].type & SEXP_FLAG_VARIABLE) {
9393                 int sexp_variable_index;
9394                 if (Fred_running) {
9395                         sexp_variable_index = get_index_sexp_variable_name(Sexp_nodes[n].text);
9396                         SDL_assert(sexp_variable_index != -1);
9397                 } else {
9398 //                      sexp_variable_index = extract_sexp_variable_index(n);
9399                         sexp_variable_index = atoi(Sexp_nodes[n].text);
9400                 }
9401                 // Reference a Sexp_variable
9402                 // string format -- "Sexp_variables[xx]=number" or "Sexp_variables[xx]=string", where xx is the index
9403
9404                 SDL_assert( !(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_NOT_USED) );
9405                 SDL_assert(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_SET);
9406
9407                 return Sexp_variables[sexp_variable_index].text;
9408         } else {
9409                 return Sexp_nodes[n].text;
9410         }
9411 }
9412
9413
9414 // Set all Sexp_variables to type uninitialized
9415 void init_sexp_vars()
9416 {
9417         for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
9418 //              if ( !(Sexp_nodes[i].type & SEXP_FLAG_PERSISTENT) )
9419 //                      Sexp_nodes[i].type = SEXP_NOT_USED;
9420                 Sexp_variables[i].type = SEXP_VARIABLE_NOT_USED;
9421         }
9422 }
9423
9424
9425 // Adds an Sexp_variable to be used in a mission.
9426 // This should be called from within mission parse.
9427 int sexp_add_variable(const char *text, const char *var_name, int type, int index)
9428 {
9429         // if index == -1, find next open slot
9430         if (index == -1) {
9431                 for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
9432                         if (Sexp_variables[i].type == SEXP_VARIABLE_NOT_USED) {
9433                                 index = i;
9434                                 break;
9435                         }
9436                 }
9437         } else {
9438                 SDL_assert( (index >= 0) && (index < MAX_SEXP_VARIABLES) );
9439         }
9440
9441         if (index >= 0) {
9442                 SDL_strlcpy(Sexp_variables[index].text, text, TOKEN_LENGTH);
9443                 SDL_strlcpy(Sexp_variables[index].variable_name, var_name, TOKEN_LENGTH);
9444                 Sexp_variables[index].type &= ~SEXP_VARIABLE_NOT_USED;
9445                 Sexp_variables[index].type = (type | SEXP_VARIABLE_SET);
9446         }
9447
9448         return index;
9449 }
9450
9451
9452 // Modifies and Sexp_variable to be used in a mission
9453 // This should be called in mission when an sexp_variable is to be modified
9454 void sexp_modify_variable(char *text, int index)
9455 {
9456         SDL_assert(index >= 0 && index < MAX_SEXP_VARIABLES);
9457         SDL_assert(Sexp_variables[index].type & SEXP_VARIABLE_SET);
9458         SDL_assert( !MULTIPLAYER_CLIENT );
9459
9460         SDL_strlcpy(Sexp_variables[index].text, text, TOKEN_LENGTH);
9461         Sexp_variables[index].type |= SEXP_VARIABLE_MODIFIED;
9462
9463         // do multi_callback_here
9464 }
9465
9466 void sexp_modify_variable(int n)
9467 {
9468         int sexp_variable_index;
9469         int new_number;
9470 //      char *new_char_var;
9471         char number_as_str[TOKEN_LENGTH];
9472
9473         // Only do single player of multi host
9474         if ( MULTIPLAYER_CLIENT ) {
9475                 return;
9476         }
9477
9478
9479         if (n != -1) {
9480                 // get sexp_variable index
9481                 SDL_assert(Sexp_nodes[n].first == -1);
9482                 sexp_variable_index = atoi(Sexp_nodes[n].text);
9483
9484                 // verify variable set
9485                 SDL_assert(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_SET);
9486
9487                 if (Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_NUMBER) {
9488                         // get new numerical value
9489                         new_number = eval_sexp(Sexp_nodes[n].rest);
9490
9491                         SDL_snprintf(number_as_str, SDL_arraysize(number_as_str), "%d", new_number);
9492                         sexp_modify_variable(number_as_str, sexp_variable_index);
9493                 } else {
9494                         // get new string
9495                         SDL_assert(Sexp_variables[sexp_variable_index].type & SEXP_VARIABLE_STRING);
9496
9497                         char *new_text = Sexp_nodes[Sexp_nodes[n].rest].text;
9498                         sexp_modify_variable(new_text, sexp_variable_index);
9499                 }
9500         }
9501 }
9502         
9503
9504
9505 // Different type needed for Fred (1) allow modification of type (2) no callback required
9506 void sexp_fred_modify_variable(const char *text, const char *var_name, int index, int type)
9507 {
9508         SDL_assert(index >= 0 && index < MAX_SEXP_VARIABLES);
9509         SDL_assert(Sexp_variables[index].type & SEXP_VARIABLE_SET);
9510         SDL_assert( (type & SEXP_VARIABLE_NUMBER) || (type & SEXP_VARIABLE_STRING) );
9511
9512         SDL_strlcpy(Sexp_variables[index].text, text, TOKEN_LENGTH);
9513         SDL_strlcpy(Sexp_variables[index].variable_name, var_name, TOKEN_LENGTH);
9514         Sexp_variables[index].type = (SEXP_VARIABLE_SET | SEXP_VARIABLE_MODIFIED | type);
9515 }
9516
9517 // return index of sexp_variable_name, -1 if not found
9518 int get_index_sexp_variable_name(const char* temp_name)
9519 {
9520         for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
9521                 if (Sexp_variables[i].type & SEXP_VARIABLE_SET) {
9522                         // check case sensitive
9523                         if ( !strcmp(Sexp_variables[i].variable_name, temp_name) ) {
9524                                 return i;
9525                         }
9526                 }
9527         }
9528
9529         // not found
9530         return -1;
9531 }
9532
9533
9534 // counts number of sexp_variables that are set
9535 int sexp_variable_count()
9536 {
9537         int count = 0;
9538
9539         for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
9540                 if ( (Sexp_variables[i].type & SEXP_VARIABLE_SET)  && !(Sexp_variables[i].type & SEXP_VARIABLE_BLOCK) ) {
9541                         count++;
9542                 }
9543         }
9544
9545         return count;
9546 }
9547
9548
9549 // deletes sexp_variable from active
9550 void sexp_variable_delete(int index)
9551 {
9552         SDL_assert(Sexp_variables[index].type & SEXP_VARIABLE_SET);
9553
9554         Sexp_variables[index].type = SEXP_VARIABLE_NOT_USED;
9555 }
9556
9557 int sexp_var_compare(const void *var1, const void *var2)
9558 {
9559         int set1, set2;
9560         sexp_variable *sexp_var1, *sexp_var2;
9561
9562         sexp_var1 = (sexp_variable*) var1;
9563         sexp_var2 = (sexp_variable*) var2;
9564
9565         set1 = sexp_var1->type & SEXP_VARIABLE_SET;
9566         set2 = sexp_var2->type & SEXP_VARIABLE_SET;
9567
9568         if (!set1 && !set2) {
9569                 return 0;
9570         } else if (set1 && !set2) {
9571                 return -1;
9572         } else if (!set1 && set2) {
9573                 return 1;
9574         } else {
9575                 return SDL_strcasecmp( sexp_var1->variable_name, sexp_var2->variable_name);
9576         }
9577 }
9578
9579 // Count number of variables in block
9580 int sexp_variable_block_count()
9581 {
9582         int count = 0;
9583         for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
9584                 if (Sexp_variables[i].type & SEXP_VARIABLE_BLOCK) {
9585                         count++;
9586                 }
9587         }
9588
9589         return count;
9590 }
9591
9592 // Sort sexp_variable list lexigraphically, with set before unset
9593 void sexp_variable_sort()
9594 {
9595         qsort( (void *)Sexp_variables, (size_t)(MAX_SEXP_VARIABLES - sexp_variable_block_count()), sizeof(sexp_variable), sexp_var_compare );
9596 }
9597
9598 int sexp_variable_allocate_block(const char* block_name, int block_type)
9599 {
9600         int num_blocks, block_count, var_count, start;
9601         block_count = sexp_variable_block_count();
9602         var_count = sexp_variable_count();
9603
9604         if (block_type & SEXP_VARIABLE_BLOCK_EXP) {
9605                 num_blocks = BLOCK_EXP_SIZE;
9606         } else {
9607                 Int3(); // add new block type here with size
9608                 return -1;
9609         }
9610
9611         if (block_count + var_count > (MAX_SEXP_VARIABLES - num_blocks)) {
9612                 // not enough free space
9613                 return -1;
9614         }
9615
9616         // squeeze all variables to front of array
9617         sexp_variable_sort();
9618
9619         // squeeze all block to end of array
9620         sexp_variable_condense_block();
9621
9622         start = MAX_SEXP_VARIABLES - block_count - num_blocks;
9623
9624         for (int idx=start; idx<start+num_blocks; idx++) {
9625                 SDL_assert(Sexp_variables[idx].type == SEXP_VARIABLE_NOT_USED);
9626                 Sexp_variables[idx].type = SEXP_VARIABLE_BLOCK | block_type;
9627                 SDL_strlcpy(Sexp_variables[idx].variable_name, block_name, TOKEN_LENGTH);
9628         }
9629
9630         return start;
9631 }
9632
9633 // squeeze all blocks to top of array
9634 void sexp_variable_condense_block()
9635 {
9636         int temp_idx, idx, var_count;
9637
9638         var_count = sexp_variable_count();
9639         temp_idx = MAX_SEXP_VARIABLES-1;
9640
9641         for (idx=MAX_SEXP_VARIABLES-1; idx>var_count-1; idx--) {
9642                 if (Sexp_variables[idx].type & SEXP_VARIABLE_BLOCK) {
9643                         if (temp_idx > idx) {
9644                                 Sexp_variables[temp_idx] = Sexp_variables[idx];
9645                                 Sexp_variables[idx].type = SEXP_VARIABLE_NOT_USED;
9646                         }
9647                         temp_idx--;
9648                 }
9649         }
9650 }
9651
9652
9653 void sexp_variable_block_free(const char *ship_name, int start_index, int block_type)
9654 {
9655         int num_blocks;
9656
9657         if (block_type & SEXP_VARIABLE_BLOCK_EXP) {
9658                 num_blocks = BLOCK_EXP_SIZE;
9659         } else {
9660                 Int3();  // new type of block
9661                 return;
9662         }
9663
9664         for (int i=start_index; i<(start_index + num_blocks); i++) {
9665                 SDL_assert(!SDL_strcasecmp(Sexp_variables[i].variable_name, ship_name));
9666
9667                 SDL_assert(Sexp_variables[i].type & block_type);
9668
9669                 Sexp_variables[i].type = SEXP_VARIABLE_NOT_USED;
9670         }
9671
9672         sexp_variable_condense_block();
9673 }
9674
9675 // evaluate number which may result from an operator or may be text
9676 // only useful for first operand
9677 int num_eval(int node)
9678 {
9679         if ( CAR(node) != -1 ) {
9680                 return eval_sexp(CAR(node));
9681         } else {
9682                 return atoi(CTEXT(node));
9683         }
9684 }
9685
9686