]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
Added some code to visualize the ground networks.
[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 }
423
424
425
426 /***************************************************************************
427  * FGATCInstruction
428  *
429  **************************************************************************/
430 FGATCInstruction::FGATCInstruction()
431 {
432     holdPattern = false;
433     holdPosition = false;
434     changeSpeed = false;
435     changeHeading = false;
436     changeAltitude = false;
437     resolveCircularWait = false;
438
439     speed = 0;
440     heading = 0;
441     alt = 0;
442 }
443
444
445 bool FGATCInstruction::hasInstruction()
446 {
447     return (holdPattern || holdPosition || changeSpeed || changeHeading
448             || changeAltitude || resolveCircularWait);
449 }
450
451 /***************************************************************************
452  * FGATCController
453  *
454  **************************************************************************/
455
456
457
458
459 FGATCController::FGATCController()
460 {
461     cerr << "running FGATController constructor" << endl;
462     dt_count = 0;
463     available = true;
464     lastTransmission = 0;
465     initialized = false;
466 }
467
468 FGATCController::~FGATCController()
469 {
470      cerr << "running FGATController destructor" << endl;
471 }
472
473 string FGATCController::getGateName(FGAIAircraft * ref)
474 {
475     return ref->atGate();
476 }
477
478 bool FGATCController::isUserAircraft(FGAIAircraft* ac) 
479
480     return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false; 
481 };
482
483 void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
484                                AtcMsgDir msgDir, bool audible)
485 {
486     string sender, receiver;
487     int stationFreq = 0;
488     int taxiFreq = 0;
489     int freqId = 0;
490     string atisInformation;
491     string text;
492     string taxiFreqStr;
493     double heading = 0;
494     string activeRunway;
495     string fltType;
496     string rwyClass;
497     string SID;
498     string transponderCode;
499     FGAIFlightPlan *fp;
500     string fltRules;
501
502     //double commFreqD;
503     sender = rec->getAircraft()->getTrafficRef()->getCallSign();
504     //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
505     switch (rec->getLeg()) {
506     case 2:
507     case 3:
508         freqId = rec->getNextFrequency();
509         stationFreq =
510             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
511             getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
512         taxiFreq =
513             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
514             getDynamics()->getGroundFrequency(3);
515         receiver =
516             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
517             getName() + "-Ground";
518         atisInformation =
519             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
520             getDynamics()->getAtisInformation();
521         break;
522     case 4:
523         receiver =
524             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
525             getName() + "-Tower";
526         break;
527     }
528     // Swap sender and receiver value in case of a ground to air transmission
529     if (msgDir == ATC_GROUND_TO_AIR) {
530         string tmp = sender;
531         sender = receiver;
532         receiver = tmp;
533     }
534     switch (msgId) {
535     case MSG_ANNOUNCE_ENGINE_START:
536         text = sender + ". Ready to Start up";
537         break;
538     case MSG_REQUEST_ENGINE_START:
539         text =
540             receiver + ", This is " + sender + ". Position " +
541             getGateName(rec->getAircraft()) + ". Information " +
542             atisInformation + ". " +
543             rec->getAircraft()->getTrafficRef()->getFlightRules() +
544             " to " +
545             rec->getAircraft()->getTrafficRef()->getArrivalAirport()->
546             getName() + ". Request start-up";
547         break;
548         // Acknowledge engine startup permission
549         // Assign departure runway
550         // Assign SID, if necessery (TODO)
551     case MSG_PERMIT_ENGINE_START:
552         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
553
554         heading = rec->getAircraft()->getTrafficRef()->getCourse();
555         fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
556         rwyClass =
557             rec->getAircraft()->GetFlightPlan()->
558             getRunwayClassFromTrafficType(fltType);
559
560         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
561             getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
562                                            heading);
563         rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
564         fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
565             getDynamics()->getSID(activeRunway, heading);
566         rec->getAircraft()->GetFlightPlan()->setSID(fp);
567         if (fp) {
568             SID = fp->getName() + " departure";
569         } else {
570             SID = "fly runway heading ";
571         }
572         //snprintf(buffer, 7, "%3.2f", heading);
573         fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
574         transponderCode = genTransponderCode(fltRules);
575         rec->getAircraft()->SetTransponderCode(transponderCode);
576         text =
577             receiver + ". Start-up approved. " + atisInformation +
578             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
579             transponderCode + ". " +
580             "For push-back and taxi clearance call " + taxiFreqStr + ". " +
581             sender + " control.";
582         break;
583     case MSG_DENY_ENGINE_START:
584         text = receiver + ". Standby";
585         break;
586     case MSG_ACKNOWLEDGE_ENGINE_START:
587         fp = rec->getAircraft()->GetFlightPlan()->getSID();
588         if (fp) {
589             SID =
590                 rec->getAircraft()->GetFlightPlan()->getSID()->getName() +
591                 " departure";
592         } else {
593             SID = "fly runway heading ";
594         }
595         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
596         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
597         transponderCode = rec->getAircraft()->GetTransponderCode();
598         text =
599             receiver + ". Start-up approved. " + atisInformation +
600             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
601             transponderCode + ". " +
602             "For push-back and taxi clearance call " + taxiFreqStr + ". " +
603             sender;
604         break;
605     case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
606         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
607         text = receiver + ". Switching to " + taxiFreqStr + ". " + sender;
608         break;
609     case MSG_INITIATE_CONTACT:
610         text = receiver + ". With you. " + sender;
611         break;
612     case MSG_ACKNOWLEDGE_INITIATE_CONTACT:
613         text = receiver + ". Roger. " + sender;
614         break;
615     case MSG_REQUEST_PUSHBACK_CLEARANCE:
616         text = receiver + ". Request push-back. " + sender;
617         break;
618     case MSG_PERMIT_PUSHBACK_CLEARANCE:
619         text = receiver + ". Push-back approved. " + sender;
620         break;
621     case MSG_HOLD_PUSHBACK_CLEARANCE:
622         text = receiver + ". Standby. " + sender;
623         break;
624     case MSG_REQUEST_TAXI_CLEARANCE:
625         text = receiver + ". Ready to Taxi. " + sender;
626         break;
627     case MSG_ISSUE_TAXI_CLEARANCE:
628         text = receiver + ". Cleared to taxi. " + sender;
629         break;
630     case MSG_ACKNOWLEDGE_TAXI_CLEARANCE:
631         text = receiver + ". Cleared to taxi. " + sender;
632         break;
633     case MSG_HOLD_POSITION:
634         text = receiver + ". Hold Position. " + sender;
635         break;
636     case MSG_ACKNOWLEDGE_HOLD_POSITION:
637         text = receiver + ". Holding Position. " + sender;
638         break;
639     case MSG_RESUME_TAXI:
640         text = receiver + ". Resume Taxiing. " + sender;
641         break;
642     case MSG_ACKNOWLEDGE_RESUME_TAXI:
643         text = receiver + ". Continuing Taxi. " + sender;
644         break;
645     default:
646         text = text + sender + ". Transmitting unknown Message";
647         break;
648     }
649     if (audible) {
650         double onBoardRadioFreq0 =
651             fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
652         double onBoardRadioFreq1 =
653             fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
654         int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
655         int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
656         //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
657
658         // Display ATC message only when one of the radios is tuned
659         // the relevant frequency.
660         // Note that distance attenuation is currently not yet implemented
661         if ((onBoardRadioFreqI0 == stationFreq)
662             || (onBoardRadioFreqI1 == stationFreq)) {
663             if (rec->allowTransmissions()) {
664                 fgSetString("/sim/messages/atc", text.c_str());
665             }
666         }
667     } else {
668         FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
669         atc->getATCDialog()->addEntry(1, text);
670         
671     }
672 }
673
674 string FGATCController::formatATCFrequency3_2(int freq)
675 {
676     char buffer[7];
677     snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
678     return string(buffer);
679 }
680
681 // TODO: Set transponder codes according to real-world routes.
682 // The current version just returns a random string of four octal numbers. 
683 string FGATCController::genTransponderCode(string fltRules)
684 {
685     if (fltRules == "VFR") {
686         return string("1200");
687     } else {
688         char buffer[5];
689         snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
690                  rand() % 8);
691         return string(buffer);
692     }
693 }
694
695 void FGATCController::init() 
696 {
697    if (!initialized) {
698        FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
699        mgr->addController(this);
700        initialized = true;
701     }
702 }
703
704 /***************************************************************************
705  * class FGTowerController
706  *
707  **************************************************************************/
708 FGTowerController::FGTowerController():
709 FGATCController()
710 {
711 }
712
713 // 
714 void FGTowerController::announcePosition(int id,
715                                          FGAIFlightPlan * intendedRoute,
716                                          int currentPosition, double lat,
717                                          double lon, double heading,
718                                          double speed, double alt,
719                                          double radius, int leg,
720                                          FGAIAircraft * ref)
721 {
722     init();
723     TrafficVectorIterator i = activeTraffic.begin();
724     // Search whether the current id alread has an entry
725     // This might be faster using a map instead of a vector, but let's start by taking a safe route
726     if (activeTraffic.size()) {
727         //while ((i->getId() != id) && i != activeTraffic.end()) {
728         while (i != activeTraffic.end()) {
729             if (i->getId() == id) {
730                 break;
731             }
732             i++;
733         }
734     }
735     // Add a new TrafficRecord if no one exsists for this aircraft.
736     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
737         FGTrafficRecord rec;
738         rec.setId(id);
739
740         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
741         rec.setRunway(intendedRoute->getRunway());
742         rec.setLeg(leg);
743         //rec.setCallSign(callsign);
744         rec.setAircraft(ref);
745         activeTraffic.push_back(rec);
746     } else {
747         i->setPositionAndHeading(lat, lon, heading, speed, alt);
748     }
749 }
750
751 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
752                                                   double heading, double speed, double alt,
753                                                   double dt)
754 {
755     TrafficVectorIterator i = activeTraffic.begin();
756     // Search whether the current id has an entry
757     // This might be faster using a map instead of a vector, but let's start by taking a safe route
758     TrafficVectorIterator current, closest;
759     if (activeTraffic.size()) {
760         //while ((i->getId() != id) && i != activeTraffic.end()) {
761         while (i != activeTraffic.end()) {
762             if (i->getId() == id) {
763                 break;
764             }
765             i++;
766         }
767     }
768 //    // update position of the current aircraft
769     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
770         SG_LOG(SG_GENERAL, SG_ALERT,
771                "AI error: updating aircraft without traffic record");
772     } else {
773         i->setPositionAndHeading(lat, lon, heading, speed, alt);
774         current = i;
775     }
776     setDt(getDt() + dt);
777
778 //    // see if we already have a clearance record for the currently active runway
779     ActiveRunwayVecIterator rwy = activeRunways.begin();
780     // again, a map might be more efficient here
781     if (activeRunways.size()) {
782         //while ((rwy->getRunwayName() != current->getRunway()) && (rwy != activeRunways.end())) {
783         while (rwy != activeRunways.end()) {
784             if (rwy->getRunwayName() == current->getRunway()) {
785                 break;
786             }
787             rwy++;
788         }
789     }
790     if (rwy == activeRunways.end()) {
791         ActiveRunway aRwy(current->getRunway(), id);
792         activeRunways.push_back(aRwy);  // Since there are no clearance records for this runway yet
793         current->setHoldPosition(false);        // Clear the current aircraft to continue
794     } else {
795         // Okay, we have a clearance record for this runway, so check
796         // whether the clearence ID matches that of the current aircraft
797         if (id == rwy->getCleared()) {
798             current->setHoldPosition(false);
799         } else {
800             current->setHoldPosition(true);
801         }
802     }
803 }
804
805
806 void FGTowerController::signOff(int id)
807 {
808     TrafficVectorIterator i = activeTraffic.begin();
809     // Search search if the current id alread has an entry
810     // This might be faster using a map instead of a vector, but let's start by taking a safe route
811     if (activeTraffic.size()) {
812         //while ((i->getId() != id) && i != activeTraffic.end()) {
813         while (i != activeTraffic.end()) {
814             if (i->getId() == id) {
815                 break;
816             }
817             i++;
818         }
819     }
820     // If this aircraft has left the runway, we can clear the departure record for this runway
821     ActiveRunwayVecIterator rwy = activeRunways.begin();
822     if (activeRunways.size()) {
823         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
824         while (rwy != activeRunways.end()) {
825             if (rwy->getRunwayName() == i->getRunway()) {
826                 break;
827             }
828             rwy++;
829         }
830         if (rwy != activeRunways.end()) {
831             rwy = activeRunways.erase(rwy);
832         } else {
833             SG_LOG(SG_GENERAL, SG_ALERT,
834                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
835         }
836     }
837     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
838         SG_LOG(SG_GENERAL, SG_ALERT,
839                "AI error: Aircraft without traffic record is signing off from tower");
840     } else {
841         i = activeTraffic.erase(i);
842     }
843 }
844
845 // NOTE:
846 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
847 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
848 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
849 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
850 // Note that this function is probably obsolete
851 bool FGTowerController::hasInstruction(int id)
852 {
853     TrafficVectorIterator i = activeTraffic.begin();
854     // Search search if the current id has an entry
855     // This might be faster using a map instead of a vector, but let's start by taking a safe route
856     if (activeTraffic.size()) {
857         //while ((i->getId() != id) && i != activeTraffic.end()) {
858         while (i != activeTraffic.end()) {
859             if (i->getId() == id) {
860                 break;
861             }
862             i++;
863         }
864     }
865     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
866         SG_LOG(SG_GENERAL, SG_ALERT,
867                "AI error: checking ATC instruction for aircraft without traffic record");
868     } else {
869         return i->hasInstruction();
870     }
871     return false;
872 }
873
874
875 FGATCInstruction FGTowerController::getInstruction(int id)
876 {
877     TrafficVectorIterator i = activeTraffic.begin();
878     // Search search if the current id has an entry
879     // This might be faster using a map instead of a vector, but let's start by taking a safe route
880     if (activeTraffic.size()) {
881         //while ((i->getId() != id) && i != activeTraffic.end()) {
882         while (i != activeTraffic.end()) {
883             if (i->getId() == id) {
884                 break;
885             }
886             i++;
887         }
888     }
889     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
890         SG_LOG(SG_GENERAL, SG_ALERT,
891                "AI error: requesting ATC instruction for aircraft without traffic record");
892     } else {
893         return i->getInstruction();
894     }
895     return FGATCInstruction();
896 }
897
898 /***************************************************************************
899  * class FGStartupController
900  *
901  **************************************************************************/
902 FGStartupController::FGStartupController():
903 FGATCController()
904 {
905 }
906
907 void FGStartupController::announcePosition(int id,
908                                            FGAIFlightPlan * intendedRoute,
909                                            int currentPosition, double lat,
910                                            double lon, double heading,
911                                            double speed, double alt,
912                                            double radius, int leg,
913                                            FGAIAircraft * ref)
914 {
915     init();
916     TrafficVectorIterator i = activeTraffic.begin();
917     // Search whether the current id alread has an entry
918     // This might be faster using a map instead of a vector, but let's start by taking a safe route
919     if (activeTraffic.size()) {
920         //while ((i->getId() != id) && i != activeTraffic.end()) {
921         while (i != activeTraffic.end()) {
922             if (i->getId() == id) {
923                 break;
924             }
925             i++;
926         }
927     }
928     // Add a new TrafficRecord if no one exsists for this aircraft.
929     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
930         FGTrafficRecord rec;
931         rec.setId(id);
932
933         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
934         rec.setRunway(intendedRoute->getRunway());
935         rec.setLeg(leg);
936         //rec.setCallSign(callsign);
937         rec.setAircraft(ref);
938         rec.setHoldPosition(true);
939         activeTraffic.push_back(rec);
940     } else {
941         i->setPositionAndHeading(lat, lon, heading, speed, alt);
942
943     }
944 }
945
946 // NOTE:
947 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
948 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
949 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
950 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
951 // Note that this function is probably obsolete
952 bool FGStartupController::hasInstruction(int id)
953 {
954     TrafficVectorIterator i = activeTraffic.begin();
955     // Search search if the current id has an entry
956     // This might be faster using a map instead of a vector, but let's start by taking a safe route
957     if (activeTraffic.size()) {
958         //while ((i->getId() != id) && i != activeTraffic.end()) {
959         while (i != activeTraffic.end()) {
960             if (i->getId() == id) {
961                 break;
962             }
963             i++;
964         }
965     }
966     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
967         SG_LOG(SG_GENERAL, SG_ALERT,
968                "AI error: checking ATC instruction for aircraft without traffic record");
969     } else {
970         return i->hasInstruction();
971     }
972     return false;
973 }
974
975
976 FGATCInstruction FGStartupController::getInstruction(int id)
977 {
978     TrafficVectorIterator i = activeTraffic.begin();
979     // Search search if the current id has an entry
980     // This might be faster using a map instead of a vector, but let's start by taking a safe route
981     if (activeTraffic.size()) {
982         //while ((i->getId() != id) && i != activeTraffic.end()) {
983         while (i != activeTraffic.end()) {
984             if (i->getId() == id) {
985                 break;
986             }
987             i++;
988         }
989     }
990     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
991         SG_LOG(SG_GENERAL, SG_ALERT,
992                "AI error: requesting ATC instruction for aircraft without traffic record");
993     } else {
994         return i->getInstruction();
995     }
996     return FGATCInstruction();
997 }
998
999 void FGStartupController::signOff(int id)
1000 {
1001     TrafficVectorIterator i = activeTraffic.begin();
1002     // Search search if the current id alread has an entry
1003     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1004     if (activeTraffic.size()) {
1005         //while ((i->getId() != id) && i != activeTraffic.end()) {
1006         while (i != activeTraffic.end()) {
1007             if (i->getId() == id) {
1008                 break;
1009             }
1010             i++;
1011         }
1012     }
1013     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1014         SG_LOG(SG_GENERAL, SG_ALERT,
1015                "AI error: Aircraft without traffic record is signing off from tower");
1016     } else {
1017         i = activeTraffic.erase(i);
1018     }
1019 }
1020
1021 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1022                                AtcMsgDir msgDir)
1023 {
1024     int state = i->getState();
1025     if ((state == st) && available) {
1026         if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1027             
1028             cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1029             static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1030             int n = trans_num->getIntValue();
1031             if (n >= 0) {
1032                 trans_num->setIntValue(-1);
1033                  // PopupCallback(n);
1034                  cerr << "Selected transmission message" << n << endl;
1035                  FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
1036                  atc->getATCDialog()->removeEntry(1);
1037             } else {
1038                 cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1039                 transmit(&(*i), msgId, msgDir, false);
1040                 return false;
1041             }
1042         }
1043         if (now > startTime) {
1044             //cerr << "Transmitting startup msg" << endl;
1045             transmit(&(*i), msgId, msgDir, true);
1046             i->updateState();
1047             lastTransmission = now;
1048             available = false;
1049             return true;
1050         }
1051     }
1052     return false;
1053 }
1054
1055 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1056                                                     double heading, double speed, double alt,
1057                                                     double dt)
1058 {
1059     TrafficVectorIterator i = activeTraffic.begin();
1060     // Search search if the current id has an entry
1061     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1062     TrafficVectorIterator current, closest;
1063     if (activeTraffic.size()) {
1064         //while ((i->getId() != id) && i != activeTraffic.end()) {
1065         while (i != activeTraffic.end()) {
1066             if (i->getId() == id) {
1067                 break;
1068             }
1069             i++;
1070         }
1071     }
1072 //    // update position of the current aircraft
1073
1074     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1075         SG_LOG(SG_GENERAL, SG_ALERT,
1076                "AI error: updating aircraft without traffic record");
1077     } else {
1078         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1079         current = i;
1080     }
1081     setDt(getDt() + dt);
1082
1083     int state = i->getState();
1084
1085     // The user controlled aircraft should have crased here, because it doesn't have a traffic reference. 
1086     // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1087     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1088     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1089     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
1090     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1091     //     << " at parking " << getGateName(i->getAircraft()) << endl;
1092
1093     if ((now - lastTransmission) > 3 + (rand() % 15)) {
1094         available = true;
1095     }
1096
1097     checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
1098     checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
1099     checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
1100     checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
1101     if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
1102         i->nextFrequency();
1103     }
1104     checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
1105     checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
1106     checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE,                ATC_AIR_TO_GROUND);
1107
1108
1109    
1110     if ((state == 8) && available) {
1111         if (now > startTime + 200) {
1112             if (i->pushBackAllowed()) {
1113                 i->allowRepeatedTransmissions();
1114                 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1115                          ATC_GROUND_TO_AIR, true);
1116                 i->updateState();
1117             } else {
1118                 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1119                          ATC_GROUND_TO_AIR, true);
1120                 i->suppressRepeatedTransmissions();
1121             }
1122             lastTransmission = now;
1123             available = false;
1124         }
1125     }
1126     if ((state == 9) && available) {
1127         i->setHoldPosition(false);
1128     }
1129 }
1130
1131
1132 /***************************************************************************
1133  * class FGApproachController
1134  *
1135  **************************************************************************/
1136 FGApproachController::FGApproachController():
1137 FGATCController()
1138 {
1139 }
1140
1141 // 
1142 void FGApproachController::announcePosition(int id,
1143                                             FGAIFlightPlan * intendedRoute,
1144                                             int currentPosition,
1145                                             double lat, double lon,
1146                                             double heading, double speed,
1147                                             double alt, double radius,
1148                                             int leg, FGAIAircraft * ref)
1149 {
1150     init();
1151     TrafficVectorIterator i = activeTraffic.begin();
1152     // Search whether the current id alread has an entry
1153     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1154     if (activeTraffic.size()) {
1155         //while ((i->getId() != id) && i != activeTraffic.end()) {
1156         while (i != activeTraffic.end()) {
1157             if (i->getId() == id) {
1158                 break;
1159             }
1160             i++;
1161         }
1162     }
1163     // Add a new TrafficRecord if no one exsists for this aircraft.
1164     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1165         FGTrafficRecord rec;
1166         rec.setId(id);
1167
1168         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1169         rec.setRunway(intendedRoute->getRunway());
1170         rec.setLeg(leg);
1171         //rec.setCallSign(callsign);
1172         rec.setAircraft(ref);
1173         activeTraffic.push_back(rec);
1174     } else {
1175         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1176     }
1177 }
1178
1179 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1180                                                      double heading, double speed, double alt,
1181                                                      double dt)
1182 {
1183     TrafficVectorIterator i = activeTraffic.begin();
1184     // Search search if the current id has an entry
1185     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1186     TrafficVectorIterator current, closest;
1187     if (activeTraffic.size()) {
1188         //while ((i->getId() != id) && i != activeTraffic.end()) {
1189         while (i != activeTraffic.end()) {
1190             if (i->getId() == id) {
1191                 break;
1192             }
1193             i++;
1194         }
1195     }
1196 //    // update position of the current aircraft
1197     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1198         SG_LOG(SG_GENERAL, SG_ALERT,
1199                "AI error: updating aircraft without traffic record");
1200     } else {
1201         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1202         current = i;
1203         //cerr << "ApproachController: checking for speed" << endl;
1204         time_t time_diff =
1205             current->getAircraft()->
1206             checkForArrivalTime(string("final001"));
1207         if (time_diff > 15) {
1208             current->setSpeedAdjustment(current->getAircraft()->
1209                                         getPerformance()->vDescent() *
1210                                         1.35);
1211         } else if (time_diff > 5) {
1212             current->setSpeedAdjustment(current->getAircraft()->
1213                                         getPerformance()->vDescent() *
1214                                         1.2);
1215         } else if (time_diff < -15) {
1216             current->setSpeedAdjustment(current->getAircraft()->
1217                                         getPerformance()->vDescent() *
1218                                         0.65);
1219         } else if (time_diff < -5) {
1220             current->setSpeedAdjustment(current->getAircraft()->
1221                                         getPerformance()->vDescent() *
1222                                         0.8);
1223         } else {
1224             current->clearSpeedAdjustment();
1225         }
1226         //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1227     }
1228     setDt(getDt() + dt);
1229 }
1230
1231 void FGApproachController::signOff(int id)
1232 {
1233     TrafficVectorIterator i = activeTraffic.begin();
1234     // Search search if the current id alread has an entry
1235     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1236     if (activeTraffic.size()) {
1237         //while ((i->getId() != id) && i != activeTraffic.end()) {
1238         while (i != activeTraffic.end()) {
1239             if (i->getId() == id) {
1240                 break;
1241             }
1242             i++;
1243         }
1244     }
1245     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1246         SG_LOG(SG_GENERAL, SG_ALERT,
1247                "AI error: Aircraft without traffic record is signing off from approach");
1248     } else {
1249         i = activeTraffic.erase(i);
1250     }
1251 }
1252
1253
1254
1255
1256 bool FGApproachController::hasInstruction(int id)
1257 {
1258     TrafficVectorIterator i = activeTraffic.begin();
1259     // Search search if the current id has an entry
1260     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1261     if (activeTraffic.size()) {
1262         //while ((i->getId() != id) && i != activeTraffic.end()) {
1263         while (i != activeTraffic.end()) {
1264             if (i->getId() == id) {
1265                 break;
1266             }
1267             i++;
1268         }
1269     }
1270     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1271         SG_LOG(SG_GENERAL, SG_ALERT,
1272                "AI error: checking ATC instruction for aircraft without traffic record");
1273     } else {
1274         return i->hasInstruction();
1275     }
1276     return false;
1277 }
1278
1279
1280 FGATCInstruction FGApproachController::getInstruction(int id)
1281 {
1282     TrafficVectorIterator i = activeTraffic.begin();
1283     // Search search if the current id has an entry
1284     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1285     if (activeTraffic.size()) {
1286         //while ((i->getId() != id) && i != activeTraffic.end()) {
1287         while (i != activeTraffic.end()) {
1288             if (i->getId() == id) {
1289                 break;
1290             }
1291             i++;
1292         }
1293     }
1294     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1295         SG_LOG(SG_GENERAL, SG_ALERT,
1296                "AI error: requesting ATC instruction for aircraft without traffic record");
1297     } else {
1298         return i->getInstruction();
1299     }
1300     return FGATCInstruction();
1301 }
1302
1303
1304 ActiveRunway *FGApproachController::getRunway(string name)
1305 {
1306     ActiveRunwayVecIterator rwy = activeRunways.begin();
1307     if (activeRunways.size()) {
1308         while (rwy != activeRunways.end()) {
1309             if (rwy->getRunwayName() == name) {
1310                 break;
1311             }
1312             rwy++;
1313         }
1314     }
1315     if (rwy == activeRunways.end()) {
1316         ActiveRunway aRwy(name, 0);
1317         activeRunways.push_back(aRwy);
1318         rwy = activeRunways.end() - 1;
1319     }
1320     return &(*rwy);
1321 }