]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned.cxx
Expose SGCondition as a ghost to Nasal directly.
[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     const SGGeod& parkLoc = park->getGeod();
1295     naRef ph = naNewHash(c);
1296     hashset(c, ph, "name", stringToNasal(c, park->getName()));
1297     hashset(c, ph, "lat", naNum(parkLoc.getLatitudeDeg()));
1298     hashset(c, ph, "lon", naNum(parkLoc.getLongitudeDeg()));
1299     hashset(c, ph, "elevation", naNum(parkLoc.getElevationM()));
1300     naVec_append(r, ph);
1301   }
1302   
1303   return r;
1304 }
1305
1306 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1307 {
1308   FGAirport* apt = airportGhost(me);
1309   if (!apt) {
1310     naRuntimeError(c, "airport.getSid called on non-airport object");
1311   }
1312   
1313   if ((argc != 1) || !naIsString(args[0])) {
1314     naRuntimeError(c, "airport.getSid passed invalid argument");
1315   }
1316   
1317   string ident = naStr_data(args[0]);
1318   return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1319 }
1320
1321 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1322 {
1323   FGAirport* apt = airportGhost(me);
1324   if (!apt) {
1325     naRuntimeError(c, "airport.getStar called on non-airport object");
1326   }
1327   
1328   if ((argc != 1) || !naIsString(args[0])) {
1329     naRuntimeError(c, "airport.getStar passed invalid argument");
1330   }
1331   
1332   string ident = naStr_data(args[0]);
1333   return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1334 }
1335
1336 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1337 {
1338   FGAirport* apt = airportGhost(me);
1339   if (!apt) {
1340     naRuntimeError(c, "airport.getIAP called on non-airport object");
1341   }
1342   
1343   if ((argc != 1) || !naIsString(args[0])) {
1344     naRuntimeError(c, "airport.getIAP passed invalid argument");
1345   }
1346   
1347   string ident = naStr_data(args[0]);
1348   return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1349 }
1350
1351 static naRef f_airport_toString(naContext c, naRef me, int argc, naRef* args)
1352 {
1353   FGAirport* apt = airportGhost(me);
1354   if (!apt) {
1355     naRuntimeError(c, "airport.tostring called on non-airport object");
1356   }
1357   
1358   return stringToNasal(c, "an airport " + apt->ident());
1359 }
1360
1361 // Returns vector of data hash for navaid of a <type>, nil on error
1362 // navaids sorted by ascending distance 
1363 // navinfo([<lat>,<lon>],[<type>],[<id>])
1364 // lat/lon (numeric): use latitude/longitude instead of ac position
1365 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1366 // id:                (partial) id of the fix
1367 // examples:
1368 // navinfo("vor")     returns all vors
1369 // navinfo("HAM")     return all navaids who's name start with "HAM"
1370 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1371 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM" 
1372 //                           sorted by distance relative to lat=34, lon=48
1373 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1374 {
1375   SGGeod pos;
1376   
1377   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1378     pos = SGGeod::fromDeg(args[1].num, args[0].num);
1379     args += 2;
1380     argc -= 2;
1381   } else {
1382     pos = globals->get_aircraft_position();
1383   }
1384   
1385   FGPositioned::Type type = FGPositioned::INVALID;
1386   nav_list_type navlist;
1387   const char * id = "";
1388   
1389   if(argc > 0 && naIsString(args[0])) {
1390     const char *s = naStr_data(args[0]);
1391     if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1392     else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1393     else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1394     else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1395     else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1396     else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1397     else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1398     else id = s; // this is an id
1399     ++args;
1400     --argc;
1401   } 
1402   
1403   if(argc > 0 && naIsString(args[0])) {
1404     if( *id != 0 ) {
1405       naRuntimeError(c, "navinfo() called with navaid id");
1406       return naNil();
1407     }
1408     id = naStr_data(args[0]);
1409     ++args;
1410     --argc;
1411   }
1412   
1413   if( argc > 0 ) {
1414     naRuntimeError(c, "navinfo() called with too many arguments");
1415     return naNil();
1416   }
1417   
1418   navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
1419   
1420   naRef reply = naNewVector(c);
1421   for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1422     naVec_append( reply, ghostForNavaid(c, *it) );
1423   }
1424   return reply;
1425 }
1426
1427 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1428 {
1429   int argOffset = 0;
1430   SGGeod pos = globals->get_aircraft_position();
1431   argOffset += geodFromArgs(args, 0, argc, pos);
1432   
1433   if (!naIsNum(args[argOffset])) {
1434     naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1435   }
1436   
1437   FGPositioned::Type type = FGPositioned::INVALID;
1438   double rangeNm = args[argOffset++].num;
1439   if (argOffset < argc) {
1440     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1441   }
1442   
1443   naRef r = naNewVector(c);
1444   FGNavList::TypeFilter filter(type);
1445   FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1446   FGPositioned::sortByRange(navs, pos);
1447   
1448   BOOST_FOREACH(FGPositionedRef a, navs) {
1449     FGNavRecord* nav = (FGNavRecord*) a.get();
1450     naVec_append(r, ghostForNavaid(c, nav));
1451   }
1452   
1453   return r;
1454 }
1455
1456 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1457 {
1458   int argOffset = 0;
1459   SGGeod pos = globals->get_aircraft_position();
1460   argOffset += geodFromArgs(args, 0, argc, pos);
1461   
1462   if (!naIsNum(args[argOffset])) {
1463     naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1464   }
1465   
1466   FGPositioned::Type type = FGPositioned::INVALID;
1467   double freqMhz = args[argOffset++].num;
1468   if (argOffset < argc) {
1469     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1470   }
1471   
1472   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1473   if (navs.empty()) {
1474     return naNil();
1475   }
1476   
1477   return ghostForNavaid(c, navs.front().ptr());
1478 }
1479
1480 static naRef f_findNavaidsByFrequency(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 (!naIsNum(args[argOffset])) {
1487     naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1488   }
1489   
1490   FGPositioned::Type type = FGPositioned::INVALID;
1491   double freqMhz = args[argOffset++].num;
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()->findAllByFreq(freqMhz, pos, 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_findNavaidsByIdent(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, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1514   }
1515   
1516   FGPositioned::Type type = FGPositioned::INVALID;
1517   string ident = naStr_data(args[argOffset++]);
1518   if (argOffset < argc) {
1519     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1520   }
1521   
1522   naRef r = naNewVector(c);
1523   nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
1524   
1525   BOOST_FOREACH(nav_rec_ptr a, navs) {
1526     naVec_append(r, ghostForNavaid(c, a.ptr()));
1527   }
1528   
1529   return r;
1530 }
1531
1532 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1533 {
1534   int argOffset = 0;
1535   SGGeod pos = globals->get_aircraft_position();
1536   argOffset += geodFromArgs(args, 0, argc, pos);
1537   
1538   if (!naIsString(args[argOffset])) {
1539     naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1540   }
1541   
1542   string ident(naStr_data(args[argOffset]));
1543   naRef r = naNewVector(c);
1544   
1545   FGPositioned::TypeFilter filter(FGPositioned::FIX);
1546   FGPositioned::List fixes = FGPositioned::findAllWithIdent(ident, &filter);
1547   FGPositioned::sortByRange(fixes, pos);
1548   
1549   BOOST_FOREACH(FGPositionedRef f, fixes) {
1550     naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1551   }
1552   
1553   return r;
1554 }
1555
1556 // Convert a cartesian point to a geodetic lat/lon/altitude.
1557 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1558 {
1559   SGGeod pos = globals->get_aircraft_position();
1560   if (argc == 0) {
1561     // fine, use aircraft position
1562   } else if (geodFromArgs(args, 0, argc, pos)) {
1563     // okay
1564   } else {
1565     naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1566   }
1567   
1568   double jd = globals->get_time_params()->getJD();
1569   double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1570   return naNum(magvarDeg);
1571 }
1572
1573 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1574 {
1575     SGGeod from = globals->get_aircraft_position(), to, p;
1576     int argOffset = geodFromArgs(args, 0, argc, p);
1577     if (geodFromArgs(args, argOffset, argc, to)) {
1578       from = p; // we parsed both FROM and TO args, so first was from
1579     } else {
1580       to = p; // only parsed one arg, so FROM is current
1581     }
1582   
1583     if (argOffset == 0) {
1584         naRuntimeError(c, "invalid arguments to courseAndDistance");
1585     }
1586     
1587     double course, course2, d;
1588     SGGeodesy::inverse(from, to, course, course2, d);
1589     
1590     naRef result = naNewVector(c);
1591     naVec_append(result, naNum(course));
1592     naVec_append(result, naNum(d * SG_METER_TO_NM));
1593     return result;
1594 }
1595
1596 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1597 {
1598   SGGeod from = globals->get_aircraft_position(), to;
1599   int argOffset = 0;
1600   
1601   // complication - don't inerpret two doubles (as the only args)
1602   // as a lat,lon pair - only do so if we have at least three args.
1603   if (argc > 2) {
1604     argOffset = geodFromArgs(args, 0, argc, from);
1605   }
1606   
1607   if ((argOffset + 1) >= argc) {
1608     naRuntimeError(c, "isufficent arguments to greatCircleMove");
1609   }
1610   
1611   if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1612     naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1613                    argOffset, argOffset + 1);
1614   }
1615   
1616   double course = args[argOffset].num, course2;
1617   double distanceNm = args[argOffset + 1].num;
1618   SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1619   
1620   // return geo.Coord
1621   naRef coord = naNewHash(c);
1622   hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1623   hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1624   return coord;
1625 }
1626
1627 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1628 {
1629     SGGeod pos = globals->get_aircraft_position();
1630     geodFromArgs(args, 0, argc, pos);
1631     SGBucket b(pos);
1632     return stringToNasal(c, b.gen_base_path());
1633 }
1634
1635 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1636 {
1637   SGGeod pos = globals->get_aircraft_position();
1638   geodFromArgs(args, 0, argc, pos);
1639   SGBucket b(pos);
1640   return naNum(b.gen_index());
1641 }
1642
1643 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1644 {
1645   if (argc == 0) {
1646     FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));  
1647     return ghostForFlightPlan(c, rm->flightPlan());
1648   }
1649   
1650   if ((argc > 0) && naIsString(args[0])) {
1651     flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1652     SGPath path(naStr_data(args[0]));
1653     if (!path.exists()) {
1654       naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1655     }
1656     
1657     if (!fp->load(path)) {
1658       SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1659       delete fp;
1660       return naNil();
1661     }
1662     
1663     return ghostForFlightPlan(c, fp);
1664   }
1665   
1666   naRuntimeError(c, "bad arguments to flightplan()");
1667   return naNil();
1668 }
1669
1670 class NasalFPDelegate : public FlightPlan::Delegate
1671 {
1672 public:
1673   NasalFPDelegate(FlightPlan* fp, FGNasalSys* sys, naRef ins) :
1674     _nasal(sys),
1675     _plan(fp),
1676     _instance(ins)
1677   {
1678     SG_LOG(SG_NASAL, SG_INFO, "created Nasal delegate for " << fp);
1679     _gcSaveKey = _nasal->gcSave(ins);
1680   }
1681   
1682   virtual ~NasalFPDelegate()
1683   {
1684     SG_LOG(SG_NASAL, SG_INFO, "destroying Nasal delegate for " << _plan);
1685     _nasal->gcRelease(_gcSaveKey);
1686   }
1687   
1688   virtual void departureChanged()
1689   {
1690     callDelegateMethod("departureChanged");
1691   }
1692   
1693   virtual void arrivalChanged()
1694   {
1695     callDelegateMethod("arrivalChanged");
1696   }
1697   
1698   virtual void waypointsChanged()
1699   {
1700     callDelegateMethod("waypointsChanged");
1701   }
1702   
1703   virtual void currentWaypointChanged()
1704   {
1705     callDelegateMethod("currentWaypointChanged");
1706   }
1707 private:
1708   
1709   void callDelegateMethod(const char* method)
1710   {
1711     naRef f;
1712     naMember_cget(_nasal->context(), _instance, method, &f);
1713     if (naIsNil(f)) {
1714       return; // no method on the delegate
1715     }
1716     
1717     naRef arg[1];
1718     arg[0] = ghostForFlightPlan(_nasal->context(), _plan);
1719     _nasal->callMethod(f, _instance, 1, arg, naNil());
1720   }
1721   
1722   FGNasalSys* _nasal;
1723   FlightPlan* _plan;
1724   naRef _instance;
1725   int _gcSaveKey;
1726 };
1727
1728 class NasalFPDelegateFactory : public FlightPlan::DelegateFactory
1729 {
1730 public:
1731   NasalFPDelegateFactory(naRef code)
1732   {
1733     _nasal = (FGNasalSys*) globals->get_subsystem("nasal");
1734     _func = code;
1735     _gcSaveKey = _nasal->gcSave(_func);
1736   }
1737   
1738   ~NasalFPDelegateFactory()
1739   {
1740     _nasal->gcRelease(_gcSaveKey);
1741   }
1742   
1743   virtual FlightPlan::Delegate* createFlightPlanDelegate(FlightPlan* fp)
1744   {
1745     naRef args[1];
1746     args[0] = ghostForFlightPlan(_nasal->context(), fp);
1747     naRef instance = _nasal->call(_func, 1, args, naNil());
1748     if (naIsNil(instance)) {
1749       return NULL;
1750     }
1751     
1752     return new NasalFPDelegate(fp, _nasal, instance);
1753   }
1754 private:
1755   FGNasalSys* _nasal;
1756   naRef _func;
1757   int _gcSaveKey;
1758 };
1759
1760 static naRef f_registerFPDelegate(naContext c, naRef me, int argc, naRef* args)
1761 {
1762   if ((argc < 1) || !naIsFunc(args[0])) {
1763     naRuntimeError(c, "non-function argument to registerFlightPlanDelegate");
1764   }
1765   
1766   NasalFPDelegateFactory* factory = new NasalFPDelegateFactory(args[0]);
1767   FlightPlan::registerDelegateFactory(factory);
1768   
1769   return naNil();
1770 }
1771
1772 static WayptRef wayptFromArg(naRef arg)
1773 {
1774   WayptRef r = wayptGhost(arg);
1775   if (r.valid()) {
1776     return r;
1777   }
1778   
1779   FGPositioned* pos = positionedGhost(arg);
1780   if (!pos) {
1781     // let's check if the arg is hash, coudl extra a geod and hence build
1782     // a simple waypoint
1783     
1784     return WayptRef();
1785   }
1786   
1787 // special-case for runways
1788   if (pos->type() == FGPositioned::RUNWAY) {
1789     return new RunwayWaypt((FGRunway*) pos, NULL);
1790   }
1791   
1792   return new NavaidWaypoint(pos, NULL);
1793 }
1794
1795 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1796 {
1797   naRef result = naNewVector(c);
1798   BOOST_FOREACH(WayptRef wpt, wps) {
1799     naVec_append(result, ghostForWaypt(c, wpt.get()));
1800   }
1801   return result;
1802 }
1803
1804 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1805 {
1806   if (argc < 2) {
1807     naRuntimeError(c, "airwaysSearch needs at least two arguments");
1808   }
1809   
1810   WayptRef start = wayptFromArg(args[0]), 
1811     end = wayptFromArg(args[1]);
1812   
1813   if (!start || !end) {
1814     SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1815     return naNil();
1816   }
1817   
1818   bool highLevel = true;
1819   if ((argc > 2) && naIsString(args[2])) {
1820     if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1821       highLevel = false;
1822     }
1823   }
1824   
1825   WayptVec route;
1826   if (highLevel) {
1827     Airway::highLevel()->route(start, end, route);
1828   } else {
1829     Airway::lowLevel()->route(start, end, route);
1830   }
1831   
1832   return convertWayptVecToNasal(c, route);
1833 }
1834
1835 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1836 {
1837   SGGeod pos;
1838   int argOffset = geodFromArgs(args, 0, argc, pos);
1839   
1840   if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1841     naRuntimeError(c, "createWP: no identifier supplied");
1842   }
1843     
1844   string ident = naStr_data(args[argOffset++]);
1845   WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1846   
1847 // set waypt flags - approach, departure, pseudo, etc
1848   if (argc > argOffset) {
1849     WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1850     wpt->setFlag(f);
1851   }
1852   
1853   return ghostForWaypt(c, wpt);
1854 }
1855
1856 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1857 {
1858   if (argc < 1) {
1859     naRuntimeError(c, "createWPFrom: need at least one argument");
1860   }
1861   
1862   FGPositioned* positioned = positionedGhost(args[0]);
1863   if (!positioned) {
1864     naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1865   }
1866   
1867   WayptRef wpt;
1868   if (positioned->type() == FGPositioned::RUNWAY) {
1869     wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1870   } else {
1871     wpt = new NavaidWaypoint(positioned, NULL);
1872   }
1873
1874   // set waypt flags - approach, departure, pseudo, etc
1875   if (argc > 1) {
1876     WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
1877     wpt->setFlag(f);
1878   }
1879   
1880   return ghostForWaypt(c, wpt);
1881 }
1882
1883 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
1884 {
1885   FlightPlan* fp = flightplanGhost(me);
1886   if (!fp) {
1887     naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
1888   }
1889
1890   int index;
1891   if (argc == 0) {
1892     index = fp->currentIndex();
1893   } else {
1894     index = (int) naNumValue(args[0]).num;
1895   }
1896   
1897   if ((index < 0) || (index >= fp->numLegs())) {
1898     return naNil();
1899   }
1900   
1901   return ghostForLeg(c, fp->legAtIndex(index));
1902 }
1903
1904 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
1905 {
1906   FlightPlan* fp = flightplanGhost(me);
1907   if (!fp) {
1908     naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
1909   }
1910   return ghostForLeg(c, fp->currentLeg());
1911 }
1912
1913 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
1914 {
1915   FlightPlan* fp = flightplanGhost(me);
1916   if (!fp) {
1917     naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
1918   }
1919   return ghostForLeg(c, fp->nextLeg());
1920 }
1921
1922 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
1923 {
1924   FlightPlan* fp = flightplanGhost(me);
1925   if (!fp) {
1926     naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
1927   }
1928   return naNum(fp->numLegs());
1929 }
1930
1931 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
1932 {
1933   FlightPlan* fp = flightplanGhost(me);
1934   if (!fp) {
1935     naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
1936   }
1937   
1938   WayptRef wp = wayptGhost(args[0]);
1939   int index = fp->numLegs();
1940   fp->insertWayptAtIndex(wp.get(), index);
1941   return naNum(index);
1942 }
1943
1944 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
1945 {
1946   FlightPlan* fp = flightplanGhost(me);
1947   if (!fp) {
1948     naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
1949   }
1950   
1951   WayptRef wp = wayptGhost(args[0]);
1952   int index = -1; // append
1953   if ((argc > 1) && naIsNum(args[1])) {
1954     index = (int) args[1].num;
1955   }
1956   
1957   fp->insertWayptAtIndex(wp.get(), index);
1958   return naNil();
1959 }
1960
1961 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
1962 {
1963   FlightPlan* fp = flightplanGhost(me);
1964   if (!fp) {
1965     naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
1966   }
1967   
1968   WayptRef wp = wayptGhost(args[0]);
1969   int index = -1; // append
1970   if ((argc > 1) && naIsNum(args[1])) {
1971     index = (int) args[1].num;
1972   }
1973   
1974   fp->insertWayptAtIndex(wp.get(), index + 1);
1975   return naNil();
1976 }
1977
1978 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
1979 {
1980   FlightPlan* fp = flightplanGhost(me);
1981   if (!fp) {
1982     naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
1983   }
1984   
1985   WayptVec wps;
1986   if (!naIsVector(args[0])) {
1987     naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
1988   }
1989
1990   int count = naVec_size(args[0]);
1991   for (int i=0; i<count; ++i) {
1992     Waypt* wp = wayptGhost(naVec_get(args[0], i));
1993     if (wp) {
1994       wps.push_back(wp);
1995     }
1996   }
1997   
1998   int index = -1; // append
1999   if ((argc > 1) && naIsNum(args[1])) {
2000     index = (int) args[1].num;
2001   }
2002
2003   fp->insertWayptsAtIndex(wps, index);
2004   return naNil();
2005 }
2006
2007 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
2008 {
2009   FlightPlan* fp = flightplanGhost(me);
2010   if (!fp) {
2011     naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
2012   }
2013   
2014   if ((argc < 1) || !naIsNum(args[0])) {
2015     naRuntimeError(c, "bad argument to flightplan.deleteWP");
2016   }
2017   
2018   int index = (int) args[0].num;
2019   fp->deleteIndex(index);
2020   return naNil();
2021 }
2022
2023 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
2024 {
2025   FlightPlan* fp = flightplanGhost(me);
2026   if (!fp) {
2027     naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
2028   }
2029   
2030   fp->clear();
2031   return naNil();
2032 }
2033
2034 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
2035 {
2036   FlightPlan* fp = flightplanGhost(me);
2037   if (!fp) {
2038     naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
2039   }
2040   
2041   if (argc < 1) {
2042     naRuntimeError(c, "insufficent args to flightplan.clearWPType");
2043   }
2044   
2045   WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
2046   fp->clearWayptsWithFlag(flag);
2047   return naNil();
2048 }
2049
2050 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
2051 {
2052   FlightPlan* fp = flightplanGhost(me);
2053   if (!fp) {
2054     naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2055   }
2056   
2057   return ghostForFlightPlan(c, fp->clone());
2058 }
2059
2060 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
2061 {
2062   FlightPlan::Leg* leg = fpLegGhost(me);
2063   if (!leg) {
2064     naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
2065   }
2066   
2067   if (argc < 2) {
2068     naRuntimeError(c, "bad arguments to leg.setSpeed");
2069   }
2070   
2071   RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2072   leg->setSpeed(rr, args[0].num);
2073   return naNil();
2074 }
2075
2076 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
2077 {
2078   FlightPlan::Leg* leg = fpLegGhost(me);
2079   if (!leg) {
2080     naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2081   }
2082   
2083   if (argc < 2) {
2084     naRuntimeError(c, "bad arguments to leg.setAltitude");
2085   }
2086   
2087   RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2088   leg->setAltitude(rr, args[0].num);
2089   return naNil();
2090 }
2091
2092 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
2093 {
2094   flightgear::Waypt* w = wayptGhost(me);
2095   if (!w) {
2096     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2097   }
2098   
2099   FGPositioned* pos = w->source();
2100   if (!pos) {
2101     return naNil();
2102   }
2103   
2104   switch (pos->type()) {
2105   case FGPositioned::VOR:
2106   case FGPositioned::NDB:
2107   case FGPositioned::ILS:
2108   case FGPositioned::LOC:
2109   case FGPositioned::GS:
2110   case FGPositioned::DME:
2111   case FGPositioned::TACAN: {
2112     FGNavRecord* nav = (FGNavRecord*) pos;
2113     return ghostForNavaid(c, nav);
2114   }
2115       
2116   default:
2117     return naNil();
2118   }
2119 }
2120
2121 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
2122 {
2123   flightgear::Waypt* w = wayptGhost(me);
2124   if (!w) {
2125     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2126   }
2127   
2128   FGPositioned* pos = w->source();
2129   if (!pos || FGAirport::isAirportType(pos)) {
2130     return naNil();
2131   }
2132   
2133   return ghostForAirport(c, (FGAirport*) pos);
2134 }
2135
2136 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
2137 {
2138   flightgear::Waypt* w = wayptGhost(me);
2139   if (!w) {
2140     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2141   }
2142   
2143   FGPositioned* pos = w->source();
2144   if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
2145     return naNil();
2146   }
2147   
2148   return ghostForRunway(c, (FGRunway*) pos);
2149 }
2150
2151 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2152 {
2153   Procedure* proc = procedureGhost(me);
2154   if (!proc) {
2155     naRuntimeError(c, "procedure.transition called on non-procedure object");
2156   }
2157   
2158   if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2159     naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2160   }
2161   
2162   ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2163   Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2164   
2165   return ghostForProcedure(c, trans);
2166 }
2167
2168 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2169 {
2170   Procedure* proc = procedureGhost(me);
2171   if (!proc) {
2172     naRuntimeError(c, "procedure.route called on non-procedure object");
2173   }
2174   
2175 // wrapping up tow different routines here - approach routing from the IAF
2176 // to the associated runway, and SID/STAR routing via an enroute transition
2177 // and possibly a runway transition or not.
2178   if (Approach::isApproach(proc->type())) {
2179     WayptRef iaf;
2180     if (argc > 0) {
2181       iaf = wayptFromArg(args[0]);
2182     }
2183     
2184     WayptVec r;
2185     Approach* app = (Approach*) proc;
2186     if (!app->route(iaf, r)) {
2187       SG_LOG(SG_NASAL, SG_WARN, "procedure.route failed for Approach somehow");
2188       return naNil();
2189     }
2190     
2191     return convertWayptVecToNasal(c, r);
2192   } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2193     naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2194   }
2195   
2196   int argOffset = 0;
2197   FGRunway* rwy = runwayGhost(args[0]);
2198   if (rwy) ++argOffset;
2199   
2200   ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2201   Transition* trans = NULL;
2202   if (argOffset < argc) {
2203     trans = (Transition*) procedureGhost(args[argOffset]);
2204   }
2205   
2206   // note either runway or trans may be NULL - that's ok
2207   WayptVec r;
2208   if (!ad->route(rwy, trans, r)) {
2209     SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2210     return naNil();
2211   }
2212   
2213   return convertWayptVecToNasal(c, r);
2214 }
2215
2216
2217 // Table of extension functions.  Terminate with zeros.
2218 static struct { const char* name; naCFunction func; } funcs[] = {
2219   { "carttogeod", f_carttogeod },
2220   { "geodtocart", f_geodtocart },
2221   { "geodinfo", f_geodinfo },
2222   { "airportinfo", f_airportinfo },
2223   { "findAirportsWithinRange", f_findAirportsWithinRange },
2224   { "findAirportsByICAO", f_findAirportsByICAO },
2225   { "navinfo", f_navinfo },
2226   { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2227   { "findNavaidByFrequency", f_findNavaidByFrequency },
2228   { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2229   { "findNavaidsByID", f_findNavaidsByIdent },
2230   { "findFixesByID", f_findFixesByIdent },
2231   { "flightplan", f_route },
2232   { "registerFlightPlanDelegate", f_registerFPDelegate },
2233   { "createWP", f_createWP },
2234   { "createWPFrom", f_createWPFrom },
2235   { "airwaysRoute", f_airwaySearch },
2236   { "magvar", f_magvar },
2237   { "courseAndDistance", f_courseAndDistance },
2238   { "greatCircleMove", f_greatCircleMove },
2239   { "tileIndex", f_tileIndex },
2240   { "tilePath", f_tilePath },
2241   { 0, 0 }
2242 };
2243
2244
2245 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
2246 {
2247     airportPrototype = naNewHash(c);
2248     hashset(c, gcSave, "airportProto", airportPrototype);
2249   
2250     hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2251     hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2252     hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2253     hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2254     hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2255     hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2256     hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2257     hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2258     hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2259     hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2260     hashset(c, airportPrototype, "tostring", naNewFunc(c, naNewCCode(c, f_airport_toString)));
2261   
2262     flightplanPrototype = naNewHash(c);
2263     hashset(c, gcSave, "flightplanProto", flightplanPrototype);
2264       
2265     hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2266     hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP))); 
2267     hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP))); 
2268     hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2269     hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP))); 
2270     hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP))); 
2271     hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP))); 
2272     hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter))); 
2273     hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints))); 
2274     hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan))); 
2275     hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType))); 
2276     hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone))); 
2277   
2278     waypointPrototype = naNewHash(c);
2279     hashset(c, gcSave, "wayptProto", waypointPrototype);
2280     
2281     hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2282     hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2283     hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2284   
2285     procedurePrototype = naNewHash(c);
2286     hashset(c, gcSave, "procedureProto", procedurePrototype);
2287     hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2288     hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2289   
2290     fpLegPrototype = naNewHash(c);
2291     hashset(c, gcSave, "fpLegProto", fpLegPrototype);
2292     hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2293     hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2294   
2295     for(int i=0; funcs[i].name; i++) {
2296       hashset(c, globals, funcs[i].name,
2297       naNewFunc(c, naNewCCode(c, funcs[i].func)));
2298     }
2299   
2300   return naNil();
2301 }
2302
2303 void postinitNasalPositioned(naRef globals, naContext c)
2304 {
2305   naRef geoModule = naHash_cget(globals, (char*) "geo");
2306   if (naIsNil(geoModule)) {
2307     SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2308     return;
2309   }
2310   
2311   geoCoordClass = naHash_cget(geoModule, (char*) "Coord");
2312 }
2313
2314