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