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