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