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