]> git.mxchange.org Git - flightgear.git/blob - src/ATC/tower.cxx
Slightly more robust handling of runway vacation
[flightgear.git] / src / ATC / tower.cxx
1 // FGTower - a class to provide tower control at towered airports.
2 //
3 // Written by David Luff, started March 2002.
4 //
5 // Copyright (C) 2002  David C. Luff - david.luff@nottingham.ac.uk
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #ifdef HAVE_STRINGS_H
26 #  include <strings.h>   // bcopy()
27 #else
28 #  include <string.h>    // MSVC doesn't have strings.h
29 #endif
30
31 #include <Main/globals.hxx>
32 #include <Airports/runways.hxx>
33 #include <simgear/math/sg_geodesy.hxx>
34 #include <simgear/debug/logstream.hxx>
35
36 #include "tower.hxx"
37 #include "ATCdisplay.hxx"
38 #include "ATCmgr.hxx"
39 #include "ATCutils.hxx"
40 #include "ATCDialog.hxx"
41 #include "commlist.hxx"
42 #include "AILocalTraffic.hxx"
43
44 SG_USING_STD(cout);
45
46 // TowerPlaneRec
47
48 TowerPlaneRec::TowerPlaneRec() :
49         planePtr(NULL),
50         clearedToLand(false),
51         clearedToLineUp(false),
52         clearedToTakeOff(false),
53         holdShortReported(false),
54         downwindReported(false),
55         longFinalReported(false),
56         longFinalAcknowledged(false),
57         finalReported(false),
58         finalAcknowledged(false),
59         rwyVacatedReported(false),
60         rwyVacatedAcknowledged(false),
61         goAroundReported(false),
62         instructedToGoAround(false),
63         onRwy(false),
64         nextOnRwy(false),
65         vfrArrivalReported(false),
66         vfrArrivalAcknowledged(false),
67         opType(TTT_UNKNOWN),
68         leg(LEG_UNKNOWN),
69         landingType(AIP_LT_UNKNOWN),
70         isUser(false)
71 {
72         plane.callsign = "UNKNOWN";
73 }
74
75 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
76         planePtr(NULL),
77         clearedToLand(false),
78         clearedToLineUp(false),
79         clearedToTakeOff(false),
80         holdShortReported(false),
81         downwindReported(false),
82         longFinalReported(false),
83         longFinalAcknowledged(false),
84         finalReported(false),
85         finalAcknowledged(false),
86         rwyVacatedReported(false),
87         rwyVacatedAcknowledged(false),
88         goAroundReported(false),
89         instructedToGoAround(false),
90         onRwy(false),
91         nextOnRwy(false),
92         vfrArrivalReported(false),
93         vfrArrivalAcknowledged(false),
94         opType(TTT_UNKNOWN),
95         leg(LEG_UNKNOWN),
96         landingType(AIP_LT_UNKNOWN),
97         isUser(false)
98 {
99         plane = p;
100 }
101
102 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
103         planePtr(NULL),
104         clearedToLand(false),
105         clearedToLineUp(false),
106         clearedToTakeOff(false),
107         holdShortReported(false),
108         downwindReported(false),
109         longFinalReported(false),
110         longFinalAcknowledged(false),
111         finalReported(false),
112         finalAcknowledged(false),
113         rwyVacatedReported(false),
114         rwyVacatedAcknowledged(false),
115         goAroundReported(false),
116         instructedToGoAround(false),
117         onRwy(false),
118         nextOnRwy(false),
119         vfrArrivalReported(false),
120         vfrArrivalAcknowledged(false),
121         opType(TTT_UNKNOWN),
122         leg(LEG_UNKNOWN),
123         landingType(AIP_LT_UNKNOWN),
124         isUser(false)
125 {
126         plane.callsign = "UNKNOWN";
127         pos = pt;
128 }
129
130 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
131         planePtr(NULL),
132         clearedToLand(false),
133         clearedToLineUp(false),
134         clearedToTakeOff(false),
135         holdShortReported(false),
136         downwindReported(false),
137         longFinalReported(false),
138         longFinalAcknowledged(false),
139         finalReported(false),
140         finalAcknowledged(false),
141         rwyVacatedReported(false),
142         rwyVacatedAcknowledged(false),
143         goAroundReported(false),
144         instructedToGoAround(false),
145         onRwy(false),
146         nextOnRwy(false),
147         vfrArrivalReported(false),
148         vfrArrivalAcknowledged(false),
149         opType(TTT_UNKNOWN),
150         leg(LEG_UNKNOWN),
151         landingType(AIP_LT_UNKNOWN),
152         isUser(false)
153 {
154         plane = p;
155         pos = pt;
156 }
157
158
159 // FGTower
160
161 /*******************************************
162                TODO List
163                            
164 Currently user is assumed to have taken off again when leaving the runway - check speed/elev for taxiing-in. (MAJOR)
165
166 Use track instead of heading to determine what leg of the circuit the user is flying. (MINOR)
167
168 Use altitude as well as position to try to determine if the user has left the circuit. (MEDIUM - other issues as well).
169
170 Currently HoldShortReported code assumes there will be only one plane holding for the runway at once and 
171 will break when planes start queueing. (CRITICAL)
172
173 Report-Runway-Vacated is left as only user ATC option following a go-around. (MAJOR)
174
175 Report-Downwind is not added as ATC option when user takes off to fly a circuit. (MAJOR)
176
177 eta of USER can be calculated very wrongly in circuit if flying straight out and turn4 etc are with +ve ortho y. 
178 This can then screw up circuit ordering for other planes (MEDIUM)
179
180 USER leaving circuit needs to be more robustly considered when intentions unknown
181 Currently only considered during climbout and breaks when user turns (MEDIUM).
182
183 GetPos() of the AI planes is called erratically - either too much or not enough. (MINOR)
184
185 GO-AROUND is instructed very late at < 12s to landing - possibly make more dependent on chance of rwy clearing before landing (FEATURE)
186
187 Need to make clear when TowerPlaneRecs do or don't get deleted in RemoveFromCircuitList etc. (MINOR until I misuse it - then CRITICAL!)
188
189 FGTower::RemoveAllUserDialogOptions() really ought to be replaced by an ATCDialog::clear_entries() function. (MINOR - efficiency).
190 *******************************************/
191
192 FGTower::FGTower() {
193         ATCmgr = globals->get_ATC_mgr();
194         
195         _type = TOWER;
196         
197         // Init the property nodes - TODO - need to make sure we're getting surface winds.
198         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
199         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
200         
201         update_count = 0;
202         update_count_max = 15;
203         
204         holdListItr = holdList.begin();
205         appList.clear();
206         appListItr = appList.begin();
207         depListItr = depList.begin();
208         rwyListItr = rwyList.begin();
209         circuitListItr = circuitList.begin();
210         trafficListItr = trafficList.begin();
211         vacatedList.clear();
212         vacatedListItr = vacatedList.begin();
213         
214         freqClear = true;
215         
216         timeSinceLastDeparture = 9999;
217         departed = false;
218         
219         nominal_downwind_leg_pos = 1000.0;
220         nominal_base_leg_pos = -1000.0;
221         // TODO - set nominal crosswind leg pos based on minimum distance from takeoff end of rwy.
222         
223         _departureControlled = false;
224 }
225
226 FGTower::~FGTower() {
227         if(!separateGround) {
228                 delete ground;
229         }
230 }
231
232 void FGTower::Init() {
233         //cout << "Initialising tower " << ident << '\n';
234         
235         // Pointers to user's position
236         user_lon_node = fgGetNode("/position/longitude-deg", true);
237         user_lat_node = fgGetNode("/position/latitude-deg", true);
238         user_elev_node = fgGetNode("/position/altitude-ft", true);
239         user_hdg_node = fgGetNode("/orientation/heading-deg", true);
240         
241         // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
242         // I'll punt the startup issue for now though!!!
243         rwyOccupied = false;
244         
245         // Setup the ground control at this airport
246         AirportATC a;
247         //cout << "Tower ident = " << ident << '\n';
248         if(ATCmgr->GetAirportATCDetails(ident, &a)) {
249                 if(a.ground_freq) {             // Ground control
250                         ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
251                         separateGround = true;
252                         if(ground == NULL) {
253                                 // Something has gone wrong :-(
254                                 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
255                                 ground = new FGGround(ident);
256                                 separateGround = false;
257                                 ground->Init();
258                                 if(_display) {
259                                         ground->SetDisplay();
260                                 } else {
261                                         ground->SetNoDisplay();
262                                 }
263                         }
264                 } else {
265                         // Initialise ground anyway to do the shortest path stuff!
266                         // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
267                         ground = new FGGround(ident);
268                         separateGround = false;
269                         ground->Init();
270                         if(_display) {
271                                 ground->SetDisplay();
272                         } else {
273                                 ground->SetNoDisplay();
274                         }
275                 }
276         } else {
277                 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
278                 // Initialise ground anyway to avoid segfault later
279                 ground = new FGGround(ident);
280                 separateGround = false;
281                 ground->Init();
282                 if(_display) {
283                         ground->SetDisplay();
284                 } else {
285                         ground->SetNoDisplay();
286                 }
287         }
288         
289         // TODO - attempt to get a departure control pointer to see if we need to hand off departing traffic to departure.
290         
291         // Get the airport elevation
292         aptElev = dclGetAirportElev(ident.c_str());
293         
294         // TODO - this function only assumes one active rwy.
295         DoRwyDetails();
296         
297         // TODO - this currently assumes only one active runway.
298         rwyOccupied = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
299         if(rwyOccupied) {
300                 //cout << "User found on active runway\n";
301                 // Assume the user is started at the threshold ready to take-off
302                 TowerPlaneRec* t = new TowerPlaneRec;
303                 t->plane.callsign = fgGetString("/sim/user/callsign");
304                 t->plane.type = GA_SINGLE;      // FIXME - hardwired!!
305                 t->opType = TTT_UNKNOWN;        // We don't know if the user wants to do circuits or a departure...
306                 t->landingType = AIP_LT_UNKNOWN;
307                 t->leg = TAKEOFF_ROLL;
308                 t->isUser = true;
309                 t->planePtr = NULL;
310                 t->clearedToTakeOff = true;
311                 rwyList.push_back(t);
312                 departed = false;
313         } else {
314                 //cout << "User not on active runway\n";
315                 // For now assume that this means the user is not at the airport and is in the air.
316                 // TODO FIXME - this will break when user starts on apron, at hold short, etc.
317                 if(!OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0))) {
318                         //cout << ident << "  ADD 0\n";
319                         current_atcdialog->add_entry(ident, "@AP Tower @CS @MI miles @CD of the airport for full stop with the ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
320                 }
321         }
322 }
323
324 void FGTower::Update(double dt) {
325         //cout << "T" << endl;
326         // Each time step, what do we need to do?
327         // We need to go through the list of outstanding requests and acknowedgements
328         // and process at least one of them.
329         // We need to go through the list of planes under our control and check if
330         // any need to be addressed.
331         // We need to check for planes not under our control coming within our 
332         // control area and address if necessary.
333         
334         // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
335         
336         // Sort the arriving planes
337         
338         /*
339         if(ident == "KEMT") {
340                 cout << update_count << "\ttL: " << trafficList.size() << "  cL: " << circuitList.size() << "  hL: " << holdList.size() << "  aL: " << appList.size() << '\n';
341         }
342         */
343         //if(ident == "EGNX") cout << display << '\n';
344         
345         if(departed != false) {
346                 timeSinceLastDeparture += dt;
347                 //if(ident == "KEMT") 
348                 //      cout << "  dt = " << dt << "  timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
349         }
350         
351         //cout << ident << " respond = " << respond << " responseReqd = " << responseReqd << '\n'; 
352         if(respond) {
353                 if(!responseReqd) SG_LOG(SG_ATC, SG_ALERT, "ERROR - respond is true and responseReqd is false in FGTower::Update(...)");
354                 Respond();
355                 respond = false;
356                 responseReqd = false;
357         }
358         
359         // Calculate the eta of each plane to the threshold.
360         // For ground traffic this is the fastest they can get there.
361         // For air traffic this is the middle approximation.
362         if(update_count == 1) {
363                 doThresholdETACalc();
364         }
365         
366         // Order the list of traffic as per expected threshold use and flag any conflicts
367         if(update_count == 2) {
368                 //bool conflicts = doThresholdUseOrder();
369                 doThresholdUseOrder();
370         }
371         
372         // sortConficts() !!!
373         
374         if(update_count == 4) {
375                 CheckHoldList(dt);
376         }
377         
378         // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
379         if(rwyList.size()) {
380                 rwyOccupied = true;
381         } else {
382                 rwyOccupied = false;
383         }
384         
385         if(update_count == 5 && rwyOccupied) {
386                 CheckRunwayList(dt);
387         }
388                 
389         if(update_count == 6) {
390                 CheckCircuitList(dt);
391         }
392         
393         if(update_count == 7) {
394                 CheckApproachList(dt);
395         }
396         
397         if(update_count == 8) {
398                 CheckDepartureList(dt);
399         }
400         
401         // TODO - do one plane from the departure list and set departed = false when out of consideration
402         
403         //doCommunication();
404         
405         if(!separateGround) {
406                 // The display stuff might have to get more clever than this when not separate 
407                 // since the tower and ground might try communicating simultaneously even though
408                 // they're mean't to be the same contoller/frequency!!
409                 // We could also get rid of this by overloading FGATC's Set(No)Display() functions.
410                 if(_display) {
411                         ground->SetDisplay();
412                 } else {
413                         ground->SetNoDisplay();
414                 }
415                 ground->Update(dt);
416         }
417         
418         ++update_count;
419         // How big should ii get - ie how long should the update cycle interval stretch?
420         if(update_count >= update_count_max) {
421                 update_count = 0;
422         }
423         
424         // Call the base class update for the response time handling.
425         FGATC::Update(dt);
426
427         /*
428         if(ident == "KEMT") {   
429                 // For AI debugging convienience - may be removed
430                 Point3D user_pos;
431                 user_pos.setlon(user_lon_node->getDoubleValue());
432                 user_pos.setlat(user_lat_node->getDoubleValue());
433                 user_pos.setelev(user_elev_node->getDoubleValue());
434                 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
435                 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
436                 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
437                 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
438         }
439         */
440         
441         //cout << "Done T" << endl;
442 }
443
444 void FGTower::ReceiveUserCallback(int code) {
445         if(code == (int)USER_REQUEST_VFR_DEPARTURE) {
446                 //cout << "User requested departure\n";
447         } else if(code == (int)USER_REQUEST_VFR_ARRIVAL) {
448                 VFRArrivalContact("USER");
449         } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP) {
450                 VFRArrivalContact("USER", FULL_STOP);
451         } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO) {
452                 VFRArrivalContact("USER", TOUCH_AND_GO);
453         } else if(code == (int)USER_REPORT_DOWNWIND) {
454                 ReportDownwind("USER");
455         } else if(code == (int)USER_REPORT_3_MILE_FINAL) {
456                 // For now we'll just call report final instead of report long final to avoid having to alter the response code
457                 ReportFinal("USER");
458         } else if(code == (int)USER_REPORT_RWY_VACATED) {
459                 ReportRunwayVacated("USER");
460         } else if(code == (int)USER_REPORT_GOING_AROUND) {
461                 ReportGoingAround("USER");
462         }
463 }
464
465 // **************** RESPONSE FUNCTIONS ****************
466
467 void FGTower::Respond() {
468         //cout << "\nEntering Respond, responseID = " << responseID << endl;
469         TowerPlaneRec* t = FindPlane(responseID);
470         if(t) {
471                 // This will grow!!!
472                 if(t->vfrArrivalReported && !t->vfrArrivalAcknowledged) {
473                         //cout << "Tower " << ident << " is responding to VFR arrival reported...\n";
474                         // Testing - hardwire straight in for now
475                         string trns = t->plane.callsign;
476                         trns += " ";
477                         trns += name;
478                         trns += " Tower";
479                         // Should we clear staight in or for downwind entry?
480                         // For now we'll clear straight in if greater than 1km from a line drawn through the threshold perpendicular to the rwy.
481                         // Later on we might check the actual heading and direct some of those to enter on downwind or base.
482                         Point3D op = ortho.ConvertToLocal(t->pos);
483                         if(op.y() < -1000) {
484                                 trns += " Report three mile straight-in runway ";
485                                 t->opType = STRAIGHT_IN;
486                                 if(t->isUser) {
487                                         current_atcdialog->add_entry(ident, "@AP Tower @CS @MI mile final Runway @RW", "Report Final", TOWER, (int)USER_REPORT_3_MILE_FINAL);
488                                 } else {
489                                         t->planePtr->RegisterTransmission(14);
490                                 }
491                         } else {
492                                 // For now we'll just request reporting downwind.
493                                 // TODO - In real life something like 'report 2 miles southwest right downwind rwy 19R' might be used
494                                 // but I'm not sure how to handle all permutations of which direction to tell to report from yet.
495                                 trns += " Report ";
496                                 //cout << "Responding, rwy.patterDirection is " << rwy.patternDirection << '\n';
497                                 trns += ((rwy.patternDirection == 1) ? "right " : "left ");
498                                 trns += "downwind runway ";
499                                 t->opType = CIRCUIT;
500                                 // leave it in the app list until it gets into pattern though.
501                                 if(t->isUser) {
502                                         current_atcdialog->add_entry(ident, "@AP Tower @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
503                                 } else {
504                                         t->planePtr->RegisterTransmission(15);
505                                 }
506                         }
507                         trns += ConvertRwyNumToSpokenString(activeRwy);
508                         if(_display) {
509                                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
510                         } else {
511                                 //cout << "Not displaying, trns was " << trns << '\n';
512                         }
513                         t->vfrArrivalAcknowledged = true;
514                 } else if(t->downwindReported) {
515                         //cout << "Tower " << ident << " is responding to downwind reported...\n";
516                         ProcessDownwindReport(t);
517                         t->downwindReported = false;
518                 } else if(t->holdShortReported) {
519                         //cout << "Tower " << ident << " is reponding to holdShortReported...\n";
520                         if(t->nextOnRwy) {
521                                 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!!)
522                                         // Do nothing for now - consider acknowloging hold short eventually
523                                 } else {
524                                         ClearHoldingPlane(t);
525                                         t->leg = TAKEOFF_ROLL;
526                                         rwyList.push_back(t);
527                                         rwyOccupied = true;
528                                         // WARNING - WE ARE ASSUMING ONLY ONE PLANE REPORTING HOLD AT A TIME BELOW
529                                         // FIXME TODO - FIX THIS!!!
530                                         if(holdList.size()) {
531                                                 if(holdListItr == holdList.end()) {
532                                                         holdListItr = holdList.begin();
533                                                 }
534                                                 holdList.erase(holdListItr);
535                                                 holdListItr = holdList.begin();
536                                         }
537                                 }
538                         } else {
539                                 // Tell him to hold and what position he is.
540                                 // Not currently sure under which circumstances we do or don't bother transmitting this.
541                                 string trns = t->plane.callsign;
542                                 trns += " hold position";
543                                 if(_display) {
544                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
545                                 }
546                                 // TODO - add some idea of what traffic is blocking him.
547                         }
548                         t->holdShortReported = false;
549                 } else if(t->finalReported && !(t->finalAcknowledged)) {
550                         //cout << "Tower " << ident << " is responding to finalReported...\n";
551                         bool disp = true;
552                         string trns = t->plane.callsign;
553                         //cout << (t->nextOnRwy ? "Next on rwy " : "Not next!! ");
554                         //cout << (rwyOccupied ? "RWY OCCUPIED!!\n" : "Rwy not occupied\n");
555                         if(t->nextOnRwy && !rwyOccupied && !(t->instructedToGoAround)) {
556                                 if(t->landingType == FULL_STOP) {
557                                         trns += " cleared to land ";
558                                 } else {
559                                         trns += " cleared for the option ";
560                                 }
561                                 // TODO - add winds
562                                 t->clearedToLand = true;
563                                 // Maybe remove report downwind from menu here as well incase user didn't bother to?
564                                 if(t->isUser) {
565                                         //cout << "ADD VACATED B\n";
566                                         // Put going around at the top (and hence default) since that'll be more desperate,
567                                         // or put rwy vacated at the top since that'll be more common?
568                                         current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND);
569                                         current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
570                                 } else {
571                                         t->planePtr->RegisterTransmission(7);
572                                 }
573                         } else if(t->eta < 20) {
574                                 // Do nothing - we'll be telling it to go around in less than 10 seconds if the
575                                 // runway doesn't clear so no point in calling "continue approach".
576                                 disp = false;
577                         } else {
578                                 trns += " continue approach";
579                                 t->clearedToLand = false;
580                         }
581                         if(_display && disp) {
582                                 globals->get_ATC_display()->RegisterSingleMessage(trns);
583                         }
584                         t->finalAcknowledged = true;
585                 } else if(t->rwyVacatedReported && !(t->rwyVacatedAcknowledged)) {
586                         ProcessRunwayVacatedReport(t);
587                         t->rwyVacatedAcknowledged = true;
588                 }
589         }
590         //freqClear = true;     // FIXME - set this to come true after enough time to render the message
591         _releaseCounter = 0.0;
592         _releaseTime = 5.5;
593         _runReleaseCounter = true;
594         //cout << "Done Respond\n" << endl;
595 }
596
597 void FGTower::ProcessDownwindReport(TowerPlaneRec* t) {
598         int i = 1;
599         int a = 0;      // Count of preceding planes on approach
600         bool cf = false;        // conflicting traffic on final
601         bool cc = false;        // preceding traffic in circuit
602         TowerPlaneRec* tc;
603         for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
604                 if((*twrItr)->plane.callsign == responseID) break;
605                 tc = *twrItr;
606                 ++i;
607         }
608         if(i > 1) { cc = true; }
609         doThresholdETACalc();
610         TowerPlaneRec* tf;
611         for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
612                 if((*twrItr)->eta < (t->eta + 45)) {
613                         a++;
614                         tf = *twrItr;
615                         cf = true;
616                         // This should set the flagged plane to be the last conflicting one, and hence the one to follow.
617                         // It ignores the fact that we might have problems slotting into the approach traffic behind it - 
618                         // eventually we'll need some fancy algorithms for that!
619                 }
620         }
621         string trns = t->plane.callsign;
622         trns += " Number ";
623         trns += ConvertNumToSpokenDigits(i + a);
624         // This assumes that the number spoken is landing position, not circuit position, since some of the traffic might be on straight-in final.
625         trns += " ";
626         TowerPlaneRec* tt;
627         if((i == 1) && (!rwyList.size()) && (t->nextOnRwy) && (!cf)) {  // Unfortunately nextOnRwy currently doesn't handle circuit/straight-in ordering properly at present, hence the cf check below.
628                 trns += "Cleared to land";      // TODO - clear for the option if appropriate
629                 t->clearedToLand = true;
630                 if(!t->isUser) t->planePtr->RegisterTransmission(7);
631         } else if((i+a) > 1) {
632                 //First set tt to point to the correct preceding plane - final or circuit
633                 if(i > 1 && a > 0) {
634                         tt = (tf->eta < tc->eta ? tf : tc);
635                 } else if(i > 1) {
636                         tt = tc;
637                 } else if(a > 0) {
638                         tt = tf;
639                 } else {
640                         // We should never get here!
641                         SG_LOG(SG_ATC, SG_ALERT, "ALERT - Logic error in FGTower::ProcessDownwindReport");
642                 }
643                 trns += "Follow the ";
644                 string s = tt->plane.callsign;
645                 int p = s.find('-');
646                 s = s.substr(0,p);
647                 trns += s;
648                 if((tt->opType) == CIRCUIT) {
649                         if(tt->planePtr->GetLeg() == FINAL) {
650                                 trns += " on final";
651                         } else if(tt->planePtr->GetLeg() == TURN4) {
652                                 trns += " turning final";
653                         } else if(tt->planePtr->GetLeg() == BASE) {
654                                 trns += " on base";
655                         } else if(tt->planePtr->GetLeg() == TURN3) {
656                                 trns += " turning base";
657                         }
658                 } else {
659                         double miles_out = CalcDistOutMiles(tt);
660                         if(miles_out < 2) {
661                                 trns += " on short final";
662                         } else {
663                                 trns += " on ";
664                                 trns += ConvertNumToSpokenDigits((int)miles_out);
665                                 trns += " mile final";
666                         }
667                 }
668         }
669         if(_display) {
670                 globals->get_ATC_display()->RegisterSingleMessage(trns);
671         }
672         if(t->isUser) {
673                 if(t->opType == TTT_UNKNOWN) t->opType = CIRCUIT;
674                 //cout << "ADD VACATED A\n";
675                 // Put going around at the top (and hence default) since that'll be more desperate,
676                 // or put rwy vacated at the top since that'll be more common?
677                 //cout << "ident = " << ident << ", adding go-around option\n";
678                 current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND);
679                 current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
680         }
681 }
682
683 void FGTower::ProcessRunwayVacatedReport(TowerPlaneRec* t) {
684         //cout << "Processing rwy vacated...\n";
685         if(t->isUser) current_atcdialog->remove_entry(ident, USER_REPORT_GOING_AROUND, TOWER);
686         string trns = t->plane.callsign;
687         if(separateGround) {
688                 trns += " Contact ground on ";
689                 double f = globals->get_ATC_mgr()->GetFrequency(ident, GROUND) / 100.0; 
690                 char buf[10];
691                 sprintf(buf, "%.2f", f);
692                 trns += buf;
693                 trns += " Good Day";
694                 if(!t->isUser) t->planePtr->RegisterTransmission(5);
695         } else {
696                 // Cop-out!!
697                 trns += " cleared for taxi to the GA parking";
698                 if(!t->isUser) t->planePtr->RegisterTransmission(6);    // TODO - this is a mega-hack!!
699         }
700         //cout << "trns = " << trns << '\n';
701         if(_display) {
702                 globals->get_ATC_display()->RegisterSingleMessage(trns);
703         }
704         RemoveFromRwyList(t->plane.callsign);
705         AddToVacatedList(t);
706         // Maybe we should check that the plane really *has* vacated the runway!
707 }
708
709 // *********** END RESPONSE FUNCTIONS *****************
710
711 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land - 
712 // this should be done prior to calling this function.
713 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
714         //cout << "Entering ClearHoldingPlane..." << endl;
715         // Lets Roll !!!!
716         string trns = t->plane.callsign;
717         //if(departed plane < some threshold in time away) {
718         if(0) {         // FIXME
719         //if(timeSinceLastDeparture <= 60.0 && departed == true) {
720                 trns += " line up";
721                 t->clearedToLineUp = true;
722                 t->planePtr->RegisterTransmission(3);   // cleared to line-up
723         //} else if(arriving plane < some threshold away) {
724         } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) {   // Hack - hardwired time
725                 trns += " cleared immediate take-off";
726                 if(trafficList.size()) {
727                         tower_plane_rec_list_iterator trfcItr = trafficList.begin();
728                         trfcItr++;      // At the moment the holding plane should be first in trafficList.
729                         // Note though that this will break if holding planes aren't put in trafficList in the future.
730                         TowerPlaneRec* trfc = *trfcItr;
731                         trns += "... traffic is";
732                         switch(trfc->plane.type) {
733                         case UNKNOWN:
734                                 break;
735                         case GA_SINGLE:
736                                 trns += " a Cessna";    // TODO - add ability to specify actual plane type somewhere
737                                 break;
738                         case GA_HP_SINGLE:
739                                 trns += " a Piper";
740                                 break;
741                         case GA_TWIN:
742                                 trns += " a King-air";
743                                 break;
744                         case GA_JET:
745                                 trns += " a Learjet";
746                                 break;
747                         case MEDIUM:
748                                 trns += " a Regional";
749                                 break;
750                         case HEAVY:
751                                 trns += " a Heavy";
752                                 break;
753                         case MIL_JET:
754                                 trns += " Military";
755                                 break;
756                         }
757                         //if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
758                         if(trfc->opType == STRAIGHT_IN) {
759                                 double miles_out = CalcDistOutMiles(trfc);
760                                 if(miles_out < 2) {
761                                         trns += " on final";
762                                 } else {
763                                         trns += " on ";
764                                         trns += ConvertNumToSpokenDigits((int)miles_out);
765                                         trns += " mile final";
766                                 }
767                         } else if(trfc->opType == CIRCUIT) {
768                                 //cout << "Getting leg of " << trfc->plane.callsign << '\n';
769                                 switch(trfc->leg) {
770                                 case FINAL:
771                                         trns += " on final";
772                                         break;
773                                 case TURN4:
774                                         trns += " turning final";
775                                         break;
776                                 case BASE:
777                                         trns += " on base";
778                                         break;
779                                 case TURN3:
780                                         trns += " turning base";
781                                         break;
782                                 case DOWNWIND:
783                                         trns += " in circuit";  // At the moment the user plane is generally flagged as unknown opType when downwind incase its a downwind departure which means we won't get here.
784                                         break;
785                                 // And to eliminate compiler warnings...
786                                 case TAKEOFF_ROLL: break;
787                                 case CLIMBOUT:     break;
788                                 case TURN1:        break;
789                                 case CROSSWIND:    break;
790                                 case TURN2:        break;
791                                 case LANDING_ROLL: break;
792                                 case LEG_UNKNOWN:  break;
793                                 }
794                         }
795                 } else {
796                         // By definition there should be some arriving traffic if we're cleared for immediate takeoff
797                         SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
798                 }
799                 t->clearedToTakeOff = true;
800                 t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
801                 departed = false;
802                 timeSinceLastDeparture = 0.0;
803         } else {
804         //} else if(timeSinceLastDeparture > 60.0 || departed == false) {       // Hack - test for timeSinceLastDeparture should be in lineup block eventually
805                 trns += " cleared for take-off";
806                 // TODO - add traffic is... ?
807                 t->clearedToTakeOff = true;
808                 t->planePtr->RegisterTransmission(4);   // cleared to take-off
809                 departed = false;
810                 timeSinceLastDeparture = 0.0;
811         }
812         if(_display) {
813                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
814         }
815         //cout << "Done ClearHoldingPlane " << endl;
816 }
817
818
819 // ***************************************************************************************
820 // ********** Functions to periodically check what the various traffic is doing **********
821
822 // Do one plane from the hold list
823 void FGTower::CheckHoldList(double dt) {
824         //cout << "Entering CheckHoldList..." << endl;
825         if(holdList.size()) {
826                 //cout << "*holdListItr = " << *holdListItr << endl;
827                 if(holdListItr == holdList.end()) {
828                         holdListItr = holdList.begin();
829                 }
830                 //cout << "*holdListItr = " << *holdListItr << endl;
831                 //Process(*holdListItr);
832                 TowerPlaneRec* t = *holdListItr;
833                 //cout << "t = " << t << endl;
834                 if(t->holdShortReported) {
835                         // NO-OP - leave it to the response handler.
836                 } else {        // not responding to report, but still need to clear if clear
837                         if(t->nextOnRwy) {
838                                 //cout << "departed = " << departed << '\n';
839                                 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
840                                 if(rwyOccupied) {
841                                         // Do nothing
842                                 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
843                                         // Do nothing - this is a bit of a hack - should maybe do line up be ready here
844                                 } else {
845                                         ClearHoldingPlane(t);
846                                         t->leg = TAKEOFF_ROLL;
847                                         rwyList.push_back(t);
848                                         rwyOccupied = true;
849                                         holdList.erase(holdListItr);
850                                         holdListItr = holdList.begin();
851                                 }
852                         }
853                         // TODO - rationalise the considerable code duplication above!
854                 }
855                 ++holdListItr;
856         }
857         //cout << "Done CheckHoldList" << endl;
858 }
859
860 // do the ciruit list
861 void FGTower::CheckCircuitList(double dt) {
862         //cout << "Entering CheckCircuitList..." << endl;
863         // Clear the constraints - we recalculate here.
864         base_leg_pos = 0.0;
865         downwind_leg_pos = 0.0;
866         crosswind_leg_pos = 0.0;
867         
868         if(circuitList.size()) {        // Do one plane from the circuit
869                 if(circuitListItr == circuitList.end()) {
870                         circuitListItr = circuitList.begin();
871                 }
872                 TowerPlaneRec* t = *circuitListItr;
873                 //cout << ident <<  ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n';
874                 if(t->isUser) {
875                         t->pos.setlon(user_lon_node->getDoubleValue());
876                         t->pos.setlat(user_lat_node->getDoubleValue());
877                         t->pos.setelev(user_elev_node->getDoubleValue());
878                         //cout << ident <<  ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n';
879                 } else {
880                         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.
881                         t->landingType = t->planePtr->GetLandingOption();
882                         //cout << "AI plane landing option is " << t->landingType << '\n';
883                 }
884                 Point3D tortho = ortho.ConvertToLocal(t->pos);
885                 if(t->isUser) {
886                         // Need to figure out which leg he's on
887                         //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
888                         double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
889                         //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
890                         // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
891                         // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
892                         if(abs(ho) < 30) {
893                                 // could be either takeoff, climbout or landing - check orthopos.y
894                                 //cout << "tortho.y = " << tortho.y() << '\n';
895                                 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
896                                         t->leg = FINAL;
897                                         //cout << "Final\n";
898                                 } else {
899                                         t->leg = CLIMBOUT;      // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
900                                         //cout << "Climbout\n";
901                                         // If it's the user we may be unsure of his/her intentions.
902                                         // (Hopefully the AI planes won't try confusing the sim!!!)
903                                         //cout << "tortho.y = " << tortho.y() << '\n';
904                                         if(t->opType == TTT_UNKNOWN) {
905                                                 if(tortho.y() > 5000) {
906                                                         // 5 km out from threshold - assume it's a departure
907                                                         t->opType = OUTBOUND;   // TODO - could check if the user has climbed significantly above circuit altitude as well.
908                                                         // Since we are unknown operation we should be in depList already.
909                                                         //cout << ident << " Removing user from circuitList (TTT_UNKNOWN)\n";
910                                                         circuitList.erase(circuitListItr);
911                                                         RemoveFromTrafficList(t->plane.callsign);
912                                                         circuitListItr = circuitList.begin();
913                                                 }
914                                         } else if(t->opType == CIRCUIT) {
915                                                 if(tortho.y() > 10000) {
916                                                         // 10 km out - assume the user has abandoned the circuit!!
917                                                         t->opType = OUTBOUND;
918                                                         depList.push_back(t);
919                                                         //cout << ident << " removing user from circuitList (CIRCUIT)\n";
920                                                         circuitList.erase(circuitListItr);
921                                                         circuitListItr = circuitList.begin();
922                                                 }
923                                         }
924                                 }
925                         } else if(abs(ho) < 60) {
926                                 // turn1 or turn 4
927                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
928                                 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
929                                         t->leg = TURN1;
930                                         //cout << "Turn1\n";
931                                 } else {
932                                         t->leg = TURN4;
933                                         //cout << "Turn4\n";
934                                 }
935                         } else if(abs(ho) < 120) {
936                                 // crosswind or base
937                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
938                                 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
939                                         t->leg = CROSSWIND;
940                                         //cout << "Crosswind\n";
941                                 } else {
942                                         t->leg = BASE;
943                                         //cout << "Base\n";
944                                 }
945                         } else if(abs(ho) < 150) {
946                                 // turn2 or turn 3
947                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
948                                 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
949                                         t->leg = TURN2;
950                                         //cout << "Turn2\n";
951                                 } else {
952                                         t->leg = TURN3;
953                                         // Probably safe now to assume the user is flying a circuit
954                                         t->opType = CIRCUIT;
955                                         //cout << "Turn3\n";
956                                 }
957                         } else {
958                                 // downwind
959                                 t->leg = DOWNWIND;
960                                 //cout << "Downwind\n";
961                         }
962                         if(t->leg == FINAL) {
963                                 if(OnActiveRunway(t->pos)) {
964                                         t->leg = LANDING_ROLL;
965                                 }
966                         }
967                 } else {
968                         t->leg = t->planePtr->GetLeg();
969                 }
970                 
971                 // Set the constraints IF this is the first plane in the circuit
972                 // 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!!
973                 if(circuitListItr == circuitList.begin()) {
974                         switch(t->leg) {
975                                 case FINAL:
976                                 // 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.
977                                 base_leg_pos = tortho.y();
978                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
979                                 break;
980                                 case TURN4:
981                                 // Fall through to base
982                                 case BASE:
983                                 base_leg_pos = tortho.y();
984                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
985                                 break;
986                                 case TURN3:
987                                 // Fall through to downwind
988                                 case DOWNWIND:
989                                 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
990                                 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
991                                 //cout << "base_leg_pos = " << base_leg_pos;
992                                 downwind_leg_pos = tortho.x();          // Assume that a following plane can simply be constrained by the immediately in front downwind plane
993                                 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
994                                 break;
995                                 case TURN2:
996                                 // Fall through to crosswind
997                                 case CROSSWIND:
998                                 crosswind_leg_pos = tortho.y();
999                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
1000                                 t->instructedToGoAround = false;
1001                                 break;
1002                                 case TURN1:
1003                                 // Fall through to climbout
1004                                 case CLIMBOUT:
1005                                 // Only use current by constraint as largest
1006                                 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
1007                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
1008                                 break;
1009                                 case TAKEOFF_ROLL:
1010                                 break;
1011                                 case LEG_UNKNOWN:
1012                                 break;
1013                                 case LANDING_ROLL:
1014                                 break;
1015                                 default:
1016                                 break;
1017                         }
1018                 }
1019                 
1020                 if(t->leg == FINAL && !(t->instructedToGoAround)) {
1021                         doThresholdETACalc();
1022                         doThresholdUseOrder();
1023                         /*
1024                         if(t->isUser) {
1025                                 cout << "Checking USER on final... ";
1026                                 cout << "eta " << t->eta;
1027                                 if(t->clearedToLand) cout << " cleared to land\n";
1028                         }
1029                         */
1030                         //cout << "YES FINAL, t->eta = " << t->eta << ", rwyList.size() = " << rwyList.size() << '\n';
1031                         if(t->landingType == FULL_STOP) {
1032                                 t->opType = INBOUND;
1033                                 //cout << "\n******** SWITCHING TO INBOUND AT POINT AAA *********\n\n";
1034                         }
1035                         if(t->eta < 12 && rwyList.size()) {
1036                                 // TODO - need to make this more sophisticated 
1037                                 // eg. is the plane accelerating down the runway taking off [OK],
1038                                 // or stationary near the start [V. BAD!!].
1039                                 // For now this should stop the AI plane landing on top of the user.
1040                                 string trns = t->plane.callsign;
1041                                 trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
1042                                 pending_transmission = trns;
1043                                 ImmediateTransmit();
1044                                 t->instructedToGoAround = true;
1045                                 t->clearedToLand = false;
1046                                 // Assume it complies!!!
1047                                 t->opType = CIRCUIT;
1048                                 t->leg = CLIMBOUT;
1049                                 if(t->planePtr) {
1050                                         //cout << "Registering Go-around transmission with AI plane\n";
1051                                         t->planePtr->RegisterTransmission(13);
1052                                 }
1053                         } else if(!t->clearedToLand) {
1054                                 if(t->nextOnRwy) {
1055                                         if(!rwyList.size()) {
1056                                                 string trns = t->plane.callsign;
1057                                                 trns += " Cleared to land";
1058                                                 pending_transmission = trns;
1059                                                 Transmit();
1060                                                 //if(t->isUser) cout << "Transmitting cleared to Land!!!\n";
1061                                                 t->clearedToLand = true;
1062                                                 if(!t->isUser) {
1063                                                         t->planePtr->RegisterTransmission(7);
1064                                                 }
1065                                         }
1066                                 } else {
1067                                         //if(t->isUser) cout << "Not next\n";
1068                                 }
1069                         }
1070                 } else if(t->leg == LANDING_ROLL) {
1071                         //cout << t->plane.callsign << " has landed - adding to rwyList\n";
1072                         rwyList.push_front(t);
1073                         // TODO - if(!clearedToLand) shout something!!
1074                         t->clearedToLand = false;
1075                         RemoveFromTrafficList(t->plane.callsign);
1076                         if(t->isUser) {
1077                                 t->opType = TTT_UNKNOWN;
1078                         }       // TODO - allow the user to specify opType via ATC menu
1079                         //cout << ident << " Removing " << t->plane.callsign << " from circuitList..." << endl;
1080                         circuitListItr = circuitList.erase(circuitListItr);
1081                         if(circuitListItr == circuitList.end() ) {
1082                                 circuitListItr = circuitList.begin();
1083                         }
1084                 }
1085                 ++circuitListItr;
1086         }
1087         //cout << "Done CheckCircuitList" << endl;
1088 }
1089
1090 // Do the runway list - we'll do the whole runway list since it's important and there'll never be many planes on the rwy at once!!
1091 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
1092 // (However, at the moment there should only be one airplane on the rwy at once, until we
1093 // start allowing planes to line up whilst previous arrival clears the rwy.)
1094 void FGTower::CheckRunwayList(double dt) {
1095         //cout << "Entering CheckRunwayList..." << endl;
1096         if(rwyOccupied) {
1097                 if(!rwyList.size()) {
1098                         rwyOccupied = false;
1099                 } else {
1100                         rwyListItr = rwyList.begin();
1101                         TowerPlaneRec* t = *rwyListItr;
1102                         if(t->isUser) {
1103                                 t->pos.setlon(user_lon_node->getDoubleValue());
1104                                 t->pos.setlat(user_lat_node->getDoubleValue());
1105                                 t->pos.setelev(user_elev_node->getDoubleValue());
1106                         } else {
1107                                 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.
1108                         }
1109                         bool on_rwy = OnActiveRunway(t->pos);
1110                         if(!on_rwy) {
1111                                 // TODO - for all of these we need to check what the user is *actually* doing!
1112                                 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
1113                                         //cout << "Tower " << ident << " is removing plane " << t->plane.callsign << " from rwy list (vacated)\n";
1114                                         //cout << "Size of rwylist was " << rwyList.size() << '\n';
1115                                         //cout << "Size of vacatedList was " << vacatedList.size() << '\n';
1116                                         RemoveFromRwyList(t->plane.callsign);
1117                                         AddToVacatedList(t);
1118                                         //cout << "Size of rwylist is " << rwyList.size() << '\n';
1119                                         //cout << "Size of vacatedList is " << vacatedList.size() << '\n';
1120                                         // At the moment we wait until Runway Vacated is reported by the plane before telling to contact ground etc.
1121                                         // It's possible we could be a bit more proactive about this.
1122                                 } else if(t->opType == OUTBOUND) {
1123                                         depList.push_back(t);
1124                                         rwyList.pop_front();
1125                                         departed = true;
1126                                         timeSinceLastDeparture = 0.0;
1127                                 } else if(t->opType == CIRCUIT) {
1128                                         //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1129                                         circuitList.push_back(t);
1130                                         AddToTrafficList(t);
1131                                         rwyList.pop_front();
1132                                         departed = true;
1133                                         timeSinceLastDeparture = 0.0;
1134                                 } else if(t->opType == TTT_UNKNOWN) {
1135                                         depList.push_back(t);
1136                                         //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1137                                         circuitList.push_back(t);
1138                                         AddToTrafficList(t);
1139                                         rwyList.pop_front();
1140                                         departed = true;
1141                                         timeSinceLastDeparture = 0.0;   // TODO - we need to take into account that the user might taxi-in when flagged opType UNKNOWN - check speed/altitude etc to make decision as to what user is up to.
1142                                 } else {
1143                                         // HELP - we shouldn't ever get here!!!
1144                                 }
1145                         }
1146                 }
1147         }
1148         //cout << "Done CheckRunwayList" << endl;
1149 }
1150
1151 // Do one plane from the approach list
1152 void FGTower::CheckApproachList(double dt) {
1153         //cout << "CheckApproachList called for " << ident << endl;
1154         //cout << "AppList.size is " << appList.size() << endl;
1155         if(appList.size()) {
1156                 if(appListItr == appList.end()) {
1157                         appListItr = appList.begin();
1158                 }
1159                 TowerPlaneRec* t = *appListItr;
1160                 //cout << "t = " << t << endl;
1161                 //cout << "Checking " << t->plane.callsign << endl;
1162                 if(t->isUser) {
1163                         t->pos.setlon(user_lon_node->getDoubleValue());
1164                         t->pos.setlat(user_lat_node->getDoubleValue());
1165                         t->pos.setelev(user_elev_node->getDoubleValue());
1166                 } else {
1167                         // TODO - set/update the position if it's an AI plane
1168                 }
1169                 //cout << "eta is " << t->eta << ", rwy is " << (rwyList.size() ? "occupied " : "clear ") << '\n';
1170                 if(t->eta < 12 && rwyList.size() && !(t->instructedToGoAround)) {
1171                         // TODO - need to make this more sophisticated 
1172                         // eg. is the plane accelerating down the runway taking off [OK],
1173                         // or stationary near the start [V. BAD!!].
1174                         // For now this should stop the AI plane landing on top of the user.
1175                         string trns = t->plane.callsign;
1176                         trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
1177                         pending_transmission = trns;
1178                         ImmediateTransmit();
1179                         t->instructedToGoAround = true;
1180                         t->clearedToLand = false;
1181                         t->nextOnRwy = false;   // But note this is recalculated so don't rely on it
1182                         // Assume it complies!!!
1183                         t->opType = CIRCUIT;
1184                         t->leg = CLIMBOUT;
1185                         if(!t->isUser) {
1186                                 if(t->planePtr) {
1187                                         //cout << "Registering Go-around transmission with AI plane\n";
1188                                         t->planePtr->RegisterTransmission(13);
1189                                 }
1190                         } else {
1191                                 // TODO - add Go-around ack to comm options,
1192                                 // remove report rwy vacated. (possibly).
1193                         }
1194                 }                               
1195                 if(t->nextOnRwy && !(t->clearedToLand) && !(t->instructedToGoAround)) {
1196                         // check distance away and whether runway occupied
1197                         // and schedule transmission if necessary
1198                 }
1199                 
1200                 // Check for landing...
1201                 bool landed = false;
1202                 if(!t->isUser) {
1203                         if(t->planePtr) {
1204                                 if(t->planePtr->GetLeg() == LANDING_ROLL) {
1205                                         landed = true;
1206                                 }
1207                         } else {
1208                                 SG_LOG(SG_ATC, SG_ALERT, "WARNING - not user and null planePtr in CheckApproachList!");
1209                         }
1210                 } else {        // user
1211                         if(OnActiveRunway(t->pos)) {
1212                                 landed = true;
1213                         }
1214                 }
1215                 
1216                 if(landed) {
1217                         // Duplicated in CheckCircuitList - must be able to rationalise this somehow!
1218                         //cout << "A " << t->plane.callsign << " has landed, adding to rwyList...\n";
1219                         rwyList.push_front(t);
1220                         // TODO - if(!clearedToLand) shout something!!
1221                         t->clearedToLand = false;
1222                         RemoveFromTrafficList(t->plane.callsign);
1223                         //if(t->isUser) {
1224                                 //      t->opType = TTT_UNKNOWN;
1225                         //}     // TODO - allow the user to specify opType via ATC menu
1226                         appListItr = appList.erase(appListItr);
1227                         if(appListItr == appList.end() ) {
1228                                 appListItr = appList.begin();
1229                         }
1230                 }
1231                 
1232                 ++appListItr;
1233         }
1234         //cout << "Done" << endl;
1235 }
1236
1237 // Do one plane from the departure list
1238 void FGTower::CheckDepartureList(double dt) {
1239         if(depList.size()) {
1240                 if(depListItr == depList.end()) {
1241                         depListItr = depList.begin();
1242                 }
1243                 TowerPlaneRec* t = *depListItr;
1244                 //cout << "Dep list, checking " << t->plane.callsign;
1245                 
1246                 double distout; // meters
1247                 if(t->isUser) distout = dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
1248                 else distout = dclGetHorizontalSeparation(Point3D(lon, lat, elev), t->planePtr->GetPos());
1249                 //cout << " distout = " << distout << '\n';
1250                 if(distout > 10000) {
1251                         string trns = t->plane.callsign;
1252                         trns += " You are now clear of my airspace, good day";
1253                         pending_transmission = trns;
1254                         Transmit();
1255                         if(t->isUser) {
1256                                 // Change the communication options
1257                                 RemoveAllUserDialogOptions();
1258                                 //cout << "ADD A\n";
1259                                 current_atcdialog->add_entry(ident, "@AP Tower @CS @MI miles @CD of the airport for full stop with the ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
1260                         } else {
1261                                 // Send a clear-of-airspace signal
1262                                 // TODO - implement this once we actually have departing AI traffic (currently all circuits or arrivals).
1263                         }
1264                         RemovePlane(t->plane.callsign);
1265                 } else {
1266                         ++depListItr;
1267                 }
1268         }
1269 }
1270
1271 // ********** End periodic check functions ***********************************************
1272 // ***************************************************************************************
1273
1274
1275 // Remove all dialog options for this tower.
1276 void FGTower::RemoveAllUserDialogOptions() {
1277         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_DEPARTURE, TOWER);
1278         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
1279         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
1280         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
1281         current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
1282         current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
1283         current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
1284         current_atcdialog->remove_entry(ident, USER_REPORT_GOING_AROUND, TOWER);        
1285 }
1286
1287 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
1288 // plus the constraint position as a rwy orientated orthopos (meters)
1289 bool FGTower::GetCrosswindConstraint(double& cpos) {
1290         if(crosswind_leg_pos != 0.0) {
1291                 cpos = crosswind_leg_pos;
1292                 return(true);
1293         } else {
1294                 cpos = 0.0;
1295                 return(false);
1296         }
1297 }
1298 bool FGTower::GetDownwindConstraint(double& dpos) {
1299         if(fabs(downwind_leg_pos) > nominal_downwind_leg_pos) {
1300                 dpos = downwind_leg_pos;
1301                 return(true);
1302         } else {
1303                 dpos = 0.0;
1304                 return(false);
1305         }
1306 }
1307 bool FGTower::GetBaseConstraint(double& bpos) {
1308         if(base_leg_pos < nominal_base_leg_pos) {
1309                 bpos = base_leg_pos;
1310                 return(true);
1311         } else {
1312                 bpos = nominal_base_leg_pos;
1313                 return(false);
1314         }
1315 }
1316
1317
1318 // Figure out which runways are active.
1319 // For now we'll just be simple and do one active runway - eventually this will get much more complex
1320 // This is a private function - public interface to the results of this is through GetActiveRunway
1321 void FGTower::DoRwyDetails() {
1322         //cout << "GetRwyDetails called" << endl;
1323         
1324         // Based on the airport-id and wind get the active runway
1325         
1326         //wind
1327         double hdg = wind_from_hdg->getDoubleValue();
1328         double speed = wind_speed_knots->getDoubleValue();
1329         hdg = (speed == 0.0 ? 270.0 : hdg);
1330         //cout << "Heading = " << hdg << '\n';
1331         
1332         FGRunway runway;
1333         bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
1334         if(rwyGood) {
1335                 //cout << "RUNWAY GOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOD\n";
1336                 activeRwy = runway.rwy_no;
1337                 rwy.rwyID = runway.rwy_no;
1338                 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
1339                 
1340                 // Get the threshold position
1341                 double other_way = runway.heading - 180.0;
1342                 while(other_way <= 0.0) {
1343                         other_way += 360.0;
1344                 }
1345         // move to the +l end/center of the runway
1346                 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
1347         Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
1348                 Point3D ref = origin;
1349         double tshlon, tshlat, tshr;
1350                 double tolon, tolat, tor;
1351                 rwy.length = runway.length * SG_FEET_TO_METER;
1352                 rwy.width = runway.width * SG_FEET_TO_METER;
1353         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
1354                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
1355         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading, 
1356                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
1357                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
1358                 // now copy what we need out of runway into rwy
1359         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
1360                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
1361                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
1362                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
1363                 rwy.hdg = runway.heading;
1364                 // Set the projection for the local area based on this active runway
1365                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
1366                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
1367                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
1368                 
1369                 // Set the pattern direction
1370                 // TODO - we'll check for a facilities file with this in eventually - for now assume left traffic except
1371                 // for certain circumstances (RH parallel rwy).
1372                 rwy.patternDirection = -1;              // Left
1373                 if(rwy.rwyID.size() == 3) {
1374                         rwy.patternDirection = (rwy.rwyID.substr(2,1) == "R" ? 1 : -1);
1375                 }
1376                 //cout << "Doing details, rwy.patterDirection is " << rwy.patternDirection << '\n';
1377         } else {
1378                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
1379                 activeRwy = "NN";
1380         }
1381 }
1382
1383
1384 // Figure out if a given position lies on the active runway
1385 // Might have to change when we consider more than one active rwy.
1386 bool FGTower::OnActiveRunway(Point3D pt) {
1387         // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
1388         Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
1389         Point3D xyp = ortho.ConvertToLocal(pt);
1390         
1391         //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
1392         //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
1393
1394         double rlen = rwy.length/2.0 + 5.0;
1395         double rwidth = rwy.width/2.0;
1396         double ldiff = fabs(xyp.y() - xyc.y());
1397         double wdiff = fabs(xyp.x() - xyc.x());
1398
1399         return((ldiff < rlen) && (wdiff < rwidth));
1400 }       
1401
1402
1403 // Figure out if a given position lies on any runway or not
1404 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
1405 bool FGTower::OnAnyRunway(Point3D pt) {
1406         ATCData ad;
1407         double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
1408         if(dist < 0.0) {
1409                 return(false);
1410         }
1411         // Based on the airport-id, go through all the runways and check for a point in them
1412         
1413         // TODO - do we actually need to search for the airport - surely we already know our ident and
1414         // can just search runways of our airport???
1415         //cout << "Airport ident is " << ad.ident << '\n';
1416         FGRunway runway;
1417         bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
1418         if(!rwyGood) {
1419                 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
1420         }
1421         bool on = false;
1422         while(runway.id == ad.ident) {          
1423                 on = OnRunway(pt, runway);
1424                 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
1425                 if(on) return(true);
1426                 globals->get_runways()->next(&runway);          
1427         }
1428         return(on);
1429 }
1430
1431
1432 // Returns true if successful
1433 bool FGTower::RemoveFromTrafficList(string id) {
1434         tower_plane_rec_list_iterator twrItr;
1435         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1436                 TowerPlaneRec* tpr = *twrItr;
1437                 if(tpr->plane.callsign == id) {
1438                         trafficList.erase(twrItr);
1439                         trafficListItr = trafficList.begin();
1440                         return(true);
1441                 }
1442         }       
1443         SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
1444         return(false);
1445 }
1446
1447
1448 // Returns true if successful
1449 bool FGTower::RemoveFromAppList(string id) {
1450         tower_plane_rec_list_iterator twrItr;
1451         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1452                 TowerPlaneRec* tpr = *twrItr;
1453                 if(tpr->plane.callsign == id) {
1454                         appList.erase(twrItr);
1455                         appListItr = appList.begin();
1456                         return(true);
1457                 }
1458         }       
1459         //SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from appList in FGTower");
1460         return(false);
1461 }
1462
1463 // Returns true if successful
1464 bool FGTower::RemoveFromRwyList(string id) {
1465         tower_plane_rec_list_iterator twrItr;
1466         for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
1467                 TowerPlaneRec* tpr = *twrItr;
1468                 if(tpr->plane.callsign == id) {
1469                         rwyList.erase(twrItr);
1470                         rwyListItr = rwyList.begin();
1471                         return(true);
1472                 }
1473         }       
1474         //SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from rwyList in FGTower");
1475         return(false);
1476 }
1477
1478
1479 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
1480 // and set nextOnRwy if so.
1481 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
1482 // For planes holding they are put in the first position with time to go, and the return value is
1483 // true if in the first position (nextOnRwy) and false otherwise.
1484 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
1485 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
1486         //cout << "ADD: " << trafficList.size();
1487         //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << endl;
1488         double separation_time = 90.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.
1489         double departure_sep_time = 60.0;       // Separation time behind departing airplanes.  Comments above also apply.
1490         bool conflict = false;
1491         double lastETA = 0.0;
1492         bool firstTime = true;
1493         // FIXME - make this more robust for different plane types eg. light following heavy.
1494         tower_plane_rec_list_iterator twrItr;
1495         //twrItr = trafficList.begin();
1496         //while(1) {
1497         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1498                 //if(twrItr == trafficList.end()) {
1499                 //      cout << "  END  ";
1500                 //      trafficList.push_back(t);
1501                 //      return(holding ? firstTime : conflict);
1502                 //} else {
1503                         TowerPlaneRec* tpr = *twrItr;
1504                         if(holding) {
1505                                 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
1506                                 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
1507                                 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0); 
1508                                 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
1509                                 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
1510                                 // and if not needs time to clear the rwy anyway.
1511                                 if(tpr->eta  - lastETA > slot_time) {
1512                                         t->nextOnRwy = firstTime;
1513                                         trafficList.insert(twrItr, t);
1514                                         //cout << "\tH\t" << trafficList.size() << '\n';
1515                                         return(firstTime);
1516                                 }
1517                                 firstTime = false;
1518                         } else {
1519                                 if(t->eta < tpr->eta) {
1520                                         // Ugg - this one's tricky.
1521                                         // It depends on what the two planes are doing and whether there's a conflict what we do.
1522                                         if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1523                                                 if(tpr->nextOnRwy) {
1524                                                         tpr->nextOnRwy = false;
1525                                                         t->nextOnRwy = true;
1526                                                 }
1527                                                 trafficList.insert(twrItr, t);
1528                                         } else {        // Ooops - this ones tricky - we have a potential conflict!
1529                                                 conflict = true;
1530                                                 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
1531                                                 if(tpr->nextOnRwy) {
1532                                                         tpr->nextOnRwy = false;
1533                                                         t->nextOnRwy = true;
1534                                                 }
1535                                                 trafficList.insert(twrItr, t);
1536                                         }
1537                                         //cout << "\tC\t" << trafficList.size() << '\n';
1538                                         return(conflict);
1539                                 }
1540                         }
1541                 //}
1542                 //++twrItr;
1543         }
1544         // If we get here we must be at the end of the list, or maybe the list is empty.
1545         if(!trafficList.size()) {
1546                 t->nextOnRwy = true;
1547                 // conflict and firstTime should be false and true respectively in this case anyway.
1548         } else {
1549                 t->nextOnRwy = false;
1550         }
1551         trafficList.push_back(t);
1552         //cout << "\tE\t" << trafficList.size() << endl;
1553         return(holding ? firstTime : conflict);
1554 }
1555
1556 // Add a tower plane rec with ETA to the circuit list in the correct position ETA-wise
1557 // Returns true if this might cause a separation conflict (based on ETA) with other traffic, false otherwise.
1558 // Safe to add a plane that is already in - planes with the same callsign are not added.
1559 bool FGTower::AddToCircuitList(TowerPlaneRec* t) {
1560         if(!t) {
1561                 //cout << "**********************************************\n";
1562                 //cout << "AddToCircuitList called with NULL pointer!!!!!\n";
1563                 //cout << "**********************************************\n";
1564                 return false;
1565         }
1566         //cout << "ADD: " << circuitList.size();
1567         //cout << ident << " AddToCircuitList called for " << t->plane.callsign << ", currently size = " << circuitList.size() << endl;
1568         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.
1569         bool conflict = false;
1570         tower_plane_rec_list_iterator twrItr;
1571         // First check if the plane is already in the list
1572         //cout << "A" << endl;
1573         //cout << "Checking whether " << t->plane.callsign << " is already in circuit list..." << endl;
1574         //cout << "B" << endl;
1575         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1576                 if((*twrItr)->plane.callsign == t->plane.callsign) {
1577                         //cout << "In list - returning...\n";
1578                         return false;
1579                 }
1580         }
1581         //cout << "Not in list - adding..." << endl;
1582         
1583         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1584                 TowerPlaneRec* tpr = *twrItr;
1585                 //cout << tpr->plane.callsign << " eta is " << tpr->eta << '\n';
1586                 //cout << "New eta is " << t->eta << '\n';              
1587                 if(t->eta < tpr->eta) {
1588                         // Ugg - this one's tricky.
1589                         // It depends on what the two planes are doing and whether there's a conflict what we do.
1590                         if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1591                                 circuitList.insert(twrItr, t);
1592                         } else {        // Ooops - this ones tricky - we have a potential conflict!
1593                                 conflict = true;
1594                                 // HACK - just add anyway for now and flag conflict.
1595                                 circuitList.insert(twrItr, t);
1596                         }
1597                         //cout << "\tC\t" << circuitList.size() << '\n';
1598                         return(conflict);
1599                 }
1600         }
1601         // If we get here we must be at the end of the list, or maybe the list is empty.
1602         //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1603         circuitList.push_back(t);       // TODO - check the separation with the preceding plane for the conflict flag.
1604         //cout << "\tE\t" << circuitList.size() << endl;
1605         return(conflict);
1606 }
1607
1608 // Add to vacated list only if not already present
1609 void FGTower::AddToVacatedList(TowerPlaneRec* t) {
1610         tower_plane_rec_list_iterator twrItr;
1611         bool found = false;
1612         for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
1613                 if((*twrItr)->plane.callsign == t->plane.callsign) {
1614                         found = true;
1615                 }
1616         }
1617         if(found) return;
1618         vacatedList.push_back(t);
1619 }
1620
1621
1622 // Calculate the eta of a plane to the threshold.
1623 // For ground traffic this is the fastest they can get there.
1624 // For air traffic this is the middle approximation.
1625 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1626         // For now we'll be very crude and hardwire expected speeds to C172-like values
1627         // The speeds below are specified in knots IAS and then converted to m/s
1628         double app_ias = 100.0 * 0.514444;                      // Speed during straight-in approach
1629         double circuit_ias = 80.0 * 0.514444;           // Speed around circuit
1630         double final_ias = 70.0 * 0.514444;             // Speed during final approach
1631         
1632         //if(printout) {
1633         //cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1634         //cout << (tpr->isUser ? "USER\n" : "AI\n");
1635         //cout << flush;
1636         //}
1637         
1638         // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1639         // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1640         
1641         Point3D op = ortho.ConvertToLocal(tpr->pos);
1642         //if(printout) {
1643         //if(!tpr->isUser) cout << "Orthopos is " << op.x() << ", " << op.y() << ' ';
1644         //cout << "opType is " << tpr->opType << '\n';
1645         //}
1646         double dist_out_m = op.y();
1647         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
1648         //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1649         
1650         if(tpr->opType == STRAIGHT_IN || tpr->opType == INBOUND) {
1651                 //cout << "CASE 1\n";
1652                 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1653                 if(dist_to_go_m < 1000) {
1654                         tpr->eta = dist_to_go_m / final_ias;
1655                 } else {
1656                         tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1657                 }
1658         } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) {       // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1659                 //cout << "CASE 2\n";
1660                 // It's complicated - depends on if base leg is delayed or not
1661                 //if(printout) {
1662                 //cout << "Leg = " << tpr->leg << '\n';
1663                 //}
1664                 if(tpr->leg == LANDING_ROLL) {
1665                         tpr->eta = 0;
1666                 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1667                         //cout << "dist_out_m = " << dist_out_m << '\n';
1668                         tpr->eta = fabs(dist_out_m) / final_ias;
1669                 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1670                         tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1671                 } else {
1672                         // Need to calculate where base leg is likely to be
1673                         // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1674                         // TODO - as a matter of design - AILocalTraffic should get the nominal no-traffic base turn distance from Tower, since in real life the published pattern might differ from airport to airport
1675                         double nominal_base_dist_out_m = -1000;
1676                         double current_base_dist_out_m;
1677                         if(!GetBaseConstraint(current_base_dist_out_m)) {
1678                                 current_base_dist_out_m = nominal_base_dist_out_m;
1679                         }
1680                         //cout << "current_base_dist_out_m = " << current_base_dist_out_m << '\n';
1681                         double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
1682                         double current_dist_across_m;
1683                         if(!GetDownwindConstraint(current_dist_across_m)) {
1684                                 current_dist_across_m = nominal_dist_across_m;
1685                         }
1686                         double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 700ft agl.
1687                         tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
1688                         //cout << "a = " << tpr->eta << '\n';
1689                         if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1690                                 tpr->eta += dist_across_m / circuit_ias;
1691                                 //cout << "b = " << tpr->eta << '\n';
1692                                 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1693                                 //cout << "c = " << tpr->eta << '\n';
1694                         } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1695                                 //cout << "CROSSWIND calc: ";
1696                                 //cout << tpr->eta << ' ';
1697                                 if(dist_across_m > nominal_dist_across_m) {
1698                                         tpr->eta += dist_across_m / circuit_ias;
1699                                         //cout << "a ";
1700                                 } else {
1701                                         tpr->eta += nominal_dist_across_m / circuit_ias;
1702                                         //cout << "b ";
1703                                 }
1704                                 //cout << tpr->eta << ' ';
1705                                 // should we use the dist across of the previous plane if there is previous still on downwind?
1706                                 //if(printout) cout << "bb = " << tpr->eta << '\n';
1707                                 if(dist_out_m > nominal_cross_dist_out_m) {
1708                                         tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1709                                         //cout << "c ";
1710                                 } else {
1711                                         tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1712                                         //cout << "d ";
1713                                 }
1714                                 //cout << tpr->eta << ' ';
1715                                 //if(printout) cout << "cc = " << tpr->eta << '\n';
1716                                 if(nominal_dist_across_m > dist_across_m) {
1717                                         tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1718                                         //cout << "e ";
1719                                 } else {
1720                                         // Nothing to add
1721                                         //cout << "f ";
1722                                 }
1723                                 //cout << tpr->eta << '\n';
1724                                 //if(printout) cout << "dd = " << tpr->eta << '\n';
1725                         } else {
1726                                 // We've only just started - why not use a generic estimate?
1727                                 tpr->eta = 240.0;
1728                         }
1729                 }
1730                 //if(printout) {
1731                 //      cout << "ETA = " << tpr->eta << '\n';
1732                 //}
1733                 //if(!tpr->isUser) cout << tpr->plane.callsign << '\t' << tpr->eta << '\n';
1734         } else {
1735                 tpr->eta = 99999;
1736         }       
1737 }
1738
1739
1740 // Calculate the distance of a plane to the threshold in meters
1741 // TODO - Modify to calculate flying distance of a plane in the circuit
1742 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1743         return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1744 }
1745
1746
1747 // Calculate the distance of a plane to the threshold in miles
1748 // TODO - Modify to calculate flying distance of a plane in the circuit
1749 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1750         return(CalcDistOutM(tpr) / 1600.0);             // FIXME - use a proper constant if possible.
1751 }
1752
1753
1754 // Iterate through all the lists, update the position of, and call CalcETA for all the planes.
1755 void FGTower::doThresholdETACalc() {
1756         //cout << "Entering doThresholdETACalc..." << endl;
1757         tower_plane_rec_list_iterator twrItr;
1758         // Do the approach list first
1759         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1760                 TowerPlaneRec* tpr = *twrItr;
1761                 if(!(tpr->isUser)) tpr->pos = tpr->planePtr->GetPos();
1762                 //cout << "APP: ";
1763                 CalcETA(tpr);
1764         }       
1765         // Then the circuit list
1766         //cout << "Circuit list size is " << circuitList.size() << '\n';
1767         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1768                 TowerPlaneRec* tpr = *twrItr;
1769                 if(!(tpr->isUser)) tpr->pos = tpr->planePtr->GetPos();
1770                 //cout << "CIRC: ";
1771                 CalcETA(tpr);
1772         }
1773         //cout << "Done doThresholdETCCalc" << endl;
1774 }
1775                 
1776
1777 // Check that the planes in traffic list are correctly ordered,
1778 // that the nearest (timewise) is flagged next on rwy, and return
1779 // true if any threshold use conflicts are detected, false otherwise.
1780 bool FGTower::doThresholdUseOrder() {
1781         //cout << "Entering doThresholdUseOrder..." << endl;
1782         bool conflict = false;
1783         
1784         // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1785         // Here's the rather simplistic assumptions we're using:
1786         // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1787         // In order of priority for runway use:
1788         // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1789         // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1790         // and holding planes until a space.
1791         // When calculating if a holding plane can use the runway, time clearance from last departure
1792         // as well as time clearance to next arrival must be considered.
1793         
1794         trafficList.clear();
1795         
1796         tower_plane_rec_list_iterator twrItr;
1797         // Do the approach list first
1798         //if(ident == "KRHV") cout << "A" << flush;
1799         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1800                 TowerPlaneRec* tpr = *twrItr;
1801                 //if(ident == "KRHV") cout << tpr->plane.callsign << '\n';
1802                 conflict = AddToTrafficList(tpr);
1803         }       
1804         // Then the circuit list
1805         //if(ident == "KRHV") cout << "C" << flush;
1806         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1807                 TowerPlaneRec* tpr = *twrItr;
1808                 //if(ident == "KRHV") cout << tpr->plane.callsign << '\n';
1809                 conflict = AddToTrafficList(tpr);
1810         }
1811         // And finally the hold list
1812         //cout << "H" << endl;
1813         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1814                 TowerPlaneRec* tpr = *twrItr;
1815                 AddToTrafficList(tpr, true);
1816         }
1817         
1818         
1819         if(0) {
1820         //if(ident == "KRHV") {
1821                 cout << "T\n";
1822                 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1823                         TowerPlaneRec* tpr = *twrItr;
1824                         cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1825                 }
1826                 cout << endl;
1827         }
1828         
1829         //cout << "Done doThresholdUseOrder" << endl;
1830         return(conflict);
1831 }
1832
1833
1834 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1835 // i.e. list_pos = 1 implies next to use runway.
1836 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1837         if(trafficList.size() < list_pos) {
1838                 return(99999);
1839         }
1840
1841         tower_plane_rec_list_iterator twrItr;
1842         twrItr = trafficList.begin();
1843         for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1844         TowerPlaneRec* tpr = *twrItr;
1845         CalcETA(tpr, printout);
1846         //cout << "ETA returned = " << tpr->eta << '\n';
1847         return(tpr->eta);
1848 }
1849         
1850
1851 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1852         // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1853         TowerPlaneRec* t = new TowerPlaneRec;
1854         t->plane = plane;
1855         t->planePtr = requestee;
1856         t->holdShortReported = true;
1857         t->clearedToLineUp = false;
1858         t->clearedToTakeOff = false;
1859         t->opType = operation;
1860         t->pos = requestee->GetPos();
1861         
1862         //cout << "Hold Short reported by " << plane.callsign << '\n';
1863         SG_LOG(SG_ATC, SG_BULK, "Hold Short reported by " << plane.callsign);
1864
1865 /*      
1866         bool next = AddToTrafficList(t, true);
1867         if(next) {
1868                 double teta = GetTrafficETA(2);
1869                 if(teta < 150.0) {
1870                         t->clearanceCounter = 7.0;      // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1871                         //cout << "Reducing response time to request due imminent traffic\n";
1872                 }
1873         } else {
1874         }
1875 */
1876         // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme
1877
1878         holdList.push_back(t);
1879         
1880         responseReqd = true;
1881 }
1882
1883 // Register the presence of an AI plane at a point where contact would already have been made in real life
1884 // CAUTION - currently it is assumed that this plane's callsign is unique - it is up to AIMgr to generate unique callsigns.
1885 void FGTower::RegisterAIPlane(PlaneRec plane, FGAIPlane* ai, tower_traffic_type op, PatternLeg lg) {
1886         // At the moment this is only going to be tested with inserting an AI plane on downwind
1887         TowerPlaneRec* t = new TowerPlaneRec;
1888         t->plane = plane;
1889         t->planePtr = ai;
1890         t->opType = op;
1891         t->leg = lg;
1892         t->pos = ai->GetPos();
1893         
1894         CalcETA(t);
1895         
1896         if(op == CIRCUIT && lg != LEG_UNKNOWN) {
1897                 AddToCircuitList(t);
1898         } else {
1899                 // FLAG A WARNING
1900         }
1901         
1902         doThresholdUseOrder();
1903 }
1904
1905 void FGTower::DeregisterAIPlane(string id) {
1906         RemovePlane(id);
1907 }
1908
1909 // Contact tower for VFR approach
1910 // eg "Cessna Charlie Foxtrot Golf Foxtrot Sierra eight miles South of the airport for full stop with Bravo"
1911 // This function probably only called via user interaction - AI planes will have an overloaded function taking a planerec.
1912 // opt defaults to AIP_LT_UNKNOWN
1913 void FGTower::VFRArrivalContact(string ID, LandingType opt) {
1914         //cout << "USER Request Landing Clearance called for ID " << ID << '\n';
1915         
1916         // For now we'll assume that the user is a light plane and can get him/her to join the circuit if necessary.
1917
1918         TowerPlaneRec* t;       
1919         string usercall = fgGetString("/sim/user/callsign");
1920         if(ID == "USER" || ID == usercall) {
1921                 t = FindPlane(usercall);
1922                 if(!t) {
1923                         //cout << "NOT t\n";
1924                         t = new TowerPlaneRec;
1925                         t->isUser = true;
1926                         t->pos.setlon(user_lon_node->getDoubleValue());
1927                         t->pos.setlat(user_lat_node->getDoubleValue());
1928                         t->pos.setelev(user_elev_node->getDoubleValue());
1929                 } else {
1930                         //cout << "IS t\n";
1931                         // Oops - the plane is already registered with this tower - maybe we took off and flew a giant circuit without
1932                         // quite getting out of tower airspace - just ignore for now and treat as new arrival.
1933                         // TODO - Maybe should remove from departure and circuit list if in there though!!
1934                 }
1935         } else {
1936                 // Oops - something has gone wrong - put out a warning
1937                 cout << "WARNING - FGTower::VFRContact(string ID, LandingType lt) called with ID " << ID << " which does not appear to be the user.\n";
1938                 return;
1939         }
1940                 
1941         
1942         // TODO
1943         // Calculate where the plane is in relation to the active runway and it's circuit
1944         // and set the op-type as appropriate.
1945         
1946         // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1947         t->opType = STRAIGHT_IN;
1948         
1949         t->plane.type = GA_SINGLE;      // FIXME - Another assumption!
1950         t->plane.callsign = usercall;
1951         
1952         t->vfrArrivalReported = true;
1953         responseReqd = true;
1954         
1955         appList.push_back(t);   // Not necessarily permanent
1956         AddToTrafficList(t);
1957         
1958         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
1959         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
1960         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
1961 }
1962
1963 // landingType defaults to AIP_LT_UNKNOWN
1964 void FGTower::VFRArrivalContact(PlaneRec plane, FGAIPlane* requestee, LandingType lt) {
1965         //cout << "VFRArrivalContact called for plane " << plane.callsign << " at " << ident << '\n';
1966         // Possible hack - assume this plane is new for now - TODO - should check really
1967         TowerPlaneRec* t = new TowerPlaneRec;
1968         t->plane = plane;
1969         t->planePtr = requestee;
1970         t->landingType = lt;
1971         t->pos = requestee->GetPos();
1972         
1973         //cout << "Hold Short reported by " << plane.callsign << '\n';
1974         SG_LOG(SG_ATC, SG_BULK, "VFR arrival contact made by " << plane.callsign);
1975         //cout << "VFR arrival contact made by " << plane.callsign << '\n';
1976
1977         // HACK - to get up and running I'm going to assume a staight-in final for now.
1978         t->opType = STRAIGHT_IN;
1979         
1980         t->vfrArrivalReported = true;
1981         responseReqd = true;
1982         
1983         //cout << "Before adding, appList.size = " << appList.size() << " at " << ident << '\n';
1984         appList.push_back(t);   // Not necessarily permanent
1985         //cout << "After adding, appList.size = " << appList.size() << " at " << ident << '\n';
1986         AddToTrafficList(t);
1987 }
1988
1989 void FGTower::RequestDepartureClearance(string ID) {
1990         //cout << "Request Departure Clearance called...\n";
1991 }
1992         
1993 void FGTower::ReportFinal(string ID) {
1994         //cout << "Report Final Called at tower " << ident << " by plane " << ID << '\n';
1995         if(ID == "USER") {
1996                 ID = fgGetString("/sim/user/callsign");
1997                 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
1998         }
1999         TowerPlaneRec* t = FindPlane(ID);
2000         if(t) {
2001                 t->finalReported = true;
2002                 t->finalAcknowledged = false;
2003                 if(!(t->clearedToLand)) {
2004                         responseReqd = true;
2005                 } else {
2006                         // possibly respond with wind even if already cleared to land?
2007                         t->finalReported = false;
2008                         t->finalAcknowledged = true;
2009                         // HACK!! - prevents next reporting being misinterpreted as this one.
2010                 }
2011         } else {
2012                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportFinal(...)");
2013         }
2014 }
2015
2016 void FGTower::ReportLongFinal(string ID) {
2017         if(ID == "USER") {
2018                 ID = fgGetString("/sim/user/callsign");
2019                 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
2020         }
2021         TowerPlaneRec* t = FindPlane(ID);
2022         if(t) {
2023                 t->longFinalReported = true;
2024                 t->longFinalAcknowledged = false;
2025                 if(!(t->clearedToLand)) {
2026                         responseReqd = true;
2027                 } // possibly respond with wind even if already cleared to land?
2028         } else {
2029                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportLongFinal(...)");
2030         }
2031 }
2032
2033 //void FGTower::ReportOuterMarker(string ID);
2034 //void FGTower::ReportMiddleMarker(string ID);
2035 //void FGTower::ReportInnerMarker(string ID);
2036
2037 void FGTower::ReportRunwayVacated(string ID) {
2038         //cout << "Report Runway Vacated Called at tower " << ident << " by plane " << ID << '\n';
2039         if(ID == "USER") {
2040                 ID = fgGetString("/sim/user/callsign");
2041                 current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
2042         }
2043         TowerPlaneRec* t = FindPlane(ID);
2044         if(t) {
2045                 //cout << "Found it...\n";
2046                 t->rwyVacatedReported = true;
2047                 responseReqd = true;
2048         } else {
2049                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
2050                 SG_LOG(SG_ATC, SG_ALERT, "A WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
2051                 //cout << "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)\n";
2052         }
2053 }
2054
2055 TowerPlaneRec* FGTower::FindPlane(string ID) {
2056         //cout << "FindPlane called for " << ID << "...\n";
2057         tower_plane_rec_list_iterator twrItr;
2058         // Do the approach list first
2059         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
2060                 //cout << "appList callsign is " << (*twrItr)->plane.callsign << '\n';
2061                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2062         }       
2063         // Then the circuit list
2064         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
2065                 //cout << "circuitList callsign is " << (*twrItr)->plane.callsign << '\n';
2066                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2067         }
2068         // Then the runway list
2069         //cout << "rwyList.size() is " << rwyList.size() << '\n';
2070         for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
2071                 //cout << "rwyList callsign is " << (*twrItr)->plane.callsign << '\n';
2072                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2073         }
2074         // The hold list
2075         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
2076                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2077         }
2078         // And finally the vacated list
2079         for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
2080                 //cout << "vacatedList callsign is " << (*twrItr)->plane.callsign << '\n';
2081                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2082         }
2083         SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
2084         //exit(-1);
2085         return(NULL);
2086 }
2087
2088 void FGTower::RemovePlane(string ID) {
2089         //cout << ident << " RemovePlane called for " << ID << '\n';
2090         // We have to be careful here - we want to erase the plane from all lists it is in,
2091         // but we can only delete it once, AT THE END.
2092         TowerPlaneRec* t = NULL;
2093         tower_plane_rec_list_iterator twrItr;
2094         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
2095                 if((*twrItr)->plane.callsign == ID) {
2096                         t = *twrItr;
2097                         twrItr = appList.erase(twrItr);
2098                         appListItr = appList.begin();
2099                 }
2100         }
2101         for(twrItr = depList.begin(); twrItr != depList.end(); twrItr++) {
2102                 if((*twrItr)->plane.callsign == ID) {
2103                         t = *twrItr;
2104                         twrItr = depList.erase(twrItr);
2105                         depListItr = depList.begin();
2106                 }
2107         }
2108         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
2109                 if((*twrItr)->plane.callsign == ID) {
2110                         t = *twrItr;
2111                         twrItr = circuitList.erase(twrItr);
2112                         circuitListItr = circuitList.begin();
2113                 }
2114         }
2115         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
2116                 if((*twrItr)->plane.callsign == ID) {
2117                         t = *twrItr;
2118                         twrItr = holdList.erase(twrItr);
2119                         holdListItr = holdList.begin();
2120                 }
2121         }
2122         for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
2123                 if((*twrItr)->plane.callsign == ID) {
2124                         t = *twrItr;
2125                         twrItr = rwyList.erase(twrItr);
2126                         rwyListItr = rwyList.begin();
2127                 }
2128         }
2129         for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
2130                 if((*twrItr)->plane.callsign == ID) {
2131                         t = *twrItr;
2132                         twrItr = vacatedList.erase(twrItr);
2133                         vacatedListItr = vacatedList.begin();
2134                 }
2135         }
2136         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
2137                 if((*twrItr)->plane.callsign == ID) {
2138                         t = *twrItr;
2139                         twrItr = trafficList.erase(twrItr);
2140                         trafficListItr = trafficList.begin();
2141                 }
2142         }
2143         // And finally, delete the record if we found it.
2144         if(t) delete t;
2145 }
2146
2147 void FGTower::ReportDownwind(string ID) {
2148         //cout << "ReportDownwind(...) called\n";
2149         if(ID == "USER") {
2150                 ID = fgGetString("/sim/user/callsign");
2151                 current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
2152         }
2153         TowerPlaneRec* t = FindPlane(ID);
2154         if(t) {
2155                 t->downwindReported = true;
2156                 responseReqd = true;
2157                 // If the plane is in the app list, remove it and put it in the circuit list instead.
2158                 // Ideally we might want to do this at the 2 mile report prior to 45 deg entry, but at
2159                 // the moment that would b&gg?r up the constraint position calculations.
2160                 RemoveFromAppList(ID);
2161                 t->leg = DOWNWIND;
2162                 if(t->isUser) {
2163                         t->pos.setlon(user_lon_node->getDoubleValue());
2164                         t->pos.setlat(user_lat_node->getDoubleValue());
2165                         t->pos.setelev(user_elev_node->getDoubleValue());
2166                 } else {
2167                         // ASSERT(t->planePtr != NULL);
2168                         t->pos = t->planePtr->GetPos();
2169                 }
2170                 CalcETA(t);
2171                 AddToCircuitList(t);
2172         } else {
2173                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
2174         }
2175 }
2176
2177 void FGTower::ReportGoingAround(string ID) {
2178         if(ID == "USER") {
2179                 ID = fgGetString("/sim/user/callsign");
2180                 RemoveAllUserDialogOptions();   // TODO - it would be much more efficient if ATCDialog simply had a clear() function!!!
2181                 current_atcdialog->add_entry(ident, "@AP Tower @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
2182         }
2183         TowerPlaneRec* t = FindPlane(ID);
2184         if(t) {
2185                 //t->goAroundReported = true;  // No need to set this until we start responding to it.
2186                 responseReqd = false;   // might change in the future but for now we'll not distract them during the go-around.
2187                 // If the plane is in the app list, remove it and put it in the circuit list instead.
2188                 RemoveFromAppList(ID);
2189                 t->leg = CLIMBOUT;
2190                 if(t->isUser) {
2191                         t->pos.setlon(user_lon_node->getDoubleValue());
2192                         t->pos.setlat(user_lat_node->getDoubleValue());
2193                         t->pos.setelev(user_elev_node->getDoubleValue());
2194                 } else {
2195                         // ASSERT(t->planePtr != NULL);
2196                         t->pos = t->planePtr->GetPos();
2197                 }
2198                 CalcETA(t);
2199                 AddToCircuitList(t);
2200         } else {
2201                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
2202         }
2203 }
2204
2205 string FGTower::GenText(const string& m, int c) {
2206         const int cmax = 300;
2207         //string message;
2208         char tag[4];
2209         char crej = '@';
2210         char mes[cmax];
2211         char dum[cmax];
2212         //char buf[10];
2213         char *pos;
2214         int len;
2215         //FGTransmission t;
2216         string usercall = fgGetString("/sim/user/callsign");
2217         
2218         //transmission_list_type     tmissions = transmissionlist_station[station];
2219         //transmission_list_iterator current   = tmissions.begin();
2220         //transmission_list_iterator last      = tmissions.end();
2221         
2222         //for ( ; current != last ; ++current ) {
2223         //      if ( current->get_code().c1 == code.c1 &&  
2224         //              current->get_code().c2 == code.c2 &&
2225         //          current->get_code().c3 == code.c3 ) {
2226                         
2227                         //if ( ttext ) message = current->get_transtext();
2228                         //else message = current->get_menutext();
2229                         strcpy( &mes[0], m.c_str() ); 
2230                         
2231                         // Replace all the '@' parameters with the actual text.
2232                         int check = 0;  // If mes gets overflowed the while loop can go infinite
2233                         while ( strchr(&mes[0], crej) != NULL  ) {      // ie. loop until no more occurances of crej ('@') found
2234                                 pos = strchr( &mes[0], crej );
2235                                 bcopy(pos, &tag[0], 3);
2236                                 tag[3] = '\0';
2237                                 int i;
2238                                 len = 0;
2239                                 for ( i=0; i<cmax; i++ ) {
2240                                         if ( mes[i] == crej ) {
2241                                                 len = i; 
2242                                                 break;
2243                                         }
2244                                 }
2245                                 strncpy( &dum[0], &mes[0], len );
2246                                 dum[len] = '\0';
2247                                 
2248                                 if ( strcmp ( tag, "@ST" ) == 0 )
2249                                         //strcat( &dum[0], tpars.station.c_str() );
2250                                         strcat(&dum[0], ident.c_str());
2251                                 else if ( strcmp ( tag, "@AP" ) == 0 )
2252                                         //strcat( &dum[0], tpars.airport.c_str() );
2253                                         strcat(&dum[0], name.c_str());
2254                                 else if ( strcmp ( tag, "@CS" ) == 0 ) 
2255                                         //strcat( &dum[0], tpars.callsign.c_str() );
2256                                         strcat(&dum[0], usercall.c_str());
2257                                 else if ( strcmp ( tag, "@TD" ) == 0 ) {
2258                                         /*
2259                                         if ( tpars.tdir == 1 ) {
2260                                                 char buf[] = "left";
2261                                                 strcat( &dum[0], &buf[0] );
2262                                         }
2263                                         else {
2264                                                 char buf[] = "right";
2265                                                 strcat( &dum[0], &buf[0] );
2266                                         }
2267                                         */
2268                                 }
2269                                 else if ( strcmp ( tag, "@HE" ) == 0 ) {
2270                                         /*
2271                                         char buf[10];
2272                                         sprintf( buf, "%i", (int)(tpars.heading) );
2273                                         strcat( &dum[0], &buf[0] );
2274                                         */
2275                                 }
2276                                 else if ( strcmp ( tag, "@VD" ) == 0 ) {
2277                                         /*
2278                                         if ( tpars.VDir == 1 ) {
2279                                                 char buf[] = "Descend and maintain";
2280                                                 strcat( &dum[0], &buf[0] );
2281                                         }
2282                                         else if ( tpars.VDir == 2 ) {
2283                                                 char buf[] = "Maintain";
2284                                                 strcat( &dum[0], &buf[0] );
2285                                         }
2286                                         else if ( tpars.VDir == 3 ) {
2287                                                 char buf[] = "Climb and maintain";
2288                                                 strcat( &dum[0], &buf[0] );
2289                                         } 
2290                                         */
2291                                 }
2292                                 else if ( strcmp ( tag, "@AL" ) == 0 ) {
2293                                         /*
2294                                         char buf[10];
2295                                         sprintf( buf, "%i", (int)(tpars.alt) );
2296                                         strcat( &dum[0], &buf[0] );
2297                                         */
2298                                 }
2299                                 else if ( strcmp ( tag, "@MI" ) == 0 ) {
2300                                         char buf[10];
2301                                         //sprintf( buf, "%3.1f", tpars.miles );
2302                                         int dist_miles = (int)dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue())) / 1600;
2303                                         sprintf(buf, "%i", dist_miles);
2304                                         strcat( &dum[0], &buf[0] );
2305                                 }
2306                                 else if ( strcmp ( tag, "@FR" ) == 0 ) {
2307                                         /*
2308                                         char buf[10];
2309                                         sprintf( buf, "%6.2f", tpars.freq );
2310                                         strcat( &dum[0], &buf[0] );
2311                                         */
2312                                 }
2313                                 else if ( strcmp ( tag, "@RW" ) == 0 ) {
2314                                         strcat(&dum[0], ConvertRwyNumToSpokenString(activeRwy).c_str());
2315                                 } else if(strcmp(tag, "@CD") == 0) {    // @CD = compass direction
2316                                         double h = GetHeadingFromTo(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
2317                                         while(h < 0.0) h += 360.0;
2318                                         while(h > 360.0) h -= 360.0;
2319                                         if(h < 22.5 || h > 337.5) {
2320                                                 strcat(&dum[0], "North");
2321                                         } else if(h < 67.5) {
2322                                                 strcat(&dum[0], "North-East");
2323                                         } else if(h < 112.5) {
2324                                                 strcat(&dum[0], "East");
2325                                         } else if(h < 157.5) {
2326                                                 strcat(&dum[0], "South-East");
2327                                         } else if(h < 202.5) {
2328                                                 strcat(&dum[0], "South");
2329                                         } else if(h < 247.5) {
2330                                                 strcat(&dum[0], "South-West");
2331                                         } else if(h < 292.5) {
2332                                                 strcat(&dum[0], "West");
2333                                         } else {
2334                                                 strcat(&dum[0], "North-West");
2335                                         }
2336                                 } else {
2337                                         cout << "Tag " << tag << " not found" << endl;
2338                                         break;
2339                                 }
2340                                 strcat( &dum[0], &mes[len+3] );
2341                                 strcpy( &mes[0], &dum[0] );
2342                                 
2343                                 ++check;
2344                                 if(check > 10) {
2345                                         SG_LOG(SG_ATC, SG_WARN, "WARNING: Possibly endless loop terminated in FGTransmissionlist::gen_text(...)"); 
2346                                         break;
2347                                 }
2348                         }
2349                         
2350                         //cout << mes  << endl;  
2351                         //break;
2352                 //}
2353         //}
2354         if ( mes != "" ) return mes;
2355         else return "No transmission found";
2356 }
2357
2358 ostream& operator << (ostream& os, tower_traffic_type ttt) {
2359         switch(ttt) {
2360         case(CIRCUIT):      return(os << "CIRCUIT");
2361         case(INBOUND):      return(os << "INBOUND");
2362         case(OUTBOUND):     return(os << "OUTBOUND");
2363         case(TTT_UNKNOWN):  return(os << "UNKNOWN");
2364         case(STRAIGHT_IN):  return(os << "STRAIGHT_IN");
2365         }
2366         return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");
2367 }
2368