]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
Merge branch 'next' into durk-atc
[flightgear.git] / src / ATC / trafficcontrol.cxx
1 // trafficrecord.cxx - Implementation of AIModels ATC code.
2 //
3 // Written by Durk Talsma, started September 2006.
4 //
5 // Copyright (C) 2006 Durk Talsma.
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include <algorithm>
28
29 #include "trafficcontrol.hxx"
30 #include "atc_mgr.hxx"
31 #include <AIModel/AIAircraft.hxx>
32 #include <AIModel/AIFlightPlan.hxx>
33 #include <AIModel/performancedata.hxx>
34 #include <AIModel/performancedb.hxx>
35 #include <ATC/atc_mgr.hxx>
36 #include <Traffic/TrafficMgr.hxx>
37 #include <Airports/groundnetwork.hxx>
38 #include <Airports/dynamics.hxx>
39 #include <Airports/simple.hxx>
40
41 using std::sort;
42
43 /***************************************************************************
44  * ActiveRunway
45  **************************************************************************/
46 time_t ActiveRunway::requestTimeSlot(time_t eta)
47 {
48     time_t newEta;
49     time_t separation = 90;
50     bool found = false;
51     if (estimatedArrivalTimes.size() == 0) {
52         estimatedArrivalTimes.push_back(eta);
53         return eta;
54     } else {
55         TimeVectorIterator i = estimatedArrivalTimes.begin();
56         //cerr << "Checking eta slots " << eta << ": " << endl;
57         for (i = estimatedArrivalTimes.begin();
58              i != estimatedArrivalTimes.end(); i++) {
59             //cerr << "Stored time : " << (*i) << endl;
60         }
61         i = estimatedArrivalTimes.begin();
62         if ((eta + separation) < (*i)) {
63             newEta = eta;
64             found = true;
65             //cerr << "Storing at beginning" << endl;
66         }
67         while ((i != estimatedArrivalTimes.end()) && (!found)) {
68             TimeVectorIterator j = i + 1;
69             if (j == estimatedArrivalTimes.end()) {
70                 if (((*i) + separation) < eta) {
71                     //cerr << "Storing at end" << endl;
72                     newEta = eta;
73                 } else {
74                     newEta = (*i) + separation;
75                     //cerr << "Storing at end + separation" << endl;
76                 }
77             } else {
78                 if ((((*j) - (*i)) > (separation * 2))) {       // found a potential slot
79                     // now check whether this slow is usable:
80                     // 1) eta should fall between the two points
81                     //    i.e. eta > i AND eta < j
82                     //
83                     //cerr << "Found potential slot after " << (*i) << endl;
84                     if (eta > (*i) && (eta < (*j))) {
85                         found = true;
86                         if (eta < ((*i) + separation)) {
87                             newEta = (*i) + separation;
88                             //cerr << "Using  original" << (*i) << " + separation " << endl;
89                         } else {
90                             newEta = eta;
91                             //cerr << "Using original after " << (*i) << endl;
92                         }
93                     } else if (eta < (*i)) {
94                         found = true;
95                         newEta = (*i) + separation;
96                         //cerr << "Using delayed slot after " << (*i) << endl;
97                     }
98                     /*
99                        if (((*j) - separation) < eta) {
100                        found = true;
101                        if (((*i) + separation) < eta) {
102                        newEta = eta;
103                        cerr << "Using original after " << (*i) << endl;
104                        } else {
105                        newEta = (*i) + separation;
106                        cerr << "Using  " << (*i) << " + separation " << endl;
107                        }
108                        } */
109                 }
110             }
111             i++;
112         }
113     }
114     //cerr << ". done. New ETA : " << newEta << endl;
115
116     estimatedArrivalTimes.push_back(newEta);
117     sort(estimatedArrivalTimes.begin(), estimatedArrivalTimes.end());
118     // do some housekeeping : remove any timestamps that are past
119     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
120     TimeVectorIterator i = estimatedArrivalTimes.begin();
121     while (i != estimatedArrivalTimes.end()) {
122         if ((*i) < now) {
123             //cerr << "Deleting timestamp " << (*i) << " (now = " << now << "). " << endl;
124             estimatedArrivalTimes.erase(i);
125             i = estimatedArrivalTimes.begin();
126         } else {
127             i++;
128         }
129     }
130     return newEta;
131 }
132
133 /***************************************************************************
134  * FGTrafficRecord
135  **************************************************************************/
136 FGTrafficRecord::FGTrafficRecord():
137 id(0), waitsForId(0),
138 currentPos(0),
139 leg(0),
140 frequencyId(0),
141 state(0),
142 allowTransmission(true),
143 latitude(0), longitude(0), heading(0), speed(0), altitude(0), radius(0)
144 {
145 }
146
147 void FGTrafficRecord::setPositionAndIntentions(int pos,
148                                                FGAIFlightPlan * route)
149 {
150
151     currentPos = pos;
152     if (intentions.size()) {
153         intVecIterator i = intentions.begin();
154         if ((*i) != pos) {
155             SG_LOG(SG_GENERAL, SG_ALERT,
156                    "Error in FGTrafficRecord::setPositionAndIntentions");
157             //cerr << "Pos : " << pos << " Curr " << *(intentions.begin())  << endl;
158             for (intVecIterator i = intentions.begin();
159                  i != intentions.end(); i++) {
160                 //cerr << (*i) << " ";
161             }
162             //cerr << endl;
163         }
164         intentions.erase(i);
165     } else {
166         //FGAIFlightPlan::waypoint* const wpt= route->getCurrentWaypoint();
167         int size = route->getNrOfWayPoints();
168         //cerr << "Setting pos" << pos << " ";
169         //cerr << "setting intentions ";
170         for (int i = 0; i < size; i++) {
171             int val = route->getRouteIndex(i);
172             //cerr << val<< " ";
173             if ((val) && (val != pos)) {
174                 intentions.push_back(val);
175                 //cerr << "[set] ";
176             }
177         }
178         //cerr << endl;
179         //while (route->next(&legNr, &routeNr)) {
180         //intentions.push_back(routeNr);
181         //}
182         //route->rewind(currentPos);
183     }
184     //exit(1);
185 }
186
187 bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
188 {
189     bool result = false;
190     //cerr << "Start check 1" << endl;
191     if (currentPos == other.currentPos) {
192         //cerr << callsign << ": Check Position and intentions: we are on the same taxiway" << other.callsign << "Index = " << currentPos << endl;
193         result = true;
194     }
195     //  else if (other.intentions.size()) 
196     //     {
197     //       cerr << "Start check 2" << endl;
198     //       intVecIterator i = other.intentions.begin(); 
199     //       while (!((i == other.intentions.end()) || ((*i) == currentPos)))
200     //     i++;
201     //       if (i != other.intentions.end()) {
202     //     cerr << "Check Position and intentions: current matches other.intentions" << endl;
203     //     result = true;
204     //       }
205     else if (intentions.size()) {
206         //cerr << "Start check 3" << endl;
207         intVecIterator i = intentions.begin();
208         //while (!((i == intentions.end()) || ((*i) == other.currentPos)))
209         while (i != intentions.end()) {
210             if ((*i) == other.currentPos) {
211                 break;
212             }
213             i++;
214         }
215         if (i != intentions.end()) {
216             //cerr << callsign << ": Check Position and intentions: .other.current matches" << other.callsign << "Index = " << (*i) << endl;
217             result = true;
218         }
219     }
220     //cerr << "Done !!" << endl;
221     return result;
222 }
223
224 void FGTrafficRecord::setPositionAndHeading(double lat, double lon,
225                                             double hdg, double spd,
226                                             double alt)
227 {
228     latitude = lat;
229     longitude = lon;
230     heading = hdg;
231     speed = spd;
232     altitude = alt;
233 }
234
235 int FGTrafficRecord::crosses(FGGroundNetwork * net,
236                              FGTrafficRecord & other)
237 {
238     if (checkPositionAndIntentions(other)
239         || (other.checkPositionAndIntentions(*this)))
240         return -1;
241     intVecIterator i, j;
242     int currentTargetNode = 0, otherTargetNode = 0;
243     if (currentPos > 0)
244         currentTargetNode = net->findSegment(currentPos)->getEnd()->getIndex(); // OKAY,... 
245     if (other.currentPos > 0)
246         otherTargetNode = net->findSegment(other.currentPos)->getEnd()->getIndex();     // OKAY,...
247     if ((currentTargetNode == otherTargetNode) && currentTargetNode > 0)
248         return currentTargetNode;
249     if (intentions.size()) {
250         for (i = intentions.begin(); i != intentions.end(); i++) {
251             if ((*i) > 0) {
252                 if ((currentTargetNode ==
253                      net->findSegment(*i)->getEnd()->getIndex())) {
254                     //cerr << "Current crosses at " << currentTargetNode <<endl;
255                     return currentTargetNode;
256                 }
257             }
258         }
259     }
260     if (other.intentions.size()) {
261         for (i = other.intentions.begin(); i != other.intentions.end();
262              i++) {
263             if ((*i) > 0) {
264                 if (otherTargetNode ==
265                     net->findSegment(*i)->getEnd()->getIndex()) {
266                     //cerr << "Other crosses at " << currentTargetNode <<endl;
267                     return otherTargetNode;
268                 }
269             }
270         }
271     }
272     if (intentions.size() && other.intentions.size()) {
273         for (i = intentions.begin(); i != intentions.end(); i++) {
274             for (j = other.intentions.begin(); j != other.intentions.end();
275                  j++) {
276                 //cerr << "finding segment " << *i << " and " << *j << endl;
277                 if (((*i) > 0) && ((*j) > 0)) {
278                     currentTargetNode =
279                         net->findSegment(*i)->getEnd()->getIndex();
280                     otherTargetNode =
281                         net->findSegment(*j)->getEnd()->getIndex();
282                     if (currentTargetNode == otherTargetNode) {
283                         //cerr << "Routes will cross at " << currentTargetNode << endl;
284                         return currentTargetNode;
285                     }
286                 }
287             }
288         }
289     }
290     return -1;
291 }
292
293 bool FGTrafficRecord::onRoute(FGGroundNetwork * net,
294                               FGTrafficRecord & other)
295 {
296     int node = -1, othernode = -1;
297     if (currentPos > 0)
298         node = net->findSegment(currentPos)->getEnd()->getIndex();
299     if (other.currentPos > 0)
300         othernode =
301             net->findSegment(other.currentPos)->getEnd()->getIndex();
302     if ((node == othernode) && (node != -1))
303         return true;
304     if (other.intentions.size()) {
305         for (intVecIterator i = other.intentions.begin();
306              i != other.intentions.end(); i++) {
307             if (*i > 0) {
308                 othernode = net->findSegment(*i)->getEnd()->getIndex();
309                 if ((node == othernode) && (node > -1))
310                     return true;
311             }
312         }
313     }
314     //if (other.currentPos > 0)
315     //  othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
316     //if (intentions.size())
317     //  {
318     //    for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
319     //    {
320     //      if (*i > 0) 
321     //        {
322     //          node = net->findSegment(*i)->getEnd()->getIndex();
323     //          if ((node == othernode) && (node > -1))
324     //            return true;
325     //        }
326     //    }
327     //  }
328     return false;
329 }
330
331
332 bool FGTrafficRecord::isOpposing(FGGroundNetwork * net,
333                                  FGTrafficRecord & other, int node)
334 {
335     // Check if current segment is the reverse segment for the other aircraft
336     FGTaxiSegment *opp;
337     //cerr << "Current segment " << currentPos << endl;
338     if ((currentPos > 0) && (other.currentPos > 0)) {
339         opp = net->findSegment(currentPos)->opposite();
340         if (opp) {
341             if (opp->getIndex() == other.currentPos)
342                 return true;
343         }
344
345         for (intVecIterator i = intentions.begin(); i != intentions.end();
346              i++) {
347             if ((opp = net->findSegment(other.currentPos)->opposite())) {
348                 if ((*i) > 0)
349                     if (opp->getIndex() ==
350                         net->findSegment(*i)->getIndex()) {
351                         if (net->findSegment(*i)->getStart()->getIndex() ==
352                             node) {
353                             {
354                                 //cerr << "Found the node " << node << endl;
355                                 return true;
356                             }
357                         }
358                     }
359             }
360             if (other.intentions.size()) {
361                 for (intVecIterator j = other.intentions.begin();
362                      j != other.intentions.end(); j++) {
363                     // cerr << "Current segment 1 " << (*i) << endl;
364                     if ((*i) > 0) {
365                         if ((opp = net->findSegment(*i)->opposite())) {
366                             if (opp->getIndex() ==
367                                 net->findSegment(*j)->getIndex()) {
368                                 //cerr << "Nodes " << net->findSegment(*i)->getIndex()
369                                 //   << " and  " << net->findSegment(*j)->getIndex()
370                                 //   << " are opposites " << endl;
371                                 if (net->findSegment(*i)->getStart()->
372                                     getIndex() == node) {
373                                     {
374                                         //cerr << "Found the node " << node << endl;
375                                         return true;
376                                     }
377                                 }
378                             }
379                         }
380                     }
381                 }
382             }
383         }
384     }
385     return false;
386 }
387
388 void FGTrafficRecord::setSpeedAdjustment(double spd)
389 {
390     instruction.setChangeSpeed(true);
391     instruction.setSpeed(spd);
392 }
393
394 void FGTrafficRecord::setHeadingAdjustment(double heading)
395 {
396     instruction.setChangeHeading(true);
397     instruction.setHeading(heading);
398 }
399
400 bool FGTrafficRecord::pushBackAllowed()
401 {
402     // With the user ATC / AI integration, checking whether the user's aircraft is near no longer works, because
403     // this will effectively block the user's aircraft itself from receiving pushback clearance. 
404     // So, what can we do?
405     /*
406     double course, az2, dist;
407     SGGeod curr(SGGeod::fromDegM(getLongitude(),
408                                  getLatitude(), getAltitude()));
409
410     double userLatitude = fgGetDouble("/position/latitude-deg");
411     double userLongitude = fgGetDouble("/position/longitude-deg");
412     SGGeod user(SGGeod::fromDeg(userLongitude, userLatitude));
413     SGGeodesy::inverse(curr, user, course, az2, dist);
414     //cerr << "Distance to user : " << dist << endl;
415     return (dist > 250);
416     */
417
418
419     // In essence, we should check whether the pusbback route itself, as well as the associcated
420     // taxiways near the pushback point are free of traffic. 
421     // To do so, we need to 
422     return true;
423 }
424
425
426
427 /***************************************************************************
428  * FGATCInstruction
429  *
430  **************************************************************************/
431 FGATCInstruction::FGATCInstruction()
432 {
433     holdPattern = false;
434     holdPosition = false;
435     changeSpeed = false;
436     changeHeading = false;
437     changeAltitude = false;
438     resolveCircularWait = false;
439
440     speed = 0;
441     heading = 0;
442     alt = 0;
443 }
444
445
446 bool FGATCInstruction::hasInstruction()
447 {
448     return (holdPattern || holdPosition || changeSpeed || changeHeading
449             || changeAltitude || resolveCircularWait);
450 }
451
452 /***************************************************************************
453  * FGATCController
454  *
455  **************************************************************************/
456
457
458
459
460 FGATCController::FGATCController()
461 {
462     cerr << "running FGATController constructor" << endl;
463     dt_count = 0;
464     available = true;
465     lastTransmission = 0;
466     initialized = false;
467 }
468
469 FGATCController::~FGATCController()
470 {
471      cerr << "running FGATController destructor" << endl;
472 }
473
474 string FGATCController::getGateName(FGAIAircraft * ref)
475 {
476     return ref->atGate();
477 }
478
479 bool FGATCController::isUserAircraft(FGAIAircraft* ac) 
480
481     return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false; 
482 };
483
484 void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
485                                AtcMsgDir msgDir, bool audible)
486 {
487     string sender, receiver;
488     int stationFreq = 0;
489     int taxiFreq = 0;
490     int freqId = 0;
491     string atisInformation;
492     string text;
493     string taxiFreqStr;
494     double heading = 0;
495     string activeRunway;
496     string fltType;
497     string rwyClass;
498     string SID;
499     string transponderCode;
500     FGAIFlightPlan *fp;
501     string fltRules;
502
503     //double commFreqD;
504     sender = rec->getAircraft()->getTrafficRef()->getCallSign();
505     //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
506     switch (rec->getLeg()) {
507     case 2:
508     case 3:
509         freqId = rec->getNextFrequency();
510         stationFreq =
511             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
512             getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
513         taxiFreq =
514             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
515             getDynamics()->getGroundFrequency(3);
516         receiver =
517             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
518             getName() + "-Ground";
519         atisInformation =
520             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
521             getDynamics()->getAtisInformation();
522         break;
523     case 4:
524         receiver =
525             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
526             getName() + "-Tower";
527         break;
528     }
529     // Swap sender and receiver value in case of a ground to air transmission
530     if (msgDir == ATC_GROUND_TO_AIR) {
531         string tmp = sender;
532         sender = receiver;
533         receiver = tmp;
534     }
535     switch (msgId) {
536     case MSG_ANNOUNCE_ENGINE_START:
537         text = sender + ". Ready to Start up";
538         break;
539     case MSG_REQUEST_ENGINE_START:
540         text =
541             receiver + ", This is " + sender + ". Position " +
542             getGateName(rec->getAircraft()) + ". Information " +
543             atisInformation + ". " +
544             rec->getAircraft()->getTrafficRef()->getFlightRules() +
545             " to " +
546             rec->getAircraft()->getTrafficRef()->getArrivalAirport()->
547             getName() + ". Request start-up";
548         break;
549         // Acknowledge engine startup permission
550         // Assign departure runway
551         // Assign SID, if necessery (TODO)
552     case MSG_PERMIT_ENGINE_START:
553         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
554
555         heading = rec->getAircraft()->getTrafficRef()->getCourse();
556         fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
557         rwyClass =
558             rec->getAircraft()->GetFlightPlan()->
559             getRunwayClassFromTrafficType(fltType);
560
561         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
562             getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
563                                            heading);
564         rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
565         fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
566             getDynamics()->getSID(activeRunway, heading);
567         rec->getAircraft()->GetFlightPlan()->setSID(fp);
568         if (fp) {
569             SID = fp->getName() + " departure";
570         } else {
571             SID = "fly runway heading ";
572         }
573         //snprintf(buffer, 7, "%3.2f", heading);
574         fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
575         transponderCode = genTransponderCode(fltRules);
576         rec->getAircraft()->SetTransponderCode(transponderCode);
577         text =
578             receiver + ". Start-up approved. " + atisInformation +
579             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
580             transponderCode + ". " +
581             "For push-back and taxi clearance call " + taxiFreqStr + ". " +
582             sender + " control.";
583         break;
584     case MSG_DENY_ENGINE_START:
585         text = receiver + ". Standby";
586         break;
587     case MSG_ACKNOWLEDGE_ENGINE_START:
588         fp = rec->getAircraft()->GetFlightPlan()->getSID();
589         if (fp) {
590             SID =
591                 rec->getAircraft()->GetFlightPlan()->getSID()->getName() +
592                 " departure";
593         } else {
594             SID = "fly runway heading ";
595         }
596         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
597         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
598         transponderCode = rec->getAircraft()->GetTransponderCode();
599         text =
600             receiver + ". Start-up approved. " + atisInformation +
601             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
602             transponderCode + ". " +
603             "For push-back and taxi clearance call " + taxiFreqStr + ". " +
604             sender;
605         break;
606     case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
607         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
608         text = receiver + ". Switching to " + taxiFreqStr + ". " + sender;
609         break;
610     case MSG_INITIATE_CONTACT:
611         text = receiver + ". With you. " + sender;
612         break;
613     case MSG_ACKNOWLEDGE_INITIATE_CONTACT:
614         text = receiver + ". Roger. " + sender;
615         break;
616     case MSG_REQUEST_PUSHBACK_CLEARANCE:
617         text = receiver + ". Request push-back. " + sender;
618         break;
619     case MSG_PERMIT_PUSHBACK_CLEARANCE:
620         text = receiver + ". Push-back approved. " + sender;
621         break;
622     case MSG_HOLD_PUSHBACK_CLEARANCE:
623         text = receiver + ". Standby. " + sender;
624         break;
625     case MSG_REQUEST_TAXI_CLEARANCE:
626         text = receiver + ". Ready to Taxi. " + sender;
627         break;
628     case MSG_ISSUE_TAXI_CLEARANCE:
629         text = receiver + ". Cleared to taxi. " + sender;
630         break;
631     case MSG_ACKNOWLEDGE_TAXI_CLEARANCE:
632         text = receiver + ". Cleared to taxi. " + sender;
633         break;
634     case MSG_HOLD_POSITION:
635         text = receiver + ". Hold Position. " + sender;
636         break;
637     case MSG_ACKNOWLEDGE_HOLD_POSITION:
638         text = receiver + ". Holding Position. " + sender;
639         break;
640     case MSG_RESUME_TAXI:
641         text = receiver + ". Resume Taxiing. " + sender;
642         break;
643     case MSG_ACKNOWLEDGE_RESUME_TAXI:
644         text = receiver + ". Continuing Taxi. " + sender;
645         break;
646     default:
647         text = text + sender + ". Transmitting unknown Message";
648         break;
649     }
650     if (audible) {
651         double onBoardRadioFreq0 =
652             fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
653         double onBoardRadioFreq1 =
654             fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
655         int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
656         int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
657         //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
658
659         // Display ATC message only when one of the radios is tuned
660         // the relevant frequency.
661         // Note that distance attenuation is currently not yet implemented
662         if ((onBoardRadioFreqI0 == stationFreq)
663             || (onBoardRadioFreqI1 == stationFreq)) {
664             if (rec->allowTransmissions()) {
665                 fgSetString("/sim/messages/atc", text.c_str());
666             }
667         }
668     } else {
669         FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
670         atc->getATCDialog()->addEntry(1, text);
671         
672     }
673 }
674
675 string FGATCController::formatATCFrequency3_2(int freq)
676 {
677     char buffer[7];
678     snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
679     return string(buffer);
680 }
681
682 // TODO: Set transponder codes according to real-world routes.
683 // The current version just returns a random string of four octal numbers. 
684 string FGATCController::genTransponderCode(string fltRules)
685 {
686     if (fltRules == "VFR") {
687         return string("1200");
688     } else {
689         char buffer[5];
690         snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
691                  rand() % 8);
692         return string(buffer);
693     }
694 }
695
696 void FGATCController::init() 
697 {
698    if (!initialized) {
699        FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
700        mgr->addController(this);
701        initialized = true;
702     }
703 }
704
705 /***************************************************************************
706  * class FGTowerController
707  *
708  **************************************************************************/
709 FGTowerController::FGTowerController():
710 FGATCController()
711 {
712 }
713
714 // 
715 void FGTowerController::announcePosition(int id,
716                                          FGAIFlightPlan * intendedRoute,
717                                          int currentPosition, double lat,
718                                          double lon, double heading,
719                                          double speed, double alt,
720                                          double radius, int leg,
721                                          FGAIAircraft * ref)
722 {
723     init();
724     TrafficVectorIterator i = activeTraffic.begin();
725     // Search whether the current id alread has an entry
726     // This might be faster using a map instead of a vector, but let's start by taking a safe route
727     if (activeTraffic.size()) {
728         //while ((i->getId() != id) && i != activeTraffic.end()) {
729         while (i != activeTraffic.end()) {
730             if (i->getId() == id) {
731                 break;
732             }
733             i++;
734         }
735     }
736     // Add a new TrafficRecord if no one exsists for this aircraft.
737     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
738         FGTrafficRecord rec;
739         rec.setId(id);
740
741         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
742         rec.setRunway(intendedRoute->getRunway());
743         rec.setLeg(leg);
744         //rec.setCallSign(callsign);
745         rec.setAircraft(ref);
746         activeTraffic.push_back(rec);
747     } else {
748         i->setPositionAndHeading(lat, lon, heading, speed, alt);
749     }
750 }
751
752 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
753                                                   double heading, double speed, double alt,
754                                                   double dt)
755 {
756     TrafficVectorIterator i = activeTraffic.begin();
757     // Search whether the current id has an entry
758     // This might be faster using a map instead of a vector, but let's start by taking a safe route
759     TrafficVectorIterator current, closest;
760     if (activeTraffic.size()) {
761         //while ((i->getId() != id) && i != activeTraffic.end()) {
762         while (i != activeTraffic.end()) {
763             if (i->getId() == id) {
764                 break;
765             }
766             i++;
767         }
768     }
769 //    // update position of the current aircraft
770     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
771         SG_LOG(SG_GENERAL, SG_ALERT,
772                "AI error: updating aircraft without traffic record");
773     } else {
774         i->setPositionAndHeading(lat, lon, heading, speed, alt);
775         current = i;
776     }
777     setDt(getDt() + dt);
778
779 //    // see if we already have a clearance record for the currently active runway
780     ActiveRunwayVecIterator rwy = activeRunways.begin();
781     // again, a map might be more efficient here
782     if (activeRunways.size()) {
783         //while ((rwy->getRunwayName() != current->getRunway()) && (rwy != activeRunways.end())) {
784         while (rwy != activeRunways.end()) {
785             if (rwy->getRunwayName() == current->getRunway()) {
786                 break;
787             }
788             rwy++;
789         }
790     }
791     if (rwy == activeRunways.end()) {
792         ActiveRunway aRwy(current->getRunway(), id);
793         activeRunways.push_back(aRwy);  // Since there are no clearance records for this runway yet
794         current->setHoldPosition(false);        // Clear the current aircraft to continue
795     } else {
796         // Okay, we have a clearance record for this runway, so check
797         // whether the clearence ID matches that of the current aircraft
798         if (id == rwy->getCleared()) {
799             current->setHoldPosition(false);
800         } else {
801             current->setHoldPosition(true);
802         }
803     }
804 }
805
806
807 void FGTowerController::signOff(int id)
808 {
809     TrafficVectorIterator i = activeTraffic.begin();
810     // Search search if the current id alread has an entry
811     // This might be faster using a map instead of a vector, but let's start by taking a safe route
812     if (activeTraffic.size()) {
813         //while ((i->getId() != id) && i != activeTraffic.end()) {
814         while (i != activeTraffic.end()) {
815             if (i->getId() == id) {
816                 break;
817             }
818             i++;
819         }
820     }
821     // If this aircraft has left the runway, we can clear the departure record for this runway
822     ActiveRunwayVecIterator rwy = activeRunways.begin();
823     if (activeRunways.size()) {
824         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
825         while (rwy != activeRunways.end()) {
826             if (rwy->getRunwayName() == i->getRunway()) {
827                 break;
828             }
829             rwy++;
830         }
831         if (rwy != activeRunways.end()) {
832             rwy = activeRunways.erase(rwy);
833         } else {
834             SG_LOG(SG_GENERAL, SG_ALERT,
835                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
836         }
837     }
838     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
839         SG_LOG(SG_GENERAL, SG_ALERT,
840                "AI error: Aircraft without traffic record is signing off from tower");
841     } else {
842         i = activeTraffic.erase(i);
843     }
844 }
845
846 // NOTE:
847 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
848 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
849 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
850 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
851 // Note that this function is probably obsolete
852 bool FGTowerController::hasInstruction(int id)
853 {
854     TrafficVectorIterator i = activeTraffic.begin();
855     // Search search if the current id has an entry
856     // This might be faster using a map instead of a vector, but let's start by taking a safe route
857     if (activeTraffic.size()) {
858         //while ((i->getId() != id) && i != activeTraffic.end()) {
859         while (i != activeTraffic.end()) {
860             if (i->getId() == id) {
861                 break;
862             }
863             i++;
864         }
865     }
866     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
867         SG_LOG(SG_GENERAL, SG_ALERT,
868                "AI error: checking ATC instruction for aircraft without traffic record");
869     } else {
870         return i->hasInstruction();
871     }
872     return false;
873 }
874
875
876 FGATCInstruction FGTowerController::getInstruction(int id)
877 {
878     TrafficVectorIterator i = activeTraffic.begin();
879     // Search search if the current id has an entry
880     // This might be faster using a map instead of a vector, but let's start by taking a safe route
881     if (activeTraffic.size()) {
882         //while ((i->getId() != id) && i != activeTraffic.end()) {
883         while (i != activeTraffic.end()) {
884             if (i->getId() == id) {
885                 break;
886             }
887             i++;
888         }
889     }
890     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
891         SG_LOG(SG_GENERAL, SG_ALERT,
892                "AI error: requesting ATC instruction for aircraft without traffic record");
893     } else {
894         return i->getInstruction();
895     }
896     return FGATCInstruction();
897 }
898
899 /***************************************************************************
900  * class FGStartupController
901  *
902  **************************************************************************/
903 FGStartupController::FGStartupController():
904 FGATCController()
905 {
906 }
907
908 void FGStartupController::announcePosition(int id,
909                                            FGAIFlightPlan * intendedRoute,
910                                            int currentPosition, double lat,
911                                            double lon, double heading,
912                                            double speed, double alt,
913                                            double radius, int leg,
914                                            FGAIAircraft * ref)
915 {
916     init();
917     TrafficVectorIterator i = activeTraffic.begin();
918     // Search whether the current id alread has an entry
919     // This might be faster using a map instead of a vector, but let's start by taking a safe route
920     if (activeTraffic.size()) {
921         //while ((i->getId() != id) && i != activeTraffic.end()) {
922         while (i != activeTraffic.end()) {
923             if (i->getId() == id) {
924                 break;
925             }
926             i++;
927         }
928     }
929     // Add a new TrafficRecord if no one exsists for this aircraft.
930     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
931         FGTrafficRecord rec;
932         rec.setId(id);
933
934         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
935         rec.setRunway(intendedRoute->getRunway());
936         rec.setLeg(leg);
937         //rec.setCallSign(callsign);
938         rec.setAircraft(ref);
939         rec.setHoldPosition(true);
940         activeTraffic.push_back(rec);
941     } else {
942         i->setPositionAndHeading(lat, lon, heading, speed, alt);
943
944     }
945 }
946
947 // NOTE:
948 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
949 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
950 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
951 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
952 // Note that this function is probably obsolete
953 bool FGStartupController::hasInstruction(int id)
954 {
955     TrafficVectorIterator i = activeTraffic.begin();
956     // Search search if the current id has an entry
957     // This might be faster using a map instead of a vector, but let's start by taking a safe route
958     if (activeTraffic.size()) {
959         //while ((i->getId() != id) && i != activeTraffic.end()) {
960         while (i != activeTraffic.end()) {
961             if (i->getId() == id) {
962                 break;
963             }
964             i++;
965         }
966     }
967     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
968         SG_LOG(SG_GENERAL, SG_ALERT,
969                "AI error: checking ATC instruction for aircraft without traffic record");
970     } else {
971         return i->hasInstruction();
972     }
973     return false;
974 }
975
976
977 FGATCInstruction FGStartupController::getInstruction(int id)
978 {
979     TrafficVectorIterator i = activeTraffic.begin();
980     // Search search if the current id has an entry
981     // This might be faster using a map instead of a vector, but let's start by taking a safe route
982     if (activeTraffic.size()) {
983         //while ((i->getId() != id) && i != activeTraffic.end()) {
984         while (i != activeTraffic.end()) {
985             if (i->getId() == id) {
986                 break;
987             }
988             i++;
989         }
990     }
991     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
992         SG_LOG(SG_GENERAL, SG_ALERT,
993                "AI error: requesting ATC instruction for aircraft without traffic record");
994     } else {
995         return i->getInstruction();
996     }
997     return FGATCInstruction();
998 }
999
1000 void FGStartupController::signOff(int id)
1001 {
1002     TrafficVectorIterator i = activeTraffic.begin();
1003     // Search search if the current id alread has an entry
1004     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1005     if (activeTraffic.size()) {
1006         //while ((i->getId() != id) && i != activeTraffic.end()) {
1007         while (i != activeTraffic.end()) {
1008             if (i->getId() == id) {
1009                 break;
1010             }
1011             i++;
1012         }
1013     }
1014     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1015         SG_LOG(SG_GENERAL, SG_ALERT,
1016                "AI error: Aircraft without traffic record is signing off from tower");
1017     } else {
1018         i = activeTraffic.erase(i);
1019     }
1020 }
1021
1022 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1023                                AtcMsgDir msgDir)
1024 {
1025     int state = i->getState();
1026     if ((state == st) && available) {
1027         if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1028             
1029             cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1030             static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1031             int n = trans_num->getIntValue();
1032             if (n >= 0) {
1033                 trans_num->setIntValue(-1);
1034                  // PopupCallback(n);
1035                  cerr << "Selected transmission message" << n << endl;
1036                  FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
1037                  atc->getATCDialog()->removeEntry(1);
1038             } else {
1039                 cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1040                 transmit(&(*i), msgId, msgDir, false);
1041                 return false;
1042             }
1043         }
1044         if (now > startTime) {
1045             //cerr << "Transmitting startup msg" << endl;
1046             transmit(&(*i), msgId, msgDir, true);
1047             i->updateState();
1048             lastTransmission = now;
1049             available = false;
1050             return true;
1051         }
1052     }
1053     return false;
1054 }
1055
1056 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1057                                                     double heading, double speed, double alt,
1058                                                     double dt)
1059 {
1060     TrafficVectorIterator i = activeTraffic.begin();
1061     // Search search if the current id has an entry
1062     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1063     TrafficVectorIterator current, closest;
1064     if (activeTraffic.size()) {
1065         //while ((i->getId() != id) && i != activeTraffic.end()) {
1066         while (i != activeTraffic.end()) {
1067             if (i->getId() == id) {
1068                 break;
1069             }
1070             i++;
1071         }
1072     }
1073 //    // update position of the current aircraft
1074
1075     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1076         SG_LOG(SG_GENERAL, SG_ALERT,
1077                "AI error: updating aircraft without traffic record");
1078     } else {
1079         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1080         current = i;
1081     }
1082     setDt(getDt() + dt);
1083
1084     int state = i->getState();
1085
1086     // The user controlled aircraft should have crased here, because it doesn't have a traffic reference. 
1087     // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1088     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1089     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1090     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
1091     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1092     //     << " at parking " << getGateName(i->getAircraft()) << endl;
1093
1094     if ((now - lastTransmission) > 3 + (rand() % 15)) {
1095         available = true;
1096     }
1097
1098     checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
1099     checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
1100     checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
1101     checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
1102     if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
1103         i->nextFrequency();
1104     }
1105     checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
1106     checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
1107     checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE,                ATC_AIR_TO_GROUND);
1108
1109
1110    
1111     if ((state == 8) && available) {
1112         if (now > startTime + 200) {
1113             if (i->pushBackAllowed()) {
1114                 i->allowRepeatedTransmissions();
1115                 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1116                          ATC_GROUND_TO_AIR, true);
1117                 i->updateState();
1118             } else {
1119                 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1120                          ATC_GROUND_TO_AIR, true);
1121                 i->suppressRepeatedTransmissions();
1122             }
1123             lastTransmission = now;
1124             available = false;
1125         }
1126     }
1127     if ((state == 9) && available) {
1128         i->setHoldPosition(false);
1129     }
1130 }
1131
1132
1133 /***************************************************************************
1134  * class FGApproachController
1135  *
1136  **************************************************************************/
1137 FGApproachController::FGApproachController():
1138 FGATCController()
1139 {
1140 }
1141
1142 // 
1143 void FGApproachController::announcePosition(int id,
1144                                             FGAIFlightPlan * intendedRoute,
1145                                             int currentPosition,
1146                                             double lat, double lon,
1147                                             double heading, double speed,
1148                                             double alt, double radius,
1149                                             int leg, FGAIAircraft * ref)
1150 {
1151     init();
1152     TrafficVectorIterator i = activeTraffic.begin();
1153     // Search whether the current id alread has an entry
1154     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1155     if (activeTraffic.size()) {
1156         //while ((i->getId() != id) && i != activeTraffic.end()) {
1157         while (i != activeTraffic.end()) {
1158             if (i->getId() == id) {
1159                 break;
1160             }
1161             i++;
1162         }
1163     }
1164     // Add a new TrafficRecord if no one exsists for this aircraft.
1165     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1166         FGTrafficRecord rec;
1167         rec.setId(id);
1168
1169         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1170         rec.setRunway(intendedRoute->getRunway());
1171         rec.setLeg(leg);
1172         //rec.setCallSign(callsign);
1173         rec.setAircraft(ref);
1174         activeTraffic.push_back(rec);
1175     } else {
1176         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1177     }
1178 }
1179
1180 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1181                                                      double heading, double speed, double alt,
1182                                                      double dt)
1183 {
1184     TrafficVectorIterator i = activeTraffic.begin();
1185     // Search search if the current id has an entry
1186     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1187     TrafficVectorIterator current, closest;
1188     if (activeTraffic.size()) {
1189         //while ((i->getId() != id) && i != activeTraffic.end()) {
1190         while (i != activeTraffic.end()) {
1191             if (i->getId() == id) {
1192                 break;
1193             }
1194             i++;
1195         }
1196     }
1197 //    // update position of the current aircraft
1198     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1199         SG_LOG(SG_GENERAL, SG_ALERT,
1200                "AI error: updating aircraft without traffic record");
1201     } else {
1202         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1203         current = i;
1204         //cerr << "ApproachController: checking for speed" << endl;
1205         time_t time_diff =
1206             current->getAircraft()->
1207             checkForArrivalTime(string("final001"));
1208         if (time_diff > 15) {
1209             current->setSpeedAdjustment(current->getAircraft()->
1210                                         getPerformance()->vDescent() *
1211                                         1.35);
1212         } else if (time_diff > 5) {
1213             current->setSpeedAdjustment(current->getAircraft()->
1214                                         getPerformance()->vDescent() *
1215                                         1.2);
1216         } else if (time_diff < -15) {
1217             current->setSpeedAdjustment(current->getAircraft()->
1218                                         getPerformance()->vDescent() *
1219                                         0.65);
1220         } else if (time_diff < -5) {
1221             current->setSpeedAdjustment(current->getAircraft()->
1222                                         getPerformance()->vDescent() *
1223                                         0.8);
1224         } else {
1225             current->clearSpeedAdjustment();
1226         }
1227         //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1228     }
1229     setDt(getDt() + dt);
1230 }
1231
1232 void FGApproachController::signOff(int id)
1233 {
1234     TrafficVectorIterator i = activeTraffic.begin();
1235     // Search search if the current id alread has an entry
1236     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1237     if (activeTraffic.size()) {
1238         //while ((i->getId() != id) && i != activeTraffic.end()) {
1239         while (i != activeTraffic.end()) {
1240             if (i->getId() == id) {
1241                 break;
1242             }
1243             i++;
1244         }
1245     }
1246     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1247         SG_LOG(SG_GENERAL, SG_ALERT,
1248                "AI error: Aircraft without traffic record is signing off from approach");
1249     } else {
1250         i = activeTraffic.erase(i);
1251     }
1252 }
1253
1254
1255
1256
1257 bool FGApproachController::hasInstruction(int id)
1258 {
1259     TrafficVectorIterator i = activeTraffic.begin();
1260     // Search search if the current id has an entry
1261     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1262     if (activeTraffic.size()) {
1263         //while ((i->getId() != id) && i != activeTraffic.end()) {
1264         while (i != activeTraffic.end()) {
1265             if (i->getId() == id) {
1266                 break;
1267             }
1268             i++;
1269         }
1270     }
1271     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1272         SG_LOG(SG_GENERAL, SG_ALERT,
1273                "AI error: checking ATC instruction for aircraft without traffic record");
1274     } else {
1275         return i->hasInstruction();
1276     }
1277     return false;
1278 }
1279
1280
1281 FGATCInstruction FGApproachController::getInstruction(int id)
1282 {
1283     TrafficVectorIterator i = activeTraffic.begin();
1284     // Search search if the current id has an entry
1285     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1286     if (activeTraffic.size()) {
1287         //while ((i->getId() != id) && i != activeTraffic.end()) {
1288         while (i != activeTraffic.end()) {
1289             if (i->getId() == id) {
1290                 break;
1291             }
1292             i++;
1293         }
1294     }
1295     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1296         SG_LOG(SG_GENERAL, SG_ALERT,
1297                "AI error: requesting ATC instruction for aircraft without traffic record");
1298     } else {
1299         return i->getInstruction();
1300     }
1301     return FGATCInstruction();
1302 }
1303
1304
1305 ActiveRunway *FGApproachController::getRunway(string name)
1306 {
1307     ActiveRunwayVecIterator rwy = activeRunways.begin();
1308     if (activeRunways.size()) {
1309         while (rwy != activeRunways.end()) {
1310             if (rwy->getRunwayName() == name) {
1311                 break;
1312             }
1313             rwy++;
1314         }
1315     }
1316     if (rwy == activeRunways.end()) {
1317         ActiveRunway aRwy(name, 0);
1318         activeRunways.push_back(aRwy);
1319         rwy = activeRunways.end() - 1;
1320     }
1321     return &(*rwy);
1322 }