TrafCod.java

  1. package org.opentrafficsim.trafficcontrol.trafcod;

  2. import java.awt.Container;
  3. import java.awt.geom.Point2D;
  4. import java.awt.image.BufferedImage;
  5. import java.io.BufferedReader;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.net.URL;
  9. import java.rmi.RemoteException;
  10. import java.util.ArrayList;
  11. import java.util.EnumSet;
  12. import java.util.LinkedHashMap;
  13. import java.util.LinkedHashSet;
  14. import java.util.List;
  15. import java.util.Locale;
  16. import java.util.Map;
  17. import java.util.Set;

  18. import javax.swing.JPanel;

  19. import org.djunits.unit.DurationUnit;
  20. import org.djunits.value.vdouble.scalar.Duration;
  21. import org.djutils.event.Event;
  22. import org.djutils.event.EventListener;
  23. import org.djutils.event.EventType;
  24. import org.djutils.exceptions.Throw;
  25. import org.djutils.immutablecollections.ImmutableCollection;
  26. import org.opentrafficsim.core.dsol.OtsModelInterface;
  27. import org.opentrafficsim.core.dsol.OtsSimulatorInterface;
  28. import org.opentrafficsim.core.network.Network;
  29. import org.opentrafficsim.core.network.NetworkException;
  30. import org.opentrafficsim.core.object.LocatedObject;
  31. import org.opentrafficsim.road.network.lane.object.detector.TrafficLightDetector;
  32. import org.opentrafficsim.road.network.lane.object.detector.TrafficLightDetector.StartEndDetector;
  33. import org.opentrafficsim.road.network.lane.object.trafficlight.TrafficLight;
  34. import org.opentrafficsim.road.network.lane.object.trafficlight.TrafficLightColor;
  35. import org.opentrafficsim.trafficcontrol.AbstractTrafficController;
  36. import org.opentrafficsim.trafficcontrol.ActuatedTrafficController;
  37. import org.opentrafficsim.trafficcontrol.TrafficControlException;
  38. import org.opentrafficsim.trafficcontrol.TrafficController;

  39. import nl.tudelft.simulation.dsol.SimRuntimeException;

  40. /**
  41.  * TrafCOD evaluator. TrafCOD is a language for writing traffic control programs. A TrafCOD program consists of a set of rules
  42.  * that must be evaluated repeatedly (until no more changes occurr) every time step. The time step size is 0.1 seconds.
  43.  * <p>
  44.  * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
  45.  * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
  46.  * </p>
  47.  * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
  48.  */
  49. public class TrafCod extends AbstractTrafficController implements ActuatedTrafficController, EventListener
  50. {
  51.     /** */
  52.     private static final long serialVersionUID = 20161014L;

  53.     /** Version of the supported TrafCOD files. */
  54.     static final int TrafCod_VERSION = 100;

  55.     /** The evaluation interval of TrafCOD. */
  56.     static final Duration EVALUATION_INTERVAL = new Duration(0.1, DurationUnit.SECOND);

  57.     /** Text leading up to the TrafCOD version number. */
  58.     private static final String VERSION_PREFIX = "trafcod-version=";

  59.     /** Text on line before the sequence line. */
  60.     private static final String SEQUENCE_KEY = "Sequence";

  61.     /** Text leading up to the control program structure. */
  62.     private static final String STRUCTURE_PREFIX = "Structure:";

  63.     /** The tokenized rules. */
  64.     private final List<Object[]> tokenisedRules = new ArrayList<>();

  65.     /** The TrafCOD variables. */
  66.     private final Map<String, Variable> variables = new LinkedHashMap<>();

  67.     /** The TrafCOD variables in order of definition. */
  68.     private final List<Variable> variablesInDefinitionOrder = new ArrayList<>();

  69.     /** The detectors. */
  70.     private final Map<String, Variable> detectors = new LinkedHashMap<>();

  71.     /** Comment starter in TrafCOD. */
  72.     static final String COMMENT_PREFIX = "#";

  73.     /** Prefix for initialization rules. */
  74.     private static final String INIT_PREFIX = "%init ";

  75.     /** Prefix for time initializer rules. */
  76.     private static final String TIME_PREFIX = "%time ";

  77.     /** Prefix for export rules. */
  78.     private static final String EXPORT_PREFIX = "%export ";

  79.     /** Number of conflict groups in the control program. */
  80.     private int numberOfConflictGroups = -1;

  81.     /** Sequence information; size of conflict group. */
  82.     private int conflictGroupSize = -1;

  83.     /** Chosen structure number (as assigned by VRIGen). */
  84.     private int structureNumber = -1;

  85.     /** The conflict groups in order that they will be served. */
  86.     private List<List<Short>> conflictGroups = new ArrayList<List<Short>>();

  87.     /** Maximum number of evaluation loops. */
  88.     private int maxLoopCount = 10;

  89.     /** Position in current expression. */
  90.     private int currentToken;

  91.     /** The expression evaluation stack. */
  92.     private List<Integer> stack = new ArrayList<Integer>();

  93.     /** Rule that is currently being evaluated. */
  94.     private Object[] currentRule;

  95.     /** The current time in units of 0.1 s. */
  96.     private int currentTime10 = 0;

  97.     /** The unparsed TrafCOD rules (needed for cloning). */
  98.     private final List<String> trafCODRules;

  99.     /** Container for controller state display. */
  100.     private final Container displayContainer = new JPanel();

  101.     /** Background image for state display. */
  102.     private final BufferedImage displayBackground;

  103.     /** Objects to draw on top of display background. */
  104.     private final List<String> displayObjectLocations;

  105.     /** Animation of the current state of this TrafCOD controller. */
  106.     private TrafCodDisplay stateDisplay = null;

  107.     /** The simulation engine. */
  108.     private final OtsSimulatorInterface simulator;

  109.     /** Space-separated list of the traffic streams in the currently active conflict group. */
  110.     private String currentConflictGroup = "";

  111.     /**
  112.      * Construct a new TrafCOD traffic light controller.
  113.      * @param controllerName name of this TrafCOD traffic light controller
  114.      * @param trafCodURL the URL of the TrafCOD rules
  115.      * @param simulator the simulation engine
  116.      * @param display if non-null, a controller display is constructed and shown in the supplied container
  117.      * @param displayBackground background for controller display image
  118.      * @param displayObjectLocations list of sensors and traffic lights and their locations on the
  119.      *            <code>displayBackGround</code>
  120.      * @throws TrafficControlException when a rule cannot be parsed
  121.      * @throws SimRuntimeException when scheduling the first evaluation event fails
  122.      * @throws IOException when loading the TrafCOD rules from the URL fails
  123.      */
  124.     public TrafCod(final String controllerName, final URL trafCodURL, final OtsSimulatorInterface simulator,
  125.             final Container display, final BufferedImage displayBackground, final List<String> displayObjectLocations)
  126.             throws TrafficControlException, SimRuntimeException, IOException
  127.     {
  128.         this(controllerName, loadTextFromURL(trafCodURL), simulator, displayBackground, displayObjectLocations);
  129.     }

  130.     /**
  131.      * Construct a new TrafCOD traffic light controller.
  132.      * @param controllerName name of this TrafCOD traffic light controller
  133.      * @param trafCODRules the TrafCOD rules
  134.      * @param simulator the simulation engine
  135.      * @param displayBackground background for controller display image
  136.      * @param displayObjectLocations list of sensors and traffic lights and their locations on the
  137.      *            <code>displayBackGround</code>
  138.      * @throws TrafficControlException when a rule cannot be parsed
  139.      * @throws SimRuntimeException when scheduling the first evaluation event fails
  140.      */
  141.     public TrafCod(final String controllerName, final List<String> trafCODRules, final OtsSimulatorInterface simulator,
  142.             final BufferedImage displayBackground, final List<String> displayObjectLocations)
  143.             throws TrafficControlException, SimRuntimeException
  144.     {
  145.         super(controllerName, simulator);
  146.         Throw.whenNull(controllerName, "controllerName may not be null");
  147.         Throw.whenNull(simulator, "simulator may not be null");
  148.         this.simulator = simulator;
  149.         this.displayBackground = displayBackground;
  150.         this.displayObjectLocations = displayObjectLocations;
  151.         Throw.whenNull(trafCODRules, "trafCodRules may not be null");
  152.         this.trafCODRules = trafCODRules;
  153.         parseTrafCODRules();

  154.         // Initialize the variables that have a non-zero initial value
  155.         for (Variable v : this.variablesInDefinitionOrder)
  156.         {
  157.             v.initialize();
  158.             double value = v.getValue();
  159.             if (v.isTimer())
  160.             {
  161.                 value /= 10.0;
  162.             }
  163.             fireTimedEvent(TrafficController.TRAFFICCONTROL_VARIABLE_CREATED,
  164.                     new Object[] {getId(), v.getName(), v.getStream(), value}, simulator.getSimulatorTime());
  165.         }
  166.         if (null != this.displayContainer && null != this.displayBackground && null != this.displayObjectLocations)
  167.         {
  168.             this.stateDisplay = new TrafCodDisplay(this.displayBackground);
  169.             this.displayContainer.add(this.stateDisplay);
  170.             try
  171.             {
  172.                 addTrafCODDisplay(this.displayObjectLocations);
  173.             }
  174.             catch (IOException e)
  175.             {
  176.                 e.printStackTrace();
  177.             }
  178.         }
  179.         // Schedule the consistency check (don't call it directly) to allow interested parties to subscribe before the
  180.         // consistency check is performed
  181.         this.simulator.scheduleEventRel(Duration.ZERO, this, "checkConsistency", null);
  182.         // The first rule evaluation should occur at t=0.1s
  183.         this.simulator.scheduleEventRel(EVALUATION_INTERVAL, this, "evalExprs", null);
  184.     }

  185.     /**
  186.      * Read a text from a URL and convert it to a list of strings.
  187.      * @param url the URL to open and read
  188.      * @return the lines read from the URL (trimmed).
  189.      * @throws IOException when opening or reading the URL failed.
  190.      */
  191.     public static List<String> loadTextFromURL(final URL url) throws IOException
  192.     {
  193.         List<String> result = new ArrayList<>();
  194.         BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
  195.         String inputLine;
  196.         while ((inputLine = in.readLine()) != null)
  197.         {
  198.             result.add(inputLine.trim());
  199.         }
  200.         return result;
  201.     }

  202.     /**
  203.      * Read and parse the TrafCOD traffic control program.
  204.      * @throws TrafficControlException when the TrafCOD file contains errors
  205.      */
  206.     private void parseTrafCODRules() throws TrafficControlException
  207.     {
  208.         for (int lineno = 0; lineno < this.trafCODRules.size(); lineno++)
  209.         {
  210.             String trimmedLine = this.trafCODRules.get(lineno);
  211.             // System.out.println(lineno + ":\t" + inputLine);
  212.             if (trimmedLine.length() == 0)
  213.             {
  214.                 continue;
  215.             }
  216.             String locationDescription = "TrafCOD rule" + "(" + lineno + ") ";
  217.             if (trimmedLine.startsWith(COMMENT_PREFIX))
  218.             {
  219.                 String commentStripped = trimmedLine.substring(1).trim();
  220.                 if (stringBeginsWithIgnoreCase(VERSION_PREFIX, commentStripped))
  221.                 {
  222.                     String versionString = commentStripped.substring(VERSION_PREFIX.length());
  223.                     try
  224.                     {
  225.                         int observedVersion = Integer.parseInt(versionString);
  226.                         if (TrafCod_VERSION != observedVersion)
  227.                         {
  228.                             throw new TrafficControlException(
  229.                                     "Wrong TrafCOD version (expected " + TrafCod_VERSION + ", got " + observedVersion + ")");
  230.                         }
  231.                     }
  232.                     catch (NumberFormatException nfe)
  233.                     {
  234.                         nfe.printStackTrace();
  235.                         throw new TrafficControlException("Could not parse TrafCOD version (got \"" + versionString + ")");
  236.                     }
  237.                 }
  238.                 else if (stringBeginsWithIgnoreCase(SEQUENCE_KEY, commentStripped))
  239.                 {
  240.                     while (trimmedLine.startsWith(COMMENT_PREFIX))
  241.                     {
  242.                         if (++lineno >= this.trafCODRules.size())
  243.                         {
  244.                             throw new TrafficControlException(
  245.                                     "Unexpected EOF (reading sequence key at " + locationDescription + ")");
  246.                         }
  247.                         trimmedLine = this.trafCODRules.get(lineno);
  248.                     }
  249.                     String[] fields = trimmedLine.split("\\s");
  250.                     Throw.when(fields.length != 2, TrafficControlException.class,
  251.                             "Wrong number of fields in Sequence information line (%s)", trimmedLine);
  252.                     try
  253.                     {
  254.                         this.numberOfConflictGroups = Integer.parseInt(fields[0]);
  255.                         this.conflictGroupSize = Integer.parseInt(fields[1]);
  256.                     }
  257.                     catch (NumberFormatException nfe)
  258.                     {
  259.                         nfe.printStackTrace();
  260.                         throw new TrafficControlException("Bad number of conflict groups or bad conflict group size");
  261.                     }
  262.                 }
  263.                 else if (stringBeginsWithIgnoreCase(STRUCTURE_PREFIX, commentStripped))
  264.                 {
  265.                     String structureNumberString = commentStripped.substring(STRUCTURE_PREFIX.length()).trim();
  266.                     try
  267.                     {
  268.                         this.structureNumber = Integer.parseInt(structureNumberString);
  269.                     }
  270.                     catch (NumberFormatException nfe)
  271.                     {
  272.                         nfe.printStackTrace();
  273.                         throw new TrafficControlException(
  274.                                 "Bad structure number (got \"" + structureNumberString + "\" at " + locationDescription + ")");
  275.                     }
  276.                     for (int i = 0; i < this.conflictGroupSize; i++)
  277.                     {
  278.                         this.conflictGroups.add(new ArrayList<Short>());
  279.                     }
  280.                     for (int conflictMemberLine = 0; conflictMemberLine < this.numberOfConflictGroups; conflictMemberLine++)
  281.                     {
  282.                         if (++lineno >= this.trafCODRules.size())
  283.                         {
  284.                             throw new TrafficControlException(
  285.                                     "Unexpected EOF (reading conflict groups at " + locationDescription + ")");
  286.                         }
  287.                         trimmedLine = this.trafCODRules.get(lineno);
  288.                         while (trimmedLine.startsWith(COMMENT_PREFIX))
  289.                         {
  290.                             if (++lineno >= this.trafCODRules.size())
  291.                             {
  292.                                 throw new TrafficControlException(
  293.                                         "Unexpected EOF (reading conflict groups at " + locationDescription + ")");
  294.                             }
  295.                             trimmedLine = this.trafCODRules.get(lineno);
  296.                         }
  297.                         String[] fields = trimmedLine.split("\\s+");
  298.                         if (fields.length != this.conflictGroupSize)
  299.                         {
  300.                             throw new TrafficControlException("Wrong number of conflict groups in Structure information");
  301.                         }
  302.                         for (int col = 0; col < this.conflictGroupSize; col++)
  303.                         {
  304.                             try
  305.                             {
  306.                                 Short stream = Short.parseShort(fields[col]);
  307.                                 this.conflictGroups.get(col).add(stream);
  308.                             }
  309.                             catch (NumberFormatException nfe)
  310.                             {
  311.                                 nfe.printStackTrace();
  312.                                 throw new TrafficControlException("Wrong number of streams in conflict group " + trimmedLine);
  313.                             }
  314.                         }
  315.                     }
  316.                 }
  317.                 continue;
  318.             }
  319.             if (stringBeginsWithIgnoreCase(INIT_PREFIX, trimmedLine))
  320.             {
  321.                 String varNameAndInitialValue = trimmedLine.substring(INIT_PREFIX.length()).trim().replaceAll("[ \t]+", " ");
  322.                 String[] fields = varNameAndInitialValue.split(" ");
  323.                 NameAndStream nameAndStream = new NameAndStream(fields[0], locationDescription);
  324.                 installVariable(nameAndStream.getName(), nameAndStream.getStream(), EnumSet.noneOf(Flags.class),
  325.                         locationDescription).setFlag(Flags.INITED);
  326.                 // The supplied initial value is ignored (in this version of the TrafCOD interpreter)!
  327.                 continue;
  328.             }
  329.             if (stringBeginsWithIgnoreCase(TIME_PREFIX, trimmedLine))
  330.             {
  331.                 String timerNameAndMaximumValue = trimmedLine.substring(INIT_PREFIX.length()).trim().replaceAll("[ \t]+", " ");
  332.                 String[] fields = timerNameAndMaximumValue.split(" ");
  333.                 NameAndStream nameAndStream = new NameAndStream(fields[0], locationDescription);
  334.                 Variable variable = installVariable(nameAndStream.getName(), nameAndStream.getStream(),
  335.                         EnumSet.noneOf(Flags.class), locationDescription);
  336.                 int value10 = Integer.parseInt(fields[1]);
  337.                 variable.setTimerMax(value10);
  338.                 continue;
  339.             }
  340.             if (stringBeginsWithIgnoreCase(EXPORT_PREFIX, trimmedLine))
  341.             {
  342.                 String varNameAndOutputValue = trimmedLine.substring(EXPORT_PREFIX.length()).trim().replaceAll("[ \t]+", " ");
  343.                 String[] fields = varNameAndOutputValue.split(" ");
  344.                 NameAndStream nameAndStream = new NameAndStream(fields[0], locationDescription);
  345.                 Variable variable = installVariable(nameAndStream.getName(), nameAndStream.getStream(),
  346.                         EnumSet.noneOf(Flags.class), locationDescription);
  347.                 int value = Integer.parseInt(fields[1]);
  348.                 variable.setOutput(value);
  349.                 continue;
  350.             }
  351.             Object[] tokenisedRule = parse(trimmedLine, locationDescription);
  352.             if (null != tokenisedRule && tokenisedRule.length > 0)
  353.             {
  354.                 this.tokenisedRules.add(tokenisedRule);
  355.             }
  356.         }
  357.     }

  358.     /**
  359.      * Check the consistency of the traffic control program and perform initializations that require a completely built network.
  360.      * @throws SimRuntimeException when the simulation model is not an OtsModelInterface
  361.      * @throws TrafficControlException when a required traffic light or sensor is not present in the network
  362.      */
  363.     public void checkConsistency() throws SimRuntimeException, TrafficControlException
  364.     {
  365.         for (Variable v : this.variablesInDefinitionOrder)
  366.         {
  367.             if (0 == v.getRefCount() && (!v.isOutput()) && (!v.getName().matches("^RA.")))
  368.             {
  369.                 // System.out.println("Warning: " + v.getName() + v.getStream() + " is never referenced");
  370.                 fireTimedEvent(TRAFFICCONTROL_CONTROLLER_WARNING,
  371.                         new Object[] {getId(), v.toString(EnumSet.of(PrintFlags.ID)) + " is never referenced"},
  372.                         this.simulator.getSimulatorTime());
  373.             }
  374.             if (!v.isDetector())
  375.             {
  376.                 if (!v.getFlags().contains(Flags.HAS_START_RULE))
  377.                 {
  378.                     // System.out.println("Warning: " + v.getName() + v.getStream() + " has no start rule");
  379.                     fireTimedEvent(TRAFFICCONTROL_CONTROLLER_WARNING,
  380.                             new Object[] {getId(), v.toString(EnumSet.of(PrintFlags.ID)) + " has no start rule"},
  381.                             this.simulator.getSimulatorTime());
  382.                 }
  383.                 if ((!v.getFlags().contains(Flags.HAS_END_RULE)) && (!v.isTimer()))
  384.                 {
  385.                     // System.out.println("Warning: " + v.getName() + v.getStream() + " has no end rule");
  386.                     fireTimedEvent(TRAFFICCONTROL_CONTROLLER_WARNING,
  387.                             new Object[] {getId(), v.toString(EnumSet.of(PrintFlags.ID)) + " has no end rule"},
  388.                             this.simulator.getSimulatorTime());
  389.                 }
  390.             }
  391.         }
  392.         Network network = null;
  393.         try
  394.         {
  395.             network = ((OtsModelInterface) this.simulator.getModel()).getNetwork();
  396.         }
  397.         catch (ClassCastException e)
  398.         {
  399.             throw new SimRuntimeException("Model is not an OtsModelInterface");
  400.         }
  401.         ImmutableCollection<TrafficLight> trafficLights = network.getObjectMap(TrafficLight.class).values();
  402.         Map<String, List<TrafficLight>> trafficLightMap = new LinkedHashMap<>();
  403.         for (TrafficLight tl : trafficLights)
  404.         {
  405.             String trafficLightName = tl.getId();
  406.             if (trafficLightName.startsWith(getId()))
  407.             {
  408.                 trafficLightName = trafficLightName.substring(getId().length());
  409.                 if (trafficLightName.startsWith("."))
  410.                 {
  411.                     trafficLightName = trafficLightName.substring(1);
  412.                 }
  413.             }
  414.             if (trafficLightName.substring(trafficLightName.length() - 2).startsWith("."))
  415.             {
  416.                 trafficLightName = trafficLightName.substring(0, trafficLightName.length() - 2);
  417.             }
  418.             List<TrafficLight> list = trafficLightMap.get(trafficLightName);
  419.             if (null == list)
  420.             {
  421.                 list = new ArrayList<>();
  422.                 trafficLightMap.put(trafficLightName, list);
  423.             }
  424.             list.add(tl);
  425.         }
  426.         Map<String, TrafficLightDetector> detectors = new LinkedHashMap<>();
  427.         // Look up all the start/end detector and collect their parents (the traffic light sensors)
  428.         for (StartEndDetector startEndDetector : network.getObjectMap(StartEndDetector.class).values())
  429.         {
  430.             TrafficLightDetector trafficLightSensor = startEndDetector.getParent();
  431.             detectors.put(trafficLightSensor.getId(), trafficLightSensor);
  432.         }
  433.         for (Variable variable : this.variables.values())
  434.         {
  435.             if (variable.isOutput())
  436.             {
  437.                 if (variable.getValue() != 0)
  438.                 {
  439.                     for (TrafficLight trafficLight : variable.getTrafficLights())
  440.                     {
  441.                         trafficLight.setTrafficLightColor(variable.getColor());
  442.                     }
  443.                 }
  444.                 int added = 0;
  445.                 String name = String.format("%s%02d", variable.getName(), variable.getStream());
  446.                 String digits = String.format("%02d", variable.getStream());
  447.                 List<TrafficLight> matchingLights = trafficLightMap.get(digits);
  448.                 if (null == matchingLights)
  449.                 {
  450.                     throw new TrafficControlException("No traffic light for stream " + digits + " found");
  451.                 }
  452.                 for (TrafficLight tl : matchingLights)
  453.                 {
  454.                     try
  455.                     {
  456.                         variable.addOutput(tl);
  457.                     }
  458.                     catch (TrafficControlException exception)
  459.                     {
  460.                         // CANNOT HAPPEN
  461.                         exception.printStackTrace();
  462.                         throw new SimRuntimeException(exception);
  463.                     }
  464.                     if (variable.getValue() != 0)
  465.                     {
  466.                         tl.setTrafficLightColor(variable.getColor());
  467.                     }
  468.                     added++;
  469.                 }
  470.                 if (0 == added)
  471.                 {
  472.                     throw new TrafficControlException("No traffic light found that matches output " + name + " and " + getId());
  473.                 }
  474.             }
  475.             else if (variable.isDetector())
  476.             {
  477.                 String name = variable.getName();
  478.                 String subNumber = name.substring(name.length() - 1);
  479.                 name = name.substring(0, name.length() - 1);
  480.                 name = String.format("%s%02d", name, variable.getStream());
  481.                 String digits = String.format("%02d", variable.getStream());
  482.                 TrafficLightDetector tls = detectors.get("D" + digits + subNumber);
  483.                 if (null == tls)
  484.                 {
  485.                     throw new TrafficControlException(
  486.                             "No sensor found that matches " + name + " subNumber " + subNumber + " and " + getId());
  487.                 }
  488.                 variable.subscribeToDetector(tls);
  489.                 if (null != this.stateDisplay)
  490.                 {
  491.                     // Lookup the detector
  492.                     EventListener el =
  493.                             this.stateDisplay.getDetectorImage(String.format("%02d.%s", variable.getStream(), subNumber));
  494.                     if (null == el)
  495.                     {
  496.                         throw new TrafficControlException("Cannor find detector image matching variable " + variable);
  497.                     }
  498.                     // System.out.println("creating subscriptions to sensor " + tls);
  499.                     tls.addListener(el, TrafficLightDetector.TRAFFIC_LIGHT_DETECTOR_TRIGGER_ENTRY_EVENT);
  500.                     tls.addListener(el, TrafficLightDetector.TRAFFIC_LIGHT_DETECTOR_TRIGGER_EXIT_EVENT);
  501.                 }
  502.             }
  503.         }
  504.     }

  505.     /**
  506.      * Construct the display of this TrafCOD machine and connect it to the displayed traffic lights and sensors to this TrafCOD
  507.      * machine.
  508.      * @param rules the individual lines that specify the graphics file and the locations of the sensor and lights in the image
  509.      * @throws TrafficControlException when the tfg data is invalid
  510.      * @throws IOException when reading the background image fails
  511.      */
  512.     private void addTrafCODDisplay(final List<String> rules) throws TrafficControlException, IOException
  513.     {
  514.         boolean useFirstCoordinates = true;
  515.         int lineno = 0;
  516.         for (String line : rules)
  517.         {
  518.             lineno++;
  519.             String rule = line.trim();
  520.             if (rule.length() == 0)
  521.             {
  522.                 continue;
  523.             }
  524.             String[] fields = rule.split("=");
  525.             if ("mapfile".contentEquals(fields[0]))
  526.             {
  527.                 if (fields[1].matches("[Bb][Mm][Pp]|[Pp][Nn][Gg]$"))
  528.                 {
  529.                     useFirstCoordinates = false; // TODO really figure out which coordinates to use
  530.                 }
  531.                 // System.out.println("map file description is " + inputLine);
  532.                 // Make a decent attempt at constructing the URL of the map file
  533.             }
  534.             else if ("light".equals(fields[0]))
  535.             {
  536.                 // Extract the stream number
  537.                 int streamNumber;
  538.                 try
  539.                 {
  540.                     streamNumber = Integer.parseInt(fields[1].substring(0, 2));
  541.                 }
  542.                 catch (NumberFormatException nfe)
  543.                 {
  544.                     throw new TrafficControlException("Bad traffic light number in coordinates: " + rule);
  545.                 }
  546.                 // Extract the coordinates and create the image
  547.                 TrafficLightImage tli =
  548.                         new TrafficLightImage(this.stateDisplay, getCoordinates(fields[1].substring(3), useFirstCoordinates),
  549.                                 String.format("Traffic Light %02d", streamNumber));
  550.                 for (Variable v : this.variablesInDefinitionOrder)
  551.                 {
  552.                     if (v.isOutput() && v.getStream() == streamNumber)
  553.                     {
  554.                         // TODO: coupling between traffic light and tli via pub/sub, not as direct output of control
  555.                         // v.addOutput(tli);
  556.                     }
  557.                 }
  558.             }
  559.             else if ("detector".equals(fields[0]))
  560.             {
  561.                 int detectorStream;
  562.                 int detectorSubNumber;
  563.                 try
  564.                 {
  565.                     detectorStream = Integer.parseInt(fields[1].substring(0, 2));
  566.                     detectorSubNumber = Integer.parseInt(fields[1].substring(3, 4));
  567.                 }
  568.                 catch (NumberFormatException nfe)
  569.                 {
  570.                     throw new TrafficControlException("Cannot parse detector number in coordinates " + rule);
  571.                 }
  572.                 String detectorName = String.format("D%02d%d", detectorStream, detectorSubNumber);
  573.                 Variable detectorVariable = this.variables.get(detectorName);
  574.                 if (null == detectorVariable)
  575.                 {
  576.                     throw new TrafficControlException(
  577.                             "coordinates defines detector " + detectorName + " which does not exist in the TrafCOD program");
  578.                 }
  579.                 // DetectorImage di =
  580.                 new DetectorImage(this.stateDisplay, getCoordinates(fields[1].substring(5), useFirstCoordinates),
  581.                         String.format("%02d.%d", detectorStream, detectorSubNumber),
  582.                         String.format("Detector %02d.%d", detectorStream, detectorSubNumber));
  583.             }
  584.             else
  585.             {
  586.                 throw new TrafficControlException("Cannot parse coordinates line " + lineno + "in \"" + line + "\"");
  587.             }
  588.         }
  589.     }

  590.     /**
  591.      * Extract two coordinates from a line of text.
  592.      * @param line the text
  593.      * @param useFirstCoordinates if true; process the first pair of integer values; if false; use the second pair of integer
  594.      *            values
  595.      * @return Point2D
  596.      * @throws TrafficControlException when the coordinates could not be parsed
  597.      */
  598.     private static Point2D getCoordinates(final String line, final boolean useFirstCoordinates) throws TrafficControlException
  599.     {
  600.         String work = line.replaceAll("[ ,\t]+", "\t").trim();
  601.         int x;
  602.         int y;
  603.         String[] fields = work.split("\t");
  604.         if (fields.length < (useFirstCoordinates ? 2 : 4))
  605.         {
  606.             throw new TrafficControlException("not enough fields in tfg line \"" + line + "\"");
  607.         }
  608.         try
  609.         {
  610.             x = Integer.parseInt(fields[useFirstCoordinates ? 0 : 2]);
  611.             y = Integer.parseInt(fields[useFirstCoordinates ? 1 : 3]);
  612.         }
  613.         catch (NumberFormatException nfe)
  614.         {
  615.             throw new TrafficControlException("Bad value in tfg line \"" + line + "\"");
  616.         }
  617.         return new Point2D.Double(x, y);
  618.     }

  619.     /**
  620.      * Decrement all running timers.
  621.      * @return the total number of timers that expired
  622.      * @throws TrafficControlException Should never happen
  623.      */
  624.     private int decrementTimers() throws TrafficControlException
  625.     {
  626.         // System.out.println("Decrement running timers");
  627.         int changeCount = 0;
  628.         for (Variable v : this.variables.values())
  629.         {
  630.             if (v.isTimer() && v.getValue() > 0 && v.decrementTimer(this.currentTime10))
  631.             {
  632.                 changeCount++;
  633.             }
  634.         }
  635.         return changeCount;
  636.     }

  637.     /**
  638.      * Reset the START, END and CHANGED flags of all timers. (These do not get reset during the normal rule evaluation phase.)
  639.      */
  640.     private void resetTimerFlags()
  641.     {
  642.         for (Variable v : this.variablesInDefinitionOrder)
  643.         {
  644.             if (v.isTimer())
  645.             {
  646.                 v.clearChangedFlag();
  647.                 v.clearFlag(Flags.START);
  648.                 v.clearFlag(Flags.END);
  649.             }
  650.         }
  651.     }

  652.     /**
  653.      * Evaluate all expressions until no more changes occur.
  654.      * @throws TrafficControlException when evaluation of a rule fails
  655.      * @throws SimRuntimeException when scheduling the next evaluation fails
  656.      */
  657.     @SuppressWarnings("unused")
  658.     private void evalExprs() throws TrafficControlException, SimRuntimeException
  659.     {
  660.         fireTimedEvent(TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING, new Object[] {getId()},
  661.                 this.simulator.getSimulatorTime());
  662.         // System.out.println("evalExprs: time is " + EngineeringFormatter.format(this.simulator.getSimulatorTime().si));
  663.         // insert some delay for testing; without this the simulation runs too fast
  664.         // try
  665.         // {
  666.         // Thread.sleep(10);
  667.         // }
  668.         // catch (InterruptedException exception)
  669.         // {
  670.         // System.out.println("Sleep in evalExprs was interrupted");
  671.         // // exception.printStackTrace();
  672.         // }
  673.         // Contrary to the C++ builder version; this implementation decrements the times at the start of evalExprs
  674.         // By doing it before updating this.currentTime10; the debugging output should be very similar
  675.         decrementTimers();
  676.         this.currentTime10 = (int) (this.simulator.getSimulatorTime().si * 10);
  677.         int loop;
  678.         for (loop = 0; loop < this.maxLoopCount; loop++)
  679.         {
  680.             int changeCount = evalExpressionsOnce();
  681.             resetTimerFlags();
  682.             if (changeCount == 0)
  683.             {
  684.                 break;
  685.             }
  686.         }
  687.         // System.out.println("Executed " + (loop + 1) + " iteration(s)");
  688.         if (loop >= this.maxLoopCount)
  689.         {
  690.             StringBuffer warningMessage = new StringBuffer();
  691.             warningMessage.append(String
  692.                     .format("Control program did not settle to a final state in %d iterations; oscillating variables:", loop));
  693.             for (Variable v : this.variablesInDefinitionOrder)
  694.             {
  695.                 if (v.getFlags().contains(Flags.CHANGED))
  696.                 {
  697.                     warningMessage.append(String.format(" %s%02d", v.getName(), v.getStream()));
  698.                 }
  699.             }
  700.             fireTimedEvent(TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING,
  701.                     new Object[] {getId(), warningMessage.toString()}, this.simulator.getSimulatorTime());
  702.         }
  703.         this.simulator.scheduleEventRel(EVALUATION_INTERVAL, this, "evalExprs", null);
  704.     }

  705.     /**
  706.      * Evaluate all expressions and return the number of changed variables.
  707.      * @return the number of changed variables
  708.      * @throws TrafficControlException when evaluation of a rule fails
  709.      */
  710.     private int evalExpressionsOnce() throws TrafficControlException
  711.     {
  712.         for (Variable variable : this.variables.values())
  713.         {
  714.             variable.clearChangedFlag();
  715.         }
  716.         int changeCount = 0;
  717.         for (Object[] rule : this.tokenisedRules)
  718.         {
  719.             if (evalRule(rule))
  720.             {
  721.                 changeCount++;
  722.             }
  723.         }
  724.         return changeCount;
  725.     }

  726.     /**
  727.      * Evaluate a rule.
  728.      * @param rule the tokenised rule
  729.      * @return true if the variable that is affected by the rule has changed; false if no variable was changed
  730.      * @throws TrafficControlException when evaluation of the rule fails
  731.      */
  732.     private boolean evalRule(final Object[] rule) throws TrafficControlException
  733.     {
  734.         boolean result = false;
  735.         Token ruleType = (Token) rule[0];
  736.         Variable destination = (Variable) rule[1];
  737.         if (destination.isTimer())
  738.         {
  739.             if (destination.getFlags().contains(Flags.TIMEREXPIRED))
  740.             {
  741.                 destination.clearFlag(Flags.TIMEREXPIRED);
  742.                 destination.setFlag(Flags.END);
  743.             }
  744.             else if (destination.getFlags().contains(Flags.START) || destination.getFlags().contains(Flags.END))
  745.             {
  746.                 destination.clearFlag(Flags.START);
  747.                 destination.clearFlag(Flags.END);
  748.                 destination.setFlag(Flags.CHANGED);
  749.             }
  750.         }
  751.         else
  752.         {
  753.             // Normal Variable or detector
  754.             if (Token.START_RULE == ruleType)
  755.             {
  756.                 destination.clearFlag(Flags.START);
  757.             }
  758.             else if (Token.END_RULE == ruleType)
  759.             {
  760.                 destination.clearFlag(Flags.END);
  761.             }
  762.             else
  763.             {
  764.                 destination.clearFlag(Flags.START);
  765.                 destination.clearFlag(Flags.END);
  766.             }
  767.         }

  768.         int currentValue = destination.getValue();
  769.         if (Token.START_RULE == ruleType && currentValue != 0 || Token.END == ruleType && currentValue == 0
  770.                 || Token.INIT_TIMER == ruleType && currentValue != 0)
  771.         {
  772.             return false; // Value cannot change from zero to nonzero or vice versa due to evaluating the expression
  773.         }
  774.         this.currentRule = rule;
  775.         this.currentToken = 2; // Point to first token of the RHS
  776.         this.stack.clear();
  777.         evalExpr(0);
  778.         if (this.currentToken < this.currentRule.length && Token.CLOSE_PAREN == this.currentRule[this.currentToken])
  779.         {
  780.             throw new TrafficControlException("Too many closing parentheses");
  781.         }
  782.         int resultValue = pop();
  783.         if (Token.END_RULE == ruleType)
  784.         {
  785.             // Invert the result
  786.             if (0 == resultValue)
  787.             {
  788.                 resultValue = destination.getValue(); // preserve the current value
  789.             }
  790.             else
  791.             {
  792.                 resultValue = 0;
  793.             }
  794.         }
  795.         if (resultValue != 0 && destination.getValue() == 0)
  796.         {
  797.             destination.setFlag(Flags.START);
  798.         }
  799.         else if (resultValue == 0 && destination.getValue() != 0)
  800.         {
  801.             destination.setFlag(Flags.END);
  802.         }
  803.         if (destination.isTimer())
  804.         {
  805.             if (resultValue != 0 && Token.END_RULE != ruleType)
  806.             {
  807.                 if (0 == destination.getValue())
  808.                 {
  809.                     result = true;
  810.                 }
  811.                 int timerValue10 = destination.getTimerMax();
  812.                 if (timerValue10 < 1)
  813.                 {
  814.                     // Cheat; ensure it will property expire on the next timer tick
  815.                     timerValue10 = 1;
  816.                 }
  817.                 result = destination.setValue(timerValue10, this.currentTime10, new CausePrinter(rule), this);
  818.             }
  819.             else if (0 == resultValue && Token.END_RULE == ruleType && destination.getValue() != 0)
  820.             {
  821.                 result = destination.setValue(0, this.currentTime10, new CausePrinter(rule), this);
  822.             }
  823.         }
  824.         else if (destination.getValue() != resultValue)
  825.         {
  826.             result = destination.setValue(resultValue, this.currentTime10, new CausePrinter(rule), this);
  827.             if (destination.isOutput())
  828.             {
  829.                 fireTimedEvent(TRAFFIC_LIGHT_CHANGED, new Object[] {getId(), destination.getStream(), destination.getColor()},
  830.                         getSimulator().getSimulatorAbsTime());
  831.             }
  832.             if (destination.isConflictGroup() && resultValue != 0)
  833.             {
  834.                 int conflictGroupRank = destination.conflictGroupRank();
  835.                 StringBuilder conflictGroupList = new StringBuilder();
  836.                 for (Short stream : this.conflictGroups.get(conflictGroupRank))
  837.                 {
  838.                     if (conflictGroupList.length() > 0)
  839.                     {
  840.                         conflictGroupList.append(" ");
  841.                     }
  842.                     conflictGroupList.append(String.format("%02d", stream));
  843.                 }
  844.                 fireTimedEvent(TRAFFICCONTROL_CONFLICT_GROUP_CHANGED,
  845.                         new Object[] {getId(), this.currentConflictGroup, conflictGroupList.toString()},
  846.                         getSimulator().getSimulatorTime());
  847.                 // System.out.println("Conflict group changed from " + this.currentConflictGroup + " to "
  848.                 // + conflictGroupList.toString());
  849.                 this.currentConflictGroup = conflictGroupList.toString();
  850.             }
  851.         }
  852.         return result;
  853.     }

  854.     /** Binding strength of relational operators. */
  855.     private static final int BIND_RELATIONAL_OPERATOR = 1;

  856.     /** Binding strength of addition and subtraction. */
  857.     private static final int BIND_ADDITION = 2;

  858.     /** Binding strength of multiplication and division. */
  859.     private static final int BIND_MULTIPLY = 3;

  860.     /** Binding strength of unary minus. */
  861.     private static final int BIND_UNARY_MINUS = 4;

  862.     /**
  863.      * Evaluate an expression. <br>
  864.      * The methods evalExpr and evalRHS together evaluate an expression. This is done using recursion and a stack. The argument
  865.      * bindingStrength that is passed around is the binding strength of the last preceding pending operator. if a binary
  866.      * operator with the same or a lower strength is encountered, the pending operator must be applied first. On the other hand
  867.      * of a binary operator with higher binding strength is encountered, that operator takes precedence over the pending
  868.      * operator. To evaluate an expression, call evalExpr with a bindingStrength value of 0. On return verify that currentToken
  869.      * has incremented to the end of the expression and that there is one value (the result) on the stack.
  870.      * @param bindingStrength the binding strength of a not yet applied binary operator (higher value must be applied first)
  871.      * @throws TrafficControlException when the expression is not valid
  872.      */
  873.     private void evalExpr(final int bindingStrength) throws TrafficControlException
  874.     {
  875.         if (this.currentToken >= this.currentRule.length)
  876.         {
  877.             throw new TrafficControlException("Missing operand at end of expression " + printRule(this.currentRule, false));
  878.         }
  879.         Token token = (Token) this.currentRule[this.currentToken++];
  880.         Object nextToken = null;
  881.         if (this.currentToken < this.currentRule.length)
  882.         {
  883.             nextToken = this.currentRule[this.currentToken];
  884.         }
  885.         switch (token)
  886.         {
  887.             case UNARY_MINUS:
  888.                 if (Token.OPEN_PAREN != nextToken && Token.VARIABLE != nextToken && Token.NEG_VARIABLE != nextToken
  889.                         && Token.CONSTANT != nextToken && Token.START != nextToken && Token.END != nextToken)
  890.                 {
  891.                     throw new TrafficControlException("Operand expected after unary minus");
  892.                 }
  893.                 evalExpr(BIND_UNARY_MINUS);
  894.                 push(-pop());
  895.                 break;

  896.             case OPEN_PAREN:
  897.                 evalExpr(0);
  898.                 if (Token.CLOSE_PAREN != this.currentRule[this.currentToken])
  899.                 {
  900.                     throw new TrafficControlException("Missing closing parenthesis");
  901.                 }
  902.                 this.currentToken++;
  903.                 break;

  904.             case START:
  905.                 if (Token.VARIABLE != nextToken || this.currentToken >= this.currentRule.length - 1)
  906.                 {
  907.                     throw new TrafficControlException("Missing variable after S");
  908.                 }
  909.                 nextToken = this.currentRule[++this.currentToken];
  910.                 if (!(nextToken instanceof Variable))
  911.                 {
  912.                     throw new TrafficControlException("Missing variable after S");
  913.                 }
  914.                 push(((Variable) nextToken).getFlags().contains(Flags.START) ? 1 : 0);
  915.                 this.currentToken++;
  916.                 break;

  917.             case END:
  918.                 if (Token.VARIABLE != nextToken || this.currentToken >= this.currentRule.length - 1)
  919.                 {
  920.                     throw new TrafficControlException("Missing variable after E");
  921.                 }
  922.                 nextToken = this.currentRule[++this.currentToken];
  923.                 if (!(nextToken instanceof Variable))
  924.                 {
  925.                     throw new TrafficControlException("Missing variable after E");
  926.                 }
  927.                 push(((Variable) nextToken).getFlags().contains(Flags.END) ? 1 : 0);
  928.                 this.currentToken++;
  929.                 break;

  930.             case VARIABLE:
  931.             {
  932.                 Variable operand = (Variable) nextToken;
  933.                 if (operand.isTimer())
  934.                 {
  935.                     push(operand.getValue() == 0 ? 0 : 1);
  936.                 }
  937.                 else
  938.                 {
  939.                     push(operand.getValue());
  940.                 }
  941.                 this.currentToken++;
  942.                 break;
  943.             }

  944.             case CONSTANT:
  945.                 push((Integer) nextToken);
  946.                 this.currentToken++;
  947.                 break;

  948.             case NEG_VARIABLE:
  949.                 Variable operand = (Variable) nextToken;
  950.                 push(operand.getValue() == 0 ? 1 : 0);
  951.                 this.currentToken++;
  952.                 break;

  953.             default:
  954.                 throw new TrafficControlException("Operand missing");
  955.         }
  956.         evalRHS(bindingStrength);
  957.     }

  958.     /**
  959.      * Evaluate the right-hand-side of an expression.
  960.      * @param bindingStrength the binding strength of the most recent, not yet applied, binary operator
  961.      * @throws TrafficControlException when the RHS of an expression is invalid
  962.      */
  963.     private void evalRHS(final int bindingStrength) throws TrafficControlException
  964.     {
  965.         while (true)
  966.         {
  967.             if (this.currentToken >= this.currentRule.length)
  968.             {
  969.                 return;
  970.             }
  971.             Token token = (Token) this.currentRule[this.currentToken];
  972.             switch (token)
  973.             {
  974.                 case CLOSE_PAREN:
  975.                     return;

  976.                 case TIMES:
  977.                     if (BIND_MULTIPLY <= bindingStrength)
  978.                     {
  979.                         return; // apply pending operator now
  980.                     }
  981.                     /*-
  982.                      * apply pending operator later
  983.                      * 1: evaluate the RHS operand.
  984.                      * 2: multiply the top-most two operands on the stack and push the result on the stack.
  985.                      */
  986.                     this.currentToken++;
  987.                     evalExpr(BIND_MULTIPLY);
  988.                     push(pop() * pop() == 0 ? 0 : 1);
  989.                     break;

  990.                 case EQ:
  991.                 case NOTEQ:
  992.                 case LE:
  993.                 case LEEQ:
  994.                 case GT:
  995.                 case GTEQ:
  996.                     if (BIND_RELATIONAL_OPERATOR <= bindingStrength)
  997.                     {
  998.                         return; // apply pending operator now
  999.                     }
  1000.                     /*-
  1001.                      * apply pending operator later
  1002.                      * 1: evaluate the RHS operand.
  1003.                      * 2: compare the top-most two operands on the stack and push the result on the stack.
  1004.                      */
  1005.                     this.currentToken++;
  1006.                     evalExpr(BIND_RELATIONAL_OPERATOR);
  1007.                     switch (token)
  1008.                     {
  1009.                         case EQ:
  1010.                             push(pop() == pop() ? 1 : 0);
  1011.                             break;

  1012.                         case NOTEQ:
  1013.                             push(pop() != pop() ? 1 : 0);
  1014.                             break;

  1015.                         case GT:
  1016.                             push(pop() < pop() ? 1 : 0);
  1017.                             break;

  1018.                         case GTEQ:
  1019.                             push(pop() <= pop() ? 1 : 0);
  1020.                             break;

  1021.                         case LE:
  1022.                             push(pop() > pop() ? 1 : 0);
  1023.                             break;

  1024.                         case LEEQ:
  1025.                             push(pop() >= pop() ? 1 : 0);
  1026.                             break;

  1027.                         default:
  1028.                             throw new TrafficControlException("Bad relational operator");
  1029.                     }
  1030.                     break;

  1031.                 case PLUS:
  1032.                     if (BIND_ADDITION <= bindingStrength)
  1033.                     {
  1034.                         return; // apply pending operator now
  1035.                     }
  1036.                     /*-
  1037.                      * apply pending operator later
  1038.                      * 1: evaluate the RHS operand.
  1039.                      * 2: add (OR) the top-most two operands on the stack and push the result on the stack.
  1040.                      */
  1041.                     this.currentToken++;
  1042.                     evalExpr(BIND_ADDITION);
  1043.                     push(pop() + pop() == 0 ? 0 : 1);
  1044.                     break;

  1045.                 case MINUS:
  1046.                     if (BIND_ADDITION <= bindingStrength)
  1047.                     {
  1048.                         return; // apply pending operator now
  1049.                     }
  1050.                     /*-
  1051.                      * apply pending operator later
  1052.                      * 1: evaluate the RHS operand.
  1053.                      * 2: subtract the top-most two operands on the stack and push the result on the stack.
  1054.                      */
  1055.                     this.currentToken++;
  1056.                     evalExpr(BIND_ADDITION);
  1057.                     push(-pop() + pop());
  1058.                     break;

  1059.                 default:
  1060.                     throw new TrafficControlException("Missing binary operator");
  1061.             }
  1062.         }
  1063.     }

  1064.     /**
  1065.      * Push a value on the evaluation stack.
  1066.      * @param value the value to push on the evaluation stack
  1067.      */
  1068.     private void push(final int value)
  1069.     {
  1070.         this.stack.add(value);
  1071.     }

  1072.     /**
  1073.      * Remove the last not-yet-removed value from the evaluation stack and return it.
  1074.      * @return the last non-yet-removed value on the evaluation stack
  1075.      * @throws TrafficControlException when the stack is empty
  1076.      */
  1077.     private int pop() throws TrafficControlException
  1078.     {
  1079.         if (this.stack.size() < 1)
  1080.         {
  1081.             throw new TrafficControlException("Stack empty");
  1082.         }
  1083.         return this.stack.remove(this.stack.size() - 1);
  1084.     }

  1085.     /**
  1086.      * Print a tokenized rule.
  1087.      * @param tokens the tokens
  1088.      * @param printValues if true; print the values of all encountered variable; if false; do not print the values of all
  1089.      *            encountered variable
  1090.      * @return a textual approximation of the original rule
  1091.      * @throws TrafficControlException when tokens does not match the expected grammar
  1092.      */
  1093.     static String printRule(final Object[] tokens, final boolean printValues) throws TrafficControlException
  1094.     {
  1095.         EnumSet<PrintFlags> variableFlags = EnumSet.of(PrintFlags.ID);
  1096.         if (printValues)
  1097.         {
  1098.             variableFlags.add(PrintFlags.VALUE);
  1099.         }
  1100.         EnumSet<PrintFlags> negatedVariableFlags = EnumSet.copyOf(variableFlags);
  1101.         negatedVariableFlags.add(PrintFlags.NEGATED);
  1102.         StringBuilder result = new StringBuilder();
  1103.         for (int inPos = 0; inPos < tokens.length; inPos++)
  1104.         {
  1105.             Object token = tokens[inPos];
  1106.             if (token instanceof Token)
  1107.             {
  1108.                 switch ((Token) token)
  1109.                 {
  1110.                     case EQUALS_RULE:
  1111.                         result.append(((Variable) tokens[++inPos]).toString(variableFlags));
  1112.                         result.append("=");
  1113.                         break;

  1114.                     case NEG_EQUALS_RULE:
  1115.                         result.append(((Variable) tokens[++inPos]).toString(negatedVariableFlags));
  1116.                         result.append("=");
  1117.                         break;

  1118.                     case START_RULE:
  1119.                         result.append(((Variable) tokens[++inPos]).toString(variableFlags));
  1120.                         result.append(".=");
  1121.                         break;

  1122.                     case END_RULE:
  1123.                         result.append(((Variable) tokens[++inPos]).toString(variableFlags));
  1124.                         result.append("N.=");
  1125.                         break;

  1126.                     case INIT_TIMER:
  1127.                         result.append(((Variable) tokens[++inPos]).toString(EnumSet.of(PrintFlags.ID, PrintFlags.INITTIMER)));
  1128.                         result.append(".=");
  1129.                         break;

  1130.                     case REINIT_TIMER:
  1131.                         result.append(((Variable) tokens[++inPos]).toString(EnumSet.of(PrintFlags.ID, PrintFlags.REINITTIMER)));
  1132.                         result.append(".=");
  1133.                         break;

  1134.                     case START:
  1135.                         result.append("S");
  1136.                         break;

  1137.                     case END:
  1138.                         result.append("E");
  1139.                         break;

  1140.                     case VARIABLE:
  1141.                         result.append(((Variable) tokens[++inPos]).toString(variableFlags));
  1142.                         break;

  1143.                     case NEG_VARIABLE:
  1144.                         result.append(((Variable) tokens[++inPos]).toString(variableFlags));
  1145.                         result.append("N");
  1146.                         break;

  1147.                     case CONSTANT:
  1148.                         result.append(tokens[++inPos]).toString();
  1149.                         break;

  1150.                     case UNARY_MINUS:
  1151.                     case MINUS:
  1152.                         result.append("-");
  1153.                         break;

  1154.                     case PLUS:
  1155.                         result.append("+");
  1156.                         break;

  1157.                     case TIMES:
  1158.                         result.append(".");
  1159.                         break;

  1160.                     case EQ:
  1161.                         result.append("=");
  1162.                         break;

  1163.                     case NOTEQ:
  1164.                         result.append("<>");
  1165.                         break;

  1166.                     case GT:
  1167.                         result.append(">");
  1168.                         break;

  1169.                     case GTEQ:
  1170.                         result.append(">=");
  1171.                         break;

  1172.                     case LE:
  1173.                         result.append("<");
  1174.                         break;

  1175.                     case LEEQ:
  1176.                         result.append("<=");
  1177.                         break;

  1178.                     case OPEN_PAREN:
  1179.                         result.append("(");
  1180.                         break;

  1181.                     case CLOSE_PAREN:
  1182.                         result.append(")");
  1183.                         break;

  1184.                     default:
  1185.                         System.out.println(
  1186.                                 "<<<ERROR>>> encountered a non-Token object: " + token + " after " + result.toString());
  1187.                         throw new TrafficControlException("Unknown token");
  1188.                 }
  1189.             }
  1190.             else
  1191.             {
  1192.                 System.out.println("<<<ERROR>>> encountered a non-Token object: " + token + " after " + result.toString());
  1193.                 throw new TrafficControlException("Not a token");
  1194.             }
  1195.         }
  1196.         return result.toString();
  1197.     }

  1198.     /**
  1199.      * States of the rule parser.
  1200.      * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
  1201.      */
  1202.     enum ParserState
  1203.     {
  1204.         /** Looking for the left hand side of an assignment. */
  1205.         FIND_LHS,
  1206.         /** Looking for an assignment operator. */
  1207.         FIND_ASSIGN,
  1208.         /** Looking for the right hand side of an assignment. */
  1209.         FIND_RHS,
  1210.         /** Looking for an optional unary minus. */
  1211.         MAY_UMINUS,
  1212.         /** Looking for an expression. */
  1213.         FIND_EXPR,
  1214.     }

  1215.     /**
  1216.      * Types of TrafCOD tokens.
  1217.      * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
  1218.      */
  1219.     enum Token
  1220.     {
  1221.         /** Equals rule. */
  1222.         EQUALS_RULE,
  1223.         /** Not equals rule. */
  1224.         NEG_EQUALS_RULE,
  1225.         /** Assignment rule. */
  1226.         ASSIGNMENT,
  1227.         /** Start rule. */
  1228.         START_RULE,
  1229.         /** End rule. */
  1230.         END_RULE,
  1231.         /** Timer initialize rule. */
  1232.         INIT_TIMER,
  1233.         /** Timer re-initialize rule. */
  1234.         REINIT_TIMER,
  1235.         /** Unary minus operator. */
  1236.         UNARY_MINUS,
  1237.         /** Less than or equal to (&lt;=). */
  1238.         LEEQ,
  1239.         /** Not equal to (!=). */
  1240.         NOTEQ,
  1241.         /** Less than (&lt;). */
  1242.         LE,
  1243.         /** Greater than or equal to (&gt;=). */
  1244.         GTEQ,
  1245.         /** Greater than (&gt;). */
  1246.         GT,
  1247.         /** Equals to (=). */
  1248.         EQ,
  1249.         /** True if following variable has just started. */
  1250.         START,
  1251.         /** True if following variable has just ended. */
  1252.         END,
  1253.         /** Variable follows. */
  1254.         VARIABLE,
  1255.         /** Variable that follows must be logically negated. */
  1256.         NEG_VARIABLE,
  1257.         /** Integer follows. */
  1258.         CONSTANT,
  1259.         /** Addition operator. */
  1260.         PLUS,
  1261.         /** Subtraction operator. */
  1262.         MINUS,
  1263.         /** Multiplication operator. */
  1264.         TIMES,
  1265.         /** Opening parenthesis. */
  1266.         OPEN_PAREN,
  1267.         /** Closing parenthesis. */
  1268.         CLOSE_PAREN,
  1269.     }

  1270.     /**
  1271.      * Parse one TrafCOD rule.
  1272.      * @param rawRule the TrafCOD rule
  1273.      * @param locationDescription description of the location (file, line) where the rule was found
  1274.      * @return array filled with the tokenized rule
  1275.      * @throws TrafficControlException when the rule is not a valid TrafCOD rule
  1276.      */
  1277.     private Object[] parse(final String rawRule, final String locationDescription) throws TrafficControlException
  1278.     {
  1279.         if (rawRule.length() == 0)
  1280.         {
  1281.             throw new TrafficControlException("empty rule at " + locationDescription);
  1282.         }
  1283.         ParserState state = ParserState.FIND_LHS;
  1284.         String rule = rawRule.toUpperCase(Locale.US);
  1285.         Token ruleType = Token.ASSIGNMENT;
  1286.         int inPos = 0;
  1287.         NameAndStream lhsNameAndStream = null;
  1288.         List<Object> tokens = new ArrayList<>();
  1289.         while (inPos < rule.length())
  1290.         {
  1291.             char character = rule.charAt(inPos);
  1292.             if (Character.isWhitespace(character))
  1293.             {
  1294.                 inPos++;
  1295.                 continue;
  1296.             }
  1297.             switch (state)
  1298.             {
  1299.                 case FIND_LHS:
  1300.                 {
  1301.                     if ('S' == character)
  1302.                     {
  1303.                         ruleType = Token.START_RULE;
  1304.                         inPos++;
  1305.                         lhsNameAndStream = new NameAndStream(rule.substring(inPos), locationDescription);
  1306.                         inPos += lhsNameAndStream.getNumberOfChars();
  1307.                     }
  1308.                     else if ('E' == character)
  1309.                     {
  1310.                         ruleType = Token.END_RULE;
  1311.                         inPos++;
  1312.                         lhsNameAndStream = new NameAndStream(rule.substring(inPos), locationDescription);
  1313.                         inPos += lhsNameAndStream.getNumberOfChars();
  1314.                     }
  1315.                     else if ('I' == character && 'T' == rule.charAt(inPos + 1))
  1316.                     {
  1317.                         ruleType = Token.INIT_TIMER;
  1318.                         inPos++; // The 'T' is part of the name of the time; do not consume it
  1319.                         lhsNameAndStream = new NameAndStream(rule.substring(inPos), locationDescription);
  1320.                         inPos += lhsNameAndStream.getNumberOfChars();
  1321.                     }
  1322.                     else if ('R' == character && 'I' == rule.charAt(inPos + 1) && 'T' == rule.charAt(inPos + 2))
  1323.                     {
  1324.                         ruleType = Token.REINIT_TIMER;
  1325.                         inPos += 2; // The 'T' is part of the name of the timer; do not consume it
  1326.                         lhsNameAndStream = new NameAndStream(rule.substring(inPos), locationDescription);
  1327.                         inPos += lhsNameAndStream.getNumberOfChars();
  1328.                     }
  1329.                     else if ('T' == character && rule.indexOf('=') >= 0
  1330.                             && (rule.indexOf('N') < 0 || rule.indexOf('N') > rule.indexOf('=')))
  1331.                     {
  1332.                         throw new TrafficControlException("Bad time initialization at " + locationDescription);
  1333.                     }
  1334.                     else
  1335.                     {
  1336.                         ruleType = Token.EQUALS_RULE;
  1337.                         lhsNameAndStream = new NameAndStream(rule.substring(inPos), locationDescription);
  1338.                         inPos += lhsNameAndStream.getNumberOfChars();
  1339.                         if (lhsNameAndStream.isNegated())
  1340.                         {
  1341.                             ruleType = Token.NEG_EQUALS_RULE;
  1342.                         }
  1343.                     }
  1344.                     state = ParserState.FIND_ASSIGN;
  1345.                     break;
  1346.                 }

  1347.                 case FIND_ASSIGN:
  1348.                 {
  1349.                     if ('.' == character && '=' == rule.charAt(inPos + 1))
  1350.                     {
  1351.                         if (Token.EQUALS_RULE == ruleType)
  1352.                         {
  1353.                             ruleType = Token.START_RULE;
  1354.                         }
  1355.                         else if (Token.NEG_EQUALS_RULE == ruleType)
  1356.                         {
  1357.                             ruleType = Token.END_RULE;
  1358.                         }
  1359.                         inPos += 2;
  1360.                     }
  1361.                     else if ('=' == character)
  1362.                     {
  1363.                         if (Token.START_RULE == ruleType || Token.END_RULE == ruleType || Token.INIT_TIMER == ruleType
  1364.                                 || Token.REINIT_TIMER == ruleType)
  1365.                         {
  1366.                             throw new TrafficControlException("Bad assignment at " + locationDescription);
  1367.                         }
  1368.                         inPos++;
  1369.                     }
  1370.                     tokens.add(ruleType);
  1371.                     EnumSet<Flags> lhsFlags = EnumSet.noneOf(Flags.class);
  1372.                     if (Token.START_RULE == ruleType || Token.EQUALS_RULE == ruleType || Token.NEG_EQUALS_RULE == ruleType
  1373.                             || Token.INIT_TIMER == ruleType || Token.REINIT_TIMER == ruleType)
  1374.                     {
  1375.                         lhsFlags.add(Flags.HAS_START_RULE);
  1376.                     }
  1377.                     if (Token.END_RULE == ruleType || Token.EQUALS_RULE == ruleType || Token.NEG_EQUALS_RULE == ruleType)
  1378.                     {
  1379.                         lhsFlags.add(Flags.HAS_END_RULE);
  1380.                     }
  1381.                     Variable lhsVariable = installVariable(lhsNameAndStream.getName(), lhsNameAndStream.getStream(), lhsFlags,
  1382.                             locationDescription);
  1383.                     tokens.add(lhsVariable);
  1384.                     state = ParserState.MAY_UMINUS;
  1385.                     break;
  1386.                 }

  1387.                 case MAY_UMINUS:
  1388.                     if ('-' == character)
  1389.                     {
  1390.                         tokens.add(Token.UNARY_MINUS);
  1391.                         inPos++;
  1392.                     }
  1393.                     state = ParserState.FIND_EXPR;
  1394.                     break;

  1395.                 case FIND_EXPR:
  1396.                 {
  1397.                     if (Character.isDigit(character))
  1398.                     {
  1399.                         int constValue = 0;
  1400.                         while (inPos < rule.length() && Character.isDigit(rule.charAt(inPos)))
  1401.                         {
  1402.                             int digit = rule.charAt(inPos) - '0';
  1403.                             if (constValue >= (Integer.MAX_VALUE - digit) / 10)
  1404.                             {
  1405.                                 throw new TrafficControlException("Number too large at " + locationDescription);
  1406.                             }
  1407.                             constValue = 10 * constValue + digit;
  1408.                             inPos++;
  1409.                         }
  1410.                         tokens.add(Token.CONSTANT);
  1411.                         tokens.add(new Integer(constValue));
  1412.                     }
  1413.                     if (inPos >= rule.length())
  1414.                     {
  1415.                         return tokens.toArray();
  1416.                     }
  1417.                     character = rule.charAt(inPos);
  1418.                     switch (character)
  1419.                     {
  1420.                         case '+':
  1421.                             tokens.add(Token.PLUS);
  1422.                             inPos++;
  1423.                             break;

  1424.                         case '-':
  1425.                             tokens.add(Token.MINUS);
  1426.                             inPos++;
  1427.                             break;

  1428.                         case '.':
  1429.                             tokens.add(Token.TIMES);
  1430.                             inPos++;
  1431.                             break;

  1432.                         case ')':
  1433.                             tokens.add(Token.CLOSE_PAREN);
  1434.                             inPos++;
  1435.                             break;

  1436.                         case '<':
  1437.                         {
  1438.                             Character nextChar = rule.charAt(++inPos);
  1439.                             if ('=' == nextChar)
  1440.                             {
  1441.                                 tokens.add(Token.LEEQ);
  1442.                                 inPos++;
  1443.                             }
  1444.                             else if ('>' == nextChar)
  1445.                             {
  1446.                                 tokens.add(Token.NOTEQ);
  1447.                                 inPos++;
  1448.                             }
  1449.                             else
  1450.                             {
  1451.                                 tokens.add(Token.LE);
  1452.                             }
  1453.                             break;
  1454.                         }

  1455.                         case '>':
  1456.                         {
  1457.                             Character nextChar = rule.charAt(++inPos);
  1458.                             if ('=' == nextChar)
  1459.                             {
  1460.                                 tokens.add(Token.GTEQ);
  1461.                                 inPos++;
  1462.                             }
  1463.                             else if ('<' == nextChar)
  1464.                             {
  1465.                                 tokens.add(Token.NOTEQ);
  1466.                                 inPos++;
  1467.                             }
  1468.                             else
  1469.                             {
  1470.                                 tokens.add(Token.GT);
  1471.                             }
  1472.                             break;
  1473.                         }

  1474.                         case '=':
  1475.                         {
  1476.                             Character nextChar = rule.charAt(++inPos);
  1477.                             if ('<' == nextChar)
  1478.                             {
  1479.                                 tokens.add(Token.LEEQ);
  1480.                                 inPos++;
  1481.                             }
  1482.                             else if ('>' == nextChar)
  1483.                             {
  1484.                                 tokens.add(Token.GTEQ);
  1485.                                 inPos++;
  1486.                             }
  1487.                             else
  1488.                             {
  1489.                                 tokens.add(Token.EQ);
  1490.                             }
  1491.                             break;
  1492.                         }

  1493.                         case '(':
  1494.                         {
  1495.                             inPos++;
  1496.                             tokens.add(Token.OPEN_PAREN);
  1497.                             state = ParserState.MAY_UMINUS;
  1498.                             break;
  1499.                         }

  1500.                         default:
  1501.                         {
  1502.                             if ('S' == character)
  1503.                             {
  1504.                                 tokens.add(Token.START);
  1505.                                 inPos++;
  1506.                             }
  1507.                             else if ('E' == character)
  1508.                             {
  1509.                                 tokens.add(Token.END);
  1510.                                 inPos++;
  1511.                             }
  1512.                             NameAndStream nas = new NameAndStream(rule.substring(inPos), locationDescription);
  1513.                             inPos += nas.getNumberOfChars();
  1514.                             if (nas.isNegated())
  1515.                             {
  1516.                                 tokens.add(Token.NEG_VARIABLE);
  1517.                             }
  1518.                             else
  1519.                             {
  1520.                                 tokens.add(Token.VARIABLE);
  1521.                             }
  1522.                             Variable variable = installVariable(nas.getName(), nas.getStream(), EnumSet.noneOf(Flags.class),
  1523.                                     locationDescription);
  1524.                             variable.incrementReferenceCount();
  1525.                             tokens.add(variable);
  1526.                         }
  1527.                     }
  1528.                     break;
  1529.                 }
  1530.                 default:
  1531.                     throw new TrafficControlException("Error: bad switch; case " + state + " should not happen");
  1532.             }
  1533.         }
  1534.         return tokens.toArray();
  1535.     }

  1536.     /**
  1537.      * Check if a String begins with the text of a supplied String (ignoring case).
  1538.      * @param sought the sought pattern (NOT a regular expression)
  1539.      * @param supplied the String that might start with the sought string
  1540.      * @return true if the supplied String begins with the sought String (case insensitive)
  1541.      */
  1542.     private boolean stringBeginsWithIgnoreCase(final String sought, final String supplied)
  1543.     {
  1544.         if (sought.length() > supplied.length())
  1545.         {
  1546.             return false;
  1547.         }
  1548.         return (sought.equalsIgnoreCase(supplied.substring(0, sought.length())));
  1549.     }

  1550.     /**
  1551.      * Generate the key for a variable name and stream for use in this.variables.
  1552.      * @param name name of the variable
  1553.      * @param stream stream of the variable
  1554.      * @return String
  1555.      */
  1556.     private String variableKey(final String name, final short stream)
  1557.     {
  1558.         if (name.startsWith("D"))
  1559.         {
  1560.             return String.format("D%02d%s", stream, name.substring(1));
  1561.         }
  1562.         return String.format("%s%02d", name.toUpperCase(Locale.US), stream);
  1563.     }

  1564.     /**
  1565.      * Lookup or create a new Variable.
  1566.      * @param name name of the variable
  1567.      * @param stream stream number of the variable
  1568.      * @param flags some (possibly empty) combination of Flags.HAS_START_RULE and Flags.HAS_END_RULE; no other flags are allowed
  1569.      * @param location description of the location in the TrafCOD file that triggered the call to this method
  1570.      * @return the new (or already existing) variable
  1571.      * @throws TrafficControlException if the variable already exists and already has (one of) the specified flag(s)
  1572.      */
  1573.     private Variable installVariable(final String name, final short stream, final EnumSet<Flags> flags, final String location)
  1574.             throws TrafficControlException
  1575.     {
  1576.         EnumSet<Flags> forbidden = EnumSet.complementOf(EnumSet.of(Flags.HAS_START_RULE, Flags.HAS_END_RULE));
  1577.         EnumSet<Flags> badFlags = EnumSet.copyOf(forbidden);
  1578.         badFlags.retainAll(flags);
  1579.         if (badFlags.size() > 0)
  1580.         {
  1581.             throw new TrafficControlException("installVariable was called with wrong flag(s): " + badFlags);
  1582.         }
  1583.         String key = variableKey(name, stream);
  1584.         Variable variable = this.variables.get(key);
  1585.         if (null == variable)
  1586.         {
  1587.             // Create and install a new variable
  1588.             variable = new Variable(name, stream, this);
  1589.             this.variables.put(key, variable);
  1590.             this.variablesInDefinitionOrder.add(variable);
  1591.             if (variable.isDetector())
  1592.             {
  1593.                 this.detectors.put(key, variable);
  1594.             }
  1595.         }
  1596.         if (flags.contains(Flags.HAS_START_RULE))
  1597.         {
  1598.             variable.setStartSource(location);
  1599.         }
  1600.         if (flags.contains(Flags.HAS_END_RULE))
  1601.         {
  1602.             variable.setEndSource(location);
  1603.         }
  1604.         return variable;
  1605.     }

  1606.     /**
  1607.      * Retrieve the simulator.
  1608.      * @return SimulatorInterface&lt;Time, Duration, SimTimeDoubleUnit&gt;
  1609.      */
  1610.     public OtsSimulatorInterface getSimulator()
  1611.     {
  1612.         return this.simulator;
  1613.     }

  1614.     /**
  1615.      * Retrieve the structure number.
  1616.      * @return the structureNumber
  1617.      */
  1618.     public int getStructureNumber()
  1619.     {
  1620.         return this.structureNumber;
  1621.     }

  1622.     @Override
  1623.     public void updateDetector(final String detectorId, final boolean detectingGTU)
  1624.     {
  1625.         Variable detector = this.detectors.get(detectorId);
  1626.         detector.setValue(detectingGTU ? 1 : 0, this.currentTime10,
  1627.                 new CausePrinter(
  1628.                         String.format("Detector %s becoming %s", detectorId, (detectingGTU ? "occupied" : "unoccupied"))),
  1629.                 this);
  1630.     }

  1631.     /**
  1632.      * Switch tracing of all variables of a particular traffic stream, or all variables that do not have an associated traffic
  1633.      * stream on or off.
  1634.      * @param stream the traffic stream number, or <code>TrafCOD.NO_STREAM</code> to affect all variables that do not have an
  1635.      *            associated traffic stream
  1636.      * @param trace if true; switch on tracing; if false; switch off tracing
  1637.      */
  1638.     public void traceVariablesOfStream(final int stream, final boolean trace)
  1639.     {
  1640.         for (Variable v : this.variablesInDefinitionOrder)
  1641.         {
  1642.             if (v.getStream() == stream)
  1643.             {
  1644.                 if (trace)
  1645.                 {
  1646.                     v.setFlag(Flags.TRACED);
  1647.                 }
  1648.                 else
  1649.                 {
  1650.                     v.clearFlag(Flags.TRACED);
  1651.                 }
  1652.             }
  1653.         }
  1654.     }

  1655.     /**
  1656.      * Switch tracing of one variable on or off.
  1657.      * @param variableName name of the variable
  1658.      * @param stream traffic stream of the variable, or <code>TrafCOD.NO_STREAM</code> to select a variable that does not have
  1659.      *            an associated traffic stream
  1660.      * @param trace if true; switch on tracing; if false; switch off tracing
  1661.      */
  1662.     public void traceVariable(final String variableName, final int stream, final boolean trace)
  1663.     {
  1664.         for (Variable v : this.variablesInDefinitionOrder)
  1665.         {
  1666.             if (v.getStream() == stream && variableName.equals(v.getName()))
  1667.             {
  1668.                 if (trace)
  1669.                 {
  1670.                     v.setFlag(Flags.TRACED);
  1671.                 }
  1672.                 else
  1673.                 {
  1674.                     v.clearFlag(Flags.TRACED);
  1675.                 }
  1676.             }
  1677.         }
  1678.     }

  1679.     @Override
  1680.     public void notify(final Event event) throws RemoteException
  1681.     {
  1682.         System.out.println("TrafCOD: received an event");
  1683.         if (event.getType().equals(TrafficController.TRAFFICCONTROL_SET_TRACING))
  1684.         {
  1685.             Object content = event.getContent();
  1686.             if (!(content instanceof Object[]))
  1687.             {
  1688.                 System.err.println("TrafCOD controller " + getId() + " received event with bad payload (" + content + ")");
  1689.                 return;
  1690.             }
  1691.             Object[] fields = (Object[]) event.getContent();
  1692.             if (getId().equals(fields[0]))
  1693.             {
  1694.                 if (fields.length < 4 || !(fields[1] instanceof String) || !(fields[2] instanceof Integer)
  1695.                         || !(fields[3] instanceof Boolean))
  1696.                 {
  1697.                     System.err.println("TrafCOD controller " + getId() + " received event with bad payload (" + content + ")");
  1698.                     return;
  1699.                 }
  1700.                 String name = (String) fields[1];
  1701.                 int stream = (Integer) fields[2];
  1702.                 boolean trace = (Boolean) fields[3];
  1703.                 if (name.length() > 1)
  1704.                 {
  1705.                     Variable v = this.variables.get(variableKey(name, (short) stream));
  1706.                     if (null == v)
  1707.                     {
  1708.                         System.err.println("Received trace notification for nonexistent variable (name=\"" + name
  1709.                                 + "\", stream=" + stream + ")");
  1710.                     }
  1711.                     if (trace)
  1712.                     {
  1713.                         v.setFlag(Flags.TRACED);
  1714.                     }
  1715.                     else
  1716.                     {
  1717.                         v.clearFlag(Flags.TRACED);
  1718.                     }
  1719.                 }
  1720.                 else
  1721.                 {
  1722.                     for (Variable v : this.variablesInDefinitionOrder)
  1723.                     {
  1724.                         if (v.getStream() == stream)
  1725.                         {
  1726.                             if (trace)
  1727.                             {
  1728.                                 v.setFlag(Flags.TRACED);
  1729.                             }
  1730.                             else
  1731.                             {
  1732.                                 v.clearFlag(Flags.TRACED);
  1733.                             }
  1734.                         }
  1735.                     }
  1736.                 }
  1737.             }
  1738.             // else: event not destined for this controller
  1739.         }

  1740.     }

  1741.     /**
  1742.      * Fire an event on behalf of this TrafCOD engine (used for tracing variable changes).
  1743.      * @param eventType the type of the event
  1744.      * @param payload the payload of the event
  1745.      */
  1746.     void fireTrafCODEvent(final EventType eventType, final Object[] payload)
  1747.     {
  1748.         fireTimedEvent(eventType, payload, getSimulator().getSimulatorTime());
  1749.     }

  1750.     @Override
  1751.     public String getFullId()
  1752.     {
  1753.         return getId();
  1754.     }

  1755.     @Override
  1756.     public Container getDisplayContainer()
  1757.     {
  1758.         return this.displayContainer;
  1759.     }

  1760.     @Override
  1761.     public String toString()
  1762.     {
  1763.         return "TrafCOD [id=" + getId() + "]";
  1764.     }

  1765. }

  1766. /**
  1767.  * Store a variable name, stream, isTimer, isNegated and number characters consumed information.
  1768.  */
  1769. class NameAndStream
  1770. {
  1771.     /** The name. */
  1772.     private final String name;

  1773.     /** The stream number. */
  1774.     private short stream = TrafficController.NO_STREAM;

  1775.     /** Number characters parsed. */
  1776.     private int numberOfChars = 0;

  1777.     /** Was a letter N consumed while parsing the name?. */
  1778.     private boolean negated = false;

  1779.     /**
  1780.      * Parse a TrafCOD identifier and extract all required information.
  1781.      * @param text the TrafCOD identifier (may be followed by more text)
  1782.      * @param locationDescription description of the location in the input file
  1783.      * @throws TrafficControlException when text is not a valid TrafCOD variable name
  1784.      */
  1785.     NameAndStream(final String text, final String locationDescription) throws TrafficControlException
  1786.     {
  1787.         int pos = 0;
  1788.         while (pos < text.length() && Character.isWhitespace(text.charAt(pos)))
  1789.         {
  1790.             pos++;
  1791.         }
  1792.         while (pos < text.length())
  1793.         {
  1794.             char character = text.charAt(pos);
  1795.             if (!Character.isLetterOrDigit(character))
  1796.             {
  1797.                 break;
  1798.             }
  1799.             pos++;
  1800.         }
  1801.         this.numberOfChars = pos;
  1802.         String trimmed = text.substring(0, pos).replaceAll(" ", "");
  1803.         if (trimmed.length() == 0)
  1804.         {
  1805.             throw new TrafficControlException("missing variable at " + locationDescription);
  1806.         }
  1807.         if (trimmed.matches("^D([Nn]?\\d\\d\\d)|(\\d\\d\\d[Nn])"))
  1808.         {
  1809.             // Handle a detector
  1810.             if (trimmed.charAt(1) == 'N' || trimmed.charAt(1) == 'n')
  1811.             {
  1812.                 // Move the 'N' to the end
  1813.                 trimmed = "D" + trimmed.substring(2, 5) + "N" + trimmed.substring(5);
  1814.                 this.negated = true;
  1815.             }
  1816.             this.name = "D" + trimmed.charAt(3);
  1817.             this.stream = (short) (10 * (trimmed.charAt(1) - '0') + trimmed.charAt(2) - '0');
  1818.             return;
  1819.         }
  1820.         StringBuilder nameBuilder = new StringBuilder();
  1821.         for (pos = 0; pos < trimmed.length(); pos++)
  1822.         {
  1823.             char nextChar = trimmed.charAt(pos);
  1824.             if (pos < trimmed.length() - 1 && Character.isDigit(nextChar) && Character.isDigit(trimmed.charAt(pos + 1))
  1825.                     && TrafficController.NO_STREAM == this.stream)
  1826.             {
  1827.                 if (0 == pos || (1 == pos && trimmed.startsWith("N")))
  1828.                 {
  1829.                     throw new TrafficControlException("Bad variable name: " + trimmed + " at " + locationDescription);
  1830.                 }
  1831.                 if (trimmed.charAt(pos - 1) == 'N')
  1832.                 {
  1833.                     // Previous N was NOT part of the name
  1834.                     nameBuilder.deleteCharAt(nameBuilder.length() - 1);
  1835.                     // Move the 'N' after the digits
  1836.                     trimmed =
  1837.                             trimmed.substring(0, pos - 1) + trimmed.substring(pos, pos + 2) + trimmed.substring(pos + 2) + "N";
  1838.                     pos--;
  1839.                 }
  1840.                 this.stream = (short) (10 * (trimmed.charAt(pos) - '0') + trimmed.charAt(pos + 1) - '0');
  1841.                 pos++;
  1842.             }
  1843.             else
  1844.             {
  1845.                 nameBuilder.append(nextChar);
  1846.             }
  1847.         }
  1848.         if (trimmed.endsWith("N"))
  1849.         {
  1850.             nameBuilder.deleteCharAt(nameBuilder.length() - 1);
  1851.             this.negated = true;
  1852.         }
  1853.         this.name = nameBuilder.toString();
  1854.     }

  1855.     /**
  1856.      * Was a negation operator ('N') embedded in the name?
  1857.      * @return boolean
  1858.      */
  1859.     public boolean isNegated()
  1860.     {
  1861.         return this.negated;
  1862.     }

  1863.     /**
  1864.      * Retrieve the stream number.
  1865.      * @return the stream number
  1866.      */
  1867.     public short getStream()
  1868.     {
  1869.         return this.stream;
  1870.     }

  1871.     /**
  1872.      * Retrieve the name.
  1873.      * @return the name (without the stream number)
  1874.      */
  1875.     public String getName()
  1876.     {
  1877.         return this.name;
  1878.     }

  1879.     /**
  1880.      * Retrieve the number of characters consumed from the input.
  1881.      * @return the number of characters consumed from the input
  1882.      */
  1883.     public int getNumberOfChars()
  1884.     {
  1885.         return this.numberOfChars;
  1886.     }

  1887.     @Override
  1888.     public String toString()
  1889.     {
  1890.         return "NameAndStream [name=" + this.name + ", stream=" + this.stream + ", numberOfChars=" + this.numberOfChars
  1891.                 + ", negated=" + this.negated + "]";
  1892.     }

  1893. }

  1894. /**
  1895.  * A TrafCOD variable, timer, or detector.
  1896.  */
  1897. class Variable implements EventListener
  1898. {
  1899.     /** ... */
  1900.     private static final long serialVersionUID = 20200313L;

  1901.     /** The TrafCOD engine. */
  1902.     private final TrafCod trafCOD;

  1903.     /** Flags. */
  1904.     private EnumSet<Flags> flags = EnumSet.noneOf(Flags.class);

  1905.     /** The current value. */
  1906.     private int value;

  1907.     /** Limit value (if this is a timer variable). */
  1908.     private int timerMax10;

  1909.     /** Output color (if this is an export variable). */
  1910.     private TrafficLightColor color;

  1911.     /** Name of this variable (without the traffic stream). */
  1912.     private final String name;

  1913.     /** Traffic stream number. */
  1914.     private final short stream;

  1915.     /** Number of rules that refer to this variable. */
  1916.     private int refCount;

  1917.     /** Time of last update in tenth of second. */
  1918.     private int updateTime10;

  1919.     /** Source of start rule. */
  1920.     private String startSource;

  1921.     /** Source of end rule. */
  1922.     private String endSource;

  1923.     /** The traffic light (only set if this Variable is an output). */
  1924.     private Set<TrafficLight> trafficLights;

  1925.     /** Letters that are used to distinguish conflict groups in the MRx variables. */
  1926.     private static String rowLetters = "ABCDXYZUVW";

  1927.     /**
  1928.      * Retrieve the number of rules that refer to this variable.
  1929.      * @return the number of rules that refer to this variable
  1930.      */
  1931.     public int getRefCount()
  1932.     {
  1933.         return this.refCount;
  1934.     }

  1935.     /**
  1936.      * Retrieve the traffic lights controlled by this variable.
  1937.      * @return the traffic lights controlled by this variable, or null when this variable has no traffic lights
  1938.      */
  1939.     public Set<TrafficLight> getTrafficLights()
  1940.     {
  1941.         return this.trafficLights;
  1942.     }

  1943.     /**
  1944.      * Construct a new Variable.
  1945.      * @param name name of the new variable (without the stream number)
  1946.      * @param stream stream number to which the new Variable is associated
  1947.      * @param trafCOD the TrafCOD engine
  1948.      */
  1949.     Variable(final String name, final short stream, final TrafCod trafCOD)
  1950.     {
  1951.         this.name = name.toUpperCase(Locale.US);
  1952.         this.stream = stream;
  1953.         this.trafCOD = trafCOD;
  1954.         if (this.name.startsWith("T"))
  1955.         {
  1956.             this.flags.add(Flags.IS_TIMER);
  1957.         }
  1958.         if (this.name.length() == 2 && this.name.startsWith("D") && Character.isDigit(this.name.charAt(1)))
  1959.         {
  1960.             this.flags.add(Flags.IS_DETECTOR);
  1961.         }
  1962.         if (TrafficController.NO_STREAM == stream && this.name.startsWith("MR") && this.name.length() == 3
  1963.                 && rowLetters.indexOf(this.name.charAt(2)) >= 0)
  1964.         {
  1965.             this.flags.add(Flags.CONFLICT_GROUP);
  1966.         }
  1967.     }

  1968.     /**
  1969.      * Retrieve the name of this variable.
  1970.      * @return the name (without the stream number) of this Variable
  1971.      */
  1972.     public String getName()
  1973.     {
  1974.         return this.name;
  1975.     }

  1976.     /**
  1977.      * Link a detector variable to a sensor.
  1978.      * @param sensor the sensor
  1979.      * @throws TrafficControlException when this variable is not a detector
  1980.      */
  1981.     public void subscribeToDetector(final TrafficLightDetector sensor) throws TrafficControlException
  1982.     {
  1983.         if (!isDetector())
  1984.         {
  1985.             throw new TrafficControlException("Cannot subscribe a non-detector to a TrafficLightSensor");
  1986.         }
  1987.         sensor.addListener(this, TrafficLightDetector.TRAFFIC_LIGHT_DETECTOR_TRIGGER_ENTRY_EVENT);
  1988.         sensor.addListener(this, TrafficLightDetector.TRAFFIC_LIGHT_DETECTOR_TRIGGER_EXIT_EVENT);
  1989.     }

  1990.     /**
  1991.      * Initialize this variable if it has the INITED flag set.
  1992.      */
  1993.     public void initialize()
  1994.     {
  1995.         if (this.flags.contains(Flags.INITED))
  1996.         {
  1997.             if (isTimer())
  1998.             {
  1999.                 setValue(this.timerMax10, 0, new CausePrinter("Timer initialization rule"), this.trafCOD);
  2000.             }
  2001.             else
  2002.             {
  2003.                 setValue(1, 0, new CausePrinter("Variable initialization rule"), this.trafCOD);
  2004.             }
  2005.         }
  2006.     }

  2007.     /**
  2008.      * Decrement the value of a timer.
  2009.      * @param timeStamp10 the current simulator time in tenths of a second
  2010.      * @return true if the timer expired due to this call; false if the timer is still running, or expired before this call
  2011.      * @throws TrafficControlException when this Variable is not a timer
  2012.      */
  2013.     public boolean decrementTimer(final int timeStamp10) throws TrafficControlException
  2014.     {
  2015.         if (!isTimer())
  2016.         {
  2017.             throw new TrafficControlException("Variable " + this + " is not a timer");
  2018.         }
  2019.         if (this.value <= 0)
  2020.         {
  2021.             return false;
  2022.         }
  2023.         if (0 == --this.value)
  2024.         {
  2025.             this.flags.add(Flags.CHANGED);
  2026.             this.flags.add(Flags.END);
  2027.             this.value = 0;
  2028.             this.updateTime10 = timeStamp10;
  2029.             if (this.flags.contains(Flags.TRACED))
  2030.             {
  2031.                 System.out.println("Timer " + toString() + " expired");
  2032.             }
  2033.             return true;
  2034.         }
  2035.         return false;
  2036.     }

  2037.     /**
  2038.      * Retrieve the color for an output Variable.
  2039.      * @return the color code for this Variable
  2040.      * @throws TrafficControlException if this Variable is not an output
  2041.      */
  2042.     public TrafficLightColor getColor() throws TrafficControlException
  2043.     {
  2044.         if (!this.flags.contains(Flags.IS_OUTPUT))
  2045.         {
  2046.             throw new TrafficControlException("Stream " + this.toString() + "is not an output");
  2047.         }
  2048.         return this.color;
  2049.     }

  2050.     /**
  2051.      * Report whether a change in this variable must be published.
  2052.      * @return true if this Variable is an output; false if this Variable is not an output
  2053.      */
  2054.     public boolean isOutput()
  2055.     {
  2056.         return this.flags.contains(Flags.IS_OUTPUT);
  2057.     }

  2058.     /**
  2059.      * Report of this Variable identifies the current conflict group.
  2060.      * @return true if this Variable identifies the current conflict group; false if it does not.
  2061.      */
  2062.     public boolean isConflictGroup()
  2063.     {
  2064.         return this.flags.contains(Flags.CONFLICT_GROUP);
  2065.     }

  2066.     /**
  2067.      * Retrieve the rank of the conflict group that this Variable represents.
  2068.      * @return the rank of the conflict group that this Variable represents
  2069.      * @throws TrafficControlException if this Variable is not a conflict group identifier
  2070.      */
  2071.     public int conflictGroupRank() throws TrafficControlException
  2072.     {
  2073.         if (!isConflictGroup())
  2074.         {
  2075.             throw new TrafficControlException("Variable " + this + " is not a conflict group identifier");
  2076.         }
  2077.         return rowLetters.indexOf(this.name.charAt(2));
  2078.     }

  2079.     /**
  2080.      * Report if this Variable is a detector.
  2081.      * @return true if this Variable is a detector; false if this Variable is not a detector
  2082.      */
  2083.     public boolean isDetector()
  2084.     {
  2085.         return this.flags.contains(Flags.IS_DETECTOR);
  2086.     }

  2087.     /**
  2088.      * @param newValue the new value of this Variable
  2089.      * @param timeStamp10 the time stamp of this update
  2090.      * @param cause rule, timer, or detector that caused the change
  2091.      * @param trafCODController the TrafCOD controller
  2092.      * @return true if the value of this variable changed
  2093.      */
  2094.     public boolean setValue(final int newValue, final int timeStamp10, final CausePrinter cause,
  2095.             final TrafCod trafCODController)
  2096.     {
  2097.         boolean result = false;
  2098.         if (this.value != newValue)
  2099.         {
  2100.             this.updateTime10 = timeStamp10;
  2101.             setFlag(Flags.CHANGED);
  2102.             if (0 == newValue)
  2103.             {
  2104.                 setFlag(Flags.END);
  2105.                 result = true;
  2106.             }
  2107.             else if (!isTimer() || 0 == this.value)
  2108.             {
  2109.                 setFlag(Flags.START);
  2110.                 result = true;
  2111.             }
  2112.             if (isOutput() && newValue != 0)
  2113.             {
  2114.                 for (TrafficLight trafficLight : this.trafficLights)
  2115.                 {
  2116.                     trafficLight.setTrafficLightColor(this.color);
  2117.                 }
  2118.             }
  2119.         }
  2120.         if (this.flags.contains(Flags.TRACED))
  2121.         {
  2122.             // System.out.println("Variable " + this.name + this.stream + " changes from " + this.value + " to " + newValue
  2123.             // + " due to " + cause.toString());
  2124.             trafCODController.fireTrafCODEvent(TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED,
  2125.                     new Object[] {trafCODController.getId(), toString(EnumSet.of(PrintFlags.ID)), this.stream, this.value,
  2126.                             newValue, cause.toString()});
  2127.         }
  2128.         this.value = newValue;
  2129.         return result;
  2130.     }

  2131.     /**
  2132.      * Copy the state of this variable from another variable. Only used when cloning the TrafCOD engine.
  2133.      * @param fromVariable the variable whose state is copied
  2134.      * @param newNetwork the Network that contains the new traffic control engine
  2135.      * @throws NetworkException when the clone of a traffic light of fromVariable does not exist in newNetwork
  2136.      */
  2137.     public void cloneState(final Variable fromVariable, final Network newNetwork) throws NetworkException
  2138.     {
  2139.         this.value = fromVariable.value;
  2140.         this.flags = EnumSet.copyOf(fromVariable.flags);
  2141.         this.updateTime10 = fromVariable.updateTime10;
  2142.         if (fromVariable.isOutput())
  2143.         {
  2144.             for (TrafficLight tl : fromVariable.trafficLights)
  2145.             {
  2146.                 LocatedObject clonedTrafficLight = newNetwork.getObjectMap().get(tl.getId());
  2147.                 if (null != clonedTrafficLight)
  2148.                 {
  2149.                     throw new NetworkException("newNetwork does not contain a clone of traffic light " + tl.getId());
  2150.                 }
  2151.                 if (clonedTrafficLight instanceof TrafficLight)
  2152.                 {
  2153.                     throw new NetworkException(
  2154.                             "newNetwork contains an object with name " + tl.getId() + " but this object is not a TrafficLight");
  2155.                 }
  2156.                 this.trafficLights.add((TrafficLight) clonedTrafficLight);
  2157.             }
  2158.         }
  2159.         if (isOutput())
  2160.         {
  2161.             for (TrafficLight trafficLight : this.trafficLights)
  2162.             {
  2163.                 trafficLight.setTrafficLightColor(this.color);
  2164.             }
  2165.         }
  2166.     }

  2167.     /**
  2168.      * Retrieve the start value of this timer in units of 0.1 seconds (1 second is represented by the value 10).
  2169.      * @return the timerMax10 value
  2170.      * @throws TrafficControlException when this class is not a Timer
  2171.      */
  2172.     public int getTimerMax() throws TrafficControlException
  2173.     {
  2174.         if (!this.isTimer())
  2175.         {
  2176.             throw new TrafficControlException("This is not a timer");
  2177.         }
  2178.         return this.timerMax10;
  2179.     }

  2180.     /**
  2181.      * Retrieve the current value of this Variable.
  2182.      * @return the value of this Variable
  2183.      */
  2184.     public int getValue()
  2185.     {
  2186.         return this.value;
  2187.     }

  2188.     /**
  2189.      * Set one flag.
  2190.      * @param flag Flags
  2191.      */
  2192.     public void setFlag(final Flags flag)
  2193.     {
  2194.         this.flags.add(flag);
  2195.     }

  2196.     /**
  2197.      * Clear one flag.
  2198.      * @param flag the flag to clear
  2199.      */
  2200.     public void clearFlag(final Flags flag)
  2201.     {
  2202.         this.flags.remove(flag);
  2203.     }

  2204.     /**
  2205.      * Report whether this Variable is a timer.
  2206.      * @return true if this Variable is a timer; false if this variable is not a timer
  2207.      */
  2208.     public boolean isTimer()
  2209.     {
  2210.         return this.flags.contains(Flags.IS_TIMER);
  2211.     }

  2212.     /**
  2213.      * Clear the CHANGED flag of this Variable.
  2214.      */
  2215.     public void clearChangedFlag()
  2216.     {
  2217.         this.flags.remove(Flags.CHANGED);
  2218.     }

  2219.     /**
  2220.      * Increment the reference counter of this variable. The reference counter counts the number of rules where this variable
  2221.      * occurs on the right hand side of the assignment operator.
  2222.      */
  2223.     public void incrementReferenceCount()
  2224.     {
  2225.         this.refCount++;
  2226.     }

  2227.     /**
  2228.      * Return a safe copy of the flags.
  2229.      * @return EnumSet&lt;Flags&gt;
  2230.      */
  2231.     public EnumSet<Flags> getFlags()
  2232.     {
  2233.         return EnumSet.copyOf(this.flags);
  2234.     }

  2235.     /**
  2236.      * Make this variable an output variable and set the color value.
  2237.      * @param colorValue the output value (as used in the TrafCOD file)
  2238.      * @throws TrafficControlException when the colorValue is invalid, or this method is called more than once for this variable
  2239.      */
  2240.     public void setOutput(final int colorValue) throws TrafficControlException
  2241.     {
  2242.         if (null != this.color)
  2243.         {
  2244.             throw new TrafficControlException("setOutput has already been called for " + this);
  2245.         }
  2246.         if (null == this.trafficLights)
  2247.         {
  2248.             this.trafficLights = new LinkedHashSet<>();
  2249.         }
  2250.         // Convert the TrafCOD color value to the corresponding TrafficLightColor
  2251.         TrafficLightColor newColor;
  2252.         switch (colorValue)
  2253.         {
  2254.             case 'R':
  2255.                 newColor = TrafficLightColor.RED;
  2256.                 break;
  2257.             case 'G':
  2258.                 newColor = TrafficLightColor.GREEN;
  2259.                 break;
  2260.             case 'Y':
  2261.                 newColor = TrafficLightColor.YELLOW;
  2262.                 break;
  2263.             default:
  2264.                 throw new TrafficControlException("Bad color value: " + colorValue);
  2265.         }
  2266.         this.color = newColor;
  2267.         this.flags.add(Flags.IS_OUTPUT);
  2268.     }

  2269.     /**
  2270.      * Add a traffic light to this variable.
  2271.      * @param trafficLight the traffic light to add
  2272.      * @throws TrafficControlException when this variable is not an output
  2273.      */
  2274.     public void addOutput(final TrafficLight trafficLight) throws TrafficControlException
  2275.     {
  2276.         if (!this.isOutput())
  2277.         {
  2278.             throw new TrafficControlException("Cannot add an output to an non-output variable");
  2279.         }
  2280.         this.trafficLights.add(trafficLight);
  2281.     }

  2282.     /**
  2283.      * Set the maximum time of this timer.
  2284.      * @param value10 the maximum time in 0.1 s
  2285.      * @throws TrafficControlException when this Variable is not a timer
  2286.      */
  2287.     public void setTimerMax(final int value10) throws TrafficControlException
  2288.     {
  2289.         if (!this.flags.contains(Flags.IS_TIMER))
  2290.         {
  2291.             throw new TrafficControlException(
  2292.                     "Cannot set maximum timer value of " + this.toString() + " because this is not a timer");
  2293.         }
  2294.         this.timerMax10 = value10;
  2295.     }

  2296.     /**
  2297.      * Describe the rule that starts this variable.
  2298.      * @return String
  2299.      */
  2300.     public String getStartSource()
  2301.     {
  2302.         return this.startSource;
  2303.     }

  2304.     /**
  2305.      * Set the description of the rule that starts this variable.
  2306.      * @param startSource description of the rule that starts this variable
  2307.      * @throws TrafficControlException when a start source has already been set
  2308.      */
  2309.     public void setStartSource(final String startSource) throws TrafficControlException
  2310.     {
  2311.         if (null != this.startSource)
  2312.         {
  2313.             throw new TrafficControlException("Conflicting rules: " + this.startSource + " vs " + startSource);
  2314.         }
  2315.         this.startSource = startSource;
  2316.         this.flags.add(Flags.HAS_START_RULE);
  2317.     }

  2318.     /**
  2319.      * Describe the rule that ends this variable.
  2320.      * @return String
  2321.      */
  2322.     public String getEndSource()
  2323.     {
  2324.         return this.endSource;
  2325.     }

  2326.     /**
  2327.      * Set the description of the rule that ends this variable.
  2328.      * @param endSource description of the rule that ends this variable
  2329.      * @throws TrafficControlException when an end source has already been set
  2330.      */
  2331.     public void setEndSource(final String endSource) throws TrafficControlException
  2332.     {
  2333.         if (null != this.endSource)
  2334.         {
  2335.             throw new TrafficControlException("Conflicting rules: " + this.startSource + " vs " + endSource);
  2336.         }
  2337.         this.endSource = endSource;
  2338.         this.flags.add(Flags.HAS_END_RULE);
  2339.     }

  2340.     /**
  2341.      * Retrieve the stream to which this variable belongs.
  2342.      * @return the stream to which this variable belongs
  2343.      */
  2344.     public short getStream()
  2345.     {
  2346.         return this.stream;
  2347.     }

  2348.     @Override
  2349.     public String toString()
  2350.     {
  2351.         return "Variable [" + toString(EnumSet.of(PrintFlags.ID, PrintFlags.VALUE, PrintFlags.FLAGS)) + "]";
  2352.     }

  2353.     /**
  2354.      * Convert selected fields to a String.
  2355.      * @param printFlags the set of fields to convert
  2356.      * @return String
  2357.      */
  2358.     public String toString(final EnumSet<PrintFlags> printFlags)
  2359.     {
  2360.         StringBuilder result = new StringBuilder();
  2361.         if (printFlags.contains(PrintFlags.ID))
  2362.         {
  2363.             if (this.flags.contains(Flags.IS_DETECTOR))
  2364.             {
  2365.                 result.append("D");
  2366.             }
  2367.             else if (isTimer() && printFlags.contains(PrintFlags.INITTIMER))
  2368.             {
  2369.                 result.append("I");
  2370.                 result.append(this.name);
  2371.             }
  2372.             else if (isTimer() && printFlags.contains(PrintFlags.REINITTIMER))
  2373.             {
  2374.                 result.append("RI");
  2375.                 result.append(this.name);
  2376.             }
  2377.             else
  2378.             {
  2379.                 result.append(this.name);
  2380.             }
  2381.             if (this.stream > 0)
  2382.             {
  2383.                 // Insert the stream BEFORE the first digit in the name (if any); otherwise append
  2384.                 int pos;
  2385.                 for (pos = 0; pos < result.length(); pos++)
  2386.                 {
  2387.                     if (Character.isDigit(result.charAt(pos)))
  2388.                     {
  2389.                         break;
  2390.                     }
  2391.                 }
  2392.                 result.insert(pos, String.format("%02d", this.stream));
  2393.             }
  2394.             if (this.flags.contains(Flags.IS_DETECTOR))
  2395.             {
  2396.                 result.append(this.name.substring(1));
  2397.             }
  2398.             if (printFlags.contains(PrintFlags.NEGATED))
  2399.             {
  2400.                 result.append("N");
  2401.             }
  2402.         }
  2403.         int printValue = Integer.MIN_VALUE; // That value should stand out if not changed by the code below this line.
  2404.         if (printFlags.contains(PrintFlags.VALUE))
  2405.         {
  2406.             if (printFlags.contains(PrintFlags.NEGATED))
  2407.             {
  2408.                 printValue = 0 == this.value ? 1 : 0;
  2409.             }
  2410.             else
  2411.             {
  2412.                 printValue = this.value;
  2413.             }
  2414.             if (printFlags.contains(PrintFlags.S))
  2415.             {
  2416.                 if (this.flags.contains(Flags.START))
  2417.                 {
  2418.                     printValue = 1;
  2419.                 }
  2420.                 else
  2421.                 {
  2422.                     printValue = 0;
  2423.                 }
  2424.             }
  2425.             if (printFlags.contains(PrintFlags.E))
  2426.             {
  2427.                 if (this.flags.contains(Flags.END))
  2428.                 {
  2429.                     printValue = 1;
  2430.                 }
  2431.                 else
  2432.                 {
  2433.                     printValue = 0;
  2434.                 }
  2435.             }
  2436.         }
  2437.         if (printFlags.contains(PrintFlags.VALUE) || printFlags.contains(PrintFlags.S) || printFlags.contains(PrintFlags.E)
  2438.                 || printFlags.contains(PrintFlags.FLAGS))
  2439.         {
  2440.             result.append("<");
  2441.             if (printFlags.contains(PrintFlags.VALUE) || printFlags.contains(PrintFlags.S) || printFlags.contains(PrintFlags.E))
  2442.             {
  2443.                 result.append(printValue);
  2444.             }
  2445.             if (printFlags.contains(PrintFlags.FLAGS))
  2446.             {
  2447.                 if (this.flags.contains(Flags.START))
  2448.                 {
  2449.                     result.append("S");
  2450.                 }
  2451.                 if (this.flags.contains(Flags.END))
  2452.                 {
  2453.                     result.append("E");
  2454.                 }
  2455.             }
  2456.             result.append(">");
  2457.         }
  2458.         if (printFlags.contains(PrintFlags.MODIFY_TIME))
  2459.         {
  2460.             result.append(String.format(" (%d.%d)", this.updateTime10 / 10, this.updateTime10 % 10));
  2461.         }
  2462.         return result.toString();
  2463.     }

  2464.     @Override
  2465.     public void notify(final Event event) throws RemoteException
  2466.     {
  2467.         if (event.getType().equals(TrafficLightDetector.TRAFFIC_LIGHT_DETECTOR_TRIGGER_ENTRY_EVENT))
  2468.         {
  2469.             setValue(1, this.updateTime10, new CausePrinter("Detector became occupied"), this.trafCOD);
  2470.         }
  2471.         else if (event.getType().equals(TrafficLightDetector.TRAFFIC_LIGHT_DETECTOR_TRIGGER_EXIT_EVENT))
  2472.         {
  2473.             setValue(0, this.updateTime10, new CausePrinter("Detector became unoccupied"), this.trafCOD);
  2474.         }
  2475.     }

  2476. }

  2477. /**
  2478.  * Class that can print a text version describing why a variable changed. Any work that has to be done (such as a call to
  2479.  * <code>TrafCOD.printRule</code>) is deferred until the <code>toString</code> method is called.
  2480.  */
  2481. class CausePrinter
  2482. {
  2483.     /** Object that describes the cause of the variable change. */
  2484.     private final Object cause;

  2485.     /**
  2486.      * Construct a new CausePrinter object.
  2487.      * @param cause this should be either a String, or a Object[] that contains a tokenized TrafCOD rule.
  2488.      */
  2489.     CausePrinter(final Object cause)
  2490.     {
  2491.         this.cause = cause;
  2492.     }

  2493.     @Override
  2494.     public String toString()
  2495.     {
  2496.         if (this.cause instanceof String)
  2497.         {
  2498.             return (String) this.cause;
  2499.         }
  2500.         else if (this.cause instanceof Object[])
  2501.         {
  2502.             try
  2503.             {
  2504.                 return TrafCod.printRule((Object[]) this.cause, true);
  2505.             }
  2506.             catch (TrafficControlException exception)
  2507.             {
  2508.                 exception.printStackTrace();
  2509.                 return ("printRule failed");
  2510.             }
  2511.         }
  2512.         return this.cause.toString();
  2513.     }
  2514. }

  2515. /**
  2516.  * Flags for toString method of a Variable.
  2517.  */
  2518. enum PrintFlags
  2519. {
  2520.     /** The name and stream of the Variable. */
  2521.     ID,
  2522.     /** The value of the Variable. */
  2523.     VALUE,
  2524.     /** Print "I" before the name (indicates that a timer is initialized). */
  2525.     INITTIMER,
  2526.     /** Print "RI" before the name (indicates that a timer is re-initialized). */
  2527.     REINITTIMER,
  2528.     /** Print value as "1" if just set, else print "0". */
  2529.     S,
  2530.     /** Print value as "1" if just reset, else print "0". */
  2531.     E,
  2532.     /** Print the negated Variable. */
  2533.     NEGATED,
  2534.     /** Print the flags of the Variable. */
  2535.     FLAGS,
  2536.     /** Print the time of last modification of the Variable. */
  2537.     MODIFY_TIME,
  2538. }

  2539. /**
  2540.  * Flags of a TrafCOD variable.
  2541.  */
  2542. enum Flags
  2543. {
  2544.     /** Variable becomes active. */
  2545.     START,
  2546.     /** Variable becomes inactive. */
  2547.     END,
  2548.     /** Timer has just expired. */
  2549.     TIMEREXPIRED,
  2550.     /** Variable has just changed value. */
  2551.     CHANGED,
  2552.     /** Variable is a timer. */
  2553.     IS_TIMER,
  2554.     /** Variable is a detector. */
  2555.     IS_DETECTOR,
  2556.     /** Variable has a start rule. */
  2557.     HAS_START_RULE,
  2558.     /** Variable has an end rule. */
  2559.     HAS_END_RULE,
  2560.     /** Variable is an output. */
  2561.     IS_OUTPUT,
  2562.     /** Variable must be initialized to 1 at start of control program. */
  2563.     INITED,
  2564.     /** Variable is traced; all changes must be printed. */
  2565.     TRACED,
  2566.     /** Variable identifies the currently active conflict group. */
  2567.     CONFLICT_GROUP,
  2568. }