]> git.mxchange.org Git - flightgear.git/blobdiff - src/Instrumentation/gps.cxx
Bugfix: don't crash on localizers with no associated runway (due to inconsistent...
[flightgear.git] / src / Instrumentation / gps.cxx
index b626e4dc1b42a525be0e511eee0669704fbe2d02..2c6f36495882344acf8d2b10ddfe32bfaec72c66 100644 (file)
@@ -24,6 +24,7 @@
 #include <simgear/math/sg_random.h>
 #include <simgear/sg_inlines.h>
 #include <simgear/math/sg_geodesy.hxx>
+#include <simgear/structure/exception.hxx>
 
 using std::auto_ptr;
 using std::string;
@@ -73,28 +74,6 @@ SGGeod SGGeodProperty::get() const
     }
 }
 
-static void tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef, 
-  const char* lonStr, const char* latStr, const char* altStr)
-{
-  aNode->tie(lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
-  aNode->tie(latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
-  
-  if (altStr) {
-    aNode->tie(altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
-  }
-}
-
-static void tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef, 
-  const char* lonStr, const char* latStr, const char* altStr)
-{
-  aNode->tie(lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
-  aNode->tie(latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
-  
-  if (altStr) {
-    aNode->tie(altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
-  }
-}
-
 static const char* makeTTWString(double TTW)
 {
   if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
@@ -207,32 +186,33 @@ private:
 GPS::Config::Config() :
   _enableTurnAnticipation(true),
   _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
-  _overflightArmDistance(0.5),
+  _overflightArmDistance(1.0),
   _waypointAlertTime(30.0),
   _tuneRadio1ToRefVor(false),
   _minRunwayLengthFt(0.0),
   _requireHardSurface(true),
-  _cdiMaxDeflectionNm(-1), // default to angular mode
+  _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
   _driveAutopilot(true)
 {
   _enableTurnAnticipation = false;
   _extCourseSource = fgGetNode("/instrumentation/nav[0]/radials/selected-deg", true);
 }
 
-void GPS::Config::init(SGPropertyNode* aCfgNode)
+void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
 {
-  aCfgNode->tie("turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
-  aCfgNode->tie("turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
-  aCfgNode->tie("wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
-  aCfgNode->tie("tune-nav-radio-to-ref-vor", SGRawValuePointer<bool>(&_tuneRadio1ToRefVor));
-  aCfgNode->tie("min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
-  aCfgNode->tie("hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
+  aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
+  
+  aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
+  aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
+  aOwner->tie(aCfg, "tune-nav-radio-to-ref-vor", SGRawValuePointer<bool>(&_tuneRadio1ToRefVor));
+  aOwner->tie(aCfg, "min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
+  aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
   
-  aCfgNode->tie("course-source", SGRawValueMethods<GPS::Config, const char*>
+  aOwner->tie(aCfg, "course-source", SGRawValueMethods<GPS::Config, const char*>
     (*this, &GPS::Config::getCourseSource, &GPS::Config::setCourseSource));
     
-  aCfgNode->tie("cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
-  aCfgNode->tie("drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
+  aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
+  aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
 }
 
 const char* 
@@ -280,13 +260,19 @@ GPS::Config::setExternalCourse(double aCourseDeg)
 ////////////////////////////////////////////////////////////////////////////
 
 GPS::GPS ( SGPropertyNode *node) : 
-  _last_valid(false),
+  _selectedCourse(0.0),
+  _dataValid(false),
+  _lastPosValid(false),
+  _mode("init"),
   _name(node->getStringValue("name", "gps")),
   _num(node->getIntValue("number", 0)),
   _computeTurnData(false),
   _anticipateTurn(false),
   _inTurn(false)
 {
+  string branch = "/instrumentation/" + _name;
+  _gpsNode = fgGetNode(branch.c_str(), _num, true );
+  _scratchNode = _gpsNode->getChild("scratch", 0, true);
 }
 
 GPS::~GPS ()
@@ -296,113 +282,39 @@ GPS::~GPS ()
 void
 GPS::init ()
 {
-    _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
-    assert(_routeMgr);
+  _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
+  assert(_routeMgr);
   
-    string branch;
-    branch = "/instrumentation/" + _name;
-
-  SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
-  _config.init(node->getChild("config", 0, true));
-    
   _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
   _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
-  _serviceable_node = node->getChild("serviceable", 0, true);
+  _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
   _serviceable_node->setBoolValue(true);
   _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
 
 // basic GPS outputs
-  node->tie("selected-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getSelectedCourse, NULL));
-  
-  _raim_node = node->getChild("raim", 0, true);
-
-  tieSGGeodReadOnly(node, _indicated_pos, "indicated-longitude-deg", 
-        "indicated-latitude-deg", "indicated-altitude-ft");
-
-  node->tie("indicated-vertical-speed", SGRawValueMethods<GPS, double>
-    (*this, &GPS::getVerticalSpeed, NULL));
-  node->tie("indicated-track-true-deg", SGRawValueMethods<GPS, double>
-    (*this, &GPS::getTrueTrack, NULL));
-  node->tie("indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
-    (*this, &GPS::getMagTrack, NULL));
-  node->tie("indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
-    (*this, &GPS::getGroundspeedKts, NULL));
-        
-  _odometer_node = node->getChild("odometer", 0, true);
-  _trip_odometer_node = node->getChild("trip-odometer", 0, true);
-  _true_bug_error_node = node->getChild("true-bug-error-deg", 0, true);
-  _magnetic_bug_error_node = node->getChild("magnetic-bug-error-deg", 0, true);
-
-// command system    
-  _mode = "obs";
-  node->tie("mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
-  node->tie("command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
-    
-  _scratchNode = node->getChild("scratch", 0, true);
-  tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
-  _scratchNode->tie("valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
-  _scratchNode->tie("distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
-  _scratchNode->tie("true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
-  _scratchNode->tie("mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
-  _scratchNode->tie("has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
-  _scratchValid = false;
-  
-// waypoint data (including various historical things)
-  SGPropertyNode *wp_node = node->getChild("wp", 0, true);
-  SGPropertyNode *wp0_node = wp_node->getChild("wp", 0, true);
+  _raim_node = _gpsNode->getChild("raim", 0, true);
+  _odometer_node = _gpsNode->getChild("odometer", 0, true);
+  _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
+  _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
+  _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
+  
+// waypoints
+  SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
   SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
 
-  tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
-  wp0_node->tie("ID", SGRawValueMethods<GPS, const char*>
-    (*this, &GPS::getWP0Ident, NULL));
-  wp0_node->tie("name", SGRawValueMethods<GPS, const char*>
-    (*this, &GPS::getWP0Name, NULL));
-    
-  tieSGGeodReadOnly(wp1_node, _wp1_position, "longitude-deg", "latitude-deg", "altitude-ft");
-  wp1_node->tie("ID", SGRawValueMethods<GPS, const char*>
-    (*this, &GPS::getWP1Ident, NULL));
-  wp1_node->tie("name", SGRawValueMethods<GPS, const char*>
-    (*this, &GPS::getWP1Name, NULL));
-
   // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
   SGPropertyNode* wp1Crs = wp1_node->getChild("desired-course-deg", 0, true);
-  wp1Crs->alias(node->getChild("selected-course-deg"));
+  wp1Crs->alias(_gpsNode->getChild("selected-course-deg"));
     
 //    _true_wp1_bearing_error_node =
 //        wp1_node->getChild("true-bearing-error-deg", 0, true);
 //    _magnetic_wp1_bearing_error_node =
   //      wp1_node->getChild("magnetic-bearing-error-deg", 0, true);
 
-  wp1_node->tie("distance-nm", SGRawValueMethods<GPS, double>
-    (*this, &GPS::getWP1Distance, NULL));
-  wp1_node->tie("bearing-true-deg", SGRawValueMethods<GPS, double>
-    (*this, &GPS::getWP1Bearing, NULL));
-  wp1_node->tie("bearing-mag-deg", SGRawValueMethods<GPS, double>
-    (*this, &GPS::getWP1MagBearing, NULL));
-  wp1_node->tie("TTW-sec", SGRawValueMethods<GPS, double>
-    (*this, &GPS::getWP1TTW, NULL));
-  wp1_node->tie("TTW", SGRawValueMethods<GPS, const char*>
-    (*this, &GPS::getWP1TTWString, NULL));
-  
-  wp1_node->tie("course-deviation-deg", SGRawValueMethods<GPS, double>
-    (*this, &GPS::getWP1CourseDeviation, NULL));
-  wp1_node->tie("course-error-nm", SGRawValueMethods<GPS, double>
-    (*this, &GPS::getWP1CourseErrorNm, NULL));
-  wp1_node->tie("to-flag", SGRawValueMethods<GPS, bool>
-    (*this, &GPS::getWP1ToFlag, NULL));
-  wp1_node->tie("from-flag", SGRawValueMethods<GPS, bool>
-    (*this, &GPS::getWP1FromFlag, NULL));
-    
-  _tracking_bug_node = node->getChild("tracking-bug", 0, true);
+  _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
          
-// leg properties (only valid in DTO/LEG modes, not OBS)
-  wp_node->tie("leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
-  wp_node->tie("leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
-  wp_node->tie("leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
-  wp_node->tie("alt-dist-ratio", SGRawValueMethods<GPS, double>(*this, &GPS::getAltDistanceRatio, NULL));
-
 // reference navid
-  SGPropertyNode_ptr ref_navaid = node->getChild("ref-navaid", 0, true);
+  SGPropertyNode_ptr ref_navaid = _gpsNode->getChild("ref-navaid", 0, true);
   _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
   _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
   _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
@@ -414,8 +326,8 @@ GPS::init ()
     
 // route properties    
   // should these move to the route manager?
-  _routeDistanceNm = node->getChild("route-distance-nm", 0, true);
-  _routeETE = node->getChild("ETE", 0, true);
+  _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
+  _routeETE = _gpsNode->getChild("ETE", 0, true);
   _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
   _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
   
@@ -430,16 +342,12 @@ GPS::init ()
   _routeFinishedSignal->addChangeListener(_listener);
   
 // navradio slaving properties  
-  node->tie("cdi-deflection", SGRawValueMethods<GPS,double>
-    (*this, &GPS::getCDIDeflection));
-
-  SGPropertyNode* toFlag = node->getChild("to-flag", 0, true);
+  SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
   toFlag->alias(wp1_node->getChild("to-flag"));
   
-  SGPropertyNode* fromFlag = node->getChild("from-flag", 0, true);
+  SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
   fromFlag->alias(wp1_node->getChild("from-flag"));
     
-        
 // autopilot drive properties
   _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
   _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
@@ -452,25 +360,108 @@ GPS::init ()
   }
   
   // last thing, add the deprecated prop watcher
-  new DeprecatedPropListener(node);
+  new DeprecatedPropListener(_gpsNode);
   
-  // initialise in OBS mode, with waypt set to the nearest airport.
-  // keep in mind at this point, _last_valid is not set
+  clearOutput();
+}
+
+void
+GPS::bind()
+{
+  _config.bind(this, _gpsNode->getChild("config", 0, true));
+// basic GPS outputs
+  tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getSelectedCourse, NULL));
   
-  auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
-  FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
-  if (apt) {
-    setScratchFromPositioned(apt, 0);
-    selectOBSMode();
+  
+  tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg", 
+        "indicated-latitude-deg", "indicated-altitude-ft");
+
+  tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getVerticalSpeed, NULL));
+  tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getTrueTrack, NULL));
+  tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getMagTrack, NULL));
+  tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getGroundspeedKts, NULL));
+  
+// command system    
+  tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
+  tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
+    
+  tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
+  tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
+  tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
+  tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
+  tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
+  tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
+  _scratchValid = false;
+  
+// waypoint data (including various historical things)
+  SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
+  SGPropertyNode *wp0_node = wp_node->getChild("wp", 0, true);
+  SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
+
+  tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
+  tie(wp0_node, "ID", SGRawValueMethods<GPS, const char*>
+    (*this, &GPS::getWP0Ident, NULL));
+  tie(wp0_node, "name", SGRawValueMethods<GPS, const char*>
+    (*this, &GPS::getWP0Name, NULL));
+    
+  tieSGGeodReadOnly(wp1_node, _wp1_position, "longitude-deg", "latitude-deg", "altitude-ft");
+  tie(wp1_node, "ID", SGRawValueMethods<GPS, const char*>
+    (*this, &GPS::getWP1Ident, NULL));
+  tie(wp1_node, "name", SGRawValueMethods<GPS, const char*>
+    (*this, &GPS::getWP1Name, NULL));
+  
+  tie(wp1_node, "distance-nm", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getWP1Distance, NULL));
+  tie(wp1_node, "bearing-true-deg", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getWP1Bearing, NULL));
+  tie(wp1_node, "bearing-mag-deg", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getWP1MagBearing, NULL));
+  tie(wp1_node, "TTW-sec", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getWP1TTW, NULL));
+  tie(wp1_node, "TTW", SGRawValueMethods<GPS, const char*>
+    (*this, &GPS::getWP1TTWString, NULL));
+  
+  tie(wp1_node, "course-deviation-deg", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getWP1CourseDeviation, NULL));
+  tie(wp1_node, "course-error-nm", SGRawValueMethods<GPS, double>
+    (*this, &GPS::getWP1CourseErrorNm, NULL));
+  tie(wp1_node, "to-flag", SGRawValueMethods<GPS, bool>
+    (*this, &GPS::getWP1ToFlag, NULL));
+  tie(wp1_node, "from-flag", SGRawValueMethods<GPS, bool>
+    (*this, &GPS::getWP1FromFlag, NULL));
+
+// leg properties (only valid in DTO/LEG modes, not OBS)
+  tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
+  tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
+  tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
+  tie(wp_node, "alt-dist-ratio", SGRawValueMethods<GPS, double>(*this, &GPS::getAltDistanceRatio, NULL));
+
+// navradio slaving properties  
+  tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
+    (*this, &GPS::getCDIDeflection));
+}
+
+void
+GPS::unbind()
+{
+  for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
+    _tiedNodes[t]->untie();
   }
+  _tiedNodes.clear();
 }
 
 void
 GPS::clearOutput()
 {
-  _last_valid = false;
+  _dataValid = false;
   _last_speed_kts = 0.0;
   _last_pos = SGGeod();
+  _lastPosValid = false;
   _indicated_pos = SGGeod();
   _last_vertical_speed = 0.0;
   _last_true_track = 0.0;
@@ -543,50 +534,58 @@ GPS::update (double delta_time_sec)
     printf("%f %f \n", error_length, error_angle);
 
 */
-    _raim_node->setDoubleValue(1.0);
-    _indicated_pos = _position.get();
+  _raim_node->setDoubleValue(1.0);
+  _indicated_pos = _position.get();
+  updateBasicData(delta_time_sec);
 
-    if (_last_valid) {
-      updateWithValid(delta_time_sec);
+  if (_dataValid) {
+    if (_mode == "obs") {
+      _selectedCourse = _config.getExternalCourse();
     } else {
-      _last_valid = true;
-        
-      if (_route_active_node->getBoolValue()) {
-        // GPS init with active route
-        SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
-        _listener->setGuard(true);
-        routeActivated();
-        routeManagerSequenced();
-        _listener->setGuard(false);
-      }
+      updateTurn();
     }
-
-    _last_pos = _indicated_pos;
-}
-
-void
-GPS::updateWithValid(double dt)
-{
-  assert(_last_valid);
-    
-  updateBasicData(dt);
+      
+    updateWaypoints();
+    updateTrackingBug();
+    updateReferenceNavaid(delta_time_sec);
+    updateRouteData();
+    driveAutopilot();
+  }
   
-  if (_mode == "obs") {
+  if (_dataValid && (_mode == "init")) {
+    // allow a realistic delay in the future, here
+    SG_LOG(SG_INSTR, SG_INFO, "GPS initialisation complete");
+    
     _selectedCourse = _config.getExternalCourse();
-  } else {
-    updateTurn();
-  }
     
-  updateWaypoints();
-  updateTrackingBug();
-  updateReferenceNavaid(dt);
-  updateRouteData();
-  driveAutopilot();
+    if (_route_active_node->getBoolValue()) {
+      // GPS init with active route
+      SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
+      selectLegMode();
+    } else {
+      // initialise in OBS mode, with waypt set to the nearest airport.
+      // keep in mind at this point, _dataValid is not set
+    
+      auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
+      FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
+      if (apt) {
+        setScratchFromPositioned(apt, 0);
+        selectOBSMode();
+      }
+    }
+  } // of init mode check
+  
+  _last_pos = _indicated_pos;
+  _lastPosValid = true;
 }
 
 void
 GPS::updateBasicData(double dt)
 {
+  if (!_lastPosValid) {
+    return;
+  }
+  
   double distance_m;
   double track2_deg;
   SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
@@ -602,6 +601,11 @@ GPS::updateBasicData(double dt)
   _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
   odometer = _trip_odometer_node->getDoubleValue();
   _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
+  
+  if (!_dataValid) {
+    SG_LOG(SG_INSTR, SG_INFO, "GPS setting data valid");
+    _dataValid = true;
+  }
 }
 
 void
@@ -718,6 +722,12 @@ void GPS::routeActivated()
   if (_route_active_node->getBoolValue()) {
     SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
     selectLegMode();
+    
+    // if we've already passed the current waypoint, sequence.
+    if (_dataValid && getWP1FromFlag()) {
+      SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
+      _routeMgr->sequence();
+    }
   } else if (_mode == "leg") {
     SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
     selectOBSMode();
@@ -733,19 +743,22 @@ void GPS::routeManagerSequenced()
   
   int index = _routeMgr->currentWaypoint(),
     count = _routeMgr->size();
-  if ((index < 1) || (index >= count)) {
+  if ((index < 0) || (index >= count)) {
     SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
     return;
   }
   
   SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
-  SGWayPoint wp0(_routeMgr->get_waypoint(index - 1));
-  SGWayPoint wp1(_routeMgr->get_waypoint(index));
-    
-  _wp0Ident = wp0.get_id();
-  _wp0Name = wp0.get_name();
-  _wp0_position = wp0.get_target();
+  
+  if (index > 0) {
+    SGWayPoint wp0(_routeMgr->get_waypoint(index - 1));
+    _wp0Ident = wp0.get_id();
+    _wp0Name = wp0.get_name();
+    _wp0_position = wp0.get_target();
 
+  }
+  
+  SGWayPoint wp1(_routeMgr->get_waypoint(index));
   _wp1Ident = wp1.get_id();
   _wp1Name = wp1.get_name();
   _wp1_position = wp1.get_target();
@@ -990,8 +1003,12 @@ void GPS::driveAutopilot()
     return;
   }
  
-  // FIXME: we want to set desired track, not heading, here
-  _apTrueHeading->setDoubleValue(getWP1Bearing());
+  // compatability feature - allow the route-manager / GPS to drive the
+  // generic autopilot heading hold *in leg mode only* 
+  if (_mode == "leg") {
+    // FIXME: we want to set desired track, not heading, here
+    _apTrueHeading->setDoubleValue(getWP1Bearing());
+  }
 }
 
 void GPS::wp1Changed()
@@ -1004,9 +1021,7 @@ void GPS::wp1Changed()
   }
   
   double altFt = _wp1_position.getElevationFt();
-  if (altFt < -9990.0) {
-    _apTargetAltitudeFt->setDoubleValue(0.0);
-  } else {
+  if (altFt > -9990.0) {
     _apTargetAltitudeFt->setDoubleValue(altFt);
   }
 }
@@ -1016,7 +1031,7 @@ void GPS::wp1Changed()
 
 double GPS::getLegDistance() const
 {
-  if (!_last_valid || (_mode == "obs")) {
+  if (!_dataValid || (_mode == "obs")) {
     return -1;
   }
   
@@ -1025,7 +1040,7 @@ double GPS::getLegDistance() const
 
 double GPS::getLegCourse() const
 {
-  if (!_last_valid || (_mode == "obs")) {
+  if (!_dataValid) {
     return -9999.0;
   }
   
@@ -1034,7 +1049,7 @@ double GPS::getLegCourse() const
 
 double GPS::getLegMagCourse() const
 {
-  if (!_last_valid || (_mode == "obs")) {
+  if (!_dataValid) {
     return 0.0;
   }
   
@@ -1045,7 +1060,7 @@ double GPS::getLegMagCourse() const
 
 double GPS::getAltDistanceRatio() const
 {
-  if (!_last_valid || (_mode == "obs")) {
+  if (!_dataValid || (_mode == "obs")) {
     return 0.0;
   }
   
@@ -1060,7 +1075,7 @@ double GPS::getAltDistanceRatio() const
 
 double GPS::getMagTrack() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return 0.0;
   }
   
@@ -1071,7 +1086,7 @@ double GPS::getMagTrack() const
 
 double GPS::getCDIDeflection() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return 0.0;
   }
   
@@ -1091,7 +1106,7 @@ double GPS::getCDIDeflection() const
 
 const char* GPS::getWP0Ident() const
 {
-  if (!_last_valid || (_mode != "leg")) {
+  if (!_dataValid || (_mode != "leg")) {
     return "";
   }
   
@@ -1100,7 +1115,7 @@ const char* GPS::getWP0Ident() const
 
 const char* GPS::getWP0Name() const
 {
-  if (!_last_valid || (_mode != "leg")) {
+  if (!_dataValid || (_mode != "leg")) {
     return "";
   }
   
@@ -1109,7 +1124,7 @@ const char* GPS::getWP0Name() const
 
 const char* GPS::getWP1Ident() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return "";
   }
   
@@ -1118,7 +1133,7 @@ const char* GPS::getWP1Ident() const
 
 const char* GPS::getWP1Name() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return "";
   }
 
@@ -1127,7 +1142,7 @@ const char* GPS::getWP1Name() const
 
 double GPS::getWP1Distance() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return -1.0;
   }
   
@@ -1136,7 +1151,7 @@ double GPS::getWP1Distance() const
 
 double GPS::getWP1TTW() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return -1.0;
   }
   
@@ -1149,7 +1164,7 @@ double GPS::getWP1TTW() const
 
 const char* GPS::getWP1TTWString() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return "";
   }
   
@@ -1158,7 +1173,7 @@ const char* GPS::getWP1TTWString() const
 
 double GPS::getWP1Bearing() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return -9999.0;
   }
   
@@ -1167,7 +1182,7 @@ double GPS::getWP1Bearing() const
 
 double GPS::getWP1MagBearing() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return -9999.0;
   }
 
@@ -1176,7 +1191,7 @@ double GPS::getWP1MagBearing() const
 
 double GPS::getWP1CourseDeviation() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return 0.0;
   }
   
@@ -1195,7 +1210,7 @@ double GPS::getWP1CourseDeviation() const
 
 double GPS::getWP1CourseErrorNm() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return 0.0;
   }
   
@@ -1206,7 +1221,7 @@ double GPS::getWP1CourseErrorNm() const
 
 bool GPS::getWP1ToFlag() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return false;
   }
   
@@ -1218,7 +1233,7 @@ bool GPS::getWP1ToFlag() const
 
 bool GPS::getWP1FromFlag() const
 {
-  if (!_last_valid) {
+  if (!_dataValid) {
     return false;
   }
   
@@ -1283,8 +1298,40 @@ void GPS::setCommand(const char* aCmd)
     previousResult();
   } else if (!strcmp(aCmd, "define-user-wpt")) {
     defineWaypoint();
+  } else if (!strcmp(aCmd, "route-insert-before")) {
+    int index = _scratchNode->getIntValue("index");
+    if (index < 0 || (_routeMgr->size() == 0)) {
+      index = _routeMgr->size();
+    } else if (index >= _routeMgr->size()) {
+      SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
+      return;
+    }
+    
+    insertWaypointAtIndex(index);
+  } else if (!strcmp(aCmd, "route-insert-after")) {
+    int index = _scratchNode->getIntValue("index");
+    if (index < 0 || (_routeMgr->size() == 0)) {
+      index = _routeMgr->size();
+    } else if (index >= _routeMgr->size()) {
+      SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
+      return;
+    } else {
+      ++index; 
+    }
+  
+    insertWaypointAtIndex(index);
+  } else if (!strcmp(aCmd, "route-delete")) {
+    int index = _scratchNode->getIntValue("index");
+    if (index < 0) {
+      index = _routeMgr->size();
+    } else if (index >= _routeMgr->size()) {
+      SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
+      return;
+    }
+    
+    removeWaypointAtIndex(index);
   } else {
-    SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognzied command:" << aCmd);
+    SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
   }
 }
 
@@ -1336,7 +1383,7 @@ void GPS::loadRouteWaypoint()
   int index = _scratchNode->getIntValue("index", -9999);
   clearScratch();
   
-  if (index == -9999) { // no index supplied, use current wp
+  if ((index < 0) || (index >= _routeMgr->size())) { // no index supplied, use current wp
     index = _routeMgr->currentWaypoint();
   }
   
@@ -1378,10 +1425,15 @@ void GPS::loadNearest()
   int limitCount = _scratchNode->getIntValue("max-results", 1);
   double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
   
-  clearScratch(); // clear now, regardless of whether we find a match or not
+  SGGeod searchPos = _indicated_pos;
+  if (isScratchPositionValid()) {
+    searchPos = _scratchPos;
+  }
   
+  clearScratch(); // clear now, regardless of whether we find a match or not
+    
   _searchResults = 
-    FGPositioned::findClosestN(_indicated_pos, limitCount, cutoffDistance, f.get());
+    FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
   _searchResultsCached = true;
   _searchResultIndex = 0;
   _searchIsRoute = false;
@@ -1442,6 +1494,12 @@ void GPS::search()
   string sty(_scratchNode->getStringValue("type"));
   _searchType = FGPositioned::typeFromName(sty);
   _searchQuery = _scratchNode->getStringValue("query");
+  if (_searchQuery.empty()) {
+    SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
+    clearScratch();
+    return;
+  }
+  
   _searchExact = _scratchNode->getBoolValue("exact", true);
   _searchOrderByRange = _scratchNode->getBoolValue("order-by-distance", true);
   _searchResultIndex = 0;
@@ -1609,6 +1667,11 @@ void GPS::selectLegMode()
   SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
   _mode = "leg";
   
+  // depending on the situation, this will either get over-written 
+  // in routeManagerSequenced or not; either way it does no harm to
+  // set it here.
+  _wp0_position = _indicated_pos;
+
   // not really sequenced, but does all the work of updating wp0/1
   routeManagerSequenced();
 }
@@ -1675,4 +1738,53 @@ void GPS::defineWaypoint()
   setScratchFromPositioned(wpt.get(), -1);
 }
 
+void GPS::insertWaypointAtIndex(int aIndex)
+{
+  // note we do allow index = routeMgr->size(), that's an append
+  if ((aIndex < 0) || (aIndex > _routeMgr->size())) {
+    throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
+  }
+  
+  if (!isScratchPositionValid()) {
+    SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
+    return;
+  }
+  
+  string ident = _scratchNode->getStringValue("ident");
+  string name = _scratchNode->getStringValue("name");
+  
+  _routeMgr->add_waypoint(SGWayPoint(_scratchPos, ident, name), aIndex);
+}
+
+void GPS::removeWaypointAtIndex(int aIndex)
+{
+  if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
+    throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
+  }
+  
+  _routeMgr->pop_waypoint(aIndex);
+}
+
+void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef, 
+  const char* lonStr, const char* latStr, const char* altStr)
+{
+  tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
+  tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
+  
+  if (altStr) {
+    tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
+  }
+}
+
+void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef, 
+  const char* lonStr, const char* latStr, const char* altStr)
+{
+  tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
+  tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
+  
+  if (altStr) {
+    tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
+  }
+}
+
 // end of gps.cxx