From 8877b442f8f687c56f18600f7080533ca1b52dc5 Mon Sep 17 00:00:00 2001
From: James Turner <zakalawe@mac.com>
Date: Fri, 11 Dec 2015 12:11:46 -0600
Subject: [PATCH] =?UTF-8?q?ATC/Traffic=20doesn=E2=80=99t=20crash=20reset.?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

- remove some global headers from AI headers, to avoid pollution
- change how ATC owns the ‘player’ FGAIAircraft so reset works
- ensure AIAircraft controllers are cleared on unbind for reset
---
 src/AIModel/AIAircraft.cxx               | 16 ++++++
 src/AIModel/AIAircraft.hxx               | 14 +++---
 src/AIModel/AIBallistic.cxx              |  1 +
 src/AIModel/AIBase.cxx                   |  4 +-
 src/AIModel/AIBase.hxx                   |  4 +-
 src/AIModel/AICarrier.cxx                |  2 +
 src/AIModel/AIEscort.cxx                 |  1 +
 src/AIModel/AIFlightPlan.cxx             |  2 +
 src/AIModel/AIFlightPlanCreate.cxx       |  2 +
 src/AIModel/AIFlightPlanCreateCruise.cxx |  2 +
 src/AIModel/AIGroundVehicle.cxx          |  1 +
 src/AIModel/AIManager.cxx                |  1 +
 src/AIModel/AIManager.hxx                | 12 ++---
 src/AIModel/AIMultiplayer.cxx            |  3 ++
 src/AIModel/AIShip.cxx                   |  1 +
 src/AIModel/AIWingman.cxx                |  1 +
 src/ATC/GroundController.cxx             |  2 +
 src/ATC/atc_mgr.cxx                      | 62 +++++++++++++++---------
 src/ATC/atc_mgr.hxx                      | 10 ++--
 src/GUI/MapWidget.cxx                    |  3 +-
 src/Main/fg_init.cxx                     |  2 +-
 src/Network/RemoteXMLRequest.hxx         |  3 ++
 src/Scenery/tilemgr.cxx                  | 24 ++++++---
 src/Scenery/tilemgr.hxx                  |  2 +
 src/Traffic/SchedFlight.cxx              |  1 -
 src/Traffic/Schedule.cxx                 | 22 +++++++--
 src/Traffic/Schedule.hxx                 | 17 ++++---
 src/Traffic/TrafficMgr.cxx               |  6 ++-
 28 files changed, 150 insertions(+), 71 deletions(-)

diff --git a/src/AIModel/AIAircraft.cxx b/src/AIModel/AIAircraft.cxx
index b7967a5af..285c3fee8 100644
--- a/src/AIModel/AIAircraft.cxx
+++ b/src/AIModel/AIAircraft.cxx
@@ -29,6 +29,7 @@
 #include <Airports/dynamics.hxx>
 #include <Airports/airport.hxx>
 #include <Main/util.hxx>
+#include <Traffic/Schedule.hxx>
 
 #include <simgear/structure/exception.hxx>
 
@@ -39,7 +40,9 @@
 // defined in AIShip.cxx
 extern double fgIsFinite(double x);
 
+#include "AIManager.hxx"
 #include "AIAircraft.hxx"
+#include "AIFlightPlan.hxx"
 #include "performancedata.hxx"
 #include "performancedb.hxx"
 #include <signal.h>
@@ -133,6 +136,12 @@ void FGAIAircraft::update(double dt) {
     Transform();
 }
 
+void FGAIAircraft::unbind()
+{
+    FGAIBase::unbind();
+    clearATCController();
+}
+
 void FGAIAircraft::setPerformance(const std::string& acType, const std::string& acclass)
 {
   static PerformanceDB perfdb; //TODO make it a global service
@@ -408,6 +417,13 @@ double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double spe
     return vs;
 }
 
+void FGAIAircraft::clearATCController()
+{
+    controller = 0;
+    prevController = 0;
+    towerController = 0;
+}
+
 void FGAIAircraft::assertSpeed(double speed)
 {
     if ((speed < -50) || (speed > 1000)) {
diff --git a/src/AIModel/AIAircraft.hxx b/src/AIModel/AIAircraft.hxx
index 3ad8b8a67..a3bb4d6d2 100644
--- a/src/AIModel/AIAircraft.hxx
+++ b/src/AIModel/AIAircraft.hxx
@@ -21,16 +21,16 @@
 #ifndef _FG_AIAircraft_HXX
 #define _FG_AIAircraft_HXX
 
-#include "AIManager.hxx"
 #include "AIBase.hxx"
 
-#include <Traffic/SchedFlight.hxx>
-#include <Traffic/Schedule.hxx>
-#include <ATC/trafficcontrol.hxx>
-
 #include <string>
 
 class PerformanceData;
+class FGAISchedule;
+class FGAIFlightPlan;
+class FGATCController;
+class FGATCInstruction;
+class FGAIWaypoint;
 
 class FGAIAircraft : public FGAIBase {
 
@@ -43,6 +43,7 @@ public:
     // virtual bool init(bool search_in_AI_path=false);
     virtual void bind();
     virtual void update(double dt);
+    virtual void unbind();
 
     void setPerformance(const std::string& acType, const std::string& perfString);
   //  void setPerformance(PerformanceData *ps);
@@ -108,12 +109,13 @@ public:
 
     FGATCController * getATCController() { return controller; };
     
+    void clearATCController();
 protected:
     void Run(double dt);
 
 private:
     FGAISchedule *trafficRef;
-    FGATCController *controller, 
+    FGATCController *controller,
                     *prevController,
                     *towerController; // Only needed to make a pre-announcement
 
diff --git a/src/AIModel/AIBallistic.cxx b/src/AIModel/AIBallistic.cxx
index be5bcd74f..3a8eb46e4 100644
--- a/src/AIModel/AIBallistic.cxx
+++ b/src/AIModel/AIBallistic.cxx
@@ -33,6 +33,7 @@
 
 #include <Main/util.hxx>
 #include <Environment/gravity.hxx>
+#include <Main/fg_props.hxx>
 
 using namespace simgear;
 using std::string;
diff --git a/src/AIModel/AIBase.cxx b/src/AIModel/AIBase.cxx
index d933e68af..51146e077 100644
--- a/src/AIModel/AIBase.cxx
+++ b/src/AIModel/AIBase.cxx
@@ -42,11 +42,13 @@
 #include <simgear/props/props.hxx>
 
 #include <Main/globals.hxx>
+#include <Main/fg_props.hxx>
 #include <Scenery/scenery.hxx>
 #include <Scripting/NasalSys.hxx>
 #include <Scripting/NasalModelData.hxx>
 #include <Sound/fg_fx.hxx>
 
+#include "AIFlightPlan.hxx"
 #include "AIBase.hxx"
 #include "AIManager.hxx"
 
@@ -219,7 +221,7 @@ FGAIBase::removeModel()
         return;
 
     FGScenery* pSceneryManager = globals->get_scenery();
-    if (pSceneryManager)
+    if (pSceneryManager && pSceneryManager->get_models_branch())
     {
         osg::ref_ptr<osg::Object> temp = _model.get();
         pSceneryManager->get_models_branch()->removeChild(aip.getSceneGraph());
diff --git a/src/AIModel/AIBase.hxx b/src/AIModel/AIBase.hxx
index f2ba097e7..da27569c1 100644
--- a/src/AIModel/AIBase.hxx
+++ b/src/AIModel/AIBase.hxx
@@ -33,8 +33,6 @@
 
 #include <simgear/math/sg_geodesy.hxx>
 
-#include <Main/fg_props.hxx>
-
 namespace osg { class PagedLOD; }
 
 namespace simgear {
@@ -325,6 +323,8 @@ public:
     std::string & getCallSign();
 };
 
+typedef SGSharedPtr<FGAIBase> FGAIBasePtr;
+
 inline void FGAIBase::setManager(FGAIManager* mgr, SGPropertyNode* p) {
     manager = mgr;
     props = p;
diff --git a/src/AIModel/AICarrier.cxx b/src/AIModel/AICarrier.cxx
index e8639395a..1a0908c93 100644
--- a/src/AIModel/AICarrier.cxx
+++ b/src/AIModel/AICarrier.cxx
@@ -30,6 +30,8 @@
 
 #include <cmath>
 #include <Main/util.hxx>
+#include <Main/globals.hxx>
+#include <Main/fg_props.hxx>
 
 #include "AICarrier.hxx"
 
diff --git a/src/AIModel/AIEscort.cxx b/src/AIModel/AIEscort.cxx
index 44e53c849..c2067ae1a 100644
--- a/src/AIModel/AIEscort.cxx
+++ b/src/AIModel/AIEscort.cxx
@@ -32,6 +32,7 @@
 
 #include <cmath>
 #include <Main/util.hxx>
+#include <Main/globals.hxx>
 #include <Viewer/viewer.hxx>
 
 #include <Scenery/scenery.hxx>
diff --git a/src/AIModel/AIFlightPlan.cxx b/src/AIModel/AIFlightPlan.cxx
index 99f68eb96..b295310c6 100644
--- a/src/AIModel/AIFlightPlan.cxx
+++ b/src/AIModel/AIFlightPlan.cxx
@@ -41,6 +41,8 @@
 #include <Environment/environment_mgr.hxx>
 #include <Environment/environment.hxx>
 
+#include <Traffic/Schedule.hxx>
+
 #include "AIFlightPlan.hxx"
 #include "AIAircraft.hxx"
 
diff --git a/src/AIModel/AIFlightPlanCreate.cxx b/src/AIModel/AIFlightPlanCreate.cxx
index 9688c391b..59d442260 100644
--- a/src/AIModel/AIFlightPlanCreate.cxx
+++ b/src/AIModel/AIFlightPlanCreate.cxx
@@ -38,10 +38,12 @@
 #include "AIAircraft.hxx"
 #include "performancedata.hxx"
 
+#include <Main/fg_props.hxx>
 #include <Environment/environment_mgr.hxx>
 #include <Environment/environment.hxx>
 #include <FDM/LaRCsim/basic_aero.h>
 #include <Navaids/navrecord.hxx>
+#include <Traffic/Schedule.hxx>
 
 using std::string;
 
diff --git a/src/AIModel/AIFlightPlanCreateCruise.cxx b/src/AIModel/AIFlightPlanCreateCruise.cxx
index 709378f90..66639444b 100644
--- a/src/AIModel/AIFlightPlanCreateCruise.cxx
+++ b/src/AIModel/AIFlightPlanCreateCruise.cxx
@@ -33,6 +33,8 @@
 #include <Environment/environment_mgr.hxx>
 #include <Environment/environment.hxx>
 
+#include <Traffic/Schedule.hxx>
+
 #include "AIFlightPlan.hxx"
 #include "AIAircraft.hxx"
 #include "performancedata.hxx"
diff --git a/src/AIModel/AIGroundVehicle.cxx b/src/AIModel/AIGroundVehicle.cxx
index 15424079e..2ef662e09 100644
--- a/src/AIModel/AIGroundVehicle.cxx
+++ b/src/AIModel/AIGroundVehicle.cxx
@@ -27,6 +27,7 @@
 #include <Viewer/viewer.hxx>
 #include <Scenery/scenery.hxx>
 #include <Airports/dynamics.hxx>
+#include <Main/globals.hxx>
 
 #include "AIGroundVehicle.hxx"
 
diff --git a/src/AIModel/AIManager.cxx b/src/AIModel/AIManager.cxx
index 2c6fc15f4..4faf23e59 100644
--- a/src/AIModel/AIManager.cxx
+++ b/src/AIModel/AIManager.cxx
@@ -32,6 +32,7 @@
 #include <boost/foreach.hpp>
 
 #include <Main/globals.hxx>
+#include <Main/fg_props.hxx>
 #include <Airports/airport.hxx>
 #include <Scripting/NasalSys.hxx>
 
diff --git a/src/AIModel/AIManager.hxx b/src/AIModel/AIManager.hxx
index a35f64968..6caa098f3 100644
--- a/src/AIModel/AIManager.hxx
+++ b/src/AIModel/AIManager.hxx
@@ -28,16 +28,8 @@
 
 #include <simgear/structure/subsystem_mgr.hxx>
 #include <simgear/structure/SGSharedPtr.hxx>
-#include <simgear/props/props_io.hxx>
-
-#include <Main/fg_props.hxx>
-
-#include <AIModel/AIBase.hxx>
-#include <AIModel/AIFlightPlan.hxx>
-
-#include <Traffic/SchedFlight.hxx>
-#include <Traffic/Schedule.hxx>
 
+class FGAIBase;
 class FGAIThermal;
 
 typedef SGSharedPtr<FGAIBase> FGAIBasePtr;
@@ -84,6 +76,8 @@ public:
      * corresponding AIObject implementation, or NULL.
      */
     FGAIBasePtr getObjectFromProperty(const SGPropertyNode* aProp) const;
+
+    static const char* subsystemName() { return "ai-model"; }
 private:
     // FGSubmodelMgr is a friend for access to the AI_list
     friend class FGSubmodelMgr;
diff --git a/src/AIModel/AIMultiplayer.cxx b/src/AIModel/AIMultiplayer.cxx
index 6e80f3776..a4176b3a6 100644
--- a/src/AIModel/AIMultiplayer.cxx
+++ b/src/AIModel/AIMultiplayer.cxx
@@ -28,6 +28,9 @@
 #include <string>
 #include <stdio.h>
 
+#include <Main/globals.hxx>
+#include <Main/fg_props.hxx>
+
 #include "AIMultiplayer.hxx"
 
 using std::string;
diff --git a/src/AIModel/AIShip.cxx b/src/AIModel/AIShip.cxx
index caea12660..9ec3718bd 100644
--- a/src/AIModel/AIShip.cxx
+++ b/src/AIModel/AIShip.cxx
@@ -37,6 +37,7 @@
 
 #include <simgear/scene/util/SGNodeMasks.hxx>
 #include <Scenery/scenery.hxx>
+#include <Main/globals.hxx>
 
 #include "AIShip.hxx"
 
diff --git a/src/AIModel/AIWingman.cxx b/src/AIModel/AIWingman.cxx
index 7c1478997..916830f28 100644
--- a/src/AIModel/AIWingman.cxx
+++ b/src/AIModel/AIWingman.cxx
@@ -23,6 +23,7 @@
 
 #include <simgear/sg_inlines.h>
 
+#include <Main/fg_props.hxx>
 
 #include "AIWingman.hxx"
 
diff --git a/src/ATC/GroundController.cxx b/src/ATC/GroundController.cxx
index 17b8f87f9..17b06b340 100644
--- a/src/ATC/GroundController.cxx
+++ b/src/ATC/GroundController.cxx
@@ -48,6 +48,8 @@
 #include <Airports/runways.hxx>
 #include <Airports/groundnetwork.hxx>
 
+#include <Main/globals.hxx>
+#include <Main/fg_props.hxx>
 #include <AIModel/AIAircraft.hxx>
 #include <AIModel/performancedata.hxx>
 #include <AIModel/AIFlightPlan.hxx>
diff --git a/src/ATC/atc_mgr.cxx b/src/ATC/atc_mgr.cxx
index fc5a06c2a..1b32bde4a 100644
--- a/src/ATC/atc_mgr.cxx
+++ b/src/ATC/atc_mgr.cxx
@@ -30,6 +30,13 @@
 #include <Airports/airportdynamicsmanager.hxx>
 #include <Airports/airport.hxx>
 #include <Scenery/scenery.hxx>
+#include <Main/globals.hxx>
+#include <Main/fg_props.hxx>
+#include <AIModel/AIAircraft.hxx>
+#include <Traffic/Schedule.hxx>
+#include <Traffic/SchedFlight.hxx>
+#include <AIModel/AIFlightPlan.hxx>
+
 #include "atc_mgr.hxx"
 
 
@@ -74,12 +81,12 @@ void FGATCManager::init() {
     double speed     = fgGetDouble("/velocities/groundspeed-kt");
     double aircraftRadius = 40; // note that this is currently hardcoded to a one-size-fits all JumboJet value. Should change later;
 
-
-    ai_ac.setCallSign ( callsign  );
-    ai_ac.setLongitude( longitude );
-    ai_ac.setLatitude ( latitude  );
-    ai_ac.setAltitude ( altitude  );
-    ai_ac.setPerformance("", "jet_transport");
+    ai_ac = new FGAIAircraft;
+    ai_ac->setCallSign ( callsign  );
+    ai_ac->setLongitude( longitude );
+    ai_ac->setLatitude ( latitude  );
+    ai_ac->setAltitude ( altitude  );
+    ai_ac->setPerformance("", "jet_transport");
 
     // NEXT UP: Create a traffic Schedule and fill that with appropriate information. This we can use to flight planning.
     // Note that these are currently only defaults. 
@@ -95,7 +102,7 @@ void FGATCManager::init() {
     
     trafficRef->assign(flight);
     FGAIFlightPlan *fp = 0; 
-    ai_ac.setTrafficRef(trafficRef);
+    ai_ac->setTrafficRef(trafficRef);
     
     string flightPlanName = airport + "-" + airport + ".xml";
     //double cruiseAlt = 100; // Doesn't really matter right now.
@@ -127,7 +134,7 @@ void FGATCManager::init() {
             string aircraftType; // Unused.
             string airline;      // Currently used for gate selection, but a fallback mechanism will apply when not specified.
             fp->setGate(pk);
-            if (!(fp->createPushBack(&ai_ac,
+            if (!(fp->createPushBack(ai_ac,
                                      false,
                                      dcs->parent(),
                                      aircraftRadius,
@@ -152,8 +159,8 @@ void FGATCManager::init() {
             leg = 3;
             string fltType = "ga";
             fp->setRunway(runway);
-            fp->createTakeOff(&ai_ac, false, dcs->parent(), 0, fltType);
-            ai_ac.setTakeOffStatus(2);
+            fp->createTakeOff(ai_ac, false, dcs->parent(), 0, fltType);
+            ai_ac->setTakeOffStatus(2);
         } else {
                 // We're on the ground somewhere. Handle this case later.
         }
@@ -170,12 +177,12 @@ void FGATCManager::init() {
     if (fp) {
         fp->restart();
         fp->setLeg(leg);
-        ai_ac.SetFlightPlan(fp);
+        ai_ac->SetFlightPlan(fp);
     }
     if (controller) {
-        controller->announcePosition(ai_ac.getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
-                                      ai_ac._getLatitude(), ai_ac._getLongitude(), heading, speed, altitude,
-                                      aircraftRadius, leg, &ai_ac);
+        controller->announcePosition(ai_ac->getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
+                                      ai_ac->_getLatitude(), ai_ac->_getLongitude(), heading, speed, altitude,
+                                      aircraftRadius, leg, ai_ac);
 
     //dialog.init();
 
@@ -183,7 +190,14 @@ void FGATCManager::init() {
    //cerr << "Adding groundnetWork to the scenegraph::init" << endl;
    //globals->get_scenery()->get_scene_graph()->addChild(node);
    }
-   initSucceeded = true;
+    initSucceeded = true;
+}
+
+void FGATCManager::shutdown()
+{
+    delete ai_ac;
+    ai_ac = NULL;
+    activeStations.clear();
 }
 
 void FGATCManager::addController(FGATCController *controller) {
@@ -205,7 +219,7 @@ void FGATCManager::update ( double time ) {
    
     
 
-    FGAIFlightPlan *fp = ai_ac.GetFlightPlan();
+    FGAIFlightPlan *fp = ai_ac->GetFlightPlan();
         
     /* test code : find out how the routing develops */
     if (fp) {
@@ -259,20 +273,20 @@ void FGATCManager::update ( double time ) {
     
     cerr << "Bearing to nearest waypoint : " << course1 << " " << dist1 << ". (course " << course2 << ")." <<  endl;
     */
-    ai_ac.setLatitude(latitude);
-    ai_ac.setLongitude(longitude);
-    ai_ac.setAltitude(altitude);
-    ai_ac.setHeading(heading);
-    ai_ac.setSpeed(speed);
-    ai_ac.update(time);
-    controller = ai_ac.getATCController();
+    ai_ac->setLatitude(latitude);
+    ai_ac->setLongitude(longitude);
+    ai_ac->setAltitude(altitude);
+    ai_ac->setHeading(heading);
+    ai_ac->setSpeed(speed);
+    ai_ac->update(time);
+    controller = ai_ac->getATCController();
     FGATCDialogNew::instance()->update(time);
     if (controller) {
        //cerr << "name of previous waypoint : " << fp->getPreviousWaypoint()->getName() << endl;
 
         //cerr << "Running FGATCManager::update()" << endl;
         //cerr << "Currently under control of " << controller->getName() << endl;
-        controller->updateAircraftInformation(ai_ac.getID(),
+        controller->updateAircraftInformation(ai_ac->getID(),
                                               latitude,
                                               longitude,
                                               heading,
diff --git a/src/ATC/atc_mgr.hxx b/src/ATC/atc_mgr.hxx
index 9f9545730..7091ed778 100644
--- a/src/ATC/atc_mgr.hxx
+++ b/src/ATC/atc_mgr.hxx
@@ -29,16 +29,14 @@
 #ifndef _ATC_MGR_HXX_
 #define _ATC_MGR_HXX_
 
-//#include <simgear/structure/SGReferenced.hxx>
-//#include <simgear/structure/SGSharedPtr.hxx>
+
 #include <simgear/structure/subsystem_mgr.hxx>
 
 
 #include <ATC/trafficcontrol.hxx>
 #include <ATC/atcdialog.hxx>
 
-#include <AIModel/AIAircraft.hxx>
-//class FGATCController;
+class FGAIAircraft;
 
 
 typedef std::vector<FGATCController*> AtcVec;
@@ -48,7 +46,7 @@ class FGATCManager : public SGSubsystem
 {
 private:
   AtcVec activeStations;
-  FGAIAircraft ai_ac;
+  FGAIAircraft* ai_ac;
   FGATCController *controller, *prevController; // The ATC controller that is responsible for the user's aircraft. 
   bool networkVisible;
   bool initSucceeded;
@@ -58,6 +56,8 @@ public:
   FGATCManager();
   ~FGATCManager();
   void init();
+  virtual void shutdown();
+
   void addController(FGATCController *controller);
   void removeController(FGATCController* controller);
   void update(double time);
diff --git a/src/GUI/MapWidget.cxx b/src/GUI/MapWidget.cxx
index b5237d8a0..bb44327fb 100644
--- a/src/GUI/MapWidget.cxx
+++ b/src/GUI/MapWidget.cxx
@@ -27,6 +27,7 @@
 #include <Navaids/routePath.hxx>
 #include <Aircraft/FlightHistory.hxx>
 #include <AIModel/AIAircraft.hxx>
+#include <AIModel/AIManager.hxx>
 #include <AIModel/AIFlightPlan.hxx>
 
 const char* RULER_LEGEND_KEY = "ruler-legend";
@@ -1977,7 +1978,7 @@ MapWidget::DrawAIObject::DrawAIObject(SGPropertyNode* m, const SGGeod& g) :
         // try to access the flight-plan of the aircraft. There are several layers
         // of potential NULL-ness here, so we have to be defensive at each stage.
         std::string originICAO, destinationICAO;
-        FGAIManager* aiManager = static_cast<FGAIManager*>(globals->get_subsystem("ai-model"));
+        FGAIManager* aiManager = globals->get_subsystem<FGAIManager>();
         FGAIBasePtr aircraft = aiManager ? aiManager->getObjectFromProperty(model) : NULL;
         if (aircraft) {
             FGAIAircraft* p = static_cast<FGAIAircraft*>(aircraft.get());
diff --git a/src/Main/fg_init.cxx b/src/Main/fg_init.cxx
index d75325574..572ca446a 100644
--- a/src/Main/fg_init.cxx
+++ b/src/Main/fg_init.cxx
@@ -1024,7 +1024,7 @@ void fgStartNewReset()
         string_list::const_iterator it;
         for (it = names.begin(); it != names.end(); ++it) {
             if ((*it == "time") || (*it == "terrasync") || (*it == "events")
-                || (*it == "lighting"))
+                || (*it == "lighting") || (*it == FGTileMgr::subsystemName()) || (*it == FGScenery::subsystemName()))
             {
                 continue;
             }
diff --git a/src/Network/RemoteXMLRequest.hxx b/src/Network/RemoteXMLRequest.hxx
index 239ff4b2b..d540db61a 100644
--- a/src/Network/RemoteXMLRequest.hxx
+++ b/src/Network/RemoteXMLRequest.hxx
@@ -20,8 +20,11 @@
 
 #ifndef REMOTEXMLREQUEST_HXXH
 #define REMOTEXMLREQUEST_HXXH
+
 #include <simgear/structure/exception.hxx>
 #include <simgear/io/HTTPMemoryRequest.hxx>
+#include <simgear/props/props_io.hxx>
+
 class RemoteXMLRequest:
   public simgear::HTTP::MemoryRequest
 {
diff --git a/src/Scenery/tilemgr.cxx b/src/Scenery/tilemgr.cxx
index ec3028d3e..9c1327b82 100644
--- a/src/Scenery/tilemgr.cxx
+++ b/src/Scenery/tilemgr.cxx
@@ -126,14 +126,7 @@ FGTileMgr::FGTileMgr():
 
 FGTileMgr::~FGTileMgr()
 {
-    delete _listener;
-    
-    // remove all nodes we might have left behind
-    osg::Group* group = globals->get_scenery()->get_terrain_branch();
-    group->removeChildren(0, group->getNumChildren());
-    // clear OSG cache
-    osgDB::Registry::instance()->clearObjectCache();
-}
+   }
 
 
 // Initialize the Tile Manager subsystem
@@ -142,6 +135,21 @@ void FGTileMgr::init()
     reinit();
 }
 
+void FGTileMgr::shutdown()
+{
+    delete _listener;
+    _listener = NULL;
+
+    FGScenery* scenery = globals->get_scenery();
+    if (scenery && scenery->get_terrain_branch()) {
+        osg::Group* group = scenery->get_terrain_branch();
+        group->removeChildren(0, group->getNumChildren());
+    }
+    // clear OSG cache
+    osgDB::Registry::instance()->clearObjectCache();
+    state = Start; // need to init again
+}
+
 void FGTileMgr::reinit()
 {
     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
diff --git a/src/Scenery/tilemgr.hxx b/src/Scenery/tilemgr.hxx
index 37c77888a..6ed281031 100644
--- a/src/Scenery/tilemgr.hxx
+++ b/src/Scenery/tilemgr.hxx
@@ -101,6 +101,8 @@ public:
     // Initialize the Tile Manager
     virtual void init();
     virtual void reinit();
+    virtual void shutdown();
+
     virtual void update(double dt);
 
     const SGBucket& get_current_bucket () const { return current_bucket; }
diff --git a/src/Traffic/SchedFlight.cxx b/src/Traffic/SchedFlight.cxx
index 228d67cbf..7ae4125ef 100644
--- a/src/Traffic/SchedFlight.cxx
+++ b/src/Traffic/SchedFlight.cxx
@@ -58,7 +58,6 @@
 #include <AIModel/AIFlightPlan.hxx>
 #include <AIModel/AIManager.hxx>
 #include <Airports/airport.hxx>
-#include <Main/fg_init.hxx>   // That's pretty ugly, but I need fgFindAirportID
 
 
 
diff --git a/src/Traffic/Schedule.cxx b/src/Traffic/Schedule.cxx
index a47dfd2ca..7e8cdbdfc 100644
--- a/src/Traffic/Schedule.cxx
+++ b/src/Traffic/Schedule.cxx
@@ -49,8 +49,8 @@
 #include <AIModel/AIManager.hxx>
 #include <AIModel/AIAircraft.hxx>
 #include <Airports/airport.hxx>
-#include <Main/fg_init.hxx>   // That's pretty ugly, but I need fgFindAirportID
-
+#include <Main/globals.hxx>
+#include <Main/fg_props.hxx>
 
 #include "SchedFlight.hxx"
 #include "TrafficMgr.hxx"
@@ -403,10 +403,12 @@ void FGAISchedule::setHeading()
     courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
 }
 
+void FGAISchedule::assign(FGScheduledFlight *ref) { flights.push_back(ref); }
+
 bool FGAISchedule::scheduleFlights(time_t now)
 {
-  //string startingPort;
-  const string& userPort = fgGetString("/sim/presets/airport-id");
+    //string startingPort;
+    const string& userPort = fgGetString("/sim/presets/airport-id");
   SG_LOG(SG_AI, SG_BULK, "Scheduling Flights for : " << modelPath << " " <<  registration << " " << homePort);
   FGScheduledFlight *flight = NULL;
   SGTimeStamp start;
@@ -503,6 +505,18 @@ bool FGAISchedule::next()
    return true;
 }
 
+time_t FGAISchedule::getDepartureTime() { return (*flights.begin())->getDepartureTime   (); }
+
+FGAirport *FGAISchedule::getDepartureAirport() { return (*flights.begin())->getDepartureAirport(); }
+
+FGAirport *FGAISchedule::getArrivalAirport() { return (*flights.begin())->getArrivalAirport  (); }
+
+int FGAISchedule::getCruiseAlt() { return (*flights.begin())->getCruiseAlt       (); }
+
+const std::string &FGAISchedule::getCallSign() { return (*flights.begin())->getCallSign (); }
+
+const std::string &FGAISchedule::getFlightRules() { return (*flights.begin())->getFlightRules (); }
+
 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string &currentDestination,
                                                       const string &req,
                                                      time_t min, time_t max)
diff --git a/src/Traffic/Schedule.hxx b/src/Traffic/Schedule.hxx
index 9ac4b49ea..12169f4b7 100644
--- a/src/Traffic/Schedule.hxx
+++ b/src/Traffic/Schedule.hxx
@@ -34,6 +34,9 @@
 
 // forward decls
 class FGAIAircraft;
+class FGScheduledFlight;
+
+typedef std::vector<FGScheduledFlight*> FGScheduledFlightVec;
 
 class FGAISchedule
 {
@@ -106,18 +109,18 @@ class FGAISchedule
   bool next();   // forces the schedule to move on to the next flight.
 
   // TODO: rework these four functions
-   time_t      getDepartureTime    () { return (*flights.begin())->getDepartureTime   (); };
-  FGAirport * getDepartureAirport () { return (*flights.begin())->getDepartureAirport(); };
-  FGAirport * getArrivalAirport   () { return (*flights.begin())->getArrivalAirport  (); };
-  int         getCruiseAlt        () { return (*flights.begin())->getCruiseAlt       (); };
+  time_t      getDepartureTime    ();
+  FGAirport * getDepartureAirport ();
+  FGAirport * getArrivalAirport   ();
+  int         getCruiseAlt        ();
   double      getRadius           () { return radius; };
   double      getGroundOffset     () { return groundOffset;};
   const std::string& getFlightType     () { return flightType;};
   const std::string& getAirline        () { return airline; };
   const std::string& getAircraft       () { return acType; };
-  const std::string& getCallSign       () { return (*flights.begin())->getCallSign (); };
+  const std::string& getCallSign       ();
   const std::string& getRegistration   () { return registration;};
-  const std::string& getFlightRules    () { return (*flights.begin())->getFlightRules (); };
+  const std::string& getFlightRules    ();
   bool getHeavy                   () { return heavy; };
   double getCourse                () { return courseToDest; };
   unsigned int getRunCount        () { return runCount; };
@@ -128,7 +131,7 @@ class FGAISchedule
   void         setScore   ();
   double       getScore   () { return score; };
   void         setHeading (); 
-  void         assign         (FGScheduledFlight *ref) { flights.push_back(ref); };
+  void         assign         (FGScheduledFlight *ref);
   void         setFlightType  (const std::string& val) { flightType = val; };
   FGScheduledFlight*findAvailableFlight (const std::string& currentDestination, const std::string &req, time_t min=0, time_t max=0);
   // used to sort in descending order of score: I've probably found a better way to
diff --git a/src/Traffic/TrafficMgr.cxx b/src/Traffic/TrafficMgr.cxx
index e17c801cf..4fc8bd38b 100644
--- a/src/Traffic/TrafficMgr.cxx
+++ b/src/Traffic/TrafficMgr.cxx
@@ -69,6 +69,8 @@
 #include <AIModel/AIBase.hxx>
 #include <Airports/airport.hxx>
 #include <Main/fg_init.hxx>
+#include <Main/globals.hxx>
+#include <Main/fg_props.hxx>
 
 #include "TrafficMgr.hxx"
 
@@ -391,7 +393,7 @@ private:
   mutable SGMutex _lock;
   bool _isFinished;
   bool _cancelThread;
-  PathList _trafficDirPaths;
+  simgear::PathList _trafficDirPaths;
    
 // parser state
     
@@ -524,7 +526,7 @@ void FGTrafficManager::init()
     
     doingInit = true;
     if (string(fgGetString("/sim/traffic-manager/datafile")).empty()) {
-        PathList dirs = globals->get_data_paths("AI/Traffic");
+        simgear::PathList dirs = globals->get_data_paths("AI/Traffic");
         
         // temporary flag to restrict loading while traffic data is found
         // through terrasync /and/ fgdata. Ultimatley we *do* want to be able to