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