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