]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned.cxx
Checkpoint - ground-net skips the cache
[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   FGParkingList parkings = dynamics->getParkings(onlyAvailable, type);
1356   FGParkingList::const_iterator it;
1357   for (it = parkings.begin(); it != parkings.end(); ++it) {
1358     FGParkingRef park = *it;
1359     const SGGeod& parkLoc = park->geod();
1360     naRef ph = naNewHash(c);
1361     hashset(c, ph, "name", stringToNasal(c, park->getName()));
1362     hashset(c, ph, "lat", naNum(parkLoc.getLatitudeDeg()));
1363     hashset(c, ph, "lon", naNum(parkLoc.getLongitudeDeg()));
1364     hashset(c, ph, "elevation", naNum(parkLoc.getElevationM()));
1365     naVec_append(r, ph);
1366   }
1367   
1368   return r;
1369 }
1370
1371 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1372 {
1373   FGAirport* apt = airportGhost(me);
1374   if (!apt) {
1375     naRuntimeError(c, "airport.getSid called on non-airport object");
1376   }
1377   
1378   if ((argc != 1) || !naIsString(args[0])) {
1379     naRuntimeError(c, "airport.getSid passed invalid argument");
1380   }
1381   
1382   std::string ident = naStr_data(args[0]);
1383   return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1384 }
1385
1386 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1387 {
1388   FGAirport* apt = airportGhost(me);
1389   if (!apt) {
1390     naRuntimeError(c, "airport.getStar called on non-airport object");
1391   }
1392   
1393   if ((argc != 1) || !naIsString(args[0])) {
1394     naRuntimeError(c, "airport.getStar passed invalid argument");
1395   }
1396   
1397   std::string ident = naStr_data(args[0]);
1398   return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1399 }
1400
1401 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1402 {
1403   FGAirport* apt = airportGhost(me);
1404   if (!apt) {
1405     naRuntimeError(c, "airport.getIAP called on non-airport object");
1406   }
1407   
1408   if ((argc != 1) || !naIsString(args[0])) {
1409     naRuntimeError(c, "airport.getIAP passed invalid argument");
1410   }
1411   
1412   std::string ident = naStr_data(args[0]);
1413   return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1414 }
1415
1416 static naRef f_airport_findBestRunway(naContext c, naRef me, int argc, naRef* args)
1417 {
1418     FGAirport* apt = airportGhost(me);
1419     if (!apt) {
1420         naRuntimeError(c, "findBestRunway called on non-airport object");
1421     }
1422     
1423     SGGeod pos;
1424     if (!geodFromArgs(args, 0, argc, pos)) {
1425         naRuntimeError(c, "findBestRunway must be passed a position");
1426     }
1427     
1428     return ghostForRunway(c,  apt->findBestRunwayForPos(pos));
1429 }
1430
1431 static naRef f_airport_toString(naContext c, naRef me, int argc, naRef* args)
1432 {
1433   FGAirport* apt = airportGhost(me);
1434   if (!apt) {
1435     naRuntimeError(c, "airport.tostring called on non-airport object");
1436   }
1437   
1438   return stringToNasal(c, "an airport " + apt->ident());
1439 }
1440
1441 // Returns vector of data hash for navaid of a <type>, nil on error
1442 // navaids sorted by ascending distance 
1443 // navinfo([<lat>,<lon>],[<type>],[<id>])
1444 // lat/lon (numeric): use latitude/longitude instead of ac position
1445 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1446 // id:                (partial) id of the fix
1447 // examples:
1448 // navinfo("vor")     returns all vors
1449 // navinfo("HAM")     return all navaids who's name start with "HAM"
1450 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1451 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM" 
1452 //                           sorted by distance relative to lat=34, lon=48
1453 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1454 {
1455   SGGeod pos;
1456   
1457   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1458     pos = SGGeod::fromDeg(args[1].num, args[0].num);
1459     args += 2;
1460     argc -= 2;
1461   } else {
1462     pos = globals->get_aircraft_position();
1463   }
1464   
1465   FGPositioned::Type type = FGPositioned::INVALID;
1466   nav_list_type navlist;
1467   const char * id = "";
1468   
1469   if(argc > 0 && naIsString(args[0])) {
1470     const char *s = naStr_data(args[0]);
1471     if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1472     else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1473     else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1474     else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1475     else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1476     else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1477     else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1478     else id = s; // this is an id
1479     ++args;
1480     --argc;
1481   } 
1482   
1483   if(argc > 0 && naIsString(args[0])) {
1484     if( *id != 0 ) {
1485       naRuntimeError(c, "navinfo() called with navaid id");
1486       return naNil();
1487     }
1488     id = naStr_data(args[0]);
1489     ++args;
1490     --argc;
1491   }
1492   
1493   if( argc > 0 ) {
1494     naRuntimeError(c, "navinfo() called with too many arguments");
1495     return naNil();
1496   }
1497   
1498   FGNavList::TypeFilter filter(type);
1499   navlist = FGNavList::findByIdentAndFreq( pos, id, 0.0, &filter );
1500   
1501   naRef reply = naNewVector(c);
1502   for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1503     naVec_append( reply, ghostForNavaid(c, *it) );
1504   }
1505   return reply;
1506 }
1507
1508 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1509 {
1510   int argOffset = 0;
1511   SGGeod pos = globals->get_aircraft_position();
1512   argOffset += geodFromArgs(args, 0, argc, pos);
1513   
1514   if (!naIsNum(args[argOffset])) {
1515     naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1516   }
1517   
1518   FGPositioned::Type type = FGPositioned::INVALID;
1519   double rangeNm = args[argOffset++].num;
1520   if (argOffset < argc) {
1521     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1522   }
1523   
1524   naRef r = naNewVector(c);
1525   FGNavList::TypeFilter filter(type);
1526   FGPositionedList navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1527   FGPositioned::sortByRange(navs, pos);
1528   
1529   BOOST_FOREACH(FGPositionedRef a, navs) {
1530     FGNavRecord* nav = (FGNavRecord*) a.get();
1531     naVec_append(r, ghostForNavaid(c, nav));
1532   }
1533   
1534   return r;
1535 }
1536
1537 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1538 {
1539   int argOffset = 0;
1540   SGGeod pos = globals->get_aircraft_position();
1541   argOffset += geodFromArgs(args, 0, argc, pos);
1542   
1543   if (!naIsNum(args[argOffset])) {
1544     naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1545   }
1546   
1547   FGPositioned::Type type = FGPositioned::INVALID;
1548   double freqMhz = args[argOffset++].num;
1549   if (argOffset < argc) {
1550     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1551   }
1552   
1553   FGNavList::TypeFilter filter(type);
1554   nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1555   if (navs.empty()) {
1556     return naNil();
1557   }
1558   
1559   return ghostForNavaid(c, navs.front().ptr());
1560 }
1561
1562 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1563 {
1564   int argOffset = 0;
1565   SGGeod pos = globals->get_aircraft_position();
1566   argOffset += geodFromArgs(args, 0, argc, pos);
1567   
1568   if (!naIsNum(args[argOffset])) {
1569     naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1570   }
1571   
1572   FGPositioned::Type type = FGPositioned::INVALID;
1573   double freqMhz = args[argOffset++].num;
1574   if (argOffset < argc) {
1575     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1576   }
1577   
1578   naRef r = naNewVector(c);
1579   
1580   FGNavList::TypeFilter filter(type);
1581   nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1582   
1583   BOOST_FOREACH(nav_rec_ptr a, navs) {
1584     naVec_append(r, ghostForNavaid(c, a.ptr()));
1585   }
1586   
1587   return r;
1588 }
1589
1590 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1591 {
1592   int argOffset = 0;
1593   SGGeod pos = globals->get_aircraft_position();
1594   argOffset += geodFromArgs(args, 0, argc, pos);
1595   
1596   if (!naIsString(args[argOffset])) {
1597     naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1598   }
1599   
1600   FGPositioned::Type type = FGPositioned::INVALID;
1601   std::string ident = naStr_data(args[argOffset++]);
1602   if (argOffset < argc) {
1603     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1604   }
1605   
1606   FGNavList::TypeFilter filter(type);
1607   naRef r = naNewVector(c);
1608   nav_list_type navs = FGNavList::findByIdentAndFreq(pos, ident, 0.0, &filter);
1609   
1610   BOOST_FOREACH(nav_rec_ptr a, navs) {
1611     naVec_append(r, ghostForNavaid(c, a.ptr()));
1612   }
1613   
1614   return r;
1615 }
1616
1617 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1618 {
1619   int argOffset = 0;
1620   SGGeod pos = globals->get_aircraft_position();
1621   argOffset += geodFromArgs(args, 0, argc, pos);
1622   
1623   if (!naIsString(args[argOffset])) {
1624     naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1625   }
1626   
1627   std::string ident(naStr_data(args[argOffset]));
1628   naRef r = naNewVector(c);
1629   
1630   FGPositioned::TypeFilter filter(FGPositioned::FIX);
1631   FGPositionedList fixes = FGPositioned::findAllWithIdent(ident, &filter);
1632   FGPositioned::sortByRange(fixes, pos);
1633   
1634   BOOST_FOREACH(FGPositionedRef f, fixes) {
1635     naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1636   }
1637   
1638   return r;
1639 }
1640
1641 // Convert a cartesian point to a geodetic lat/lon/altitude.
1642 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1643 {
1644   SGGeod pos = globals->get_aircraft_position();
1645   if (argc == 0) {
1646     // fine, use aircraft position
1647   } else if (geodFromArgs(args, 0, argc, pos)) {
1648     // okay
1649   } else {
1650     naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1651   }
1652   
1653   double jd = globals->get_time_params()->getJD();
1654   double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1655   return naNum(magvarDeg);
1656 }
1657
1658 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1659 {
1660     SGGeod from = globals->get_aircraft_position(), to, p;
1661     int argOffset = geodFromArgs(args, 0, argc, p);
1662     if (geodFromArgs(args, argOffset, argc, to)) {
1663       from = p; // we parsed both FROM and TO args, so first was from
1664     } else {
1665       to = p; // only parsed one arg, so FROM is current
1666     }
1667   
1668     if (argOffset == 0) {
1669         naRuntimeError(c, "invalid arguments to courseAndDistance");
1670     }
1671     
1672     double course, course2, d;
1673     SGGeodesy::inverse(from, to, course, course2, d);
1674     
1675     naRef result = naNewVector(c);
1676     naVec_append(result, naNum(course));
1677     naVec_append(result, naNum(d * SG_METER_TO_NM));
1678     return result;
1679 }
1680
1681 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1682 {
1683   SGGeod from = globals->get_aircraft_position(), to;
1684   int argOffset = 0;
1685   
1686   // complication - don't inerpret two doubles (as the only args)
1687   // as a lat,lon pair - only do so if we have at least three args.
1688   if (argc > 2) {
1689     argOffset = geodFromArgs(args, 0, argc, from);
1690   }
1691   
1692   if ((argOffset + 1) >= argc) {
1693     naRuntimeError(c, "isufficent arguments to greatCircleMove");
1694   }
1695   
1696   if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1697     naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1698                    argOffset, argOffset + 1);
1699   }
1700   
1701   double course = args[argOffset].num, course2;
1702   double distanceNm = args[argOffset + 1].num;
1703   SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1704   
1705   // return geo.Coord
1706   naRef coord = naNewHash(c);
1707   hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1708   hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1709   return coord;
1710 }
1711
1712 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1713 {
1714     SGGeod pos = globals->get_aircraft_position();
1715     geodFromArgs(args, 0, argc, pos);
1716     SGBucket b(pos);
1717     return stringToNasal(c, b.gen_base_path());
1718 }
1719
1720 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1721 {
1722   SGGeod pos = globals->get_aircraft_position();
1723   geodFromArgs(args, 0, argc, pos);
1724   SGBucket b(pos);
1725   return naNum(b.gen_index());
1726 }
1727
1728 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1729 {
1730   if (argc == 0) {
1731     FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));  
1732     return ghostForFlightPlan(c, rm->flightPlan());
1733   }
1734   
1735   if ((argc > 0) && naIsString(args[0])) {
1736     flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1737     SGPath path(naStr_data(args[0]));
1738     if (!path.exists()) {
1739       naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1740     }
1741     
1742     if (!fp->load(path)) {
1743       SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1744       delete fp;
1745       return naNil();
1746     }
1747     
1748     return ghostForFlightPlan(c, fp);
1749   }
1750   
1751   naRuntimeError(c, "bad arguments to flightplan()");
1752   return naNil();
1753 }
1754
1755 class NasalFPDelegate : public FlightPlan::Delegate
1756 {
1757 public:
1758   NasalFPDelegate(FlightPlan* fp, FGNasalSys* sys, naRef ins) :
1759     _nasal(sys),
1760     _plan(fp),
1761     _instance(ins)
1762   {
1763     _gcSaveKey = _nasal->gcSave(ins);
1764   }
1765   
1766   virtual ~NasalFPDelegate()
1767   {
1768     _nasal->gcRelease(_gcSaveKey);
1769   }
1770   
1771   virtual void departureChanged()
1772   {
1773     callDelegateMethod("departureChanged");
1774   }
1775   
1776   virtual void arrivalChanged()
1777   {
1778     callDelegateMethod("arrivalChanged");
1779   }
1780   
1781   virtual void waypointsChanged()
1782   {
1783     callDelegateMethod("waypointsChanged");
1784   }
1785   
1786   virtual void currentWaypointChanged()
1787   {
1788     callDelegateMethod("currentWaypointChanged");
1789   }
1790     
1791   virtual void cleared()
1792   {
1793     callDelegateMethod("cleared");
1794   }
1795     
1796   virtual void endOfFlightPlan()
1797   {
1798     callDelegateMethod("endOfFlightPlan");
1799   }
1800
1801   virtual void activated()
1802   {
1803     callDelegateMethod("activated");
1804   }
1805 private:
1806   
1807   void callDelegateMethod(const char* method)
1808   {
1809     naRef f;
1810     naContext ctx = naNewContext();
1811       
1812     if (naMember_cget(ctx, _instance, method, &f) != 0) {
1813         naRef arg[1];
1814         arg[0] = ghostForFlightPlan(ctx, _plan);
1815         _nasal->callMethod(f, _instance, 1, arg, naNil());
1816     }
1817     
1818     naFreeContext(ctx);
1819   }
1820   
1821   FGNasalSys* _nasal;
1822   FlightPlan* _plan;
1823   naRef _instance;
1824   int _gcSaveKey;
1825 };
1826
1827
1828 class NasalFPDelegateFactory : public FlightPlan::DelegateFactory
1829 {
1830 public:
1831   NasalFPDelegateFactory(naRef code)
1832   {
1833     _nasal = (FGNasalSys*) globals->get_subsystem("nasal");
1834     _func = code;
1835     _gcSaveKey = _nasal->gcSave(_func);
1836   }
1837   
1838   virtual ~NasalFPDelegateFactory()
1839   {
1840     _nasal->gcRelease(_gcSaveKey);
1841   }
1842   
1843   virtual FlightPlan::Delegate* createFlightPlanDelegate(FlightPlan* fp)
1844   {
1845     naRef args[1];
1846     naContext ctx = naNewContext();
1847     args[0] = ghostForFlightPlan(ctx, fp);
1848     naRef instance = _nasal->call(_func, 1, args, naNil());
1849     
1850       FlightPlan::Delegate* result = NULL;
1851       if (!naIsNil(instance)) {
1852           // will GC-save instance
1853           result = new NasalFPDelegate(fp, _nasal, instance);
1854       }
1855       
1856       naFreeContext(ctx);
1857       return result;
1858   }
1859 private:
1860   FGNasalSys* _nasal;
1861   naRef _func;
1862   int _gcSaveKey;
1863 };
1864
1865 static std::vector<NasalFPDelegateFactory*> static_nasalDelegateFactories;
1866
1867 void shutdownNasalPositioned()
1868 {
1869     std::vector<NasalFPDelegateFactory*>::iterator it;
1870     for (it = static_nasalDelegateFactories.begin();
1871          it != static_nasalDelegateFactories.end(); ++it)
1872     {
1873         FlightPlan::unregisterDelegateFactory(*it);
1874         delete (*it);
1875     }
1876     static_nasalDelegateFactories.clear();
1877 }
1878
1879 static naRef f_registerFPDelegate(naContext c, naRef me, int argc, naRef* args)
1880 {
1881   if ((argc < 1) || !naIsFunc(args[0])) {
1882     naRuntimeError(c, "non-function argument to registerFlightPlanDelegate");
1883   }
1884   
1885   NasalFPDelegateFactory* factory = new NasalFPDelegateFactory(args[0]);
1886   FlightPlan::registerDelegateFactory(factory);
1887     static_nasalDelegateFactories.push_back(factory);
1888   return naNil();
1889 }
1890
1891 static WayptRef wayptFromArg(naRef arg)
1892 {
1893   WayptRef r = wayptGhost(arg);
1894   if (r.valid()) {
1895     return r;
1896   }
1897   
1898   FGPositioned* pos = positionedGhost(arg);
1899   if (!pos) {
1900     // let's check if the arg is hash, coudl extra a geod and hence build
1901     // a simple waypoint
1902     
1903     return WayptRef();
1904   }
1905   
1906 // special-case for runways
1907   if (pos->type() == FGPositioned::RUNWAY) {
1908     return new RunwayWaypt((FGRunway*) pos, NULL);
1909   }
1910   
1911   return new NavaidWaypoint(pos, NULL);
1912 }
1913
1914 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1915 {
1916   naRef result = naNewVector(c);
1917   BOOST_FOREACH(WayptRef wpt, wps) {
1918     naVec_append(result, ghostForWaypt(c, wpt.get()));
1919   }
1920   return result;
1921 }
1922
1923 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1924 {
1925   if (argc < 2) {
1926     naRuntimeError(c, "airwaysSearch needs at least two arguments");
1927   }
1928   
1929   WayptRef start = wayptFromArg(args[0]), 
1930     end = wayptFromArg(args[1]);
1931   
1932   if (!start || !end) {
1933     SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1934     return naNil();
1935   }
1936   
1937   bool highLevel = true;
1938   if ((argc > 2) && naIsString(args[2])) {
1939     if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1940       highLevel = false;
1941     }
1942   }
1943   
1944   WayptVec route;
1945   if (highLevel) {
1946     Airway::highLevel()->route(start, end, route);
1947   } else {
1948     Airway::lowLevel()->route(start, end, route);
1949   }
1950   
1951   return convertWayptVecToNasal(c, route);
1952 }
1953
1954 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1955 {
1956   SGGeod pos;
1957   int argOffset = geodFromArgs(args, 0, argc, pos);
1958   
1959   if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1960     naRuntimeError(c, "createWP: no identifier supplied");
1961   }
1962     
1963   std::string ident = naStr_data(args[argOffset++]);
1964   WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1965   
1966 // set waypt flags - approach, departure, pseudo, etc
1967   if (argc > argOffset) {
1968     WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1969     if (f == 0) {
1970       naRuntimeError(c, "createWP: bad waypoint role");
1971     }
1972       
1973     wpt->setFlag(f);
1974   }
1975   
1976   return ghostForWaypt(c, wpt);
1977 }
1978
1979 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1980 {
1981   if (argc < 1) {
1982     naRuntimeError(c, "createWPFrom: need at least one argument");
1983   }
1984   
1985   FGPositioned* positioned = positionedGhost(args[0]);
1986   if (!positioned) {
1987     naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1988   }
1989   
1990   WayptRef wpt;
1991   if (positioned->type() == FGPositioned::RUNWAY) {
1992     wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1993   } else {
1994     wpt = new NavaidWaypoint(positioned, NULL);
1995   }
1996
1997   // set waypt flags - approach, departure, pseudo, etc
1998   if (argc > 1) {
1999     WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
2000     if (f == 0) {
2001       naRuntimeError(c, "createWPFrom: bad waypoint role");
2002     }
2003     wpt->setFlag(f);
2004   }
2005   
2006   return ghostForWaypt(c, wpt);
2007 }
2008
2009 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
2010 {
2011   FlightPlan* fp = flightplanGhost(me);
2012   if (!fp) {
2013     naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
2014   }
2015
2016   int index;
2017   if (argc == 0) {
2018     index = fp->currentIndex();
2019   } else {
2020     index = (int) naNumValue(args[0]).num;
2021   }
2022   
2023   if ((index < 0) || (index >= fp->numLegs())) {
2024     return naNil();
2025   }
2026   
2027   return ghostForLeg(c, fp->legAtIndex(index));
2028 }
2029
2030 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
2031 {
2032   FlightPlan* fp = flightplanGhost(me);
2033   if (!fp) {
2034     naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
2035   }
2036   return ghostForLeg(c, fp->currentLeg());
2037 }
2038
2039 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
2040 {
2041   FlightPlan* fp = flightplanGhost(me);
2042   if (!fp) {
2043     naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
2044   }
2045   return ghostForLeg(c, fp->nextLeg());
2046 }
2047
2048 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
2049 {
2050   FlightPlan* fp = flightplanGhost(me);
2051   if (!fp) {
2052     naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
2053   }
2054   return naNum(fp->numLegs());
2055 }
2056
2057 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
2058 {
2059   FlightPlan* fp = flightplanGhost(me);
2060   if (!fp) {
2061     naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
2062   }
2063   
2064   WayptRef wp = wayptGhost(args[0]);
2065   int index = fp->numLegs();
2066   fp->insertWayptAtIndex(wp.get(), index);
2067   return naNum(index);
2068 }
2069
2070 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
2071 {
2072   FlightPlan* fp = flightplanGhost(me);
2073   if (!fp) {
2074     naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
2075   }
2076   
2077   WayptRef wp = wayptGhost(args[0]);
2078   int index = -1; // append
2079   if ((argc > 1) && naIsNum(args[1])) {
2080     index = (int) args[1].num;
2081   }
2082   
2083   fp->insertWayptAtIndex(wp.get(), index);
2084   return naNil();
2085 }
2086
2087 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
2088 {
2089   FlightPlan* fp = flightplanGhost(me);
2090   if (!fp) {
2091     naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
2092   }
2093   
2094   WayptRef wp = wayptGhost(args[0]);
2095   int index = -1; // append
2096   if ((argc > 1) && naIsNum(args[1])) {
2097     index = (int) args[1].num;
2098   }
2099   
2100   fp->insertWayptAtIndex(wp.get(), index + 1);
2101   return naNil();
2102 }
2103
2104 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
2105 {
2106   FlightPlan* fp = flightplanGhost(me);
2107   if (!fp) {
2108     naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
2109   }
2110   
2111   WayptVec wps;
2112   if (!naIsVector(args[0])) {
2113     naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
2114   }
2115
2116   int count = naVec_size(args[0]);
2117   for (int i=0; i<count; ++i) {
2118     Waypt* wp = wayptGhost(naVec_get(args[0], i));
2119     if (wp) {
2120       wps.push_back(wp);
2121     }
2122   }
2123   
2124   int index = -1; // append
2125   if ((argc > 1) && naIsNum(args[1])) {
2126     index = (int) args[1].num;
2127   }
2128
2129   fp->insertWayptsAtIndex(wps, index);
2130   return naNil();
2131 }
2132
2133 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
2134 {
2135   FlightPlan* fp = flightplanGhost(me);
2136   if (!fp) {
2137     naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
2138   }
2139   
2140   if ((argc < 1) || !naIsNum(args[0])) {
2141     naRuntimeError(c, "bad argument to flightplan.deleteWP");
2142   }
2143   
2144   int index = (int) args[0].num;
2145   fp->deleteIndex(index);
2146   return naNil();
2147 }
2148
2149 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
2150 {
2151   FlightPlan* fp = flightplanGhost(me);
2152   if (!fp) {
2153     naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
2154   }
2155   
2156   fp->clear();
2157   return naNil();
2158 }
2159
2160 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
2161 {
2162   FlightPlan* fp = flightplanGhost(me);
2163   if (!fp) {
2164     naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
2165   }
2166   
2167   if (argc < 1) {
2168     naRuntimeError(c, "insufficent args to flightplan.clearWPType");
2169   }
2170   
2171   WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
2172   if (flag == 0) {
2173     naRuntimeError(c, "clearWPType: bad waypoint role");
2174   }
2175     
2176   fp->clearWayptsWithFlag(flag);
2177   return naNil();
2178 }
2179
2180 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
2181 {
2182   FlightPlan* fp = flightplanGhost(me);
2183   if (!fp) {
2184     naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2185   }
2186   
2187   return ghostForFlightPlan(c, fp->clone());
2188 }
2189
2190 static naRef f_flightplan_pathGeod(naContext c, naRef me, int argc, naRef* args)
2191 {
2192   FlightPlan* fp = flightplanGhost(me);
2193   if (!fp) {
2194     naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2195   }
2196
2197   if ((argc < 1) || !naIsNum(args[0])) {
2198     naRuntimeError(c, "bad argument to flightplan.pathGeod");
2199   }
2200
2201   if ((argc > 1) && !naIsNum(args[1])) {
2202     naRuntimeError(c, "bad argument to flightplan.pathGeod");
2203   }
2204
2205   int index = (int) args[0].num;
2206   double offset = (argc > 1) ? args[1].num : 0.0;
2207   naRef result = naNewHash(c);
2208   SGGeod g = fp->pointAlongRoute(index, offset);
2209   hashset(c, result, "lat", naNum(g.getLatitudeDeg()));
2210   hashset(c, result, "lon", naNum(g.getLongitudeDeg()));
2211   return result;
2212 }
2213
2214 static naRef f_flightplan_finish(naContext c, naRef me, int argc, naRef* args)
2215 {
2216     FlightPlan* fp = flightplanGhost(me);
2217     if (!fp) {
2218         naRuntimeError(c, "flightplan.finish called on non-flightplan object");
2219     }
2220     
2221     fp->finish();
2222     return naNil();
2223 }
2224
2225 static naRef f_flightplan_indexOfWp(naContext c, naRef me, int argc, naRef* args)
2226 {
2227   FlightPlan* fp = flightplanGhost(me);
2228   if (!fp) {
2229     naRuntimeError(c, "flightplan.indexOfWP called on non-flightplan object");
2230   }
2231   
2232   FGPositioned* positioned = positionedGhost(args[0]);
2233   if (positioned) {
2234     return naNum(fp->findWayptIndex(positioned));
2235   }
2236   
2237   SGGeod pos;
2238   int argOffset = geodFromArgs(args, 0, argc, pos);
2239   if (argOffset > 0) {
2240     return naNum(fp->findWayptIndex(pos));
2241   }
2242
2243   return naNum(-1);
2244 }
2245
2246 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
2247 {
2248   FlightPlan::Leg* leg = fpLegGhost(me);
2249   if (!leg) {
2250     naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
2251   }
2252
2253     double speed = 0.0;
2254     if ((argc < 2) || !convertToNum(args[0], speed))
2255         naRuntimeError(c, "bad arguments to setSpeed");
2256     
2257   RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2258   leg->setSpeed(rr, speed);
2259   
2260   return naNil();
2261 }
2262
2263 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
2264 {
2265   FlightPlan::Leg* leg = fpLegGhost(me);
2266   if (!leg) {
2267     naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2268   }
2269   
2270     double alt = 0.0;
2271     if ((argc < 2) || !convertToNum(args[0], alt))
2272         naRuntimeError(c, "bad arguments to leg.setAltitude");
2273     
2274   RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2275     leg->setAltitude(rr, alt);
2276
2277   return naNil();
2278 }
2279
2280 static naRef f_leg_path(naContext c, naRef me, int argc, naRef* args)
2281 {
2282   FlightPlan::Leg* leg = fpLegGhost(me);
2283   if (!leg) {
2284     naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2285   }
2286   
2287   RoutePath path(leg->owner());
2288   SGGeodVec gv(path.pathForIndex(leg->index()));
2289
2290   naRef result = naNewVector(c);
2291   BOOST_FOREACH(SGGeod p, gv) {
2292     // construct a geo.Coord!
2293     naRef coord = naNewHash(c);
2294     hashset(c, coord, "lat", naNum(p.getLatitudeDeg()));
2295     hashset(c, coord, "lon", naNum(p.getLongitudeDeg()));
2296     naVec_append(result, coord);
2297   }
2298
2299   return result;
2300 }
2301
2302 static naRef f_leg_courseAndDistanceFrom(naContext c, naRef me, int argc, naRef* args)
2303 {
2304     FlightPlan::Leg* leg = fpLegGhost(me);
2305     if (!leg) {
2306         naRuntimeError(c, "leg.courseAndDistanceFrom called on non-flightplan-leg object");
2307     }
2308     
2309     SGGeod pos;
2310     geodFromArgs(args, 0, argc, pos);
2311   
2312     RoutePath path(leg->owner());
2313     SGGeod wpPos = path.positionForIndex(leg->index());
2314     double courseDeg, az2, distanceM;
2315     SGGeodesy::inverse(pos, wpPos, courseDeg, az2, distanceM);
2316   
2317     naRef result = naNewVector(c);
2318     naVec_append(result, naNum(courseDeg));
2319     naVec_append(result, naNum(distanceM * SG_METER_TO_NM));
2320     return result;
2321 }
2322
2323 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
2324 {
2325   flightgear::Waypt* w = wayptGhost(me);
2326   if (!w) {
2327     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2328   }
2329   
2330   FGPositioned* pos = w->source();
2331   if (!pos) {
2332     return naNil();
2333   }
2334   
2335   switch (pos->type()) {
2336   case FGPositioned::VOR:
2337   case FGPositioned::NDB:
2338   case FGPositioned::ILS:
2339   case FGPositioned::LOC:
2340   case FGPositioned::GS:
2341   case FGPositioned::DME:
2342   case FGPositioned::TACAN: {
2343     FGNavRecord* nav = (FGNavRecord*) pos;
2344     return ghostForNavaid(c, nav);
2345   }
2346       
2347   default:
2348     return naNil();
2349   }
2350 }
2351
2352 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
2353 {
2354   flightgear::Waypt* w = wayptGhost(me);
2355   if (!w) {
2356     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2357   }
2358   
2359   FGPositioned* pos = w->source();
2360   if (!pos || FGAirport::isAirportType(pos)) {
2361     return naNil();
2362   }
2363   
2364   return ghostForAirport(c, (FGAirport*) pos);
2365 }
2366
2367 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
2368 {
2369   flightgear::Waypt* w = wayptGhost(me);
2370   if (!w) {
2371     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2372   }
2373   
2374   FGPositioned* pos = w->source();
2375   if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
2376     return naNil();
2377   }
2378   
2379   return ghostForRunway(c, (FGRunway*) pos);
2380 }
2381
2382 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2383 {
2384   Procedure* proc = procedureGhost(me);
2385   if (!proc) {
2386     naRuntimeError(c, "procedure.transition called on non-procedure object");
2387   }
2388   
2389   if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2390     naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2391   }
2392   
2393   ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2394   Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2395   
2396   return ghostForProcedure(c, trans);
2397 }
2398
2399 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2400 {
2401   Procedure* proc = procedureGhost(me);
2402   if (!proc) {
2403     naRuntimeError(c, "procedure.route called on non-procedure object");
2404   }
2405   
2406 // wrapping up tow different routines here - approach routing from the IAF
2407 // to the associated runway, and SID/STAR routing via an enroute transition
2408 // and possibly a runway transition or not.
2409   if (Approach::isApproach(proc->type())) {
2410     WayptRef iaf;
2411     if (argc > 0) {
2412       iaf = wayptFromArg(args[0]);
2413     }
2414     
2415     WayptVec r;
2416     Approach* app = (Approach*) proc;
2417     if (!app->route(iaf, r)) {
2418       return naNil();
2419     }
2420     
2421     return convertWayptVecToNasal(c, r);
2422   } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2423     naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2424   }
2425   
2426   int argOffset = 0;
2427   FGRunway* rwy = runwayGhost(args[0]);
2428   if (rwy) ++argOffset;
2429   
2430   ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2431   Transition* trans = NULL;
2432   if (argOffset < argc) {
2433     trans = (Transition*) procedureGhost(args[argOffset]);
2434   }
2435   
2436   // note either runway or trans may be NULL - that's ok
2437   WayptVec r;
2438   if (!ad->route(rwy, trans, r)) {
2439     SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2440     return naNil();
2441   }
2442   
2443   return convertWayptVecToNasal(c, r);
2444 }
2445
2446
2447 // Table of extension functions.  Terminate with zeros.
2448 static struct { const char* name; naCFunction func; } funcs[] = {
2449   { "carttogeod", f_carttogeod },
2450   { "geodtocart", f_geodtocart },
2451   { "geodinfo", f_geodinfo },
2452   { "airportinfo", f_airportinfo },
2453   { "findAirportsWithinRange", f_findAirportsWithinRange },
2454   { "findAirportsByICAO", f_findAirportsByICAO },
2455   { "navinfo", f_navinfo },
2456   { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2457   { "findNavaidByFrequency", f_findNavaidByFrequency },
2458   { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2459   { "findNavaidsByID", f_findNavaidsByIdent },
2460   { "findFixesByID", f_findFixesByIdent },
2461   { "flightplan", f_route },
2462   { "registerFlightPlanDelegate", f_registerFPDelegate },
2463   { "createWP", f_createWP },
2464   { "createWPFrom", f_createWPFrom },
2465   { "airwaysRoute", f_airwaySearch },
2466   { "magvar", f_magvar },
2467   { "courseAndDistance", f_courseAndDistance },
2468   { "greatCircleMove", f_greatCircleMove },
2469   { "tileIndex", f_tileIndex },
2470   { "tilePath", f_tilePath },
2471   { 0, 0 }
2472 };
2473
2474
2475 naRef initNasalPositioned(naRef globals, naContext c)
2476 {
2477     airportPrototype = naNewHash(c);
2478     naSave(c, airportPrototype);
2479   
2480     hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2481     hashset(c, airportPrototype, "runwaysWithoutReciprocals", naNewFunc(c, naNewCCode(c, f_airport_runwaysWithoutReciprocals)));
2482     hashset(c, airportPrototype, "helipad", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2483     hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2484     hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2485     hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2486     hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2487     hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2488     hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2489     hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2490     hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2491     hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2492     hashset(c, airportPrototype, "findBestRunwayForPos", naNewFunc(c, naNewCCode(c, f_airport_findBestRunway)));
2493     hashset(c, airportPrototype, "tostring", naNewFunc(c, naNewCCode(c, f_airport_toString)));
2494   
2495     flightplanPrototype = naNewHash(c);
2496     naSave(c, flightplanPrototype);
2497       
2498     hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2499     hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP))); 
2500     hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP))); 
2501     hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2502     hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP))); 
2503     hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP))); 
2504     hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP))); 
2505     hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter))); 
2506     hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints))); 
2507     hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan))); 
2508     hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType))); 
2509     hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone))); 
2510     hashset(c, flightplanPrototype, "pathGeod", naNewFunc(c, naNewCCode(c, f_flightplan_pathGeod)));
2511     hashset(c, flightplanPrototype, "finish", naNewFunc(c, naNewCCode(c, f_flightplan_finish)));
2512     hashset(c, flightplanPrototype, "indexOfWP", naNewFunc(c, naNewCCode(c, f_flightplan_indexOfWp)));
2513     
2514     waypointPrototype = naNewHash(c);
2515     naSave(c, waypointPrototype);
2516     
2517     hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2518     hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2519     hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2520   
2521     procedurePrototype = naNewHash(c);
2522     naSave(c, procedurePrototype);
2523     hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2524     hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2525   
2526     fpLegPrototype = naNewHash(c);
2527     naSave(c, fpLegPrototype);
2528     hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2529     hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2530     hashset(c, fpLegPrototype, "path", naNewFunc(c, naNewCCode(c, f_leg_path)));
2531     hashset(c, fpLegPrototype, "courseAndDistanceFrom", naNewFunc(c, naNewCCode(c, f_leg_courseAndDistanceFrom)));
2532   
2533     for(int i=0; funcs[i].name; i++) {
2534       hashset(c, globals, funcs[i].name,
2535       naNewFunc(c, naNewCCode(c, funcs[i].func)));
2536     }
2537   
2538   return naNil();
2539 }
2540
2541 void postinitNasalPositioned(naRef globals, naContext c)
2542 {
2543   naRef geoModule = naHash_cget(globals, (char*) "geo");
2544   if (naIsNil(geoModule)) {
2545     SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2546     return;
2547   }
2548   
2549   geoCoordClass = naHash_cget(geoModule, (char*) "Coord");
2550 }
2551
2552