ARMapRenderer: Use fewer LineRenderers drawing multi-segment lines when we can.
ARMapRenderer: Use fewer LineRenderers drawing multi-segment lines when we can.

--- a/ARMapRenderer.cs
+++ b/ARMapRenderer.cs
@@ -38,6 +38,8 @@
 	{
 		#region Fields
 		private Dictionary<Guid, LineRenderer> vesselLineRenderers;
+		private Dictionary<Guid, bool> vesselFrameCache;
+		private bool dumpBool;
 		#endregion
 
 		#region Properties
@@ -50,21 +52,27 @@
 					this.vesselLineRenderers = new Dictionary<Guid, LineRenderer>();
 				}
 
-				if (!this.vesselLineRenderers.ContainsKey(idx))
+				LineRenderer lr;
+
+				if (this.vesselLineRenderers.TryGetValue(idx, out lr))
+				{
+					return lr;
+				}
+				else
 				{
 					GameObject obj = new GameObject();
 					obj.layer = 31;
 
-					LineRenderer lr = obj.AddComponent<LineRenderer>();
-
-					lr.SetColors(Color.green, Color.green);
+					lr = obj.AddComponent<LineRenderer>();
+
+					// lr.SetColors(Color.green, Color.green);
 					lr.material = MapView.OrbitLinesMaterial;
-					lr.SetVertexCount(2);
+					// lr.SetVertexCount(2);
 
 					this.vesselLineRenderers[idx] = lr;
-				}
-
-				return this.vesselLineRenderers[idx];
+
+					return lr;
+				}
 			}
 		}
 		#endregion
@@ -75,6 +83,7 @@
 			if (ARConfiguration.PrettyLines)
 			{
 				this.vesselLineRenderers = new Dictionary<Guid, LineRenderer>();
+				this.vesselFrameCache = new Dictionary<Guid, bool>();
 			}
 		}
 
@@ -101,6 +110,8 @@
 					MapView.MapCamera.Distance
 				);
 
+				this.vesselFrameCache.Clear();
+
 				log.AppendLine("vesselFrameCache cleared.");
 
 				if (FlightGlobals.ready && FlightGlobals.Vessels != null)
@@ -112,6 +123,12 @@
 						if (vessel == null)
 						{
 							log.AppendFormat("Skipping vessel {0} altogether because it is null.\n");
+							continue;
+						}
+
+						if (this.vesselFrameCache.TryGetValue(vessel.id, out dumpBool))
+						{
+							log.AppendFormat("Skipping vessel {0} because it's already been processed this frame.");
 							continue;
 						}
 
@@ -128,41 +145,12 @@
 								continue;
 						}
 
-						log.Append("\tChecking connection status...\n");
-
-						/*if (vessel.HasConnectedRelay())
-						{
-							log.AppendLine("\tHas a connection, checking for the best relay to use for the line.");*/
-
-							IAntennaRelay vesselRelay = null;
-							float bestScore = float.PositiveInfinity;
-							float relayScore = float.NaN;
-
-							foreach (IAntennaRelay relay in RelayDatabase.Instance[vessel].Values)
-							{
-								relayScore = (float)relay.transmitDistance / relay.maxTransmitDistance;
-
-								if (relayScore < bestScore)
-								{
-									bestScore = relayScore;
-									vesselRelay = relay as IAntennaRelay;
-								}
-							}
-
-							if (vesselRelay != null)
-							{
-								log.AppendFormat("\t...picked relay {0} with a score of {1}", 
-									vesselRelay, relayScore
-								);
-
-								this.SetRelayVertices(vesselRelay);
-							}
-						/*}
-						else if (this.vesselLineRenderers.ContainsKey(vessel.id))
-						{
-							log.AppendLine("\tDisabling line because vessel has no connection.");
-							this[vessel.id].enabled = false;
-						}*/
+						IAntennaRelay vesselRelay = vessel.GetBestRelay();
+
+						if (vesselRelay != null)
+						{
+							this.SetRelayVertices(vesselRelay);
+						}
 					}
 				}
 			}
@@ -188,71 +176,90 @@
 
 		private void SetRelayVertices(IAntennaRelay relay)
 		{
-			if (relay == null)
-			{
-				return;
-			}
+			Color lastColor = default(Color);
+			Color thisColor;
 
 			LineRenderer renderer = this[relay.vessel.id];
-
-			Vector3d start;
-			Vector3d end;
-
-			renderer.enabled = true;
-
-			if (!relay.CanTransmit())
-			{
-				renderer.SetColors(Color.red, Color.red);
+			Vector3d start = ScaledSpace.LocalToScaledSpace(relay.vessel.GetWorldPos3D());
+
+			float lineWidth;
+			float d = Screen.height / 2f + 0.01f;
+
+			if (MapView.Draw3DLines)
+			{
+				lineWidth = 0.005859375f * MapView.MapCamera.Distance;
 			}
 			else
 			{
-				if (relay.transmitDistance < relay.nominalTransmitDistance)
-				{
-					renderer.SetColors(Color.green, Color.green);
+				lineWidth = 2f;
+
+				start = MapView.MapCamera.camera.WorldToScreenPoint(start);
+
+				start.z = start.z >= 0f ? d : -d;
+			}
+
+			renderer.SetWidth(lineWidth, lineWidth);
+
+			renderer.SetPosition(0, start);
+
+			int idx = 0;
+
+			while (relay != null)
+			{
+				Vector3d nextPoint;
+
+				renderer.enabled = true;
+
+				if (!relay.CanTransmit())
+				{
+					thisColor = Color.red;
 				}
 				else
 				{
-					renderer.SetColors(Color.yellow, Color.yellow);
-				}
-			}
-
-			start = ScaledSpace.LocalToScaledSpace(relay.vessel.GetWorldPos3D());
-
-			if (relay.KerbinDirect)
-			{
-				end = ScaledSpace.LocalToScaledSpace(AntennaRelay.Kerbin.position);
-			}
-			else
-			{
-				if (relay.targetRelay == null)
-				{
-					return;
-				}
-				end = ScaledSpace.LocalToScaledSpace(relay.targetRelay.vessel.GetWorldPos3D());
-			}
-
-			float lineWidth;
-
-			if (MapView.Draw3DLines)
-			{
-				lineWidth = 0.005859375f * MapView.MapCamera.Distance;
-			}
-			else
-			{
-				lineWidth = 2f;
-
-				start = MapView.MapCamera.camera.WorldToScreenPoint(start);
-				end = MapView.MapCamera.camera.WorldToScreenPoint(end);
-
-				float d = Screen.height / 2f + 0.01f;
-				start.z = start.z >= 0f ? d : -d;
-				end.z = end.z >= 0f ? d : -d;
-			}
-
-			renderer.SetWidth(lineWidth, lineWidth);
-
-			renderer.SetPosition(0, start);
-			renderer.SetPosition(1, end);
+					if (relay.transmitDistance < relay.nominalTransmitDistance)
+					{
+						thisColor = Color.green;
+					}
+					else
+					{
+						thisColor = Color.yellow;
+					}
+				}
+
+				if (lastColor != default(Color) && thisColor != lastColor)
+				{
+					break;
+				}
+
+				lastColor = thisColor;
+				renderer.SetColors(thisColor, thisColor);
+
+				this.vesselFrameCache[relay.vessel.id] = true;
+
+				if (relay.KerbinDirect)
+				{
+					nextPoint = ScaledSpace.LocalToScaledSpace(AntennaRelay.Kerbin.position);
+					relay = null;
+				}
+				else
+				{
+					if (relay.targetRelay == null)
+					{
+						return;
+					}
+
+					nextPoint = ScaledSpace.LocalToScaledSpace(relay.targetRelay.vessel.GetWorldPos3D());
+					relay = relay.targetRelay;
+				}
+
+				if (!MapView.Draw3DLines)
+				{
+					nextPoint = MapView.MapCamera.camera.WorldToScreenPoint(nextPoint);
+					nextPoint.z = nextPoint.z >= 0f ? d : -d;
+				}
+
+				renderer.SetPosition(++idx, nextPoint);
+			}
 		}
 
 		public void Cleanup()
@@ -266,6 +273,11 @@
 				}
 				this.vesselLineRenderers.Clear();
 			}
+
+			if (this.vesselFrameCache != null && this.vesselFrameCache.Count > 0)
+			{
+				this.vesselFrameCache.Clear();
+			}
 		}
 	}
 }

--- a/AntennaRelay.cs
+++ b/AntennaRelay.cs
@@ -33,10 +33,17 @@
 
 namespace AntennaRange
 {
+	/// <summary>
+	/// Relay code at the heart of AntennaRange
+	/// </summary>
 	public class AntennaRelay
 	{
 		// We don't have a Bard, so we'll hide Kerbin here.
 		private static CelestialBody _Kerbin;
+
+		/// <summary>
+		/// Fetches, caches, and returns a <see cref="CelestialBody"/> reference to Kerbin
+		/// </summary>
 		public static CelestialBody Kerbin
 		{
 			get
@@ -50,12 +57,19 @@
 			}
 		}
 
-		protected bool canTransmit;
-
+		private bool canTransmit;
+
+		private IAntennaRelay nearestRelay;
+		private IAntennaRelay bestOccludedRelay;
+
+		private System.Diagnostics.Stopwatch searchTimer;
+		private long millisecondsBetweenSearches;
+
+		/// <summary>
+		/// The <see cref="AntennaRange.ModuleLimitedDataTransmitter"/> reference underlying this AntennaRelay, as an
+		/// <see cref="AntennaRange.IAntennaRelay"/>
+		/// </summary>
 		protected IAntennaRelay moduleRef;
-
-		protected System.Diagnostics.Stopwatch searchTimer;
-		protected long millisecondsBetweenSearches;
 
 		/// <summary>
 		/// Gets the parent Vessel.
@@ -70,36 +84,23 @@
 		}
 
 		/// <summary>
-		/// Gets or sets the nearest relay.
-		/// </summary>
-		/// <value>The nearest relay</value>
-		public IAntennaRelay nearestRelay
+		/// Gets the target <see cref="AntennaRange.IAntennaRelay"/>relay.
+		/// </summary>
+		public IAntennaRelay targetRelay
 		{
 			get;
 			protected set;
 		}
 
-		public IAntennaRelay bestOccludedRelay
+		/// <summary>
+		/// Gets the first <see cref="CelestialBody"/> found to be blocking line of sight.
+		/// </summary>
+		public virtual CelestialBody firstOccludingBody
 		{
 			get;
 			protected set;
 		}
 
-		public IAntennaRelay targetRelay
-		{
-			get;
-			protected set;
-		}
-
-		/// <summary>
-		/// Gets the first <see cref="CelestialBody"/> found to be blocking line of sight.
-		/// </summary>
-		public virtual CelestialBody firstOccludingBody
-		{
-			get;
-			protected set;
-		}
-
 		/// <summary>
 		/// Gets the transmit distance.
 		/// </summary>
@@ -121,6 +122,9 @@
 			}
 		}
 
+		/// <summary>
+		/// Gets the nominal transmit distance at which the Antenna behaves just as prescribed by Squad's config.
+		/// </summary>
 		public virtual double nominalTransmitDistance
 		{
 			get;
@@ -131,12 +135,16 @@
 		/// The maximum distance at which this relay can operate.
 		/// </summary>
 		/// <value>The max transmit distance.</value>
-		public virtual float maxTransmitDistance
+		public virtual double maxTransmitDistance
 		{
 			get;
 			set;
 		}
 
+		/// <summary>
+		/// Gets a value indicating whether this <see cref="AntennaRange.IAntennaRelay"/> Relay is communicating
+		/// directly with Kerbin.
+		/// </summary>
 		public virtual bool KerbinDirect
 		{
 			get;
@@ -489,6 +497,10 @@
 			RelayDatabase.Instance.CheckedVesselsTable.Remove(vessel.id);
 		}
 
+		/// <summary>
+		/// Returns a <see cref="System.String"/> that represents the current <see cref="AntennaRange.AntennaRelay"/>.
+		/// </summary>
+		/// <returns>A <see cref="System.String"/> that represents the current <see cref="AntennaRange.AntennaRelay"/>.</returns>
 		public override string ToString()
 		{
 			if (this is ProtoAntennaRelay)
@@ -499,9 +511,10 @@
 		}
 
 		/// <summary>
-		/// Initializes a new instance of the <see cref="AntennaRange.ProtoDataTransmitter"/> class.
-		/// </summary>
-		/// <param name="ms"><see cref="ProtoPartModuleSnapshot"/></param>
+		/// Initializes a new instance of the <see cref="AntennaRange.AntennaRelay"/> class.
+		/// </summary>
+		/// <param name="module">The module reference underlying this AntennaRelay,
+		/// as an <see cref="AntennaRange.IAntennaRelay"/></param>
 		public AntennaRelay(IAntennaRelay module)
 		{
 			this.moduleRef = module;

--- a/IAntennaRelay.cs
+++ b/IAntennaRelay.cs
@@ -31,41 +31,39 @@
 
 namespace AntennaRange
 {
-	/*
-	 * Interface defining the basic functionality of AntennaRelay modules for AntennaRange.
-	 * */
+	/// <summary>
+	/// Interface defining the basic functionality of AntennaRelay modules for AntennaRange.
+	/// </summary>
 	public interface IAntennaRelay
 	{
 		/// <summary>
 		/// Gets the parent Vessel.
 		/// </summary>
-		/// <value>The parent Vessel.</value>
 		Vessel vessel { get; }
 
-		IAntennaRelay nearestRelay { get; }
-
-		IAntennaRelay bestOccludedRelay { get; }
-
+		/// <summary>
+		/// Gets the target <see cref="AntennaRange.IAntennaRelay"/>relay.
+		/// </summary>
 		IAntennaRelay targetRelay { get; }
 
 		/// <summary>
 		/// Gets the distance to the nearest relay or Kerbin, whichever is closer.
 		/// </summary>
-		/// <value>The distance to the nearest relay or Kerbin, whichever is closer.</value>
 		double transmitDistance { get; }
 
+		/// <summary>
+		/// Gets the nominal transmit distance at which the Antenna behaves just as prescribed by Squad's config.
+		/// </summary>
 		double nominalTransmitDistance { get; }
 
 		/// <summary>
 		/// The maximum distance at which this relay can operate.
 		/// </summary>
-		/// <value>The max transmit distance.</value>
-		float maxTransmitDistance { get; }
+		double maxTransmitDistance { get; }
 
 		/// <summary>
 		/// The first CelestialBody blocking line of sight to a 
 		/// </summary>
-		/// <value>The first occluding body.</value>
 		CelestialBody firstOccludingBody { get; }
 
 		/// <summary>
@@ -75,14 +73,20 @@
 		bool KerbinDirect { get; }
 
 		/// <summary>
+		/// Gets the Part title.
+		/// </summary>
+		string Title { get; }
+
+		/// <summary>
 		/// Determines whether this instance can transmit.
+		/// <c>true</c> if this instance can transmit; otherwise, <c>false</c>.
 		/// </summary>
-		/// <returns><c>true</c> if this instance can transmit; otherwise, <c>false</c>.</returns>
 		bool CanTransmit();
 
+		/// <summary>
+		/// Returns a <see cref="System.String"/> that represents the current <see cref="AntennaRange.IAntennaRelay"/>.
+		/// </summary>
 		string ToString();
-
-		string Title { get; }
 	}
 }
 

--- a/ModuleLimitedDataTransmitter.cs
+++ b/ModuleLimitedDataTransmitter.cs
@@ -36,71 +36,90 @@
 
 namespace AntennaRange
 {
-	/*
-	 * ModuleLimitedDataTransmitter is designed as a drop-in replacement for ModuleDataTransmitter, and handles range-
-	 * finding, power scaling, and data scaling for antennas during science transmission.  Its functionality varies with
-	 * three tunables: nominalRange, maxPowerFactor, and maxDataFactor, set in .cfg files.
-	 * 
-	 * In general, the scaling functions assume the following relation:
-	 * 
-	 *     D² α P/R,
-	 * 
-	 * where D is the total transmission distance, P is the transmission power, and R is the data rate.
-	 * 
-	 * */
-
-	/*
-	 * Fields
-	 * */
+	/// <summary>
+	/// <para>ModuleLimitedDataTransmitter is designed as a drop-in replacement for ModuleDataTransmitter, and handles
+	/// rangefinding, power scaling, and data scaling for antennas during science transmission.  Its functionality
+	/// varies with three tunables: nominalRange, maxPowerFactor, and maxDataFactor, set in .cfg files.</para>
+	/// 
+	/// <para>In general, the scaling functions assume the following relation:</para>
+	/// 
+	///	<para>	D² α P/R,</para>
+	/// 
+	/// <para>where D is the total transmission distance, P is the transmission power, and R is the data rate.</para>
+	/// </summary>
 	public class ModuleLimitedDataTransmitter : ModuleDataTransmitter, IScienceDataTransmitter, IAntennaRelay
 	{
 		// Stores the packetResourceCost as defined in the .cfg file.
-		protected float _basepacketResourceCost;
+		private float _basepacketResourceCost;
 
 		// Stores the packetSize as defined in the .cfg file.
-		protected float _basepacketSize;
+		private float _basepacketSize;
 
 		// Every antenna is a relay.
-		protected AntennaRelay relay;
-
-		// Keep track of vessels with transmitters for relay purposes.
-		protected List<Vessel> _relayVessels;
+		private AntennaRelay relay;
 
 		// Sometimes we will need to communicate errors; this is how we do it.
-		protected ScreenMessage ErrorMsg;
-
-		// The distance from Kerbin at which the antenna will perform exactly as prescribed by packetResourceCost
-		// and packetSize.
+		private ScreenMessage ErrorMsg;
+
+		/// <summary>
+		/// The distance from Kerbin at which the antenna will perform exactly as prescribed by packetResourceCost
+		/// and packetSize.
+		/// </summary>
 		[KSPField(isPersistant = false)]
-		public float nominalRange;
-
+		public double nominalRange;
+
+		/// <summary>
+		/// Relay status string for use in action menus.
+		/// </summary>
 		[KSPField(isPersistant = false, guiActive = true, guiName = "Status")]
 		public string UIrelayStatus;
 
+		/// <summary>
+		/// Relay target string for use in action menus.
+		/// </summary>
 		[KSPField(isPersistant = false, guiActive = true, guiName = "Relay")]
 		public string UIrelayTarget;
 
+		/// <summary>
+		/// Transmit distance string for use in action menus.
+		/// </summary>
 		[KSPField(isPersistant = false, guiActive = true, guiName = "Transmission Distance")]
 		public string UItransmitDistance;
 
+		/// <summary>
+		/// Maximum distance string for use in action menus.
+		/// </summary>
 		[KSPField(isPersistant = false, guiActive = true, guiName = "Maximum Distance")]
 		public string UImaxTransmitDistance;
 
+		/// <summary>
+		/// Packet size string for use in action menus.
+		/// </summary>
 		[KSPField(isPersistant = false, guiActive = true, guiName = "Packet Size")]
 		public string UIpacketSize;
 
+		/// <summary>
+		/// Packet cost string for use in action menus.
+		/// </summary>
 		[KSPField(isPersistant = false, guiActive = true, guiName = "Packet Cost")]
 		public string UIpacketCost;
 
-		// The multiplier on packetResourceCost that defines the maximum power output of the antenna.  When the power
-		// cost exceeds packetResourceCost * maxPowerFactor, transmission will fail.
+		/// <summary>
+		/// The multiplier on packetResourceCost that defines the maximum power output of the antenna.  When the power
+		/// cost exceeds packetResourceCost * maxPowerFactor, transmission will fail.
+		/// </summary>
 		[KSPField(isPersistant = false)]
 		public float maxPowerFactor;
 
-		// The multipler on packetSize that defines the maximum data bandwidth of the antenna.
+		/// <summary>
+		/// The multipler on packetSize that defines the maximum data bandwidth of the antenna.
+		/// </summary>
 		[KSPField(isPersistant = false)]
 		public float maxDataFactor;
 
+		/// <summary>
+		/// The packet throttle.
+		/// </summary>
 		[KSPField(
 			isPersistant = true,
 			guiName = "Packet Throttle",
@@ -111,12 +130,14 @@
 		[UI_FloatRange(maxValue = 100f, minValue = 2.5f, stepIncrement = 2.5f)]
 		public float packetThrottle;
 
-		protected bool actionUIUpdate;
+		private bool actionUIUpdate;
 
 		/*
 		 * Properties
 		 * */
-		// Returns the parent vessel housing this antenna.
+		/// <summary>
+		/// Gets the parent Vessel.
+		/// </summary>
 		public new Vessel vessel
 		{
 			get
@@ -137,7 +158,10 @@
 			}
 		}
 
-		public IAntennaRelay nearestRelay
+		/// <summary>
+		/// Gets the target <see cref="AntennaRange.IAntennaRelay"/>relay.
+		/// </summary>
+		public IAntennaRelay targetRelay
 		{
 			get
 			{
@@ -146,43 +170,19 @@
 					return null;
 				}
 
-				return this.relay.nearestRelay;
-			}
-		}
-
-		public IAntennaRelay bestOccludedRelay
+				return this.relay.targetRelay;
+			}
+		}
+
+		/// <summary>
+		/// Gets the distance to the nearest relay or Kerbin, whichever is closer.
+		/// </summary>
+		public double transmitDistance
 		{
 			get
 			{
 				if (this.relay == null)
 				{
-					return null;
-				}
-
-				return this.relay.bestOccludedRelay;
-			}
-		}
-
-		public IAntennaRelay targetRelay
-		{
-			get
-			{
-				if (this.relay == null)
-				{
-					return null;
-				}
-
-				return this.relay.targetRelay;
-			}
-		}
-
-		// Returns the distance to the nearest relay or Kerbin, whichever is closer.
-		public double transmitDistance
-		{
-			get
-			{
-				if (this.relay == null)
-				{
 					return double.PositiveInfinity;
 				}
 
@@ -190,6 +190,9 @@
 			}
 		}
 
+		/// <summary>
+		/// Gets the nominal transmit distance at which the Antenna behaves just as prescribed by Squad's config.
+		/// </summary>
 		public double nominalTransmitDistance
 		{
 			get
@@ -198,16 +201,21 @@
 			}
 		}
 
-		// Returns the maximum distance this module can transmit
-		public float maxTransmitDistance
+		/// <summary>
+		/// The maximum distance at which this relay can operate.
+		/// </summary>
+		public double maxTransmitDistance
 		{
 			get
 			{
 				// TODO: Cache this in a way that doesn't break everything.
-				return Mathf.Sqrt(this.maxPowerFactor) * this.nominalRange;
-			}
-		}
-
+				return Math.Sqrt(this.maxPowerFactor) * this.nominalRange;
+			}
+		}
+
+		/// <summary>
+		/// The first CelestialBody blocking line of sight to a 
+		/// </summary>
 		public CelestialBody firstOccludingBody
 		{
 			get
@@ -242,8 +250,10 @@
 		 * 
 		 * So... hopefully that doesn't screw with anything else.
 		 * */
-		// Override ModuleDataTransmitter.DataRate to just return packetSize, because we want antennas to be scored in
-		// terms of joules/byte
+		/// <summary>
+		/// Override ModuleDataTransmitter.DataRate to just return packetSize, because we want antennas to be scored in
+		/// terms of joules/byte
+		/// </summary>
 		public new float DataRate
 		{
 			get
@@ -261,9 +271,11 @@
 			}
 		}
 
-		// Override ModuleDataTransmitter.DataResourceCost to just return packetResourceCost, because we want antennas
-		// to be scored in terms of joules/byte
-		public new float DataResourceCost
+		/// <summary>
+		/// Override ModuleDataTransmitter.DataResourceCost to just return packetResourceCost, because we want antennas
+		/// to be scored in terms of joules/byte
+		/// </summary>
+		public new double DataResourceCost
 		{
 			get
 			{
@@ -280,6 +292,10 @@
 			}
 		}
 
+		/// <summary>
+		/// Gets a value indicating whether this <see cref="AntennaRange.IAntennaRelay"/> Relay is communicating
+		/// directly with Kerbin.
+		/// </summary>
 		public bool KerbinDirect
 		{
 			get
@@ -293,6 +309,9 @@
 			}
 		}
 
+		/// <summary>
+		/// Gets the Part title.
+		/// </summary>
 		public string Title
 		{
 			get
@@ -316,6 +335,9 @@
 			this.packetThrottle = 100f;
 		}
 
+		/// <summary>
+		/// PartModule OnAwake override; runs at Unity Awake.
+		/// </summary>
 		public override void OnAwake()
 		{
 			base.OnAwake();
@@ -339,7 +361,10 @@
 			));
 		}
 
-		// At least once, when the module starts with a state on the launch pad or later, go find Kerbin.
+		/// <summary>
+		/// PartModule OnStart override; runs at Unity Start.
+		/// </summary>
+		/// <param name="state">State.</param>
 		public override void OnStart (StartState state)
 		{
 			base.OnStart (state);
@@ -357,9 +382,12 @@
 			}
 		}
 
-		// When the module loads, fetch the Squad KSPFields from the base.  This is necessary in part because
-		// overloading packetSize and packetResourceCostinto a property in ModuleLimitedDataTransmitter didn't
-		// work.
+		/// <summary>
+		/// When the module loads, fetch the Squad KSPFields from the base.  This is necessary in part because
+		/// overloading packetSize and packetResourceCostinto a property in ModuleLimitedDataTransmitter didn't
+		/// work.
+		/// </summary>
+		/// <param name="node"><see cref="ConfigNode"/> with data for this module.</param>
 		public override void OnLoad(ConfigNode node)
 		{
 			this.Fields.Load(node);
@@ -368,81 +396,9 @@
 			base.OnLoad (node);
 		}
 
-		// Post an error in the communication messages describing the reason transmission has failed.  Currently there
-		// is only one reason for this.
-		protected void PostCannotTransmitError()
-		{
-			string ErrorText = string.Intern("Unable to transmit: no visible receivers in range!");
-
-			this.ErrorMsg.message = string.Format(
-				"<color='#{0}{1}{2}{3}'><b>{4}</b></color>",
-				((int)(XKCDColors.OrangeRed.r * 255f)).ToString("x2"),
-				((int)(XKCDColors.OrangeRed.g * 255f)).ToString("x2"),
-				((int)(XKCDColors.OrangeRed.b * 255f)).ToString("x2"),
-				((int)(XKCDColors.OrangeRed.a * 255f)).ToString("x2"),
-				ErrorText
-			);
-
-			Tools.PostDebugMessage(this.GetType().Name + ": " + this.ErrorMsg.message);
-
-			ScreenMessages.PostScreenMessage(this.ErrorMsg, false);
-		}
-
-		// Before transmission, set packetResourceCost.  Per above, packet cost increases with the square of
-		// distance.  packetResourceCost maxes out at _basepacketResourceCost * maxPowerFactor, at which point
-		// transmission fails (see CanTransmit).
-		protected void PreTransmit_SetPacketResourceCost()
-		{
-			if (ARConfiguration.FixedPowerCost || this.transmitDistance <= this.nominalRange)
-			{
-				base.packetResourceCost = this._basepacketResourceCost;
-			}
-			else
-			{
-				double rangeFactor = (this.transmitDistance / this.nominalRange);
-				rangeFactor *= rangeFactor;
-
-				base.packetResourceCost = this._basepacketResourceCost
-					* (float)rangeFactor;
-
-				Tools.PostDebugMessage(
-					this,
-					"Pretransmit: packet cost set to {0} before throttle (rangeFactor = {1}).",
-					base.packetResourceCost,
-					rangeFactor);
-			}
-
-			base.packetResourceCost *= this.packetThrottle / 100f;
-		}
-
-		// Before transmission, set packetSize.  Per above, packet size increases with the inverse square of
-		// distance.  packetSize maxes out at _basepacketSize * maxDataFactor.
-		protected void PreTransmit_SetPacketSize()
-		{
-			if (!ARConfiguration.FixedPowerCost && this.transmitDistance >= this.nominalRange)
-			{
-				base.packetSize = this._basepacketSize;
-			}
-			else
-			{
-				double rangeFactor = (this.nominalRange / this.transmitDistance);
-				rangeFactor *= rangeFactor;
-
-				base.packetSize = Math.Min(
-					this._basepacketSize * (float)rangeFactor,
-					this._basepacketSize * this.maxDataFactor);
-
-				Tools.PostDebugMessage(
-					this,
-					"Pretransmit: packet size set to {0} before throttle (rangeFactor = {1}).",
-					base.packetSize,
-					rangeFactor);
-			}
-
-			base.packetSize *= this.packetThrottle / 100f;
-		}
-
-		// Override ModuleDataTransmitter.GetInfo to add nominal and maximum range to the VAB description.
+		/// <summary>
+		/// Override ModuleDataTransmitter.GetInfo to add nominal and maximum range to the VAB description.
+		/// </summary>
 		public override string GetInfo()
 		{
 			string text = base.GetInfo();
@@ -451,7 +407,10 @@
 			return text;
 		}
 
-		// Override ModuleDataTransmitter.CanTransmit to return false when transmission is not possible.
+		/// <summary>
+		/// Determines whether this instance can transmit.
+		/// <c>true</c> if this instance can transmit; otherwise, <c>false</c>.
+		/// </summary>
 		public new bool CanTransmit()
 		{
 			if (this.part == null || this.relay == null)
@@ -459,51 +418,41 @@
 				return false;
 			}
 
-			PartStates partState = this.part.State;
-			if (partState == PartStates.DEAD || partState == PartStates.DEACTIVATED)
-			{
-				Tools.PostDebugMessage(string.Format(
-					"{0}: {1} on {2} cannot transmit: {3}",
-					this.GetType().Name,
-					this.part.partInfo.title,
-					this.vessel.vesselName,
-					Enum.GetName(typeof(PartStates), partState)
-				));
-				return false;
-			}
+			switch (this.part.State)
+			{
+				case PartStates.DEAD:
+				case PartStates.DEACTIVATED:
+					Tools.PostDebugMessage(string.Format(
+						"{0}: {1} on {2} cannot transmit: {3}",
+						this.GetType().Name,
+						this.part.partInfo.title,
+						this.vessel.vesselName,
+						Enum.GetName(typeof(PartStates), this.part.State)
+					));
+					return false;
+				default:
+					break;
+			}
+
 			return this.relay.CanTransmit();
 		}
 
-		// Override ModuleDataTransmitter.TransmitData to check against CanTransmit and fail out when CanTransmit
-		// returns false.
-		public new void TransmitData(List<ScienceData> dataQueue)
+		/// <summary>
+		/// Override ModuleDataTransmitter.TransmitData to check against CanTransmit and fail out when CanTransmit
+		/// returns false.
+		/// </summary>
+		/// <param name="dataQueue">List of <see cref="ScienceData"/> to transmit.</param>
+		/// <param name="callback">Callback function</param>
+		public new void TransmitData(List<ScienceData> dataQueue, Callback callback)
 		{
 			this.PreTransmit_SetPacketSize();
 			this.PreTransmit_SetPacketResourceCost();
 
 			if (this.CanTransmit())
 			{
-				StringBuilder message = new StringBuilder();
-
-				message.Append("[");
-				message.Append(base.part.partInfo.title);
-				message.Append("]: ");
-
-				message.Append("Beginning transmission ");
-
-				if (this.KerbinDirect)
-				{
-					message.Append("directly to Kerbin.");
-				}
-				else
-				{
-					message.Append("via ");
-					message.Append(this.relay.targetRelay);
-				}
-
-				ScreenMessages.PostScreenMessage(message.ToString(), 4f, ScreenMessageStyle.UPPER_LEFT);
-
-				base.TransmitData(dataQueue);
+				ScreenMessages.PostScreenMessage(this.buildTransmitMessage(), 4f, ScreenMessageStyle.UPPER_LEFT);
+
+				base.TransmitData(dataQueue, callback);
 			}
 			else
 			{
@@ -568,7 +517,7 @@
 
 					foreach (ScienceData data in dataQueue)
 					{
-						msg.AppendFormat("\n{0}\n", data.title);
+						msg.AppendFormat("\t{0}\n", data.title);
 					}
 
 					ScreenMessages.PostScreenMessage(msg.ToString(), 4f, ScreenMessageStyle.UPPER_LEFT);
@@ -576,7 +525,7 @@
 					Tools.PostDebugMessage(msg.ToString());
 				}
 
-				this.PostCannotTransmitError ();
+				this.PostCannotTransmitError();
 			}
 
 			Tools.PostDebugMessage (
@@ -586,8 +535,20 @@
 			);
 		}
 
-		// Override ModuleDataTransmitter.StartTransmission to check against CanTransmit and fail out when CanTransmit
-		// returns false.
+		/// <summary>
+		/// Override ModuleDataTransmitter.TransmitData to check against CanTransmit and fail out when CanTransmit
+		/// returns false.
+		/// </summary>
+		/// <param name="dataQueue">List of <see cref="ScienceData"/> to transmit.</param>
+		public new void TransmitData(List<ScienceData> dataQueue)
+		{
+			this.TransmitData(dataQueue, null);
+		}
+
+		/// <summary>
+		/// Override ModuleDataTransmitter.StartTransmission to check against CanTransmit and fail out when CanTransmit
+		/// returns false.
+		/// </summary>
 		public new void StartTransmission()
 		{
 			PreTransmit_SetPacketSize ();
@@ -601,25 +562,7 @@
 
 			if (this.CanTransmit())
 			{
-				StringBuilder message = new StringBuilder();
-
-				message.Append("[");
-				message.Append(base.part.partInfo.title);
-				message.Append("]: ");
-
-				message.Append("Beginning transmission ");
-
-				if (this.KerbinDirect)
-				{
-					message.Append("directly to Kerbin.");
-				}
-				else
-				{
-					message.Append("via ");
-					message.Append(this.relay.targetRelay);
-				}
-
-				ScreenMessages.PostScreenMessage(message.ToString(), 4f, ScreenMessageStyle.UPPER_LEFT);
+				ScreenMessages.PostScreenMessage(this.buildTransmitMessage(), 4f, ScreenMessageStyle.UPPER_LEFT);
 
 				base.StartTransmission();
 			}
@@ -629,6 +572,9 @@
 			}
 		}
 
+		/// <summary>
+		/// MonoBehaviour Update
+		/// </summary>
 		public void Update()
 		{
 			if (this.actionUIUpdate)
@@ -666,22 +612,10 @@
 			}
 		}
 
-		public void onPartActionUICreate(Part eventPart)
-		{
-			if (eventPart == base.part)
-			{
-				this.actionUIUpdate = true;
-			}
-		}
-
-		public void onPartActionUIDismiss(Part eventPart)
-		{
-			if (eventPart == base.part)
-			{
-				this.actionUIUpdate = false;
-			}
-		}
-
+		/// <summary>
+		/// Returns a <see cref="System.String"/> that represents the current <see cref="AntennaRange.ModuleLimitedDataTransmitter"/>.
+		/// </summary>
+		/// <returns>A <see cref="System.String"/> that represents the current <see cref="AntennaRange.ModuleLimitedDataTransmitter"/>.</returns>
 		public override string ToString()
 		{
 			StringBuilder msg = new StringBuilder();
@@ -707,8 +641,123 @@
 			return msg.ToString();
 		}
 
+		// When we catch an onPartActionUICreate event for our part, go ahead and update every frame to look pretty.
+		private void onPartActionUICreate(Part eventPart)
+		{
+			if (eventPart == base.part)
+			{
+				this.actionUIUpdate = true;
+			}
+		}
+
+		// When we catch an onPartActionUIDismiss event for our part, stop updating every frame to look pretty.
+		private void onPartActionUIDismiss(Part eventPart)
+		{
+			if (eventPart == base.part)
+			{
+				this.actionUIUpdate = false;
+			}
+		}
+
+		// Post an error in the communication messages describing the reason transmission has failed.  Currently there
+		// is only one reason for this.
+		private void PostCannotTransmitError()
+		{
+			string ErrorText = string.Intern("Unable to transmit: no visible receivers in range!");
+
+			this.ErrorMsg.message = string.Format(
+				"<color='#{0}{1}{2}{3}'><b>{4}</b></color>",
+				((int)(XKCDColors.OrangeRed.r * 255f)).ToString("x2"),
+				((int)(XKCDColors.OrangeRed.g * 255f)).ToString("x2"),
+				((int)(XKCDColors.OrangeRed.b * 255f)).ToString("x2"),
+				((int)(XKCDColors.OrangeRed.a * 255f)).ToString("x2"),
+				ErrorText
+			);
+
+			Tools.PostDebugMessage(this.GetType().Name + ": " + this.ErrorMsg.message);
+
+			ScreenMessages.PostScreenMessage(this.ErrorMsg, false);
+		}
+
+		// Before transmission, set packetResourceCost.  Per above, packet cost increases with the square of
+		// distance.  packetResourceCost maxes out at _basepacketResourceCost * maxPowerFactor, at which point
+		// transmission fails (see CanTransmit).
+		private void PreTransmit_SetPacketResourceCost()
+		{
+			if (ARConfiguration.FixedPowerCost || this.transmitDistance <= this.nominalRange)
+			{
+				base.packetResourceCost = this._basepacketResourceCost;
+			}
+			else
+			{
+				float rangeFactor = (float)(this.transmitDistance / this.nominalRange);
+				rangeFactor *= rangeFactor;
+
+				base.packetResourceCost = this._basepacketResourceCost
+					* rangeFactor;
+
+				Tools.PostDebugMessage(
+					this,
+					"Pretransmit: packet cost set to {0} before throttle (rangeFactor = {1}).",
+					base.packetResourceCost,
+					rangeFactor);
+			}
+
+			base.packetResourceCost *= this.packetThrottle / 100f;
+		}
+
+		// Before transmission, set packetSize.  Per above, packet size increases with the inverse square of
+		// distance.  packetSize maxes out at _basepacketSize * maxDataFactor.
+		private void PreTransmit_SetPacketSize()
+		{
+			if (!ARConfiguration.FixedPowerCost && this.transmitDistance >= this.nominalRange)
+			{
+				base.packetSize = this._basepacketSize;
+			}
+			else
+			{
+				float rangeFactor = (float)(this.nominalRange / this.transmitDistance);
+				rangeFactor *= rangeFactor;
+
+				base.packetSize = Mathf.Min(
+					this._basepacketSize * rangeFactor,
+					this._basepacketSize * this.maxDataFactor);
+
+				Tools.PostDebugMessage(
+					this,
+					"Pretransmit: packet size set to {0} before throttle (rangeFactor = {1}).",
+					base.packetSize,
+					rangeFactor);
+			}
+
+			base.packetSize *= this.packetThrottle / 100f;
+		}
+
+		private string buildTransmitMessage()
+		{
+			StringBuilder message = new StringBuilder();
+
+			message.Append("[");
+			message.Append(base.part.partInfo.title);
+			message.Append("]: ");
+
+			message.Append("Beginning transmission ");
+
+			if (this.KerbinDirect)
+			{
+				message.Append("directly to Kerbin.");
+			}
+			else
+			{
+				message.Append("via ");
+				message.Append(this.relay.targetRelay);
+			}
+
+			return message.ToString();
+		}
+
+		#if DEBUG
 		// When debugging, it's nice to have a button that just tells you everything.
-
 		[KSPEvent (guiName = "Show Debug Info", active = true, guiActive = true)]
 		public void DebugInfo()
 		{
@@ -728,10 +777,9 @@
 				"DataRate: {9}\n" +
 				"DataResourceCost: {10}\n" +
 				"TransmitterScore: {11}\n" +
-				"NearestRelay: {12}\n" +
-				"BestOccludedRelay: {13}\n" +
-				"KerbinDirect: {14}\n" +
-				"Vessel ID: {15}",
+				"targetRelay: {12}\n" +
+				"KerbinDirect: {13}\n" +
+				"Vessel ID: {14}",
 				this.name,
 				this._basepacketSize,
 				base.packetSize,
@@ -744,8 +792,7 @@
 				this.DataRate,
 				this.DataResourceCost,
 				ScienceUtil.GetTransmitterScore(this),
-				this.relay.nearestRelay == null ? "null" : this.relay.nearestRelay.ToString(),
-				this.relay.bestOccludedRelay == null ? "null" : this.relay.bestOccludedRelay.ToString(),
+				this.relay.targetRelay == null ? "null" : this.relay.targetRelay.ToString(),
 				this.KerbinDirect,
 				this.vessel.id
 				);
@@ -767,11 +814,12 @@
 
 			Tools.PostDebugMessage(sb.ToString());
 		}
-
-		/*[KSPEvent (guiName = "Dump RelayDB", active = true, guiActive = true)]
+		 
+		[KSPEvent (guiName = "Dump RelayDB", active = true, guiActive = true)]
 		public void DumpRelayDB()
 		{
 			RelayDatabase.Instance.Dump();
-		}*/
+		}
+		#endif
 	}
 }

--- a/ProtoAntennaRelay.cs
+++ b/ProtoAntennaRelay.cs
@@ -40,16 +40,29 @@
 	public class ProtoAntennaRelay : AntennaRelay, IAntennaRelay
 	{
 		// Stores the prototype part so we can make sure we haven't exploded or so.
-		protected ProtoPartSnapshot protoPart;
+		private ProtoPartSnapshot protoPart;
 
+		/// <summary>
+		/// Gets the parent Vessel.
+		/// </summary>
 		public override Vessel vessel
 		{
 			get
 			{
-				return this.protoPart.pVesselRef.vesselRef;
+				if (this.protoPart != null && this.protoPart.pVesselRef != null)
+				{
+					return this.protoPart.pVesselRef.vesselRef;
+				}
+				else
+				{
+					return null;
+				}
 			}
 		}
 
+		/// <summary>
+		/// Gets the nominal transmit distance at which the Antenna behaves just as prescribed by Squad's config.
+		/// </summary>
 		public override double nominalTransmitDistance
 		{
 			get
@@ -59,10 +72,9 @@
 		}
 
 		/// <summary>
-		/// The maximum distance at which this transmitter can operate.
+		/// The maximum distance at which this relay can operate.
 		/// </summary>
-		/// <value>The max transmit distance.</value>
-		public override float maxTransmitDistance
+		public override double maxTransmitDistance
 		{
 			get
 			{
@@ -87,6 +99,10 @@
 			}
 		}
 
+		/// <summary>
+		/// Determines whether this instance can transmit.
+		/// <c>true</c> if this instance can transmit; otherwise, <c>false</c>.
+		/// </summary>
 		public override bool CanTransmit()
 		{
 			PartStates partState = (PartStates)this.protoPart.state;
@@ -104,6 +120,10 @@
 			return base.CanTransmit();
 		}
 
+		/// <summary>
+		/// Returns a <see cref="System.String"/> that represents the current <see cref="AntennaRange.ProtoAntennaRelay"/>.
+		/// </summary>
+		/// <returns>A <see cref="System.String"/> that represents the current <see cref="AntennaRange.ProtoAntennaRelay"/>.</returns>
 		public override string ToString()
 		{
 			return string.Format(

--- a/RelayExtensions.cs
+++ b/RelayExtensions.cs
@@ -135,6 +135,26 @@
 				return ConnectionStatus.None;
 			}
 		}
+
+		public static IAntennaRelay GetBestRelay(this Vessel vessel)
+		{
+			IAntennaRelay bestRelay = null;
+			double bestScore = double.PositiveInfinity;
+			double relayScore = double.NaN;
+
+			foreach (IAntennaRelay relay in vessel.GetAntennaRelays())
+			{
+				relayScore = relay.transmitDistance / relay.maxTransmitDistance;
+
+				if (relayScore < bestScore)
+				{
+					bestScore = relayScore;
+					bestRelay = relay;
+				}
+			}
+
+			return bestRelay;
+		}
 	}
 
 	public enum ConnectionStatus