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