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