]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned.cxx
1baf07d0463407fa478f8c73d860d99c246d5922
[flightgear.git] / src / Scripting / NasalPositioned.cxx
1 // NasalPositioned.cxx -- expose FGPositioned classes to Nasal
2 //
3 // Written by James Turner, started 2012.
4 //
5 // Copyright (C) 2012 James Turner
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 #include <string.h>
26
27 #include "NasalPositioned.hxx"
28
29 #include <boost/foreach.hpp>
30 #include <boost/algorithm/string/case_conv.hpp>
31
32 #include <simgear/sg_inlines.h>
33 #include <simgear/scene/material/mat.hxx>
34 #include <simgear/magvar/magvar.hxx>
35 #include <simgear/timing/sg_time.hxx>
36 #include <simgear/bucket/newbucket.hxx>
37
38 #include <Airports/runways.hxx>
39 #include <Airports/simple.hxx>
40 #include <Airports/dynamics.hxx>
41 #include <Airports/parking.hxx>
42 #include <Scripting/NasalSys.hxx>
43 #include <Navaids/navlist.hxx>
44 #include <Navaids/procedure.hxx>
45 #include <Main/globals.hxx>
46 #include <Main/fg_props.hxx>
47 #include <Scenery/scenery.hxx>
48 #include <ATC/CommStation.hxx>
49 #include <Navaids/FlightPlan.hxx>
50 #include <Navaids/waypoint.hxx>
51 #include <Navaids/fix.hxx>
52 #include <Autopilot/route_mgr.hxx>
53 #include <Navaids/procedure.hxx>
54 #include <Navaids/airways.hxx>
55
56 using namespace flightgear;
57
58 static void positionedGhostDestroy(void* g);
59 static void wayptGhostDestroy(void* g);
60 static void legGhostDestroy(void* g);
61 static void routeBaseGhostDestroy(void* g);
62
63 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
64
65 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
66 naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, 0 };
67
68 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
69 naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, 0 };
70
71 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out);
72 naGhostType RunwayGhostType = { positionedGhostDestroy, "runway", runwayGhostGetMember, 0 };
73
74 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out);
75 naGhostType FixGhostType = { positionedGhostDestroy, "fix", fixGhostGetMember, 0 };
76
77 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out);
78 naGhostType WayptGhostType = { wayptGhostDestroy, 
79   "waypoint",
80   wayptGhostGetMember,
81   0};
82
83 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out);
84 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value);
85
86 naGhostType FPLegGhostType = { legGhostDestroy, 
87   "flightplan-leg",
88   legGhostGetMember,
89   legGhostSetMember};
90
91 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out);
92 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value);
93
94 naGhostType FlightPlanGhostType = { routeBaseGhostDestroy, 
95   "flightplan",
96   flightplanGhostGetMember,
97   flightplanGhostSetMember
98 };
99
100 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out);
101 naGhostType ProcedureGhostType = { routeBaseGhostDestroy, 
102   "procedure",
103   procedureGhostGetMember,
104   0};
105
106 static void hashset(naContext c, naRef hash, const char* key, naRef val)
107 {
108   naRef s = naNewString(c);
109   naStr_fromdata(s, (char*)key, strlen(key));
110   naHash_set(hash, s, val);
111 }
112
113 static naRef stringToNasal(naContext c, const std::string& s)
114 {
115     return naStr_fromdata(naNewString(c),
116                    const_cast<char *>(s.c_str()), 
117                    s.length());
118 }
119
120 static WayptFlag wayptFlagFromString(const char* s)
121 {
122   if (!strcmp(s, "sid")) return WPT_DEPARTURE;
123   if (!strcmp(s, "star")) return WPT_ARRIVAL;
124   if (!strcmp(s, "approach")) return WPT_APPROACH;
125   if (!strcmp(s, "missed")) return WPT_MISS;
126   if (!strcmp(s, "pseudo")) return WPT_PSEUDO;
127   
128   return (WayptFlag) 0;
129 }
130
131 static naRef wayptFlagToNasal(naContext c, unsigned int flags)
132 {
133   if (flags & WPT_PSEUDO) return stringToNasal(c, "pseudo");
134   if (flags & WPT_DEPARTURE) return stringToNasal(c, "sid");
135   if (flags & WPT_ARRIVAL) return stringToNasal(c, "star");
136   if (flags & WPT_MISS) return stringToNasal(c, "missed");
137   if (flags & WPT_APPROACH) return stringToNasal(c, "approach");
138   return naNil();
139 }
140
141 static FGPositioned* positionedGhost(naRef r)
142 {
143     if ((naGhost_type(r) == &AirportGhostType) ||
144         (naGhost_type(r) == &NavaidGhostType) ||
145         (naGhost_type(r) == &RunwayGhostType) ||
146         (naGhost_type(r) == &FixGhostType))
147     {
148         return (FGPositioned*) naGhost_ptr(r);
149     }
150   
151     return 0;
152 }
153
154 static FGAirport* airportGhost(naRef r)
155 {
156   if (naGhost_type(r) == &AirportGhostType)
157     return (FGAirport*) naGhost_ptr(r);
158   return 0;
159 }
160
161 static FGNavRecord* navaidGhost(naRef r)
162 {
163   if (naGhost_type(r) == &NavaidGhostType)
164     return (FGNavRecord*) naGhost_ptr(r);
165   return 0;
166 }
167
168 static FGRunway* runwayGhost(naRef r)
169 {
170   if (naGhost_type(r) == &RunwayGhostType)
171     return (FGRunway*) naGhost_ptr(r);
172   return 0;
173 }
174
175 static FGFix* fixGhost(naRef r)
176 {
177   if (naGhost_type(r) == &FixGhostType)
178     return (FGFix*) naGhost_ptr(r);
179   return 0;
180 }
181
182
183 static void positionedGhostDestroy(void* g)
184 {
185     FGPositioned* pos = (FGPositioned*)g;
186     if (!FGPositioned::put(pos)) // unref
187         delete pos;
188 }
189
190 static Waypt* wayptGhost(naRef r)
191 {
192   if (naGhost_type(r) == &WayptGhostType)
193     return (Waypt*) naGhost_ptr(r);
194   
195   if (naGhost_type(r) == &FPLegGhostType) {
196     FlightPlan::Leg* leg = (FlightPlan::Leg*) naGhost_ptr(r);
197     return leg->waypoint();
198   }
199   
200   return 0;
201 }
202
203 static void wayptGhostDestroy(void* g)
204 {
205   Waypt* wpt = (Waypt*)g;
206   if (!Waypt::put(wpt)) // unref
207     delete wpt;
208 }
209
210 static void legGhostDestroy(void* g)
211 {
212   // nothing for now
213 }
214
215
216 static FlightPlan::Leg* fpLegGhost(naRef r)
217 {
218   if (naGhost_type(r) == &FPLegGhostType)
219     return (FlightPlan::Leg*) naGhost_ptr(r);
220   return 0;
221 }
222
223 static Procedure* procedureGhost(naRef r)
224 {
225   if (naGhost_type(r) == &ProcedureGhostType)
226     return (Procedure*) naGhost_ptr(r);
227   return 0;
228 }
229
230 static FlightPlan* flightplanGhost(naRef r)
231 {
232   if (naGhost_type(r) == &FlightPlanGhostType)
233     return (FlightPlan*) naGhost_ptr(r);
234   return 0;
235 }
236
237 static void routeBaseGhostDestroy(void* g)
238 {
239   // nothing for now
240 }
241
242 static naRef airportPrototype;
243 static naRef flightplanPrototype;
244 static naRef waypointPrototype;
245 static naRef geoCoordClass;
246 static naRef fpLegPrototype;
247 static naRef procedurePrototype;
248
249 naRef ghostForAirport(naContext c, const FGAirport* apt)
250 {
251   if (!apt) {
252     return naNil();
253   }
254   
255   FGPositioned::get(apt); // take a ref
256   return naNewGhost2(c, &AirportGhostType, (void*) apt);
257 }
258
259 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
260 {
261   if (!n) {
262     return naNil();
263   }
264   
265   FGPositioned::get(n); // take a ref
266   return naNewGhost2(c, &NavaidGhostType, (void*) n);
267 }
268
269 naRef ghostForRunway(naContext c, const FGRunway* r)
270 {
271   if (!r) {
272     return naNil();
273   }
274   
275   FGPositioned::get(r); // take a ref
276   return naNewGhost2(c, &RunwayGhostType, (void*) r);
277 }
278
279 naRef ghostForFix(naContext c, const FGFix* r)
280 {
281   if (!r) {
282     return naNil();
283   }
284   
285   FGPositioned::get(r); // take a ref
286   return naNewGhost2(c, &FixGhostType, (void*) r);
287 }
288
289
290 naRef ghostForWaypt(naContext c, const Waypt* wpt)
291 {
292   if (!wpt) {
293     return naNil();
294   }
295   
296   Waypt::get(wpt); // take a ref
297   return naNewGhost2(c, &WayptGhostType, (void*) wpt);
298 }
299
300 naRef ghostForLeg(naContext c, const FlightPlan::Leg* leg)
301 {
302   if (!leg) {
303     return naNil();
304   }
305   
306   return naNewGhost2(c, &FPLegGhostType, (void*) leg);
307 }
308
309 naRef ghostForFlightPlan(naContext c, const FlightPlan* fp)
310 {
311   if (!fp) {
312     return naNil();
313   }
314   
315   return naNewGhost2(c, &FlightPlanGhostType, (void*) fp);
316 }
317
318 naRef ghostForProcedure(naContext c, const Procedure* proc)
319 {
320   if (!proc) {
321     return naNil();
322   }
323   
324   return naNewGhost2(c, &ProcedureGhostType, (void*) proc);
325 }
326
327 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
328 {
329   const char* fieldName = naStr_data(field);
330   FGAirport* apt = (FGAirport*) g;
331   
332   if (!strcmp(fieldName, "parents")) {
333     *out = naNewVector(c);
334     naVec_append(*out, airportPrototype);
335   } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, apt->ident());
336   else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, apt->name());
337   else if (!strcmp(fieldName, "lat")) *out = naNum(apt->getLatitude());
338   else if (!strcmp(fieldName, "lon")) *out = naNum(apt->getLongitude());
339   else if (!strcmp(fieldName, "elevation")) {
340     *out = naNum(apt->getElevation() * SG_FEET_TO_METER);
341   } else if (!strcmp(fieldName, "has_metar")) {
342     *out = naNum(apt->getMetar());
343   } else if (!strcmp(fieldName, "runways")) {
344     *out = naNewHash(c);
345     for(unsigned int r=0; r<apt->numRunways(); ++r) {
346       FGRunway* rwy(apt->getRunwayByIndex(r));
347       naRef rwyid = stringToNasal(c, rwy->ident());
348       naRef rwydata = ghostForRunway(c, rwy);
349       naHash_set(*out, rwyid, rwydata);
350     }
351
352   } else {
353     return 0;
354   }
355   
356   return "";
357 }
358
359 static const char* waypointCommonGetMember(naContext c, Waypt* wpt, const char* fieldName, naRef* out)
360 {
361   if (!strcmp(fieldName, "wp_name")) *out = stringToNasal(c, wpt->ident());
362   else if (!strcmp(fieldName, "wp_type")) *out = stringToNasal(c, wpt->type());
363   else if (!strcmp(fieldName, "wp_role")) *out = wayptFlagToNasal(c, wpt->flags());
364   else if (!strcmp(fieldName, "wp_lat")) *out = naNum(wpt->position().getLatitudeDeg());
365   else if (!strcmp(fieldName, "wp_lon")) *out = naNum(wpt->position().getLongitudeDeg());
366   else if (!strcmp(fieldName, "wp_parent_name")) {
367     Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
368     *out = proc ? stringToNasal(c, proc->ident()) : naNil();
369   } else if (!strcmp(fieldName, "wp_parent")) {
370     Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
371     *out = ghostForProcedure(c, proc);
372   } else if (!strcmp(fieldName, "fly_type")) {
373     if (wpt->type() == "hold") {
374       *out = stringToNasal(c, "Hold");
375     } else {
376       *out = stringToNasal(c, wpt->flag(WPT_OVERFLIGHT) ? "flyOver" : "flyBy");
377     }
378   } else {
379     return NULL; // member not found
380   }
381
382   return "";
383 }
384
385 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
386 {
387   const char* fieldName = naStr_data(field);
388   Waypt* wpt = (flightgear::Waypt*) g;
389   return waypointCommonGetMember(c, wpt, fieldName, out);
390 }
391
392 static RouteRestriction routeRestrictionFromString(const char* s)
393 {
394   string u(s);
395   boost::to_lower(u);
396   if (u == "computed") return RESTRICT_COMPUTED;
397   if (u == "at") return RESTRICT_AT;
398   if (u == "mach") return SPEED_RESTRICT_MACH;
399   if (u == "computed-mach") return SPEED_COMPUTED_MACH;
400   if (u == "delete") return RESTRICT_DELETE;
401   return RESTRICT_NONE;
402 };
403
404 naRef routeRestrictionToNasal(naContext c, RouteRestriction rr)
405 {
406   switch (rr) {
407     case RESTRICT_NONE: return naNil();
408     case RESTRICT_AT: return stringToNasal(c, "at");
409     case RESTRICT_ABOVE: return stringToNasal(c, "above");
410     case RESTRICT_BELOW: return stringToNasal(c, "below");
411     case SPEED_RESTRICT_MACH: return stringToNasal(c, "mach");
412     case RESTRICT_COMPUTED: return stringToNasal(c, "computed");
413     case SPEED_COMPUTED_MACH: return stringToNasal(c, "computed-mach");
414     case RESTRICT_DELETE: return stringToNasal(c, "delete");
415   }
416   
417   return naNil();
418 }
419
420 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out)
421 {
422   const char* fieldName = naStr_data(field);
423   FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
424   Waypt* wpt = leg->waypoint();
425   
426   if (!strcmp(fieldName, "parents")) {
427     *out = naNewVector(c);
428     naVec_append(*out, fpLegPrototype);
429   } else if (!strcmp(fieldName, "index")) {
430     *out = naNum(leg->index());
431   } else if (!strcmp(fieldName, "alt_cstr")) {
432     *out = naNum(leg->altitudeFt());
433   } else if (!strcmp(fieldName, "alt_cstr_type")) {
434     *out = routeRestrictionToNasal(c, leg->altitudeRestriction());
435   } else if (!strcmp(fieldName, "speed_cstr")) {
436     double s = isMachRestrict(leg->speedRestriction()) ? leg->speedMach() : leg->speedKts();
437     *out = naNum(s);
438   } else if (!strcmp(fieldName, "speed_cstr_type")) {
439     *out = routeRestrictionToNasal(c, leg->speedRestriction());  
440   } else if (!strcmp(fieldName, "leg_distance")) {
441     *out = naNum(leg->distanceNm());
442   } else if (!strcmp(fieldName, "leg_bearing")) {
443     *out = naNum(leg->courseDeg());
444   } else if (!strcmp(fieldName, "distance_along_route")) {
445     *out = naNum(leg->distanceAlongRoute());
446   } else { // check for fields defined on the underlying waypoint
447     return waypointCommonGetMember(c, wpt, fieldName, out);
448   }
449   
450   return ""; // success
451 }
452
453 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value)
454 {
455   const char* fieldName = naStr_data(field);
456   FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
457   
458   if (!strcmp(fieldName, "wp_role")) {
459     if (!naIsString(value)) naRuntimeError(c, "wp_role must be a string");
460     if (leg->waypoint()->owner() != NULL) naRuntimeError(c, "cannot override wp_role on waypoint with parent");
461     WayptFlag f = wayptFlagFromString(naStr_data(value));
462     if (f == 0) {
463       naRuntimeError(c, "unrecognized wp_role value %s", naStr_data(value));
464     }
465     
466     leg->waypoint()->setFlag(f, true);
467   }
468 }
469
470 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out)
471 {
472   const char* fieldName = naStr_data(field);
473   FlightPlan* fp = (FlightPlan*) g;
474   
475   if (!strcmp(fieldName, "parents")) {
476     *out = naNewVector(c);
477     naVec_append(*out, flightplanPrototype);
478   } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fp->ident());
479   else if (!strcmp(fieldName, "departure")) *out = ghostForAirport(c, fp->departureAirport());
480   else if (!strcmp(fieldName, "destination")) *out = ghostForAirport(c, fp->destinationAirport());
481   else if (!strcmp(fieldName, "departure_runway")) *out = ghostForRunway(c, fp->departureRunway());
482   else if (!strcmp(fieldName, "destination_runway")) *out = ghostForRunway(c, fp->destinationRunway());
483   else if (!strcmp(fieldName, "sid")) *out = ghostForProcedure(c, fp->sid());
484   else if (!strcmp(fieldName, "sid_trans")) *out = ghostForProcedure(c, fp->sidTransition());
485   else if (!strcmp(fieldName, "star")) *out = ghostForProcedure(c, fp->star());
486   else if (!strcmp(fieldName, "star_trans")) *out = ghostForProcedure(c, fp->starTransition());
487   else if (!strcmp(fieldName, "approach")) *out = ghostForProcedure(c, fp->approach());
488   else if (!strcmp(fieldName, "current")) *out = naNum(fp->currentIndex());
489   else {
490     return 0;
491   }
492   
493   return "";
494 }
495
496 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value)
497 {
498   const char* fieldName = naStr_data(field);
499   FlightPlan* fp = (FlightPlan*) g;
500   
501   if (!strcmp(fieldName, "id")) {
502     if (!naIsString(value)) naRuntimeError(c, "flightplan.id must be a string");
503     fp->setIdent(naStr_data(value));
504   } else if (!strcmp(fieldName, "current")) {
505     int index = value.num;
506     if ((index < 0) || (index >= fp->numLegs())) {
507       return;
508     }
509     fp->setCurrentIndex(index);
510   } else if (!strcmp(fieldName, "departure")) {
511     FGAirport* apt = airportGhost(value);
512     if (apt) {
513       fp->setDeparture(apt);
514       return;
515     }
516     
517     FGRunway* rwy = runwayGhost(value);
518     if (rwy){
519       fp->setDeparture(rwy);
520       return;
521     }
522     
523     naRuntimeError(c, "bad argument type setting departure");
524   } else if (!strcmp(fieldName, "destination")) {
525     FGAirport* apt = airportGhost(value);
526     if (apt) {
527       fp->setDestination(apt);
528       return;
529     }
530     
531     FGRunway* rwy = runwayGhost(value);
532     if (rwy){
533       fp->setDestination(rwy);
534       return;
535     }
536     
537     naRuntimeError(c, "bad argument type setting destination");
538   } else if (!strcmp(fieldName, "departure_runway")) {
539     FGRunway* rwy = runwayGhost(value);
540     if (rwy){
541       fp->setDeparture(rwy);
542       return;
543     }
544     
545     naRuntimeError(c, "bad argument type setting departure");
546   } else if (!strcmp(fieldName, "destination_runway")) {
547     FGRunway* rwy = runwayGhost(value);
548     if (rwy){
549       fp->setDestination(rwy);
550       return;
551     }
552     
553     naRuntimeError(c, "bad argument type setting departure");
554   } else if (!strcmp(fieldName, "sid")) {
555     Procedure* proc = procedureGhost(value);
556     if (proc && (proc->type() == PROCEDURE_SID)) {
557       fp->setSID((flightgear::SID*) proc);
558       return;
559     }
560     // allow a SID transition to be set, implicitly include the SID itself
561     if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
562       fp->setSID((Transition*) proc);
563       return;
564     }
565         
566     if (naIsString(value)) {
567       FGAirport* apt = fp->departureAirport();
568       fp->setSID(apt->findSIDWithIdent(naStr_data(value)));
569       return;
570     }
571     
572     naRuntimeError(c, "bad argument type setting SID");
573   } else if (!strcmp(fieldName, "star")) {
574     Procedure* proc = procedureGhost(value);
575     if (proc && (proc->type() == PROCEDURE_STAR)) {
576       fp->setSTAR((STAR*) proc);
577       return;
578     }
579     
580     if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
581       fp->setSTAR((Transition*) proc);
582       return;
583     }
584     
585     if (naIsString(value)) {
586       FGAirport* apt = fp->destinationAirport();
587       fp->setSTAR(apt->findSTARWithIdent(naStr_data(value)));
588       return;
589     }
590     
591     naRuntimeError(c, "bad argument type setting STAR");
592   } else if (!strcmp(fieldName, "approach")) {
593     Procedure* proc = procedureGhost(value);
594     if (proc && Approach::isApproach(proc->type())) {
595       fp->setApproach((Approach*) proc);
596       return;
597     }
598     
599     if (naIsString(value)) {
600       FGAirport* apt = fp->destinationAirport();
601       fp->setApproach(apt->findApproachWithIdent(naStr_data(value)));
602       return;
603     }
604     
605     naRuntimeError(c, "bad argument type setting approach");
606   }
607 }
608
609
610 static naRef procedureTpType(naContext c, ProcedureType ty)
611 {
612   switch (ty) {
613     case PROCEDURE_SID: return stringToNasal(c, "sid");
614     case PROCEDURE_STAR: return stringToNasal(c, "star");
615     case PROCEDURE_APPROACH_VOR: 
616     case PROCEDURE_APPROACH_ILS: 
617     case PROCEDURE_APPROACH_RNAV: 
618     case PROCEDURE_APPROACH_NDB:
619       return stringToNasal(c, "IAP");
620     default:
621       return naNil();
622   }
623 }
624
625 static naRef procedureRadioType(naContext c, ProcedureType ty)
626 {
627   switch (ty) {
628     case PROCEDURE_APPROACH_VOR: return stringToNasal(c, "VOR");
629     case PROCEDURE_APPROACH_ILS: return stringToNasal(c, "ILS");
630     case PROCEDURE_APPROACH_RNAV: return stringToNasal(c, "RNAV");
631     case PROCEDURE_APPROACH_NDB: return stringToNasal(c, "NDB");
632     default:
633       return naNil();
634   }
635 }
636
637 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out)
638 {
639   const char* fieldName = naStr_data(field);
640   Procedure* proc = (Procedure*) g;
641   
642   if (!strcmp(fieldName, "parents")) {
643     *out = naNewVector(c);
644     naVec_append(*out, procedurePrototype);
645   } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, proc->ident());
646   else if (!strcmp(fieldName, "airport")) *out = ghostForAirport(c, proc->airport());
647   else if (!strcmp(fieldName, "tp_type")) *out = procedureTpType(c, proc->type());
648   else if (!strcmp(fieldName, "radio")) *out = procedureRadioType(c, proc->type());
649   else if (!strcmp(fieldName, "runways")) {
650     *out = naNewVector(c);
651     BOOST_FOREACH(FGRunwayPtr rwy, proc->runways()) {
652       naVec_append(*out, stringToNasal(c, rwy->ident()));
653     }
654   } else if (!strcmp(fieldName, "transitions")) {
655     if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
656       *out = naNil();
657       return "";
658     }
659         
660     ArrivalDeparture* ad = static_cast<ArrivalDeparture*>(proc);
661     *out = naNewVector(c);
662     BOOST_FOREACH(string id, ad->transitionIdents()) {
663       naVec_append(*out, stringToNasal(c, id));
664     }
665   } else {
666     return 0;
667   }
668   
669   return "";
670 }
671
672 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
673 {
674   const char* fieldName = naStr_data(field);
675   FGRunway* rwy = (FGRunway*) g;
676   
677   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, rwy->ident());
678   else if (!strcmp(fieldName, "lat")) *out = naNum(rwy->latitude());
679   else if (!strcmp(fieldName, "lon")) *out = naNum(rwy->longitude());
680   else if (!strcmp(fieldName, "heading")) *out = naNum(rwy->headingDeg());
681   else if (!strcmp(fieldName, "length")) *out = naNum(rwy->lengthM());
682   else if (!strcmp(fieldName, "width")) *out = naNum(rwy->widthM());
683   else if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
684   else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
685   else if (!strcmp(fieldName, "ils_frequency_mhz")) {
686     *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
687   } else if (!strcmp(fieldName, "ils")) {
688     *out = ghostForNavaid(c, rwy->ILS());
689   } else {
690     return 0;
691   }
692   
693   return "";
694 }
695
696 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
697 {
698   const char* fieldName = naStr_data(field);
699   FGNavRecord* nav = (FGNavRecord*) g;
700   
701   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
702   else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
703   else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
704   else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
705   else if (!strcmp(fieldName, "elevation")) {
706     *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
707   } else if (!strcmp(fieldName, "type")) {
708     *out = stringToNasal(c, nav->nameForType(nav->type()));
709   } else if (!strcmp(fieldName, "frequency")) {
710     *out = naNum(nav->get_freq()); 
711   } else if (!strcmp(fieldName, "range_nm")) {
712     *out = naNum(nav->get_range()); 
713   } else if (!strcmp(fieldName, "course")) {
714     if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
715       double radial = nav->get_multiuse();
716       SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
717       *out = naNum(radial);
718     } else {
719       *out = naNil();
720     }
721   } else {
722     return 0;
723   }
724   
725   return "";
726 }
727
728 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out)
729 {
730   const char* fieldName = naStr_data(field);
731   FGFix* fix = (FGFix*) g;
732   
733   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fix->ident());
734   else if (!strcmp(fieldName, "lat")) *out = naNum(fix->get_lat());
735   else if (!strcmp(fieldName, "lon")) *out = naNum(fix->get_lon());
736   else {
737     return 0;
738   }
739   
740   return "";
741 }
742
743 static bool hashIsCoord(naRef h)
744 {
745   naRef parents = naHash_cget(h, (char*) "parents");
746   if (!naIsVector(parents)) {
747     return false;
748   }
749   
750   return naEqual(naVec_get(parents, 0), geoCoordClass);
751 }
752
753 bool geodFromHash(naRef ref, SGGeod& result)
754 {
755   if (!naIsHash(ref)) {
756     return false;
757   }
758
759   
760 // check for manual latitude / longitude names
761   naRef lat = naHash_cget(ref, (char*) "lat");
762   naRef lon = naHash_cget(ref, (char*) "lon");
763   if (naIsNum(lat) && naIsNum(lon)) {
764     result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
765     return true;
766   }
767   
768   if (hashIsCoord(ref)) {
769     naRef lat = naHash_cget(ref, (char*) "_lat");
770     naRef lon = naHash_cget(ref, (char*) "_lon");
771     if (naIsNum(lat) && naIsNum(lon)) {
772       result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
773       return true;
774     }
775   }
776     
777 // check for any synonyms?
778     // latitude + longitude?
779   
780   return false;
781 }
782
783 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
784 {
785   if (offset >= argc) {
786     return 0;
787   }
788   
789   if (naIsGhost(args[offset])) {
790     naGhostType* gt = naGhost_type(args[offset]);
791     if (gt == &AirportGhostType) {
792       result = airportGhost(args[offset])->geod();
793       return 1;
794     }
795     
796     if (gt == &NavaidGhostType) {
797       result = navaidGhost(args[offset])->geod();
798       return 1;
799     }
800     
801     if (gt == &RunwayGhostType) {
802       result = runwayGhost(args[offset])->geod();
803       return 1;
804     }
805     
806     if (gt == &FixGhostType) {
807       result = fixGhost(args[offset])->geod();
808       return 1;
809     }
810     
811     if (gt == &WayptGhostType) {
812       result = wayptGhost(args[offset])->position();
813       return 1;
814     }
815   }
816   
817   if (geodFromHash(args[offset], result)) {
818     return 1;
819   }
820   
821   if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
822     double lat = naNumValue(args[0]).num,
823     lon = naNumValue(args[1]).num;
824     result = SGGeod::fromDeg(lon, lat);
825     return 2;
826   }
827   
828   return 0;
829 }
830
831 // Convert a cartesian point to a geodetic lat/lon/altitude.
832 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
833 {
834   double lat, lon, alt, xyz[3];
835   if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
836   for(int i=0; i<3; i++)
837     xyz[i] = naNumValue(args[i]).num;
838   sgCartToGeod(xyz, &lat, &lon, &alt);
839   lat *= SG_RADIANS_TO_DEGREES;
840   lon *= SG_RADIANS_TO_DEGREES;
841   naRef vec = naNewVector(c);
842   naVec_append(vec, naNum(lat));
843   naVec_append(vec, naNum(lon));
844   naVec_append(vec, naNum(alt));
845   return vec;
846 }
847
848 // Convert a geodetic lat/lon/altitude to a cartesian point.
849 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
850 {
851   if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
852   double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
853   double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
854   double alt = naNumValue(args[2]).num;
855   double xyz[3];
856   sgGeodToCart(lat, lon, alt, xyz);
857   naRef vec = naNewVector(c);
858   naVec_append(vec, naNum(xyz[0]));
859   naVec_append(vec, naNum(xyz[1]));
860   naVec_append(vec, naNum(xyz[2]));
861   return vec;
862 }
863
864 // For given geodetic point return array with elevation, and a material data
865 // hash, or nil if there's no information available (tile not loaded). If
866 // information about the material isn't available, then nil is returned instead
867 // of the hash.
868 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
869 {
870 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
871   if(argc < 2 || argc > 3)
872     naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
873   double lat = naNumValue(args[0]).num;
874   double lon = naNumValue(args[1]).num;
875   double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
876   const SGMaterial *mat;
877   SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
878   if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
879     return naNil();
880   naRef vec = naNewVector(c);
881   naVec_append(vec, naNum(elev));
882   naRef matdata = naNil();
883   if(mat) {
884     matdata = naNewHash(c);
885     naRef names = naNewVector(c);
886     BOOST_FOREACH(const std::string& n, mat->get_names())
887       naVec_append(names, stringToNasal(c, n));
888       
889     HASHSET("names", 5, names);
890     HASHSET("solid", 5, naNum(mat->get_solid()));
891     HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
892     HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
893     HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
894     HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
895     HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
896   }
897   naVec_append(vec, matdata);
898   return vec;
899 #undef HASHSET
900 }
901
902
903 class AirportInfoFilter : public FGAirport::AirportFilter
904 {
905 public:
906   AirportInfoFilter() : type(FGPositioned::AIRPORT) {
907   }
908   
909   bool fromArg(naRef arg)
910   {
911     const char *s = naStr_data(arg);
912     if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
913     else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
914     else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
915     else
916       return false;
917     
918     return true;
919   }
920   
921   virtual FGPositioned::Type minType() const {
922     return type;
923   }
924   
925   virtual FGPositioned::Type maxType() const {
926     return type;
927   }
928   
929   FGPositioned::Type type;
930 };
931
932 // Returns data hash for particular or nearest airport of a <type>, or nil
933 // on error.
934 //
935 // airportinfo(<id>);                   e.g. "KSFO"
936 // airportinfo(<type>);                 type := ("airport"|"seaport"|"heliport")
937 // airportinfo()                        same as  airportinfo("airport")
938 // airportinfo(<lat>, <lon> [, <type>]);
939 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
940 {
941   SGGeod pos = globals->get_aircraft_position();
942   FGAirport* apt = NULL;
943   
944   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
945     pos = SGGeod::fromDeg(args[1].num, args[0].num);
946     args += 2;
947     argc -= 2;
948   }
949   
950   double maxRange = 10000.0; // expose this? or pick a smaller value?
951   
952   AirportInfoFilter filter; // defaults to airports only
953   
954   if(argc == 0) {
955     // fall through and use AIRPORT
956   } else if(argc == 1 && naIsString(args[0])) {
957     if (filter.fromArg(args[0])) {
958       // done!
959     } else {
960       // user provided an <id>, hopefully
961       apt = FGAirport::findByIdent(naStr_data(args[0]));
962       if (!apt) {
963         // return nil here, but don't raise a runtime error; this is a
964         // legitamate way to validate an ICAO code, for example in a
965         // dialog box or similar.
966         return naNil();
967       }
968     }
969   } else {
970     naRuntimeError(c, "airportinfo() with invalid function arguments");
971     return naNil();
972   }
973   
974   if(!apt) {
975     apt = FGAirport::findClosest(pos, maxRange, &filter);
976     if(!apt) return naNil();
977   }
978   
979   return ghostForAirport(c, apt);
980 }
981
982 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
983 {
984   int argOffset = 0;
985   SGGeod pos = globals->get_aircraft_position();
986   argOffset += geodFromArgs(args, 0, argc, pos);
987   
988   if (!naIsNum(args[argOffset])) {
989     naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
990   }
991   
992   AirportInfoFilter filter; // defaults to airports only
993   double rangeNm = args[argOffset++].num;
994   if (argOffset < argc) {
995     filter.fromArg(args[argOffset++]);
996   }
997   
998   naRef r = naNewVector(c);
999   
1000   FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1001   FGPositioned::sortByRange(apts, pos);
1002   
1003   BOOST_FOREACH(FGPositionedRef a, apts) {
1004     FGAirport* apt = (FGAirport*) a.get();
1005     naVec_append(r, ghostForAirport(c, apt));
1006   }
1007   
1008   return r;
1009 }
1010
1011 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
1012 {
1013   if (!naIsString(args[0])) {
1014     naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
1015   }
1016   
1017   int argOffset = 0;
1018   string prefix(naStr_data(args[argOffset++]));
1019   AirportInfoFilter filter; // defaults to airports only
1020   if (argOffset < argc) {
1021     filter.fromArg(args[argOffset++]);
1022   }
1023   
1024   naRef r = naNewVector(c);
1025   
1026   FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
1027   
1028   BOOST_FOREACH(FGPositionedRef a, apts) {
1029     FGAirport* apt = (FGAirport*) a.get();
1030     naVec_append(r, ghostForAirport(c, apt));
1031   }
1032   
1033   return r;
1034 }
1035
1036 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
1037 {
1038     FGAirport* apt = airportGhost(me);
1039     if (!apt) {
1040       naRuntimeError(c, "airport.tower called on non-airport object");
1041     }
1042   
1043     // build a hash for the tower position    
1044     SGGeod towerLoc = apt->getTowerLocation();
1045     naRef tower = naNewHash(c);
1046     hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
1047     hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
1048     hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
1049     return tower;
1050 }
1051
1052 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
1053 {
1054     FGAirport* apt = airportGhost(me);
1055     if (!apt) {
1056       naRuntimeError(c, "airport.comms called on non-airport object");
1057     }
1058     naRef comms = naNewVector(c);
1059     
1060 // if we have an explicit type, return a simple vector of frequencies
1061     if (argc > 0 && naIsScalar(args[0])) {
1062         std::string commName = naStr_data(args[0]);
1063         FGPositioned::Type commType = FGPositioned::typeFromName(commName);
1064         
1065         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
1066             naVec_append(comms, naNum(comm->freqMHz()));
1067         }
1068     } else {
1069 // otherwise return a vector of hashes, one for each comm station.
1070         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
1071             naRef commHash = naNewHash(c);
1072             hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
1073             hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
1074             naVec_append(comms, commHash);
1075         }
1076     }
1077     
1078     return comms;
1079 }
1080
1081 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
1082 {
1083   FGAirport* apt = airportGhost(me);
1084   if (!apt) {
1085     naRuntimeError(c, "airport.runway called on non-airport object");
1086   }
1087   
1088   if ((argc < 1) || !naIsString(args[0])) {
1089     naRuntimeError(c, "airport.runway expects a runway ident argument");
1090   }
1091   
1092   std::string ident(naStr_data(args[0]));
1093   boost::to_upper(ident);
1094   if (!apt->hasRunwayWithIdent(ident)) {
1095     return naNil();
1096   }
1097   
1098   return ghostForRunway(c, apt->getRunwayByIdent(ident));
1099 }
1100
1101 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1102 {
1103   FGAirport* apt = airportGhost(me);
1104   if (!apt) {
1105     naRuntimeError(c, "airport.sids called on non-airport object");
1106   }
1107   
1108   naRef sids = naNewVector(c);
1109   
1110   FGRunway* rwy = NULL;
1111   if (argc > 0 && naIsString(args[0])) {
1112     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1113       return naNil();
1114     }
1115
1116     rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1117   } else if (argc > 0) {
1118     rwy = runwayGhost(args[0]);
1119   }
1120
1121   if (rwy) {
1122     BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
1123       naRef procId = stringToNasal(c, sid->ident());
1124       naVec_append(sids, procId);
1125     }
1126   } else {
1127     for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1128       flightgear::SID* sid = apt->getSIDByIndex(s);
1129       naRef procId = stringToNasal(c, sid->ident());
1130       naVec_append(sids, procId);
1131     }
1132   }
1133   
1134   return sids;
1135 }
1136
1137 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1138 {
1139   FGAirport* apt = airportGhost(me);
1140   if (!apt) {
1141     naRuntimeError(c, "airport.stars called on non-airport object");
1142   }
1143   
1144   naRef stars = naNewVector(c);
1145   
1146   FGRunway* rwy = NULL;
1147   if (argc > 0 && naIsString(args[0])) {
1148     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1149       return naNil();
1150     }
1151         
1152     rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1153   } else if (argc > 0) {
1154     rwy = runwayGhost(args[0]);
1155   }
1156   
1157   if (rwy) {
1158     BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
1159       naRef procId = stringToNasal(c, s->ident());
1160       naVec_append(stars, procId);
1161     }
1162   } else {
1163     for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1164       flightgear::STAR* star = apt->getSTARByIndex(s);
1165       naRef procId = stringToNasal(c, star->ident());
1166       naVec_append(stars, procId);
1167     }
1168   }
1169   
1170   return stars;
1171 }
1172
1173 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1174 {
1175   FGAirport* apt = airportGhost(me);
1176   if (!apt) {
1177     naRuntimeError(c, "airport.getApproachList called on non-airport object");
1178   }
1179   
1180   naRef approaches = naNewVector(c);
1181   
1182   ProcedureType ty = PROCEDURE_INVALID;
1183   if ((argc > 1) && naIsString(args[1])) {
1184     std::string u(naStr_data(args[1]));
1185     boost::to_upper(u);
1186     if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1187     if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1188     if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1189     if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1190   }
1191   
1192   FGRunway* rwy = NULL;
1193   if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1194     // ok
1195   } else if (argc > 0 && naIsString(args[0])) {
1196     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1197       return naNil();
1198     }
1199     
1200     rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1201   }
1202   
1203   if (rwy) {
1204     BOOST_FOREACH(Approach* s, rwy->getApproaches()) {
1205       if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1206         continue;
1207       }
1208       
1209       naRef procId = stringToNasal(c, s->ident());
1210       naVec_append(approaches, procId);
1211     }
1212   } else {
1213     // no runway specified, report them all
1214     for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1215       Approach* app = apt->getApproachByIndex(s);
1216       if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1217         continue;
1218       }
1219       
1220       naRef procId = stringToNasal(c, app->ident());
1221       naVec_append(approaches, procId);
1222     }
1223   }
1224   
1225   return approaches;
1226 }
1227
1228 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1229 {
1230   FGAirport* apt = airportGhost(me);
1231   if (!apt) {
1232     naRuntimeError(c, "airport.parking called on non-airport object");
1233   }
1234   
1235   naRef r = naNewVector(c);
1236   std::string type;
1237   bool onlyAvailable = false;
1238   
1239   if (argc > 0 && naIsString(args[0])) {
1240     type = naStr_data(args[0]);
1241   }
1242   
1243   if ((argc > 1) && naIsNum(args[1])) {
1244     onlyAvailable = (args[1].num != 0.0);
1245   }
1246   
1247   FGAirportDynamics* dynamics = apt->getDynamics();
1248   for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
1249     FGParking* park = dynamics->getParking(i);
1250   // filter out based on availability and type
1251     if (onlyAvailable && !park->isAvailable()) {
1252       continue;
1253     }
1254     
1255     if (!type.empty() && (park->getType() != type)) {
1256       continue;
1257     }
1258     
1259     naRef nm = stringToNasal(c, park->getName());
1260     naVec_append(r, nm);
1261   }
1262   
1263   return r;
1264 }
1265
1266 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1267 {
1268   FGAirport* apt = airportGhost(me);
1269   if (!apt) {
1270     naRuntimeError(c, "airport.getSid called on non-airport object");
1271   }
1272   
1273   if ((argc != 1) || !naIsString(args[0])) {
1274     naRuntimeError(c, "airport.getSid passed invalid argument");
1275   }
1276   
1277   string ident = naStr_data(args[0]);
1278   return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1279 }
1280
1281 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1282 {
1283   FGAirport* apt = airportGhost(me);
1284   if (!apt) {
1285     naRuntimeError(c, "airport.getStar called on non-airport object");
1286   }
1287   
1288   if ((argc != 1) || !naIsString(args[0])) {
1289     naRuntimeError(c, "airport.getStar passed invalid argument");
1290   }
1291   
1292   string ident = naStr_data(args[0]);
1293   return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1294 }
1295
1296 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1297 {
1298   FGAirport* apt = airportGhost(me);
1299   if (!apt) {
1300     naRuntimeError(c, "airport.getIAP called on non-airport object");
1301   }
1302   
1303   if ((argc != 1) || !naIsString(args[0])) {
1304     naRuntimeError(c, "airport.getIAP passed invalid argument");
1305   }
1306   
1307   string ident = naStr_data(args[0]);
1308   return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1309 }
1310
1311 static naRef f_airport_toString(naContext c, naRef me, int argc, naRef* args)
1312 {
1313   FGAirport* apt = airportGhost(me);
1314   if (!apt) {
1315     naRuntimeError(c, "airport.tostring called on non-airport object");
1316   }
1317   
1318   return stringToNasal(c, "an airport " + apt->ident());
1319 }
1320
1321 // Returns vector of data hash for navaid of a <type>, nil on error
1322 // navaids sorted by ascending distance 
1323 // navinfo([<lat>,<lon>],[<type>],[<id>])
1324 // lat/lon (numeric): use latitude/longitude instead of ac position
1325 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1326 // id:                (partial) id of the fix
1327 // examples:
1328 // navinfo("vor")     returns all vors
1329 // navinfo("HAM")     return all navaids who's name start with "HAM"
1330 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1331 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM" 
1332 //                           sorted by distance relative to lat=34, lon=48
1333 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1334 {
1335   SGGeod pos;
1336   
1337   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1338     pos = SGGeod::fromDeg(args[1].num, args[0].num);
1339     args += 2;
1340     argc -= 2;
1341   } else {
1342     pos = globals->get_aircraft_position();
1343   }
1344   
1345   FGPositioned::Type type = FGPositioned::INVALID;
1346   nav_list_type navlist;
1347   const char * id = "";
1348   
1349   if(argc > 0 && naIsString(args[0])) {
1350     const char *s = naStr_data(args[0]);
1351     if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1352     else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1353     else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1354     else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1355     else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1356     else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1357     else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1358     else id = s; // this is an id
1359     ++args;
1360     --argc;
1361   } 
1362   
1363   if(argc > 0 && naIsString(args[0])) {
1364     if( *id != 0 ) {
1365       naRuntimeError(c, "navinfo() called with navaid id");
1366       return naNil();
1367     }
1368     id = naStr_data(args[0]);
1369     ++args;
1370     --argc;
1371   }
1372   
1373   if( argc > 0 ) {
1374     naRuntimeError(c, "navinfo() called with too many arguments");
1375     return naNil();
1376   }
1377   
1378   navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
1379   
1380   naRef reply = naNewVector(c);
1381   for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1382     naVec_append( reply, ghostForNavaid(c, *it) );
1383   }
1384   return reply;
1385 }
1386
1387 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1388 {
1389   int argOffset = 0;
1390   SGGeod pos = globals->get_aircraft_position();
1391   argOffset += geodFromArgs(args, 0, argc, pos);
1392   
1393   if (!naIsNum(args[argOffset])) {
1394     naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1395   }
1396   
1397   FGPositioned::Type type = FGPositioned::INVALID;
1398   double rangeNm = args[argOffset++].num;
1399   if (argOffset < argc) {
1400     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1401   }
1402   
1403   naRef r = naNewVector(c);
1404   FGNavList::TypeFilter filter(type);
1405   FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1406   FGPositioned::sortByRange(navs, pos);
1407   
1408   BOOST_FOREACH(FGPositionedRef a, navs) {
1409     FGNavRecord* nav = (FGNavRecord*) a.get();
1410     naVec_append(r, ghostForNavaid(c, nav));
1411   }
1412   
1413   return r;
1414 }
1415
1416 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1417 {
1418   int argOffset = 0;
1419   SGGeod pos = globals->get_aircraft_position();
1420   argOffset += geodFromArgs(args, 0, argc, pos);
1421   
1422   if (!naIsNum(args[argOffset])) {
1423     naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1424   }
1425   
1426   FGPositioned::Type type = FGPositioned::INVALID;
1427   double freqMhz = args[argOffset++].num;
1428   if (argOffset < argc) {
1429     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1430   }
1431   
1432   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1433   if (navs.empty()) {
1434     return naNil();
1435   }
1436   
1437   return ghostForNavaid(c, navs.front().ptr());
1438 }
1439
1440 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1441 {
1442   int argOffset = 0;
1443   SGGeod pos = globals->get_aircraft_position();
1444   argOffset += geodFromArgs(args, 0, argc, pos);
1445   
1446   if (!naIsNum(args[argOffset])) {
1447     naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1448   }
1449   
1450   FGPositioned::Type type = FGPositioned::INVALID;
1451   double freqMhz = args[argOffset++].num;
1452   if (argOffset < argc) {
1453     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1454   }
1455   
1456   naRef r = naNewVector(c);
1457   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1458   
1459   BOOST_FOREACH(nav_rec_ptr a, navs) {
1460     naVec_append(r, ghostForNavaid(c, a.ptr()));
1461   }
1462   
1463   return r;
1464 }
1465
1466 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1467 {
1468   int argOffset = 0;
1469   SGGeod pos = globals->get_aircraft_position();
1470   argOffset += geodFromArgs(args, 0, argc, pos);
1471   
1472   if (!naIsString(args[argOffset])) {
1473     naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1474   }
1475   
1476   FGPositioned::Type type = FGPositioned::INVALID;
1477   string ident = naStr_data(args[argOffset++]);
1478   if (argOffset < argc) {
1479     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1480   }
1481   
1482   naRef r = naNewVector(c);
1483   nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
1484   
1485   BOOST_FOREACH(nav_rec_ptr a, navs) {
1486     naVec_append(r, ghostForNavaid(c, a.ptr()));
1487   }
1488   
1489   return r;
1490 }
1491
1492 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1493 {
1494   int argOffset = 0;
1495   SGGeod pos = globals->get_aircraft_position();
1496   argOffset += geodFromArgs(args, 0, argc, pos);
1497   
1498   if (!naIsString(args[argOffset])) {
1499     naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1500   }
1501   
1502   string ident(naStr_data(args[argOffset]));
1503   naRef r = naNewVector(c);
1504   
1505   FGPositioned::TypeFilter filter(FGPositioned::FIX);
1506   FGPositioned::List fixes = FGPositioned::findAllWithIdent(ident, &filter);
1507   FGPositioned::sortByRange(fixes, pos);
1508   
1509   BOOST_FOREACH(FGPositionedRef f, fixes) {
1510     naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1511   }
1512   
1513   return r;
1514 }
1515
1516 // Convert a cartesian point to a geodetic lat/lon/altitude.
1517 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1518 {
1519   SGGeod pos = globals->get_aircraft_position();
1520   if (argc == 0) {
1521     // fine, use aircraft position
1522   } else if (geodFromArgs(args, 0, argc, pos)) {
1523     // okay
1524   } else {
1525     naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1526   }
1527   
1528   double jd = globals->get_time_params()->getJD();
1529   double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1530   return naNum(magvarDeg);
1531 }
1532
1533 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1534 {
1535     SGGeod from = globals->get_aircraft_position(), to, p;
1536     int argOffset = geodFromArgs(args, 0, argc, p);
1537     if (geodFromArgs(args, argOffset, argc, to)) {
1538       from = p; // we parsed both FROM and TO args, so first was from
1539     } else {
1540       to = p; // only parsed one arg, so FROM is current
1541     }
1542   
1543     if (argOffset == 0) {
1544         naRuntimeError(c, "invalid arguments to courseAndDistance");
1545     }
1546     
1547     double course, course2, d;
1548     SGGeodesy::inverse(from, to, course, course2, d);
1549     
1550     naRef result = naNewVector(c);
1551     naVec_append(result, naNum(course));
1552     naVec_append(result, naNum(d * SG_METER_TO_NM));
1553     return result;
1554 }
1555
1556 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1557 {
1558   SGGeod from = globals->get_aircraft_position(), to;
1559   int argOffset = 0;
1560   
1561   // complication - don't inerpret two doubles (as the only args)
1562   // as a lat,lon pair - only do so if we have at least three args.
1563   if (argc > 2) {
1564     argOffset = geodFromArgs(args, 0, argc, from);
1565   }
1566   
1567   if ((argOffset + 1) >= argc) {
1568     naRuntimeError(c, "isufficent arguments to greatCircleMove");
1569   }
1570   
1571   if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1572     naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1573                    argOffset, argOffset + 1);
1574   }
1575   
1576   double course = args[argOffset].num, course2;
1577   double distanceNm = args[argOffset + 1].num;
1578   SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1579   
1580   // return geo.Coord
1581   naRef coord = naNewHash(c);
1582   hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1583   hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1584   return coord;
1585 }
1586
1587 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1588 {
1589     SGGeod pos = globals->get_aircraft_position();
1590     geodFromArgs(args, 0, argc, pos);
1591     SGBucket b(pos);
1592     return stringToNasal(c, b.gen_base_path());
1593 }
1594
1595 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1596 {
1597   SGGeod pos = globals->get_aircraft_position();
1598   geodFromArgs(args, 0, argc, pos);
1599   SGBucket b(pos);
1600   return naNum(b.gen_index());
1601 }
1602
1603 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1604 {
1605   if (argc == 0) {
1606     FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));  
1607     return ghostForFlightPlan(c, rm->flightPlan());
1608   }
1609   
1610   if ((argc > 0) && naIsString(args[0])) {
1611     flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1612     SGPath path(naStr_data(args[0]));
1613     if (!path.exists()) {
1614       naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1615     }
1616     
1617     if (!fp->load(path)) {
1618       SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1619       delete fp;
1620       return naNil();
1621     }
1622     
1623     return ghostForFlightPlan(c, fp);
1624   }
1625   
1626   naRuntimeError(c, "bad arguments to flightplan()");
1627   return naNil();
1628 }
1629
1630 class NasalFPDelegate : public FlightPlan::Delegate
1631 {
1632 public:
1633   NasalFPDelegate(FlightPlan* fp, FGNasalSys* sys, naRef ins) :
1634     _nasal(sys),
1635     _plan(fp),
1636     _instance(ins)
1637   {
1638     SG_LOG(SG_NASAL, SG_INFO, "created Nasal delegate for " << fp);
1639     _gcSaveKey = _nasal->gcSave(ins);
1640   }
1641   
1642   virtual ~NasalFPDelegate()
1643   {
1644     SG_LOG(SG_NASAL, SG_INFO, "destroying Nasal delegate for " << _plan);
1645     _nasal->gcRelease(_gcSaveKey);
1646   }
1647   
1648   virtual void departureChanged()
1649   {
1650     callDelegateMethod("departureChanged");
1651   }
1652   
1653   virtual void arrivalChanged()
1654   {
1655     callDelegateMethod("arrivalChanged");
1656   }
1657   
1658   virtual void waypointsChanged()
1659   {
1660     callDelegateMethod("waypointsChanged");
1661   }
1662   
1663   virtual void currentWaypointChanged()
1664   {
1665     callDelegateMethod("currentWaypointChanged");
1666   }
1667 private:
1668   
1669   void callDelegateMethod(const char* method)
1670   {
1671     naRef f;
1672     naMember_cget(_nasal->context(), _instance, method, &f);
1673     if (naIsNil(f)) {
1674       return; // no method on the delegate
1675     }
1676     
1677     naRef arg[1];
1678     arg[0] = ghostForFlightPlan(_nasal->context(), _plan);
1679     _nasal->callMethod(f, _instance, 1, arg, naNil());
1680   }
1681   
1682   FGNasalSys* _nasal;
1683   FlightPlan* _plan;
1684   naRef _instance;
1685   int _gcSaveKey;
1686 };
1687
1688 class NasalFPDelegateFactory : public FlightPlan::DelegateFactory
1689 {
1690 public:
1691   NasalFPDelegateFactory(naRef code)
1692   {
1693     _nasal = (FGNasalSys*) globals->get_subsystem("nasal");
1694     _func = code;
1695     _gcSaveKey = _nasal->gcSave(_func);
1696   }
1697   
1698   ~NasalFPDelegateFactory()
1699   {
1700     _nasal->gcRelease(_gcSaveKey);
1701   }
1702   
1703   virtual FlightPlan::Delegate* createFlightPlanDelegate(FlightPlan* fp)
1704   {
1705     naRef args[1];
1706     args[0] = ghostForFlightPlan(_nasal->context(), fp);
1707     naRef instance = _nasal->call(_func, 1, args, naNil());
1708     if (naIsNil(instance)) {
1709       return NULL;
1710     }
1711     
1712     return new NasalFPDelegate(fp, _nasal, instance);
1713   }
1714 private:
1715   FGNasalSys* _nasal;
1716   naRef _func;
1717   int _gcSaveKey;
1718 };
1719
1720 static naRef f_registerFPDelegate(naContext c, naRef me, int argc, naRef* args)
1721 {
1722   if ((argc < 1) || !naIsFunc(args[0])) {
1723     naRuntimeError(c, "non-function argument to registerFlightPlanDelegate");
1724   }
1725   
1726   NasalFPDelegateFactory* factory = new NasalFPDelegateFactory(args[0]);
1727   FlightPlan::registerDelegateFactory(factory);
1728   
1729   return naNil();
1730 }
1731
1732 static WayptRef wayptFromArg(naRef arg)
1733 {
1734   WayptRef r = wayptGhost(arg);
1735   if (r.valid()) {
1736     return r;
1737   }
1738   
1739   FGPositioned* pos = positionedGhost(arg);
1740   if (!pos) {
1741     // let's check if the arg is hash, coudl extra a geod and hence build
1742     // a simple waypoint
1743     
1744     return WayptRef();
1745   }
1746   
1747 // special-case for runways
1748   if (pos->type() == FGPositioned::RUNWAY) {
1749     return new RunwayWaypt((FGRunway*) pos, NULL);
1750   }
1751   
1752   return new NavaidWaypoint(pos, NULL);
1753 }
1754
1755 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1756 {
1757   naRef result = naNewVector(c);
1758   BOOST_FOREACH(WayptRef wpt, wps) {
1759     naVec_append(result, ghostForWaypt(c, wpt.get()));
1760   }
1761   return result;
1762 }
1763
1764 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1765 {
1766   if (argc < 2) {
1767     naRuntimeError(c, "airwaysSearch needs at least two arguments");
1768   }
1769   
1770   WayptRef start = wayptFromArg(args[0]), 
1771     end = wayptFromArg(args[1]);
1772   
1773   if (!start || !end) {
1774     SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1775     return naNil();
1776   }
1777   
1778   bool highLevel = true;
1779   if ((argc > 2) && naIsString(args[2])) {
1780     if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1781       highLevel = false;
1782     }
1783   }
1784   
1785   WayptVec route;
1786   if (highLevel) {
1787     Airway::highLevel()->route(start, end, route);
1788   } else {
1789     Airway::lowLevel()->route(start, end, route);
1790   }
1791   
1792   return convertWayptVecToNasal(c, route);
1793 }
1794
1795 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1796 {
1797   SGGeod pos;
1798   int argOffset = geodFromArgs(args, 0, argc, pos);
1799   
1800   if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1801     naRuntimeError(c, "createWP: no identifier supplied");
1802   }
1803     
1804   string ident = naStr_data(args[argOffset++]);
1805   WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1806   
1807 // set waypt flags - approach, departure, pseudo, etc
1808   if (argc > argOffset) {
1809     WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1810     wpt->setFlag(f);
1811   }
1812   
1813   return ghostForWaypt(c, wpt);
1814 }
1815
1816 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1817 {
1818   if (argc < 1) {
1819     naRuntimeError(c, "createWPFrom: need at least one argument");
1820   }
1821   
1822   FGPositioned* positioned = positionedGhost(args[0]);
1823   if (!positioned) {
1824     naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1825   }
1826   
1827   WayptRef wpt;
1828   if (positioned->type() == FGPositioned::RUNWAY) {
1829     wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1830   } else {
1831     wpt = new NavaidWaypoint(positioned, NULL);
1832   }
1833
1834   // set waypt flags - approach, departure, pseudo, etc
1835   if (argc > 1) {
1836     WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
1837     wpt->setFlag(f);
1838   }
1839   
1840   return ghostForWaypt(c, wpt);
1841 }
1842
1843 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
1844 {
1845   FlightPlan* fp = flightplanGhost(me);
1846   if (!fp) {
1847     naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
1848   }
1849
1850   int index;
1851   if (argc == 0) {
1852     index = fp->currentIndex();
1853   } else {
1854     index = (int) naNumValue(args[0]).num;
1855   }
1856   
1857   if ((index < 0) || (index >= fp->numLegs())) {
1858     return naNil();
1859   }
1860   
1861   return ghostForLeg(c, fp->legAtIndex(index));
1862 }
1863
1864 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
1865 {
1866   FlightPlan* fp = flightplanGhost(me);
1867   if (!fp) {
1868     naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
1869   }
1870   return ghostForLeg(c, fp->currentLeg());
1871 }
1872
1873 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
1874 {
1875   FlightPlan* fp = flightplanGhost(me);
1876   if (!fp) {
1877     naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
1878   }
1879   return ghostForLeg(c, fp->nextLeg());
1880 }
1881
1882 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
1883 {
1884   FlightPlan* fp = flightplanGhost(me);
1885   if (!fp) {
1886     naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
1887   }
1888   return naNum(fp->numLegs());
1889 }
1890
1891 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
1892 {
1893   FlightPlan* fp = flightplanGhost(me);
1894   if (!fp) {
1895     naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
1896   }
1897   
1898   WayptRef wp = wayptGhost(args[0]);
1899   int index = fp->numLegs();
1900   fp->insertWayptAtIndex(wp.get(), index);
1901   return naNum(index);
1902 }
1903
1904 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
1905 {
1906   FlightPlan* fp = flightplanGhost(me);
1907   if (!fp) {
1908     naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
1909   }
1910   
1911   WayptRef wp = wayptGhost(args[0]);
1912   int index = -1; // append
1913   if ((argc > 1) && naIsNum(args[1])) {
1914     index = (int) args[1].num;
1915   }
1916   
1917   fp->insertWayptAtIndex(wp.get(), index);
1918   return naNil();
1919 }
1920
1921 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
1922 {
1923   FlightPlan* fp = flightplanGhost(me);
1924   if (!fp) {
1925     naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
1926   }
1927   
1928   WayptRef wp = wayptGhost(args[0]);
1929   int index = -1; // append
1930   if ((argc > 1) && naIsNum(args[1])) {
1931     index = (int) args[1].num;
1932   }
1933   
1934   fp->insertWayptAtIndex(wp.get(), index + 1);
1935   return naNil();
1936 }
1937
1938 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
1939 {
1940   FlightPlan* fp = flightplanGhost(me);
1941   if (!fp) {
1942     naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
1943   }
1944   
1945   WayptVec wps;
1946   if (!naIsVector(args[0])) {
1947     naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
1948   }
1949
1950   int count = naVec_size(args[0]);
1951   for (int i=0; i<count; ++i) {
1952     Waypt* wp = wayptGhost(naVec_get(args[0], i));
1953     if (wp) {
1954       wps.push_back(wp);
1955     }
1956   }
1957   
1958   int index = -1; // append
1959   if ((argc > 1) && naIsNum(args[1])) {
1960     index = (int) args[1].num;
1961   }
1962
1963   fp->insertWayptsAtIndex(wps, index);
1964   return naNil();
1965 }
1966
1967 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
1968 {
1969   FlightPlan* fp = flightplanGhost(me);
1970   if (!fp) {
1971     naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
1972   }
1973   
1974   if ((argc < 1) || !naIsNum(args[0])) {
1975     naRuntimeError(c, "bad argument to flightplan.deleteWP");
1976   }
1977   
1978   int index = (int) args[0].num;
1979   fp->deleteIndex(index);
1980   return naNil();
1981 }
1982
1983 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
1984 {
1985   FlightPlan* fp = flightplanGhost(me);
1986   if (!fp) {
1987     naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
1988   }
1989   
1990   fp->clear();
1991   return naNil();
1992 }
1993
1994 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
1995 {
1996   FlightPlan* fp = flightplanGhost(me);
1997   if (!fp) {
1998     naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
1999   }
2000   
2001   if (argc < 1) {
2002     naRuntimeError(c, "insufficent args to flightplan.clearWPType");
2003   }
2004   
2005   WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
2006   fp->clearWayptsWithFlag(flag);
2007   return naNil();
2008 }
2009
2010 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
2011 {
2012   FlightPlan* fp = flightplanGhost(me);
2013   if (!fp) {
2014     naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2015   }
2016   
2017   return ghostForFlightPlan(c, fp->clone());
2018 }
2019
2020 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
2021 {
2022   FlightPlan::Leg* leg = fpLegGhost(me);
2023   if (!leg) {
2024     naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
2025   }
2026   
2027   if (argc < 2) {
2028     naRuntimeError(c, "bad arguments to leg.setSpeed");
2029   }
2030   
2031   RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2032   leg->setSpeed(rr, args[0].num);
2033   return naNil();
2034 }
2035
2036 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
2037 {
2038   FlightPlan::Leg* leg = fpLegGhost(me);
2039   if (!leg) {
2040     naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2041   }
2042   
2043   if (argc < 2) {
2044     naRuntimeError(c, "bad arguments to leg.setAltitude");
2045   }
2046   
2047   RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2048   leg->setAltitude(rr, args[0].num);
2049   return naNil();
2050 }
2051
2052 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
2053 {
2054   flightgear::Waypt* w = wayptGhost(me);
2055   if (!w) {
2056     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2057   }
2058   
2059   FGPositioned* pos = w->source();
2060   if (!pos) {
2061     return naNil();
2062   }
2063   
2064   switch (pos->type()) {
2065   case FGPositioned::VOR:
2066   case FGPositioned::NDB:
2067   case FGPositioned::ILS:
2068   case FGPositioned::LOC:
2069   case FGPositioned::GS:
2070   case FGPositioned::DME:
2071   case FGPositioned::TACAN: {
2072     FGNavRecord* nav = (FGNavRecord*) pos;
2073     return ghostForNavaid(c, nav);
2074   }
2075       
2076   default:
2077     return naNil();
2078   }
2079 }
2080
2081 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
2082 {
2083   flightgear::Waypt* w = wayptGhost(me);
2084   if (!w) {
2085     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2086   }
2087   
2088   FGPositioned* pos = w->source();
2089   if (!pos || FGAirport::isAirportType(pos)) {
2090     return naNil();
2091   }
2092   
2093   return ghostForAirport(c, (FGAirport*) pos);
2094 }
2095
2096 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
2097 {
2098   flightgear::Waypt* w = wayptGhost(me);
2099   if (!w) {
2100     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2101   }
2102   
2103   FGPositioned* pos = w->source();
2104   if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
2105     return naNil();
2106   }
2107   
2108   return ghostForRunway(c, (FGRunway*) pos);
2109 }
2110
2111 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2112 {
2113   Procedure* proc = procedureGhost(me);
2114   if (!proc) {
2115     naRuntimeError(c, "procedure.transition called on non-procedure object");
2116   }
2117   
2118   if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2119     naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2120   }
2121   
2122   ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2123   Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2124   
2125   return ghostForProcedure(c, trans);
2126 }
2127
2128 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2129 {
2130   Procedure* proc = procedureGhost(me);
2131   if (!proc) {
2132     naRuntimeError(c, "procedure.route called on non-procedure object");
2133   }
2134   
2135 // wrapping up tow different routines here - approach routing from the IAF
2136 // to the associated runway, and SID/STAR routing via an enroute transition
2137 // and possibly a runway transition or not.
2138   if (Approach::isApproach(proc->type())) {
2139     WayptRef iaf;
2140     if (argc > 0) {
2141       iaf = wayptFromArg(args[0]);
2142     }
2143     
2144     WayptVec r;
2145     Approach* app = (Approach*) proc;
2146     if (!app->route(iaf, r)) {
2147       SG_LOG(SG_NASAL, SG_WARN, "procedure.route failed for Approach somehow");
2148       return naNil();
2149     }
2150     
2151     return convertWayptVecToNasal(c, r);
2152   } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2153     naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2154   }
2155   
2156   int argOffset = 0;
2157   FGRunway* rwy = runwayGhost(args[0]);
2158   if (rwy) ++argOffset;
2159   
2160   ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2161   Transition* trans = NULL;
2162   if (argOffset < argc) {
2163     trans = (Transition*) procedureGhost(args[argOffset]);
2164   }
2165   
2166   // note either runway or trans may be NULL - that's ok
2167   WayptVec r;
2168   if (!ad->route(rwy, trans, r)) {
2169     SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2170     return naNil();
2171   }
2172   
2173   return convertWayptVecToNasal(c, r);
2174 }
2175
2176
2177 // Table of extension functions.  Terminate with zeros.
2178 static struct { const char* name; naCFunction func; } funcs[] = {
2179   { "carttogeod", f_carttogeod },
2180   { "geodtocart", f_geodtocart },
2181   { "geodinfo", f_geodinfo },
2182   { "airportinfo", f_airportinfo },
2183   { "findAirportsWithinRange", f_findAirportsWithinRange },
2184   { "findAirportsByICAO", f_findAirportsByICAO },
2185   { "navinfo", f_navinfo },
2186   { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2187   { "findNavaidByFrequency", f_findNavaidByFrequency },
2188   { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2189   { "findNavaidsByID", f_findNavaidsByIdent },
2190   { "findFixesByID", f_findFixesByIdent },
2191   { "flightplan", f_route },
2192   { "registerFlightPlanDelegate", f_registerFPDelegate },
2193   { "createWP", f_createWP },
2194   { "createWPFrom", f_createWPFrom },
2195   { "airwaysRoute", f_airwaySearch },
2196   { "magvar", f_magvar },
2197   { "courseAndDistance", f_courseAndDistance },
2198   { "greatCircleMove", f_greatCircleMove },
2199   { "tileIndex", f_tileIndex },
2200   { "tilePath", f_tilePath },
2201   { 0, 0 }
2202 };
2203
2204
2205 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
2206 {
2207     airportPrototype = naNewHash(c);
2208     hashset(c, gcSave, "airportProto", airportPrototype);
2209   
2210     hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2211     hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2212     hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2213     hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2214     hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2215     hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2216     hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2217     hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2218     hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2219     hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2220     hashset(c, airportPrototype, "tostring", naNewFunc(c, naNewCCode(c, f_airport_toString)));
2221   
2222     flightplanPrototype = naNewHash(c);
2223     hashset(c, gcSave, "flightplanProto", flightplanPrototype);
2224       
2225     hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2226     hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP))); 
2227     hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP))); 
2228     hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2229     hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP))); 
2230     hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP))); 
2231     hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP))); 
2232     hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter))); 
2233     hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints))); 
2234     hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan))); 
2235     hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType))); 
2236     hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone))); 
2237   
2238     waypointPrototype = naNewHash(c);
2239     hashset(c, gcSave, "wayptProto", waypointPrototype);
2240     
2241     hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2242     hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2243     hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2244   
2245     procedurePrototype = naNewHash(c);
2246     hashset(c, gcSave, "procedureProto", procedurePrototype);
2247     hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2248     hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2249   
2250     fpLegPrototype = naNewHash(c);
2251     hashset(c, gcSave, "fpLegProto", fpLegPrototype);
2252     hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2253     hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2254   
2255     for(int i=0; funcs[i].name; i++) {
2256       hashset(c, globals, funcs[i].name,
2257       naNewFunc(c, naNewCCode(c, funcs[i].func)));
2258     }
2259   
2260   return naNil();
2261 }
2262
2263 void postinitNasalPositioned(naRef globals, naContext c)
2264 {
2265   naRef geoModule = naHash_cget(globals, (char*) "geo");
2266   if (naIsNil(geoModule)) {
2267     SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2268     return;
2269   }
2270   
2271   geoCoordClass = naHash_cget(geoModule, (char*) "Coord");
2272 }
2273
2274