]> git.mxchange.org Git - flightgear.git/blobdiff - src/ATC/tower.cxx
Catch sound exceptions at the earliest, report problem has an alert, and continue...
[flightgear.git] / src / ATC / tower.cxx
index acef4984ea7ff3a61f9d97857f211c58f2567ca4..d3a1113b85b36aca49c3b88d7ee1bf2a1e606403 100644 (file)
 // along with this program; if not, write to the Free Software
 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
+#ifdef HAVE_CONFIG_H
+#  include <config.h>
+#endif
+
+#ifdef HAVE_STRINGS_H
+#  include <strings.h>   // bcopy()
+#else
+#  include <string.h>    // MSVC doesn't have strings.h
+#endif
+
 #include <Main/globals.hxx>
 #include <Airports/runways.hxx>
 #include <simgear/math/sg_geodesy.hxx>
@@ -27,6 +37,7 @@
 #include "ATCdisplay.hxx"
 #include "ATCmgr.hxx"
 #include "ATCutils.hxx"
+#include "ATCDialog.hxx"
 #include "commlist.hxx"
 #include "AILocalTraffic.hxx"
 
@@ -35,86 +46,110 @@ SG_USING_STD(cout);
 // TowerPlaneRec
 
 TowerPlaneRec::TowerPlaneRec() :
-clearedToLand(false),
-clearedToLineUp(false),
-clearedToTakeOff(false),
-holdShortReported(false),
-downwindReported(false),
-longFinalReported(false),
-longFinalAcknowledged(false),
-finalReported(false),
-finalAcknowledged(false),
-instructedToGoAround(false),
-onRwy(false),
-nextOnRwy(false),
-opType(TTT_UNKNOWN),
-leg(LEG_UNKNOWN),
-landingType(AIP_LT_UNKNOWN),
-isUser(false)
+       planePtr(NULL),
+       clearedToLand(false),
+       clearedToLineUp(false),
+       clearedToTakeOff(false),
+       holdShortReported(false),
+       downwindReported(false),
+       longFinalReported(false),
+       longFinalAcknowledged(false),
+       finalReported(false),
+       finalAcknowledged(false),
+       rwyVacatedReported(false),
+       rwyVacatedAcknowledged(false),
+       goAroundReported(false),
+       instructedToGoAround(false),
+       onRwy(false),
+       nextOnRwy(false),
+       vfrArrivalReported(false),
+       vfrArrivalAcknowledged(false),
+       opType(TTT_UNKNOWN),
+       leg(LEG_UNKNOWN),
+       landingType(AIP_LT_UNKNOWN),
+       isUser(false)
 {
        plane.callsign = "UNKNOWN";
 }
 
-TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
-clearedToLand(false),
-clearedToLineUp(false),
-clearedToTakeOff(false),
-holdShortReported(false),
-downwindReported(false),
-longFinalReported(false),
-longFinalAcknowledged(false),
-finalReported(false),
-finalAcknowledged(false),
-instructedToGoAround(false),
-onRwy(false),
-nextOnRwy(false),
-opType(TTT_UNKNOWN),
-leg(LEG_UNKNOWN),
-landingType(AIP_LT_UNKNOWN),
-isUser(false)
+TowerPlaneRec::TowerPlaneRec(const PlaneRec& p) :
+       planePtr(NULL),
+       clearedToLand(false),
+       clearedToLineUp(false),
+       clearedToTakeOff(false),
+       holdShortReported(false),
+       downwindReported(false),
+       longFinalReported(false),
+       longFinalAcknowledged(false),
+       finalReported(false),
+       finalAcknowledged(false),
+       rwyVacatedReported(false),
+       rwyVacatedAcknowledged(false),
+       goAroundReported(false),
+       instructedToGoAround(false),
+       onRwy(false),
+       nextOnRwy(false),
+       vfrArrivalReported(false),
+       vfrArrivalAcknowledged(false),
+       opType(TTT_UNKNOWN),
+       leg(LEG_UNKNOWN),
+       landingType(AIP_LT_UNKNOWN),
+       isUser(false)
 {
        plane = p;
 }
 
-TowerPlaneRec::TowerPlaneRec(Point3D pt) :
-clearedToLand(false),
-clearedToLineUp(false),
-clearedToTakeOff(false),
-holdShortReported(false),
-downwindReported(false),
-longFinalReported(false),
-longFinalAcknowledged(false),
-finalReported(false),
-finalAcknowledged(false),
-instructedToGoAround(false),
-onRwy(false),
-nextOnRwy(false),
-opType(TTT_UNKNOWN),
-leg(LEG_UNKNOWN),
-landingType(AIP_LT_UNKNOWN),
-isUser(false)
+TowerPlaneRec::TowerPlaneRec(const Point3D& pt) :
+       planePtr(NULL),
+       clearedToLand(false),
+       clearedToLineUp(false),
+       clearedToTakeOff(false),
+       holdShortReported(false),
+       downwindReported(false),
+       longFinalReported(false),
+       longFinalAcknowledged(false),
+       finalReported(false),
+       finalAcknowledged(false),
+       rwyVacatedReported(false),
+       rwyVacatedAcknowledged(false),
+       goAroundReported(false),
+       instructedToGoAround(false),
+       onRwy(false),
+       nextOnRwy(false),
+       vfrArrivalReported(false),
+       vfrArrivalAcknowledged(false),
+       opType(TTT_UNKNOWN),
+       leg(LEG_UNKNOWN),
+       landingType(AIP_LT_UNKNOWN),
+       isUser(false)
 {
        plane.callsign = "UNKNOWN";
        pos = pt;
 }
 
-TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
-clearedToLand(false),
-clearedToLineUp(false),
-clearedToTakeOff(false),
-holdShortReported(false),
-downwindReported(false),
-longFinalReported(false),
-longFinalAcknowledged(false),
-finalReported(false),
-finalAcknowledged(false),
-instructedToGoAround(false),
-onRwy(false),
-nextOnRwy(false),
-opType(TTT_UNKNOWN),
-leg(LEG_UNKNOWN),
-landingType(AIP_LT_UNKNOWN),
-isUser(false)
+TowerPlaneRec::TowerPlaneRec(const PlaneRec& p, const Point3D& pt) :
+       planePtr(NULL),
+       clearedToLand(false),
+       clearedToLineUp(false),
+       clearedToTakeOff(false),
+       holdShortReported(false),
+       downwindReported(false),
+       longFinalReported(false),
+       longFinalAcknowledged(false),
+       finalReported(false),
+       finalAcknowledged(false),
+       rwyVacatedReported(false),
+       rwyVacatedAcknowledged(false),
+       goAroundReported(false),
+       instructedToGoAround(false),
+       onRwy(false),
+       nextOnRwy(false),
+       vfrArrivalReported(false),
+       vfrArrivalAcknowledged(false),
+       opType(TTT_UNKNOWN),
+       leg(LEG_UNKNOWN),
+       landingType(AIP_LT_UNKNOWN),
+       isUser(false)
 {
        plane = p;
        pos = pt;
@@ -126,25 +161,41 @@ isUser(false)
 /*******************************************
                TODO List
                           
-Currently user is assumed to have taken off again when leaving the runway - check speed/elev for taxiing-in.
+Currently user is assumed to have taken off again when leaving the runway - check speed/elev for taxiing-in. (MAJOR)
 
-AI plane lands even when user on rwy - make it go-around instead.
+Use track instead of heading to determine what leg of the circuit the user is flying. (MINOR)
 
-Tell AI plane to contact ground when taxiing in.
+Use altitude as well as position to try to determine if the user has left the circuit. (MEDIUM - other issues as well).
 
-Use track instead of heading to determine what leg of the circuit the user is flying.
+Currently HoldShortReported code assumes there will be only one plane holding for the runway at once and 
+will break when planes start queueing. (CRITICAL)
 
-Use altitude as well as position to try to determine if the user has left the circuit.
+Report-Runway-Vacated is left as only user ATC option following a go-around. (MAJOR)
 
-Currently HoldShortReported code assumes there will be only one plane holding for the runway at once and 
-will break when planes start queueing.
+Report-Downwind is not added as ATC option when user takes off to fly a circuit. (MAJOR)
+
+eta of USER can be calculated very wrongly in circuit if flying straight out and turn4 etc are with +ve ortho y. 
+This can then screw up circuit ordering for other planes (MEDIUM)
+
+USER leaving circuit needs to be more robustly considered when intentions unknown
+Currently only considered during climbout and breaks when user turns (MEDIUM).
+
+GetPos() of the AI planes is called erratically - either too much or not enough. (MINOR)
+
+GO-AROUND is instructed very late at < 12s to landing - possibly make more dependent on chance of rwy clearing before landing (FEATURE)
+
+Need to make clear when TowerPlaneRecs do or don't get deleted in RemoveFromCircuitList etc. (MINOR until I misuse it - then CRITICAL!)
+
+FGTower::RemoveAllUserDialogOptions() really ought to be replaced by an ATCDialog::clear_entries() function. (MINOR - efficiency).
 
-Implement ReportRunwayVacated
+At the moment planes in the lists are not guaranteed to always have a sensible ETA - it should be set as part of AddList functions, and lists should only be accessed this way. (FAIRLY MAJOR). 
 *******************************************/
 
 FGTower::FGTower() {
        ATCmgr = globals->get_ATC_mgr();
        
+       _type = TOWER;
+       
        // Init the property nodes - TODO - need to make sure we're getting surface winds.
        wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
        wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
@@ -153,16 +204,25 @@ FGTower::FGTower() {
        update_count_max = 15;
        
        holdListItr = holdList.begin();
+       appList.clear();
        appListItr = appList.begin();
        depListItr = depList.begin();
        rwyListItr = rwyList.begin();
        circuitListItr = circuitList.begin();
        trafficListItr = trafficList.begin();
+       vacatedList.clear();
+       vacatedListItr = vacatedList.begin();
        
        freqClear = true;
        
        timeSinceLastDeparture = 9999;
        departed = false;
+       
+       nominal_downwind_leg_pos = 1000.0;
+       nominal_base_leg_pos = -1000.0;
+       // TODO - set nominal crosswind leg pos based on minimum distance from takeoff end of rwy.
+       
+       _departureControlled = false;
 }
 
 FGTower::~FGTower() {
@@ -172,7 +232,7 @@ FGTower::~FGTower() {
 }
 
 void FGTower::Init() {
-    display = false;
+       //cout << "Initialising tower " << ident << '\n';
        
        // Pointers to user's position
        user_lon_node = fgGetNode("/position/longitude-deg", true);
@@ -197,7 +257,7 @@ void FGTower::Init() {
                                ground = new FGGround(ident);
                                separateGround = false;
                                ground->Init();
-                               if(display) {
+                               if(_display) {
                                        ground->SetDisplay();
                                } else {
                                        ground->SetNoDisplay();
@@ -209,7 +269,7 @@ void FGTower::Init() {
                        ground = new FGGround(ident);
                        separateGround = false;
                        ground->Init();
-                       if(display) {
+                       if(_display) {
                                ground->SetDisplay();
                        } else {
                                ground->SetNoDisplay();
@@ -221,25 +281,29 @@ void FGTower::Init() {
                ground = new FGGround(ident);
                separateGround = false;
                ground->Init();
-               if(display) {
+               if(_display) {
                        ground->SetDisplay();
                } else {
                        ground->SetNoDisplay();
                }
        }
        
+       // TODO - attempt to get a departure control pointer to see if we need to hand off departing traffic to departure.
+       
        // Get the airport elevation
-       aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
+       aptElev = fgGetAirportElev(ident.c_str());
        
+       // TODO - this function only assumes one active rwy.
        DoRwyDetails();
        
-       // FIXME - this currently assumes use of the active rwy by the user.
-       rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
+       // TODO - this currently assumes only one active runway.
+       rwyOccupied = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
        if(rwyOccupied) {
+               //cout << "User found on active runway\n";
                // Assume the user is started at the threshold ready to take-off
                TowerPlaneRec* t = new TowerPlaneRec;
-               t->plane.callsign = "Charlie Foxtrot Sierra";   // C-FGFS !!! - fixme - this is a bit hardwired
-               t->plane.type = GA_SINGLE;
+               t->plane.callsign = fgGetString("/sim/user/callsign");
+               t->plane.type = GA_SINGLE;      // FIXME - hardwired!!
                t->opType = TTT_UNKNOWN;        // We don't know if the user wants to do circuits or a departure...
                t->landingType = AIP_LT_UNKNOWN;
                t->leg = TAKEOFF_ROLL;
@@ -247,7 +311,16 @@ void FGTower::Init() {
                t->planePtr = NULL;
                t->clearedToTakeOff = true;
                rwyList.push_back(t);
+               rwyListItr = rwyList.begin();
                departed = false;
+       } else {
+               //cout << "User not on active runway\n";
+               // For now assume that this means the user is not at the airport and is in the air.
+               // TODO FIXME - this will break when user starts on apron, at hold short, etc.
+               if(!OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0))) {
+                       //cout << ident << "  ADD 0\n";
+                       current_atcdialog->add_entry(ident, "@AP Tower @CS @MI miles @CD of the airport for full stop with ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
+               }
        }
 }
 
@@ -270,6 +343,7 @@ void FGTower::Update(double dt) {
                cout << update_count << "\ttL: " << trafficList.size() << "  cL: " << circuitList.size() << "  hL: " << holdList.size() << "  aL: " << appList.size() << '\n';
        }
        */
+       //if(ident == "EGNX") cout << display << '\n';
        
        if(departed != false) {
                timeSinceLastDeparture += dt;
@@ -323,6 +397,10 @@ void FGTower::Update(double dt) {
                CheckApproachList(dt);
        }
        
+       if(update_count == 8) {
+               CheckDepartureList(dt);
+       }
+       
        // TODO - do one plane from the departure list and set departed = false when out of consideration
        
        //doCommunication();
@@ -331,7 +409,8 @@ void FGTower::Update(double dt) {
                // The display stuff might have to get more clever than this when not separate 
                // since the tower and ground might try communicating simultaneously even though
                // they're mean't to be the same contoller/frequency!!
-               if(display) {
+               // We could also get rid of this by overloading FGATC's Set(No)Display() functions.
+               if(_display) {
                        ground->SetDisplay();
                } else {
                        ground->SetNoDisplay();
@@ -348,6 +427,7 @@ void FGTower::Update(double dt) {
        // Call the base class update for the response time handling.
        FGATC::Update(dt);
 
+       /*
        if(ident == "KEMT") {   
                // For AI debugging convienience - may be removed
                Point3D user_pos;
@@ -359,33 +439,89 @@ void FGTower::Update(double dt) {
                fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
                fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
        }
+       */
        
        //cout << "Done T" << endl;
 }
 
+void FGTower::ReceiveUserCallback(int code) {
+       if(code == (int)USER_REQUEST_VFR_DEPARTURE) {
+               //cout << "User requested departure\n";
+       } else if(code == (int)USER_REQUEST_VFR_ARRIVAL) {
+               VFRArrivalContact("USER");
+       } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP) {
+               VFRArrivalContact("USER", FULL_STOP);
+       } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO) {
+               VFRArrivalContact("USER", TOUCH_AND_GO);
+       } else if(code == (int)USER_REPORT_DOWNWIND) {
+               ReportDownwind("USER");
+       } else if(code == (int)USER_REPORT_3_MILE_FINAL) {
+               // For now we'll just call report final instead of report long final to avoid having to alter the response code
+               ReportFinal("USER");
+       } else if(code == (int)USER_REPORT_RWY_VACATED) {
+               ReportRunwayVacated("USER");
+       } else if(code == (int)USER_REPORT_GOING_AROUND) {
+               ReportGoingAround("USER");
+       }
+}
+
+// **************** RESPONSE FUNCTIONS ****************
+
 void FGTower::Respond() {
-       //cout << "Entering Respond..." << endl;
+       //cout << "\nEntering Respond, responseID = " << responseID << endl;
        TowerPlaneRec* t = FindPlane(responseID);
        if(t) {
                // This will grow!!!
-               if(t->downwindReported) {
-                       t->downwindReported = false;
-                       int i = 1;
-                       for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
-                               if((*twrItr)->plane.callsign == responseID) break;
-                               ++i;
-                       }                       
-                       string trns = "Number ";
-                       trns += ConvertNumToSpokenDigits(i);
+               if(t->vfrArrivalReported && !t->vfrArrivalAcknowledged) {
+                       //cout << "Tower " << ident << " is responding to VFR arrival reported...\n";
+                       // Testing - hardwire straight in for now
+                       string trns = t->plane.callsign;
                        trns += " ";
-                       trns += t->plane.callsign;
-                       if(display) {
-                               globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
-                       }
-                       if(t->isUser && t->opType == TTT_UNKNOWN) {
+                       trns += name;
+                       trns += " Tower";
+                       // Should we clear staight in or for downwind entry?
+                       // For now we'll clear straight in if greater than 1km from a line drawn through the threshold perpendicular to the rwy.
+                       // Later on we might check the actual heading and direct some of those to enter on downwind or base.
+                       Point3D op = ortho.ConvertToLocal(t->pos);
+                       if(op.y() < -1000) {
+                               trns += " Report three mile straight-in runway ";
+                               t->opType = STRAIGHT_IN;
+                               if(t->isUser) {
+                                       current_atcdialog->add_entry(ident, "@AP Tower @CS @MI mile final Runway @RW", "Report Final", TOWER, (int)USER_REPORT_3_MILE_FINAL);
+                               } else {
+                                       t->planePtr->RegisterTransmission(14);
+                               }
+                       } else {
+                               // For now we'll just request reporting downwind.
+                               // TODO - In real life something like 'report 2 miles southwest right downwind rwy 19R' might be used
+                               // but I'm not sure how to handle all permutations of which direction to tell to report from yet.
+                               trns += " Report ";
+                               //cout << "Responding, rwy.patterDirection is " << rwy.patternDirection << '\n';
+                               trns += ((rwy.patternDirection == 1) ? "right " : "left ");
+                               trns += "downwind runway ";
                                t->opType = CIRCUIT;
+                               // leave it in the app list until it gets into pattern though.
+                               if(t->isUser) {
+                                       current_atcdialog->add_entry(ident, "@AP Tower @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
+                               } else {
+                                       t->planePtr->RegisterTransmission(15);
+                               }
                        }
+                       trns += ConvertRwyNumToSpokenString(activeRwy);
+                       if(_display) {
+                               //globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
+                               pending_transmission = trns;
+                               Transmit();
+                       } else {
+                               //cout << "Not displaying, trns was " << trns << '\n';
+                       }
+                       t->vfrArrivalAcknowledged = true;
+               } else if(t->downwindReported) {
+                       //cout << "Tower " << ident << " is responding to downwind reported...\n";
+                       ProcessDownwindReport(t);
+                       t->downwindReported = false;
                } else if(t->holdShortReported) {
+                       //cout << "Tower " << ident << " is reponding to holdShortReported...\n";
                        if(t->nextOnRwy) {
                                if(rwyOccupied) {       // TODO - ought to add a sanity check that it isn't this plane only on the runway (even though it shouldn't be!!)
                                        // Do nothing for now - consider acknowloging hold short eventually
@@ -393,10 +529,11 @@ void FGTower::Respond() {
                                        ClearHoldingPlane(t);
                                        t->leg = TAKEOFF_ROLL;
                                        rwyList.push_back(t);
+                                       rwyListItr = rwyList.begin();
                                        rwyOccupied = true;
                                        // WARNING - WE ARE ASSUMING ONLY ONE PLANE REPORTING HOLD AT A TIME BELOW
                                        // FIXME TODO - FIX THIS!!!
-                                       if(holdList.size()) {
+                                       if(!holdList.empty()) {
                                                if(holdListItr == holdList.end()) {
                                                        holdListItr = holdList.begin();
                                                }
@@ -409,16 +546,21 @@ void FGTower::Respond() {
                                // Not currently sure under which circumstances we do or don't bother transmitting this.
                                string trns = t->plane.callsign;
                                trns += " hold position";
-                               if(display) {
-                                       globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
+                               if(_display) {
+                                       //globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
+                                       pending_transmission = trns;
+                                       Transmit();
                                }
                                // TODO - add some idea of what traffic is blocking him.
                        }
                        t->holdShortReported = false;
                } else if(t->finalReported && !(t->finalAcknowledged)) {
+                       //cout << "Tower " << ident << " is responding to finalReported...\n";
                        bool disp = true;
                        string trns = t->plane.callsign;
-                       if(t->nextOnRwy && !rwyOccupied) {
+                       //cout << (t->nextOnRwy ? "Next on rwy " : "Not next!! ");
+                       //cout << (rwyOccupied ? "RWY OCCUPIED!!\n" : "Rwy not occupied\n");
+                       if(t->nextOnRwy && !rwyOccupied && !(t->instructedToGoAround)) {
                                if(t->landingType == FULL_STOP) {
                                        trns += " cleared to land ";
                                } else {
@@ -426,6 +568,16 @@ void FGTower::Respond() {
                                }
                                // TODO - add winds
                                t->clearedToLand = true;
+                               // Maybe remove report downwind from menu here as well incase user didn't bother to?
+                               if(t->isUser) {
+                                       //cout << "ADD VACATED B\n";
+                                       // Put going around at the top (and hence default) since that'll be more desperate,
+                                       // or put rwy vacated at the top since that'll be more common?
+                                       current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND);
+                                       current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
+                               } else {
+                                       t->planePtr->RegisterTransmission(7);
+                               }
                        } else if(t->eta < 20) {
                                // Do nothing - we'll be telling it to go around in less than 10 seconds if the
                                // runway doesn't clear so no point in calling "continue approach".
@@ -434,16 +586,149 @@ void FGTower::Respond() {
                                trns += " continue approach";
                                t->clearedToLand = false;
                        }
-                       if(display && disp) {
-                               globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
+                       if(_display && disp) {
+                               //globals->get_ATC_display()->RegisterSingleMessage(trns);
+                               pending_transmission = trns;
+                               Transmit();
                        }
                        t->finalAcknowledged = true;
+               } else if(t->rwyVacatedReported && !(t->rwyVacatedAcknowledged)) {
+                       ProcessRunwayVacatedReport(t);
+                       t->rwyVacatedAcknowledged = true;
                }
        }
-       freqClear = true;       // FIXME - set this to come true after enough time to render the message
-       //cout << "Done Respond" << endl;
+       //freqClear = true;     // FIXME - set this to come true after enough time to render the message
+       _releaseCounter = 0.0;
+       _releaseTime = 5.5;
+       _runReleaseCounter = true;
+       //cout << "Done Respond\n" << endl;
 }
 
+void FGTower::ProcessDownwindReport(TowerPlaneRec* t) {
+       int i = 1;
+       int a = 0;      // Count of preceding planes on approach
+       bool cf = false;        // conflicting traffic on final
+       bool cc = false;        // preceding traffic in circuit
+       TowerPlaneRec* tc = NULL;
+       for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
+               if((*twrItr)->plane.callsign == responseID) break;
+               tc = *twrItr;
+               ++i;
+       }
+       if(i > 1) { cc = true; }
+       doThresholdETACalc();
+       TowerPlaneRec* tf = NULL;
+       for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
+               if((*twrItr)->eta < (t->eta + 45)) {
+                       a++;
+                       tf = *twrItr;
+                       cf = true;
+                       // This should set the flagged plane to be the last conflicting one, and hence the one to follow.
+                       // It ignores the fact that we might have problems slotting into the approach traffic behind it - 
+                       // eventually we'll need some fancy algorithms for that!
+               }
+       }
+       string trns = t->plane.callsign;
+       trns += " Number ";
+       trns += ConvertNumToSpokenDigits(i + a);
+       // This assumes that the number spoken is landing position, not circuit position, since some of the traffic might be on straight-in final.
+       trns += " ";
+       TowerPlaneRec* tt = NULL;
+       if((i == 1) && rwyList.empty() && (t->nextOnRwy) && (!cf)) {    // Unfortunately nextOnRwy currently doesn't handle circuit/straight-in ordering properly at present, hence the cf check below.
+               trns += "Cleared to land";      // TODO - clear for the option if appropriate
+               t->clearedToLand = true;
+               if(!t->isUser) t->planePtr->RegisterTransmission(7);
+       } else if((i+a) > 1) {
+               //First set tt to point to the correct preceding plane - final or circuit
+               if(tc && tf) {
+                       tt = (tf->eta < tc->eta ? tf : tc);
+               } else if(tc) {
+                       tt = tc;
+               } else if(tf) {
+                       tt = tf;
+               } else {
+                       // We should never get here!
+                       SG_LOG(SG_ATC, SG_ALERT, "ALERT - Logic error in FGTower::ProcessDownwindReport");
+                       return;
+               }
+               trns += "Follow the ";
+               string s = tt->plane.callsign;
+               int p = s.find('-');
+               s = s.substr(0,p);
+               trns += s;
+               if((tt->opType) == CIRCUIT) {
+                       PatternLeg leg;
+                       if(t->isUser) {
+                               leg = tt->leg;
+                       } else {
+                               leg = tt->planePtr->GetLeg();
+                       }
+                       if(leg == FINAL) {
+                               trns += " on final";
+                       } else if(leg == TURN4) {
+                               trns += " turning final";
+                       } else if(leg == BASE) {
+                               trns += " on base";
+                       } else if(leg == TURN3) {
+                               trns += " turning base";
+                       }
+               } else {
+                       double miles_out = CalcDistOutMiles(tt);
+                       if(miles_out < 2) {
+                               trns += " on short final";
+                       } else {
+                               trns += " on ";
+                               trns += ConvertNumToSpokenDigits((int)miles_out);
+                               trns += " mile final";
+                       }
+               }
+       }
+       if(_display) {
+               //globals->get_ATC_display()->RegisterSingleMessage(trns);
+               pending_transmission = trns;
+               Transmit();
+       }
+       if(t->isUser) {
+               if(t->opType == TTT_UNKNOWN) t->opType = CIRCUIT;
+               //cout << "ADD VACATED A\n";
+               // Put going around at the top (and hence default) since that'll be more desperate,
+               // or put rwy vacated at the top since that'll be more common?
+               //cout << "ident = " << ident << ", adding go-around option\n";
+               current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND);
+               current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
+       }
+}
+
+void FGTower::ProcessRunwayVacatedReport(TowerPlaneRec* t) {
+       //cout << "Processing rwy vacated...\n";
+       if(t->isUser) current_atcdialog->remove_entry(ident, USER_REPORT_GOING_AROUND, TOWER);
+       string trns = t->plane.callsign;
+       if(separateGround) {
+               trns += " Contact ground on ";
+               double f = globals->get_ATC_mgr()->GetFrequency(ident, GROUND) / 100.0; 
+               char buf[10];
+               sprintf(buf, "%.2f", f);
+               trns += buf;
+               trns += " Good Day";
+               if(!t->isUser) t->planePtr->RegisterTransmission(5);
+       } else {
+               // Cop-out!!
+               trns += " cleared for taxi to general aviation parking";
+               if(!t->isUser) t->planePtr->RegisterTransmission(6);    // TODO - this is a mega-hack!!
+       }
+       //cout << "trns = " << trns << '\n';
+       if(_display) {
+               //globals->get_ATC_display()->RegisterSingleMessage(trns);
+               pending_transmission = trns;
+               Transmit();
+       }
+       RemoveFromRwyList(t->plane.callsign);
+       AddToVacatedList(t);
+       // Maybe we should check that the plane really *has* vacated the runway!
+}
+
+// *********** END RESPONSE FUNCTIONS *****************
+
 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land - 
 // this should be done prior to calling this function.
 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
@@ -545,16 +830,22 @@ void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
                departed = false;
                timeSinceLastDeparture = 0.0;
        }
-       if(display) {
-               globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
+       if(_display) {
+               //globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
+               pending_transmission = trns;
+               Transmit();
        }
        //cout << "Done ClearHoldingPlane " << endl;
 }
 
+
+// ***************************************************************************************
+// ********** Functions to periodically check what the various traffic is doing **********
+
 // Do one plane from the hold list
 void FGTower::CheckHoldList(double dt) {
        //cout << "Entering CheckHoldList..." << endl;
-       if(holdList.size()) {
+       if(!holdList.empty()) {
                //cout << "*holdListItr = " << *holdListItr << endl;
                if(holdListItr == holdList.end()) {
                        holdListItr = holdList.begin();
@@ -577,9 +868,12 @@ void FGTower::CheckHoldList(double dt) {
                                        ClearHoldingPlane(t);
                                        t->leg = TAKEOFF_ROLL;
                                        rwyList.push_back(t);
+                                       rwyListItr = rwyList.begin();
                                        rwyOccupied = true;
                                        holdList.erase(holdListItr);
                                        holdListItr = holdList.begin();
+                                       if (holdList.empty())
+                                         return;
                                }
                        }
                        // TODO - rationalise the considerable code duplication above!
@@ -597,15 +891,17 @@ void FGTower::CheckCircuitList(double dt) {
        downwind_leg_pos = 0.0;
        crosswind_leg_pos = 0.0;
        
-       if(circuitList.size()) {        // Do one plane from the circuit
+       if(!circuitList.empty()) {      // Do one plane from the circuit
                if(circuitListItr == circuitList.end()) {
                        circuitListItr = circuitList.begin();
                }
                TowerPlaneRec* t = *circuitListItr;
+               //cout << ident <<  ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n';
                if(t->isUser) {
                        t->pos.setlon(user_lon_node->getDoubleValue());
                        t->pos.setlat(user_lat_node->getDoubleValue());
                        t->pos.setelev(user_elev_node->getDoubleValue());
+                       //cout << ident <<  ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n';
                } else {
                        t->pos = t->planePtr->GetPos();         // We should probably only set the pos's on one walk through the traffic list in the update function, to save a few CPU should we end up duplicating this.
                        t->landingType = t->planePtr->GetLandingOption();
@@ -619,7 +915,7 @@ void FGTower::CheckCircuitList(double dt) {
                        //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
                        // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
                        // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
-                       if(abs(ho) < 30) {
+                       if(fabs(ho) < 30) {
                                // could be either takeoff, climbout or landing - check orthopos.y
                                //cout << "tortho.y = " << tortho.y() << '\n';
                                if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
@@ -630,26 +926,32 @@ void FGTower::CheckCircuitList(double dt) {
                                        //cout << "Climbout\n";
                                        // If it's the user we may be unsure of his/her intentions.
                                        // (Hopefully the AI planes won't try confusing the sim!!!)
+                                       //cout << "tortho.y = " << tortho.y() << '\n';
                                        if(t->opType == TTT_UNKNOWN) {
                                                if(tortho.y() > 5000) {
                                                        // 5 km out from threshold - assume it's a departure
                                                        t->opType = OUTBOUND;   // TODO - could check if the user has climbed significantly above circuit altitude as well.
                                                        // Since we are unknown operation we should be in depList already.
-                                                       circuitList.erase(circuitListItr);
+                                                       //cout << ident << " Removing user from circuitList (TTT_UNKNOWN)\n";
+                                                       circuitListItr = circuitList.erase(circuitListItr);
                                                        RemoveFromTrafficList(t->plane.callsign);
-                                                       circuitListItr = circuitList.begin();
+                                                       if (circuitList.empty())
+                                                           return;
                                                }
                                        } else if(t->opType == CIRCUIT) {
                                                if(tortho.y() > 10000) {
                                                        // 10 km out - assume the user has abandoned the circuit!!
                                                        t->opType = OUTBOUND;
                                                        depList.push_back(t);
-                                                       circuitList.erase(circuitListItr);
-                                                       circuitListItr = circuitList.begin();
+                                                       depListItr = depList.begin();
+                                                       //cout << ident << " removing user from circuitList (CIRCUIT)\n";
+                                                       circuitListItr = circuitList.erase(circuitListItr);
+                                                       if (circuitList.empty())
+                                                         return;
                                                }
                                        }
                                }
-                       } else if(abs(ho) < 60) {
+                       } else if(fabs(ho) < 60) {
                                // turn1 or turn 4
                                // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
                                if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
@@ -659,7 +961,7 @@ void FGTower::CheckCircuitList(double dt) {
                                        t->leg = TURN4;
                                        //cout << "Turn4\n";
                                }
-                       } else if(abs(ho) < 120) {
+                       } else if(fabs(ho) < 120) {
                                // crosswind or base
                                // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
                                if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
@@ -669,7 +971,7 @@ void FGTower::CheckCircuitList(double dt) {
                                        t->leg = BASE;
                                        //cout << "Base\n";
                                }
-                       } else if(abs(ho) < 150) {
+                       } else if(fabs(ho) < 150) {
                                // turn2 or turn 3
                                // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
                                if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
@@ -699,70 +1001,111 @@ void FGTower::CheckCircuitList(double dt) {
                // TODO - at the moment we're constraining plane 2 based on plane 1 - this won't (or might not) work for 3 planes in the circuit!!
                if(circuitListItr == circuitList.begin()) {
                        switch(t->leg) {
-                       case FINAL:
+                               case FINAL:
                                // Base leg must be at least as far out as the plane is - actually possibly not necessary for separation, but we'll use that for now.
                                base_leg_pos = tortho.y();
                                //cout << "base_leg_pos = " << base_leg_pos << '\n';
                                break;
-                       case TURN4:
+                               case TURN4:
                                // Fall through to base
-                       case BASE:
+                               case BASE:
                                base_leg_pos = tortho.y();
                                //cout << "base_leg_pos = " << base_leg_pos << '\n';
                                break;
-                       case TURN3:
+                               case TURN3:
                                // Fall through to downwind
-                       case DOWNWIND:
+                               case DOWNWIND:
                                // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
                                base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
                                //cout << "base_leg_pos = " << base_leg_pos;
                                downwind_leg_pos = tortho.x();          // Assume that a following plane can simply be constrained by the immediately in front downwind plane
                                //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
                                break;
-                       case TURN2:
+                               case TURN2:
                                // Fall through to crosswind
-                       case CROSSWIND:
+                               case CROSSWIND:
                                crosswind_leg_pos = tortho.y();
                                //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
                                t->instructedToGoAround = false;
                                break;
-                       case TURN1:
+                               case TURN1:
                                // Fall through to climbout
-                       case CLIMBOUT:
+                               case CLIMBOUT:
                                // Only use current by constraint as largest
                                crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
                                //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
                                break;
-                       case TAKEOFF_ROLL:
+                               case TAKEOFF_ROLL:
                                break;
-                       case LEG_UNKNOWN:
+                               case LEG_UNKNOWN:
                                break;
-                       case LANDING_ROLL:
+                               case LANDING_ROLL:
                                break;
-                       default:
+                               default:
                                break;
                        }
                }
                
-               if(t->leg == FINAL) {
-                       if(t->landingType == FULL_STOP) t->opType = INBOUND;
-                       if(t->eta < 12 && rwyList.size() && !(t->instructedToGoAround)) {
+               if(t->leg == FINAL && !(t->instructedToGoAround)) {
+                       doThresholdETACalc();
+                       doThresholdUseOrder();
+                       /*
+                       if(t->isUser) {
+                               cout << "Checking USER on final... ";
+                               cout << "eta " << t->eta;
+                               if(t->clearedToLand) cout << " cleared to land\n";
+                       }
+                       */
+                       //cout << "YES FINAL, t->eta = " << t->eta << ", rwyList.size() = " << rwyList.size() << '\n';
+                       if(t->landingType == FULL_STOP) {
+                               t->opType = INBOUND;
+                               //cout << "\n******** SWITCHING TO INBOUND AT POINT AAA *********\n\n";
+                       }
+                       if(t->eta < 12 && rwyList.size()) {
                                // TODO - need to make this more sophisticated 
                                // eg. is the plane accelerating down the runway taking off [OK],
                                // or stationary near the start [V. BAD!!].
                                // For now this should stop the AI plane landing on top of the user.
                                string trns = t->plane.callsign;
                                trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
-                               if(display) {
-                                       globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
-                               }
+                               pending_transmission = trns;
+                               ImmediateTransmit();
                                t->instructedToGoAround = true;
+                               t->clearedToLand = false;
+                               // Assume it complies!!!
+                               t->opType = CIRCUIT;
+                               t->leg = CLIMBOUT;
                                if(t->planePtr) {
-                                       cout << "Registering Go-around transmission with AI plane\n";
+                                       //cout << "Registering Go-around transmission with AI plane\n";
                                        t->planePtr->RegisterTransmission(13);
                                }
+                       } else if(!t->clearedToLand) {
+                               // The whip through the appList is a hack since currently t->nextOnRwy doesn't always work
+                               // TODO - fix this!
+                               bool cf = false;
+                               for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
+                                       if((*twrItr)->eta < t->eta) {
+                                               cf = true;
+                                       }
+                               }
+                               if(t->nextOnRwy && !cf) {
+                                       if(!rwyList.size()) {
+                                               string trns = t->plane.callsign;
+                                               trns += " Cleared to land";
+                                               pending_transmission = trns;
+                                               Transmit();
+                                               //if(t->isUser) cout << "Transmitting cleared to Land!!!\n";
+                                               t->clearedToLand = true;
+                                               if(!t->isUser) {
+                                                       t->planePtr->RegisterTransmission(7);
+                                               }
+                                       }
+                               } else {
+                                       //if(t->isUser) cout << "Not next\n";
+                               }
                        }
                } else if(t->leg == LANDING_ROLL) {
+                       //cout << t->plane.callsign << " has landed - adding to rwyList\n";
                        rwyList.push_front(t);
                        // TODO - if(!clearedToLand) shout something!!
                        t->clearedToLand = false;
@@ -770,9 +1113,12 @@ void FGTower::CheckCircuitList(double dt) {
                        if(t->isUser) {
                                t->opType = TTT_UNKNOWN;
                        }       // TODO - allow the user to specify opType via ATC menu
+                       //cout << ident << " Removing " << t->plane.callsign << " from circuitList..." << endl;
                        circuitListItr = circuitList.erase(circuitListItr);
                        if(circuitListItr == circuitList.end() ) {
                                circuitListItr = circuitList.begin();
+                               // avoid increment of circuitListItr (would increment to second element, or crash if no element left)
+                               return;
                        }
                }
                ++circuitListItr;
@@ -801,24 +1147,37 @@ void FGTower::CheckRunwayList(double dt) {
                        }
                        bool on_rwy = OnActiveRunway(t->pos);
                        if(!on_rwy) {
+                               // TODO - for all of these we need to check what the user is *actually* doing!
                                if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
-                                       rwyList.pop_front();
-                                       delete t;
-                                       // TODO - tell it to taxi / contact ground / don't delete it etc!
+                                       //cout << "Tower " << ident << " is removing plane " << t->plane.callsign << " from rwy list (vacated)\n";
+                                       //cout << "Size of rwylist was " << rwyList.size() << '\n';
+                                       //cout << "Size of vacatedList was " << vacatedList.size() << '\n';
+                                       RemoveFromRwyList(t->plane.callsign);
+                                       AddToVacatedList(t);
+                                       //cout << "Size of rwylist is " << rwyList.size() << '\n';
+                                       //cout << "Size of vacatedList is " << vacatedList.size() << '\n';
+                                       // At the moment we wait until Runway Vacated is reported by the plane before telling to contact ground etc.
+                                       // It's possible we could be a bit more proactive about this.
                                } else if(t->opType == OUTBOUND) {
                                        depList.push_back(t);
+                                       depListItr = depList.begin();
                                        rwyList.pop_front();
                                        departed = true;
                                        timeSinceLastDeparture = 0.0;
                                } else if(t->opType == CIRCUIT) {
+                                       //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
                                        circuitList.push_back(t);
+                                       circuitListItr = circuitList.begin();
                                        AddToTrafficList(t);
                                        rwyList.pop_front();
                                        departed = true;
                                        timeSinceLastDeparture = 0.0;
                                } else if(t->opType == TTT_UNKNOWN) {
                                        depList.push_back(t);
+                                       depListItr = depList.begin();
+                                       //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
                                        circuitList.push_back(t);
+                                       circuitListItr = circuitList.begin();
                                        AddToTrafficList(t);
                                        rwyList.pop_front();
                                        departed = true;
@@ -834,25 +1193,164 @@ void FGTower::CheckRunwayList(double dt) {
 
 // Do one plane from the approach list
 void FGTower::CheckApproachList(double dt) {
-       if(appList.size()) {
+       //cout << "CheckApproachList called for " << ident << endl;
+       //cout << "AppList.size is " << appList.size() << endl;
+       if(!appList.empty()) {
                if(appListItr == appList.end()) {
                        appListItr = appList.begin();
                }
                TowerPlaneRec* t = *appListItr;
                //cout << "t = " << t << endl;
+               //cout << "Checking " << t->plane.callsign << endl;
                if(t->isUser) {
                        t->pos.setlon(user_lon_node->getDoubleValue());
                        t->pos.setlat(user_lat_node->getDoubleValue());
                        t->pos.setelev(user_elev_node->getDoubleValue());
                } else {
                        // TODO - set/update the position if it's an AI plane
-               }                               
-               if(t->nextOnRwy && !(t->clearedToLand)) {
-                       // check distance away and whether runway occupied
-                       // and schedule transmission if necessary
-               }                               
+               }
+               doThresholdETACalc();   // We need this here because planes in the lists are not guaranteed to *always* have the correct ETA
+               //cout << "eta is " << t->eta << ", rwy is " << (rwyList.size() ? "occupied " : "clear ") << '\n';
+               if(t->eta < 12 && rwyList.size() && !(t->instructedToGoAround)) {
+                       // TODO - need to make this more sophisticated 
+                       // eg. is the plane accelerating down the runway taking off [OK],
+                       // or stationary near the start [V. BAD!!].
+                       // For now this should stop the AI plane landing on top of the user.
+                       string trns = t->plane.callsign;
+                       trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
+                       pending_transmission = trns;
+                       ImmediateTransmit();
+                       t->instructedToGoAround = true;
+                       t->clearedToLand = false;
+                       t->nextOnRwy = false;   // But note this is recalculated so don't rely on it
+                       // Assume it complies!!!
+                       t->opType = CIRCUIT;
+                       t->leg = CLIMBOUT;
+                       if(!t->isUser) {
+                               if(t->planePtr) {
+                                       //cout << "Registering Go-around transmission with AI plane\n";
+                                       t->planePtr->RegisterTransmission(13);
+                               }
+                       } else {
+                               // TODO - add Go-around ack to comm options,
+                               // remove report rwy vacated. (possibly).
+                       }
+               } else if(t->eta < 90 && !t->clearedToLand) {
+                       //doThresholdETACalc();
+                       doThresholdUseOrder();
+                       // The whip through the appList is a hack since currently t->nextOnRwy doesn't always work
+                       // TODO - fix this!
+                       bool cf = false;
+                       for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
+                               if((*twrItr)->eta < t->eta) {
+                                       cf = true;
+                               }
+                       }
+                       if(t->nextOnRwy && !cf) {
+                               if(!rwyList.size()) {
+                                       string trns = t->plane.callsign;
+                                       trns += " Cleared to land";
+                                       pending_transmission = trns;
+                                       Transmit();
+                                       //if(t->isUser) cout << "Transmitting cleared to Land!!!\n";
+                                       t->clearedToLand = true;
+                                       if(!t->isUser) {
+                                               t->planePtr->RegisterTransmission(7);
+                                       }
+                               }
+                       } else {
+                               //if(t->isUser) cout << "Not next\n";
+                       }
+               }
+               
+               // Check for landing...
+               bool landed = false;
+               if(!t->isUser) {
+                       if(t->planePtr) {
+                               if(t->planePtr->GetLeg() == LANDING_ROLL) {
+                                       landed = true;
+                               }
+                       } else {
+                               SG_LOG(SG_ATC, SG_ALERT, "WARNING - not user and null planePtr in CheckApproachList!");
+                       }
+               } else {        // user
+                       if(OnActiveRunway(t->pos)) {
+                               landed = true;
+                       }
+               }
+               
+               if(landed) {
+                       // Duplicated in CheckCircuitList - must be able to rationalise this somehow!
+                       //cout << "A " << t->plane.callsign << " has landed, adding to rwyList...\n";
+                       rwyList.push_front(t);
+                       // TODO - if(!clearedToLand) shout something!!
+                       t->clearedToLand = false;
+                       RemoveFromTrafficList(t->plane.callsign);
+                       //if(t->isUser) {
+                               //      t->opType = TTT_UNKNOWN;
+                       //}     // TODO - allow the user to specify opType via ATC menu
+                       appListItr = appList.erase(appListItr);
+                       if(appListItr == appList.end() ) {
+                               appListItr = appList.begin();
+                       }
+                       if (appList.empty())
+                         return;
+
+               }
+               
                ++appListItr;
        }
+       //cout << "Done" << endl;
+}
+
+// Do one plane from the departure list
+void FGTower::CheckDepartureList(double dt) {
+       if(!depList.empty()) {
+               if(depListItr == depList.end()) {
+                       depListItr = depList.begin();
+               }
+               TowerPlaneRec* t = *depListItr;
+               //cout << "Dep list, checking " << t->plane.callsign;
+               
+               double distout; // meters
+               if(t->isUser) distout = dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
+               else distout = dclGetHorizontalSeparation(Point3D(lon, lat, elev), t->planePtr->GetPos());
+               //cout << " distout = " << distout << '\n';
+               if(distout > 10000) {
+                       string trns = t->plane.callsign;
+                       trns += " You are now clear of my airspace, good day";
+                       pending_transmission = trns;
+                       Transmit();
+                       if(t->isUser) {
+                               // Change the communication options
+                               RemoveAllUserDialogOptions();
+                               //cout << "ADD A\n";
+                               current_atcdialog->add_entry(ident, "@AP Tower @CS @MI miles @CD of the airport for full stop with ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
+                       } else {
+                               // Send a clear-of-airspace signal
+                               // TODO - implement this once we actually have departing AI traffic (currently all circuits or arrivals).
+                       }
+                       RemovePlane(t->plane.callsign);
+               } else {
+                       ++depListItr;
+               }
+       }
+}
+
+// ********** End periodic check functions ***********************************************
+// ***************************************************************************************
+
+
+// Remove all dialog options for this tower.
+void FGTower::RemoveAllUserDialogOptions() {
+       current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_DEPARTURE, TOWER);
+       current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
+       current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
+       current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
+       current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
+       current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
+       current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
+       current_atcdialog->remove_entry(ident, USER_REPORT_GOING_AROUND, TOWER);        
 }
 
 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
@@ -867,7 +1365,7 @@ bool FGTower::GetCrosswindConstraint(double& cpos) {
        }
 }
 bool FGTower::GetDownwindConstraint(double& dpos) {
-       if(downwind_leg_pos != 0.0) {
+       if(fabs(downwind_leg_pos) > nominal_downwind_leg_pos) {
                dpos = downwind_leg_pos;
                return(true);
        } else {
@@ -876,11 +1374,11 @@ bool FGTower::GetDownwindConstraint(double& dpos) {
        }
 }
 bool FGTower::GetBaseConstraint(double& bpos) {
-       if(base_leg_pos != 0.0) {
+       if(base_leg_pos < nominal_base_leg_pos) {
                bpos = base_leg_pos;
                return(true);
        } else {
-               bpos = 0.0;
+               bpos = nominal_base_leg_pos;
                return(false);
        }
 }
@@ -903,26 +1401,27 @@ void FGTower::DoRwyDetails() {
        FGRunway runway;
        bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
        if(rwyGood) {
-               activeRwy = runway.rwy_no;
-               rwy.rwyID = runway.rwy_no;
+               //cout << "RUNWAY GOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOD\n";
+               activeRwy = runway._rwy_no;
+               rwy.rwyID = runway._rwy_no;
                SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
                
                // Get the threshold position
-               double other_way = runway.heading - 180.0;
+               double other_way = runway._heading - 180.0;
                while(other_way <= 0.0) {
                        other_way += 360.0;
                }
        // move to the +l end/center of the runway
-               //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
-       Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
+               //cout << "Runway center is at " << runway._lon << ", " << runway._lat << '\n';
+       Point3D origin = Point3D(runway._lon, runway._lat, aptElev);
                Point3D ref = origin;
        double tshlon, tshlat, tshr;
                double tolon, tolat, tor;
-               rwy.length = runway.length * SG_FEET_TO_METER;
-               rwy.width = runway.width * SG_FEET_TO_METER;
+               rwy.length = runway._length * SG_FEET_TO_METER;
+               rwy.width = runway._width * SG_FEET_TO_METER;
        geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
                                rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
-       geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading, 
+       geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway._heading, 
                                rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
                // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
                // now copy what we need out of runway into rwy
@@ -930,11 +1429,20 @@ void FGTower::DoRwyDetails() {
                Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
                //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
                //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
-               rwy.hdg = runway.heading;
+               rwy.hdg = runway._heading;
                // Set the projection for the local area based on this active runway
                ortho.Init(rwy.threshold_pos, rwy.hdg); 
                rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
                rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
+               
+               // Set the pattern direction
+               // TODO - we'll check for a facilities file with this in eventually - for now assume left traffic except
+               // for certain circumstances (RH parallel rwy).
+               rwy.patternDirection = -1;              // Left
+               if(rwy.rwyID.size() == 3) {
+                       rwy.patternDirection = (rwy.rwyID.substr(2,1) == "R" ? 1 : -1);
+               }
+               //cout << "Doing details, rwy.patterDirection is " << rwy.patternDirection << '\n';
        } else {
                SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
                activeRwy = "NN";
@@ -944,7 +1452,7 @@ void FGTower::DoRwyDetails() {
 
 // Figure out if a given position lies on the active runway
 // Might have to change when we consider more than one active rwy.
-bool FGTower::OnActiveRunway(Point3D pt) {
+bool FGTower::OnActiveRunway(const Point3D& pt) {
        // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
        Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
        Point3D xyp = ortho.ConvertToLocal(pt);
@@ -963,7 +1471,7 @@ bool FGTower::OnActiveRunway(Point3D pt) {
 
 // Figure out if a given position lies on any runway or not
 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
-bool FGTower::OnAnyRunway(Point3D pt) {
+bool FGTower::OnAnyRunway(const Point3D& pt) {
        ATCData ad;
        double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
        if(dist < 0.0) {
@@ -980,9 +1488,9 @@ bool FGTower::OnAnyRunway(Point3D pt) {
                SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
        }
        bool on = false;
-       while(runway.id == ad.ident) {          
+       while(runway._id == ad.ident) {         
                on = OnRunway(pt, runway);
-               //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
+               //cout << "Runway " << runway._rwy_no << ": On = " << (on ? "true\n" : "false\n");
                if(on) return(true);
                globals->get_runways()->next(&runway);          
        }
@@ -991,12 +1499,13 @@ bool FGTower::OnAnyRunway(Point3D pt) {
 
 
 // Returns true if successful
-bool FGTower::RemoveFromTrafficList(string id) {
+bool FGTower::RemoveFromTrafficList(const string& id) {
        tower_plane_rec_list_iterator twrItr;
        for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
                TowerPlaneRec* tpr = *twrItr;
                if(tpr->plane.callsign == id) {
                        trafficList.erase(twrItr);
+                       trafficListItr = trafficList.begin();
                        return(true);
                }
        }       
@@ -1005,6 +1514,37 @@ bool FGTower::RemoveFromTrafficList(string id) {
 }
 
 
+// Returns true if successful
+bool FGTower::RemoveFromAppList(const string& id) {
+       tower_plane_rec_list_iterator twrItr;
+       for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
+               TowerPlaneRec* tpr = *twrItr;
+               if(tpr->plane.callsign == id) {
+                       appList.erase(twrItr);
+                       appListItr = appList.begin();
+                       return(true);
+               }
+       }       
+       //SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from appList in FGTower");
+       return(false);
+}
+
+// Returns true if successful
+bool FGTower::RemoveFromRwyList(const string& id) {
+       tower_plane_rec_list_iterator twrItr;
+       for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
+               TowerPlaneRec* tpr = *twrItr;
+               if(tpr->plane.callsign == id) {
+                       rwyList.erase(twrItr);
+                       rwyListItr = rwyList.begin();
+                       return(true);
+               }
+       }       
+       //SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from rwyList in FGTower");
+       return(false);
+}
+
+
 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
 // and set nextOnRwy if so.
 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
@@ -1074,6 +1614,8 @@ bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
        if(!trafficList.size()) {
                t->nextOnRwy = true;
                // conflict and firstTime should be false and true respectively in this case anyway.
+       } else {
+               t->nextOnRwy = false;
        }
        trafficList.push_back(t);
        //cout << "\tE\t" << trafficList.size() << endl;
@@ -1082,35 +1624,72 @@ bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
 
 // Add a tower plane rec with ETA to the circuit list in the correct position ETA-wise
 // Returns true if this might cause a separation conflict (based on ETA) with other traffic, false otherwise.
+// Safe to add a plane that is already in - planes with the same callsign are not added.
 bool FGTower::AddToCircuitList(TowerPlaneRec* t) {
+       if(!t) {
+               //cout << "**********************************************\n";
+               //cout << "AddToCircuitList called with NULL pointer!!!!!\n";
+               //cout << "**********************************************\n";
+               return false;
+       }
        //cout << "ADD: " << circuitList.size();
-       //cout << "AddToCircuitList called, currently size = " << circuitList.size() << endl;
+       //cout << ident << " AddToCircuitList called for " << t->plane.callsign << ", currently size = " << circuitList.size() << endl;
        double separation_time = 60.0;  // seconds - this is currently a guess for light plane separation, and includes a few seconds for a holding plane to taxi onto the rwy.
        bool conflict = false;
        tower_plane_rec_list_iterator twrItr;
+       // First check if the plane is already in the list
+       //cout << "A" << endl;
+       //cout << "Checking whether " << t->plane.callsign << " is already in circuit list..." << endl;
+       //cout << "B" << endl;
        for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
-                       TowerPlaneRec* tpr = *twrItr;
-                               
-                               if(t->eta < tpr->eta) {
-                                       // Ugg - this one's tricky.
-                                       // It depends on what the two planes are doing and whether there's a conflict what we do.
-                                       if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
-                                               circuitList.insert(twrItr, t);
-                                       } else {        // Ooops - this ones tricky - we have a potential conflict!
-                                               conflict = true;
-                                               // HACK - just add anyway for now and flag conflict.
-                                               circuitList.insert(twrItr, t);
-                                       }
-                                       //cout << "\tC\t" << circuitList.size() << '\n';
-                                       return(conflict);
-                               }
+               if((*twrItr)->plane.callsign == t->plane.callsign) {
+                       //cout << "In list - returning...\n";
+                       return false;
+               }
+       }
+       //cout << "Not in list - adding..." << endl;
+       
+       for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
+               TowerPlaneRec* tpr = *twrItr;
+               //cout << tpr->plane.callsign << " eta is " << tpr->eta << '\n';
+               //cout << "New eta is " << t->eta << '\n';              
+               if(t->eta < tpr->eta) {
+                       // Ugg - this one's tricky.
+                       // It depends on what the two planes are doing and whether there's a conflict what we do.
+                       if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
+                               circuitList.insert(twrItr, t);
+                               circuitListItr = circuitList.begin();
+                       } else {        // Ooops - this ones tricky - we have a potential conflict!
+                               conflict = true;
+                               // HACK - just add anyway for now and flag conflict.
+                               circuitList.insert(twrItr, t);
+                               circuitListItr = circuitList.begin();
+                       }
+                       //cout << "\tC\t" << circuitList.size() << '\n';
+                       return(conflict);
+               }
        }
        // If we get here we must be at the end of the list, or maybe the list is empty.
+       //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
        circuitList.push_back(t);       // TODO - check the separation with the preceding plane for the conflict flag.
+       circuitListItr = circuitList.begin();
        //cout << "\tE\t" << circuitList.size() << endl;
        return(conflict);
 }
 
+// Add to vacated list only if not already present
+void FGTower::AddToVacatedList(TowerPlaneRec* t) {
+       tower_plane_rec_list_iterator twrItr;
+       bool found = false;
+       for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
+               if((*twrItr)->plane.callsign == t->plane.callsign) {
+                       found = true;
+               }
+       }
+       if(found) return;
+       vacatedList.push_back(t);
+}
+
 
 // Calculate the eta of a plane to the threshold.
 // For ground traffic this is the fastest they can get there.
@@ -1133,14 +1712,15 @@ void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
        
        Point3D op = ortho.ConvertToLocal(tpr->pos);
        //if(printout) {
-       //      cout << "Orthopos is " << op.x() << ", " << op.y() << '\n';
-       //      cout << "opType is " << tpr->opType << '\n';
+       //if(!tpr->isUser) cout << "Orthopos is " << op.x() << ", " << op.y() << ' ';
+       //cout << "opType is " << tpr->opType << '\n';
        //}
        double dist_out_m = op.y();
-       double dist_across_m = fabs(op.x());    // FIXME = the fabs is a hack to cope with the fact that we don't know the circuit direction yet
+       double dist_across_m = fabs(op.x());    // The fabs is a hack to cope with the fact that we don't know the circuit direction yet
        //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
        
-       if(tpr->opType == STRAIGHT_IN) {
+       if(tpr->opType == STRAIGHT_IN || tpr->opType == INBOUND) {
+               //cout << "CASE 1\n";
                double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
                if(dist_to_go_m < 1000) {
                        tpr->eta = dist_to_go_m / final_ias;
@@ -1148,13 +1728,15 @@ void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
                        tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
                }
        } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) {       // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
+               //cout << "CASE 2\n";
                // It's complicated - depends on if base leg is delayed or not
                //if(printout) {
-               //      cout << "Leg = " << tpr->leg << '\n';
+               //cout << "Leg = " << tpr->leg << '\n';
                //}
                if(tpr->leg == LANDING_ROLL) {
                        tpr->eta = 0;
                } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
+                       //cout << "dist_out_m = " << dist_out_m << '\n';
                        tpr->eta = fabs(dist_out_m) / final_ias;
                } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
                        tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
@@ -1167,38 +1749,50 @@ void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
                        if(!GetBaseConstraint(current_base_dist_out_m)) {
                                current_base_dist_out_m = nominal_base_dist_out_m;
                        }
+                       //cout << "current_base_dist_out_m = " << current_base_dist_out_m << '\n';
                        double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
                        double current_dist_across_m;
                        if(!GetDownwindConstraint(current_dist_across_m)) {
                                current_dist_across_m = nominal_dist_across_m;
                        }
-                       double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
+                       double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 700ft agl.
                        tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
-                       //if(printout) cout << "a = " << tpr->eta << '\n';
+                       //cout << "a = " << tpr->eta << '\n';
                        if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
                                tpr->eta += dist_across_m / circuit_ias;
-                               //if(printout) cout << "b = " << tpr->eta << '\n';
+                               //cout << "b = " << tpr->eta << '\n';
                                tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
-                               //if(printout) cout << "c = " << tpr->eta << '\n';
+                               //cout << "c = " << tpr->eta << '\n';
                        } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
+                               //cout << "CROSSWIND calc: ";
+                               //cout << tpr->eta << ' ';
                                if(dist_across_m > nominal_dist_across_m) {
                                        tpr->eta += dist_across_m / circuit_ias;
+                                       //cout << "a ";
                                } else {
                                        tpr->eta += nominal_dist_across_m / circuit_ias;
+                                       //cout << "b ";
                                }
+                               //cout << tpr->eta << ' ';
                                // should we use the dist across of the previous plane if there is previous still on downwind?
                                //if(printout) cout << "bb = " << tpr->eta << '\n';
                                if(dist_out_m > nominal_cross_dist_out_m) {
                                        tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
+                                       //cout << "c ";
                                } else {
                                        tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
+                                       //cout << "d ";
                                }
+                               //cout << tpr->eta << ' ';
                                //if(printout) cout << "cc = " << tpr->eta << '\n';
                                if(nominal_dist_across_m > dist_across_m) {
                                        tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
+                                       //cout << "e ";
                                } else {
                                        // Nothing to add
+                                       //cout << "f ";
                                }
+                               //cout << tpr->eta << '\n';
                                //if(printout) cout << "dd = " << tpr->eta << '\n';
                        } else {
                                // We've only just started - why not use a generic estimate?
@@ -1208,6 +1802,7 @@ void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
                //if(printout) {
                //      cout << "ETA = " << tpr->eta << '\n';
                //}
+               //if(!tpr->isUser) cout << tpr->plane.callsign << '\t' << tpr->eta << '\n';
        } else {
                tpr->eta = 99999;
        }       
@@ -1228,18 +1823,23 @@ double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
 }
 
 
-// Iterate through all the lists and call CalcETA for all the planes.
+// Iterate through all the lists, update the position of, and call CalcETA for all the planes.
 void FGTower::doThresholdETACalc() {
        //cout << "Entering doThresholdETACalc..." << endl;
        tower_plane_rec_list_iterator twrItr;
        // Do the approach list first
        for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
                TowerPlaneRec* tpr = *twrItr;
+               if(!(tpr->isUser)) tpr->pos = tpr->planePtr->GetPos();
+               //cout << "APP: ";
                CalcETA(tpr);
        }       
        // Then the circuit list
+       //cout << "Circuit list size is " << circuitList.size() << '\n';
        for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
                TowerPlaneRec* tpr = *twrItr;
+               if(!(tpr->isUser)) tpr->pos = tpr->planePtr->GetPos();
+               //cout << "CIRC: ";
                CalcETA(tpr);
        }
        //cout << "Done doThresholdETCCalc" << endl;
@@ -1267,15 +1867,17 @@ bool FGTower::doThresholdUseOrder() {
        
        tower_plane_rec_list_iterator twrItr;
        // Do the approach list first
-       //cout << "A" << flush;
+       //if(ident == "KRHV") cout << "A" << flush;
        for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
                TowerPlaneRec* tpr = *twrItr;
+               //if(ident == "KRHV") cout << tpr->plane.callsign << '\n';
                conflict = AddToTrafficList(tpr);
        }       
        // Then the circuit list
-       //cout << "C" << flush;
+       //if(ident == "KRHV") cout << "C" << flush;
        for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
                TowerPlaneRec* tpr = *twrItr;
+               //if(ident == "KRHV") cout << tpr->plane.callsign << '\n';
                conflict = AddToTrafficList(tpr);
        }
        // And finally the hold list
@@ -1285,8 +1887,10 @@ bool FGTower::doThresholdUseOrder() {
                AddToTrafficList(tpr, true);
        }
        
+       
        if(0) {
-       //if(ident == "KEMT") {
+       //if(ident == "KRHV") {
+               cout << "T\n";
                for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
                        TowerPlaneRec* tpr = *twrItr;
                        cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
@@ -1316,7 +1920,7 @@ double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
 }
        
 
-void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
+void FGTower::ContactAtHoldShort(const PlaneRec& plane, FGAIPlane* requestee, tower_traffic_type operation) {
        // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
        TowerPlaneRec* t = new TowerPlaneRec;
        t->plane = plane;
@@ -1350,7 +1954,7 @@ void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_tra
 
 // Register the presence of an AI plane at a point where contact would already have been made in real life
 // CAUTION - currently it is assumed that this plane's callsign is unique - it is up to AIMgr to generate unique callsigns.
-void FGTower::RegisterAIPlane(PlaneRec plane, FGAIPlane* ai, tower_traffic_type op, PatternLeg lg) {
+void FGTower::RegisterAIPlane(const PlaneRec& plane, FGAIPlane* ai, const tower_traffic_type& op, const PatternLeg& lg) {
        // At the moment this is only going to be tested with inserting an AI plane on downwind
        TowerPlaneRec* t = new TowerPlaneRec;
        t->plane = plane;
@@ -1370,90 +1974,473 @@ void FGTower::RegisterAIPlane(PlaneRec plane, FGAIPlane* ai, tower_traffic_type
        doThresholdUseOrder();
 }
 
-void FGTower::RequestLandingClearance(string ID) {
-       //cout << "Request Landing Clearance called...\n";
-       
-       // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
-       // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
+void FGTower::DeregisterAIPlane(const string& id) {
+       RemovePlane(id);
+}
+
+// Contact tower for VFR approach
+// eg "Cessna Charlie Foxtrot Golf Foxtrot Sierra eight miles South of the airport for full stop with Bravo"
+// This function probably only called via user interaction - AI planes will have an overloaded function taking a planerec.
+// opt defaults to AIP_LT_UNKNOWN
+void FGTower::VFRArrivalContact(const string& ID, const LandingType& opt) {
+       //cout << "USER Request Landing Clearance called for ID " << ID << '\n';
        
-       TowerPlaneRec* t = new TowerPlaneRec;
-       t->isUser = true;
-       t->clearedToLand = false;
-       t->pos.setlon(user_lon_node->getDoubleValue());
-       t->pos.setlat(user_lat_node->getDoubleValue());
-       t->pos.setelev(user_elev_node->getDoubleValue());
+       // For now we'll assume that the user is a light plane and can get him/her to join the circuit if necessary.
+
+       TowerPlaneRec* t;       
+       string usercall = fgGetString("/sim/user/callsign");
+       if(ID == "USER" || ID == usercall) {
+               t = FindPlane(usercall);
+               if(!t) {
+                       //cout << "NOT t\n";
+                       t = new TowerPlaneRec;
+                       t->isUser = true;
+                       t->pos.setlon(user_lon_node->getDoubleValue());
+                       t->pos.setlat(user_lat_node->getDoubleValue());
+                       t->pos.setelev(user_elev_node->getDoubleValue());
+               } else {
+                       //cout << "IS t\n";
+                       // Oops - the plane is already registered with this tower - maybe we took off and flew a giant circuit without
+                       // quite getting out of tower airspace - just ignore for now and treat as new arrival.
+                       // TODO - Maybe should remove from departure and circuit list if in there though!!
+               }
+       } else {
+               // Oops - something has gone wrong - put out a warning
+               cout << "WARNING - FGTower::VFRContact(string ID, LandingType lt) called with ID " << ID << " which does not appear to be the user.\n";
+               return;
+       }
+               
        
        // TODO
-       // Calculate where the user is in relation to the active runway and it's circuit
+       // Calculate where the plane is in relation to the active runway and it's circuit
        // and set the op-type as appropriate.
        
        // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
        t->opType = STRAIGHT_IN;
        
        t->plane.type = GA_SINGLE;      // FIXME - Another assumption!
-       t->plane.callsign = ID;
+       t->plane.callsign = usercall;
+       
+       t->vfrArrivalReported = true;
+       responseReqd = true;
+       
+       appList.push_back(t);   // Not necessarily permanent
+       appListItr = appList.begin();
+       AddToTrafficList(t);
+       
+       current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
+       current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
+       current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
+}
+
+// landingType defaults to AIP_LT_UNKNOWN
+void FGTower::VFRArrivalContact(const PlaneRec& plane, FGAIPlane* requestee, const LandingType& lt) {
+       //cout << "VFRArrivalContact called for plane " << plane.callsign << " at " << ident << '\n';
+       // Possible hack - assume this plane is new for now - TODO - should check really
+       TowerPlaneRec* t = new TowerPlaneRec;
+       t->plane = plane;
+       t->planePtr = requestee;
+       t->landingType = lt;
+       t->pos = requestee->GetPos();
+       
+       //cout << "Hold Short reported by " << plane.callsign << '\n';
+       SG_LOG(SG_ATC, SG_BULK, "VFR arrival contact made by " << plane.callsign);
+       //cout << "VFR arrival contact made by " << plane.callsign << '\n';
+
+       // HACK - to get up and running I'm going to assume a staight-in final for now.
+       t->opType = STRAIGHT_IN;
+       
+       t->vfrArrivalReported = true;
+       responseReqd = true;
        
+       //cout << "Before adding, appList.size = " << appList.size() << " at " << ident << '\n';
        appList.push_back(t);   // Not necessarily permanent
+       appListItr = appList.begin();
+       //cout << "After adding, appList.size = " << appList.size() << " at " << ident << '\n';
        AddToTrafficList(t);
 }
 
-void FGTower::RequestDepartureClearance(string ID) {
+void FGTower::RequestDepartureClearance(const string& ID) {
        //cout << "Request Departure Clearance called...\n";
 }
        
-void FGTower::ReportFinal(string ID) {
-       TowerPlaneRec* t = FindPlane(ID);
+void FGTower::ReportFinal(const string& ID) {
+       //cout << "Report Final Called at tower " << ident << " by plane " << ID << '\n';
+       string uid=ID;
+       if(ID == "USER") {
+               uid = fgGetString("/sim/user/callsign");
+               current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
+       }
+       TowerPlaneRec* t = FindPlane(uid);
        if(t) {
                t->finalReported = true;
                t->finalAcknowledged = false;
                if(!(t->clearedToLand)) {
                        responseReqd = true;
-               } // possibly respond with wind even if already cleared to land?
+               } else {
+                       // possibly respond with wind even if already cleared to land?
+                       t->finalReported = false;
+                       t->finalAcknowledged = true;
+                       // HACK!! - prevents next reporting being misinterpreted as this one.
+               }
        } else {
                SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportFinal(...)");
        }
 }
 
-//void FGTower::ReportLongFinal(string ID);
+void FGTower::ReportLongFinal(const string& ID) {
+       string uid=ID;
+       if(ID == "USER") {
+               uid = fgGetString("/sim/user/callsign");
+               current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
+       }
+       TowerPlaneRec* t = FindPlane(uid);
+       if(t) {
+               t->longFinalReported = true;
+               t->longFinalAcknowledged = false;
+               if(!(t->clearedToLand)) {
+                       responseReqd = true;
+               } // possibly respond with wind even if already cleared to land?
+       } else {
+               SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportLongFinal(...)");
+       }
+}
+
 //void FGTower::ReportOuterMarker(string ID);
 //void FGTower::ReportMiddleMarker(string ID);
 //void FGTower::ReportInnerMarker(string ID);
-//void FGTower::ReportGoingAround(string ID);
 
-void FGTower::ReportRunwayVacated(string ID) {
-       //cout << "Report Runway Vacated Called...\n";
+void FGTower::ReportRunwayVacated(const string& ID) {
+       //cout << "Report Runway Vacated Called at tower " << ident << " by plane " << ID << '\n';
+       string uid=ID;
+       if(ID == "USER") {
+               uid = fgGetString("/sim/user/callsign");
+               current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
+       }
+       TowerPlaneRec* t = FindPlane(uid);
+       if(t) {
+               //cout << "Found it...\n";
+               t->rwyVacatedReported = true;
+               responseReqd = true;
+       } else {
+               SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
+               SG_LOG(SG_ATC, SG_ALERT, "A WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
+               //cout << "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)\n";
+       }
 }
 
-TowerPlaneRec* FGTower::FindPlane(string ID) {
+TowerPlaneRec* FGTower::FindPlane(const string& ID) {
+       //cout << "FindPlane called for " << ID << "...\n";
        tower_plane_rec_list_iterator twrItr;
        // Do the approach list first
        for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
+               //cout << "appList callsign is " << (*twrItr)->plane.callsign << '\n';
                if((*twrItr)->plane.callsign == ID) return(*twrItr);
        }       
        // Then the circuit list
        for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
+               //cout << "circuitList callsign is " << (*twrItr)->plane.callsign << '\n';
                if((*twrItr)->plane.callsign == ID) return(*twrItr);
        }
-       // And finally the hold list
+       // Then the runway list
+       //cout << "rwyList.size() is " << rwyList.size() << '\n';
+       for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
+               //cout << "rwyList callsign is " << (*twrItr)->plane.callsign << '\n';
+               if((*twrItr)->plane.callsign == ID) return(*twrItr);
+       }
+       // The hold list
        for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
                if((*twrItr)->plane.callsign == ID) return(*twrItr);
        }
+       // And finally the vacated list
+       for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
+               //cout << "vacatedList callsign is " << (*twrItr)->plane.callsign << '\n';
+               if((*twrItr)->plane.callsign == ID) return(*twrItr);
+       }
        SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
+       //exit(-1);
        return(NULL);
 }
 
-void FGTower::ReportDownwind(string ID) {
+void FGTower::RemovePlane(const string& ID) {
+       //cout << ident << " RemovePlane called for " << ID << '\n';
+       // We have to be careful here - we want to erase the plane from all lists it is in,
+       // but we can only delete it once, AT THE END.
+       TowerPlaneRec* t = NULL;
+       tower_plane_rec_list_iterator twrItr;
+       for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
+               if((*twrItr)->plane.callsign == ID) {
+                       t = *twrItr;
+                       twrItr = appList.erase(twrItr);
+                       appListItr = appList.begin();
+                       break;
+               }
+       }
+       for(twrItr = depList.begin(); twrItr != depList.end(); twrItr++) {
+               if((*twrItr)->plane.callsign == ID) {
+                       t = *twrItr;
+                       twrItr = depList.erase(twrItr);
+                       depListItr = depList.begin();
+                       break;
+               }
+       }
+       for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
+               if((*twrItr)->plane.callsign == ID) {
+                       t = *twrItr;
+                       twrItr = circuitList.erase(twrItr);
+                       circuitListItr = circuitList.begin();
+                       break;
+               }
+       }
+       for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
+               if((*twrItr)->plane.callsign == ID) {
+                       t = *twrItr;
+                       twrItr = holdList.erase(twrItr);
+                       holdListItr = holdList.begin();
+                       break;
+               }
+       }
+       for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
+               if((*twrItr)->plane.callsign == ID) {
+                       t = *twrItr;
+                       twrItr = rwyList.erase(twrItr);
+                       rwyListItr = rwyList.begin();
+                       break;
+               }
+       }
+       for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
+               if((*twrItr)->plane.callsign == ID) {
+                       t = *twrItr;
+                       twrItr = vacatedList.erase(twrItr);
+                       vacatedListItr = vacatedList.begin();
+                       break;
+               }
+       }
+       for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
+               if((*twrItr)->plane.callsign == ID) {
+                       t = *twrItr;
+                       twrItr = trafficList.erase(twrItr);
+                       trafficListItr = trafficList.begin();
+                       break;
+               }
+       }
+       // And finally, delete the record.
+       delete t;
+}
+
+void FGTower::ReportDownwind(const string& ID) {
        //cout << "ReportDownwind(...) called\n";
-       // Tell the plane reporting what number she is in the circuit
-       TowerPlaneRec* t = FindPlane(ID);
+       string uid=ID;
+       if(ID == "USER") {
+               uid = fgGetString("/sim/user/callsign");
+               current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
+       }
+       TowerPlaneRec* t = FindPlane(uid);
        if(t) {
                t->downwindReported = true;
                responseReqd = true;
+               // If the plane is in the app list, remove it and put it in the circuit list instead.
+               // Ideally we might want to do this at the 2 mile report prior to 45 deg entry, but at
+               // the moment that would b&gg?r up the constraint position calculations.
+               RemoveFromAppList(ID);
+               t->leg = DOWNWIND;
+               if(t->isUser) {
+                       t->pos.setlon(user_lon_node->getDoubleValue());
+                       t->pos.setlat(user_lat_node->getDoubleValue());
+                       t->pos.setelev(user_elev_node->getDoubleValue());
+               } else {
+                       // ASSERT(t->planePtr != NULL);
+                       t->pos = t->planePtr->GetPos();
+               }
+               CalcETA(t);
+               AddToCircuitList(t);
+       } else {
+               SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
+       }
+}
+
+void FGTower::ReportGoingAround(const string& ID) {
+       string uid=ID;
+       if(ID == "USER") {
+               uid = fgGetString("/sim/user/callsign");
+               RemoveAllUserDialogOptions();   // TODO - it would be much more efficient if ATCDialog simply had a clear() function!!!
+               current_atcdialog->add_entry(ident, "@AP Tower @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
+       }
+       TowerPlaneRec* t = FindPlane(uid);
+       if(t) {
+               //t->goAroundReported = true;  // No need to set this until we start responding to it.
+               responseReqd = false;   // might change in the future but for now we'll not distract them during the go-around.
+               // If the plane is in the app list, remove it and put it in the circuit list instead.
+               RemoveFromAppList(ID);
+               t->leg = CLIMBOUT;
+               if(t->isUser) {
+                       t->pos.setlon(user_lon_node->getDoubleValue());
+                       t->pos.setlat(user_lat_node->getDoubleValue());
+                       t->pos.setelev(user_elev_node->getDoubleValue());
+               } else {
+                       // ASSERT(t->planePtr != NULL);
+                       t->pos = t->planePtr->GetPos();
+               }
+               CalcETA(t);
+               AddToCircuitList(t);
        } else {
                SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
        }
 }
 
+string FGTower::GenText(const string& m, int c) {
+       const int cmax = 300;
+       //string message;
+       char tag[4];
+       char crej = '@';
+       char mes[cmax];
+       char dum[cmax];
+       //char buf[10];
+       char *pos;
+       int len;
+       //FGTransmission t;
+       string usercall = fgGetString("/sim/user/callsign");
+       
+       //transmission_list_type     tmissions = transmissionlist_station[station];
+       //transmission_list_iterator current   = tmissions.begin();
+       //transmission_list_iterator last      = tmissions.end();
+       
+       //for ( ; current != last ; ++current ) {
+       //      if ( current->get_code().c1 == code.c1 &&  
+       //              current->get_code().c2 == code.c2 &&
+       //          current->get_code().c3 == code.c3 ) {
+                       
+                       //if ( ttext ) message = current->get_transtext();
+                       //else message = current->get_menutext();
+                       strcpy( &mes[0], m.c_str() ); 
+                       
+                       // Replace all the '@' parameters with the actual text.
+                       int check = 0;  // If mes gets overflowed the while loop can go infinite
+                       while ( strchr(&mes[0], crej) != NULL  ) {      // ie. loop until no more occurances of crej ('@') found
+                               pos = strchr( &mes[0], crej );
+                               memmove(&tag[0], pos, 3);
+                               tag[3] = '\0';
+                               int i;
+                               len = 0;
+                               for ( i=0; i<cmax; i++ ) {
+                                       if ( mes[i] == crej ) {
+                                               len = i; 
+                                               break;
+                                       }
+                               }
+                               strncpy( &dum[0], &mes[0], len );
+                               dum[len] = '\0';
+                               
+                               if ( strcmp ( tag, "@ST" ) == 0 )
+                                       //strcat( &dum[0], tpars.station.c_str() );
+                                       strcat(&dum[0], ident.c_str());
+                               else if ( strcmp ( tag, "@AP" ) == 0 )
+                                       //strcat( &dum[0], tpars.airport.c_str() );
+                                       strcat(&dum[0], name.c_str());
+                               else if ( strcmp ( tag, "@CS" ) == 0 ) 
+                                       //strcat( &dum[0], tpars.callsign.c_str() );
+                                       strcat(&dum[0], usercall.c_str());
+                               else if ( strcmp ( tag, "@TD" ) == 0 ) {
+                                       /*
+                                       if ( tpars.tdir == 1 ) {
+                                               char buf[] = "left";
+                                               strcat( &dum[0], &buf[0] );
+                                       }
+                                       else {
+                                               char buf[] = "right";
+                                               strcat( &dum[0], &buf[0] );
+                                       }
+                                       */
+                               }
+                               else if ( strcmp ( tag, "@HE" ) == 0 ) {
+                                       /*
+                                       char buf[10];
+                                       sprintf( buf, "%i", (int)(tpars.heading) );
+                                       strcat( &dum[0], &buf[0] );
+                                       */
+                               }
+                               else if ( strcmp ( tag, "@VD" ) == 0 ) {
+                                       /*
+                                       if ( tpars.VDir == 1 ) {
+                                               char buf[] = "Descend and maintain";
+                                               strcat( &dum[0], &buf[0] );
+                                       }
+                                       else if ( tpars.VDir == 2 ) {
+                                               char buf[] = "Maintain";
+                                               strcat( &dum[0], &buf[0] );
+                                       }
+                                       else if ( tpars.VDir == 3 ) {
+                                               char buf[] = "Climb and maintain";
+                                               strcat( &dum[0], &buf[0] );
+                                       } 
+                                       */
+                               }
+                               else if ( strcmp ( tag, "@AL" ) == 0 ) {
+                                       /*
+                                       char buf[10];
+                                       sprintf( buf, "%i", (int)(tpars.alt) );
+                                       strcat( &dum[0], &buf[0] );
+                                       */
+                               }
+                               else if ( strcmp ( tag, "@MI" ) == 0 ) {
+                                       char buf[10];
+                                       //sprintf( buf, "%3.1f", tpars.miles );
+                                       int dist_miles = (int)dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue())) / 1600;
+                                       sprintf(buf, "%i", dist_miles);
+                                       strcat( &dum[0], &buf[0] );
+                               }
+                               else if ( strcmp ( tag, "@FR" ) == 0 ) {
+                                       /*
+                                       char buf[10];
+                                       sprintf( buf, "%6.2f", tpars.freq );
+                                       strcat( &dum[0], &buf[0] );
+                                       */
+                               }
+                               else if ( strcmp ( tag, "@RW" ) == 0 ) {
+                                       strcat(&dum[0], ConvertRwyNumToSpokenString(activeRwy).c_str());
+                               } else if(strcmp(tag, "@CD") == 0) {    // @CD = compass direction
+                                       double h = GetHeadingFromTo(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
+                                       while(h < 0.0) h += 360.0;
+                                       while(h > 360.0) h -= 360.0;
+                                       if(h < 22.5 || h > 337.5) {
+                                               strcat(&dum[0], "North");
+                                       } else if(h < 67.5) {
+                                               strcat(&dum[0], "North-East");
+                                       } else if(h < 112.5) {
+                                               strcat(&dum[0], "East");
+                                       } else if(h < 157.5) {
+                                               strcat(&dum[0], "South-East");
+                                       } else if(h < 202.5) {
+                                               strcat(&dum[0], "South");
+                                       } else if(h < 247.5) {
+                                               strcat(&dum[0], "South-West");
+                                       } else if(h < 292.5) {
+                                               strcat(&dum[0], "West");
+                                       } else {
+                                               strcat(&dum[0], "North-West");
+                                       }
+                               } else {
+                                       cout << "Tag " << tag << " not found" << endl;
+                                       break;
+                               }
+                               strcat( &dum[0], &mes[len+3] );
+                               strcpy( &mes[0], &dum[0] );
+                               
+                               ++check;
+                               if(check > 10) {
+                                       SG_LOG(SG_ATC, SG_WARN, "WARNING: Possibly endless loop terminated in FGTransmissionlist::gen_text(...)"); 
+                                       break;
+                               }
+                       }
+                       
+                       //cout << mes  << endl;  
+                       //break;
+               //}
+       //}
+       if ( mes != "" ) return mes;
+       else return "No transmission found";
+}
+
 ostream& operator << (ostream& os, tower_traffic_type ttt) {
        switch(ttt) {
        case(CIRCUIT):      return(os << "CIRCUIT");