ModuleLimitedDataTransmitter: Changed TransmitData to apparently work now.
ModuleLimitedDataTransmitter: Changed TransmitData to apparently work now.

--- a/ARFlightController.cs
+++ b/ARFlightController.cs
@@ -165,7 +165,7 @@
 			if (this.appLauncherButton == null && !ToolbarManager.ToolbarAvailable && ApplicationLauncher.Ready)
 			{
 				this.appLauncherButton = ApplicationLauncher.Instance.AddModApplication(
-					ApplicationLauncher.AppScenes.FLIGHT,
+					ApplicationLauncher.AppScenes.FLIGHT | ApplicationLauncher.AppScenes.MAPVIEW,
 					this.appLauncherTextures[ConnectionStatus.None]
 				);
 			}
@@ -235,35 +235,63 @@
 
 			this.log.Clear();
 
-			if (
-				(this.toolbarButton != null || this.appLauncherButton != null) &&
-				HighLogic.LoadedSceneIsFlight &&
-				FlightGlobals.ActiveVessel != null
-			)
-			{
-				log.Append("Checking vessel relay status.\n");
-
-				this.currentConnectionStatus = FlightGlobals.ActiveVessel.GetConnectionStatus();
-
-				log.AppendFormat("currentConnectionStatus: {0}, setting texture to {1}",
-					this.currentConnectionStatus, this.currentConnectionTexture);
-
-				if (this.toolbarButton != null)
-				{
-					this.toolbarButton.TexturePath = this.currentConnectionTexture;
-
-					if (this.currentConnectionStatus == ConnectionStatus.None)
+			if (HighLogic.LoadedSceneIsFlight && FlightGlobals.ActiveVessel != null)
+			{
+				Vessel vessel;
+				IAntennaRelay relay;
+				IList<IAntennaRelay> activeVesselRelays;
+
+				for (int vIdx = 0; vIdx < FlightGlobals.Vessels.Count; vIdx++)
+				{
+					vessel = FlightGlobals.Vessels[vIdx];
+
+					if (vessel == FlightGlobals.ActiveVessel)
 					{
-						this.toolbarButton.Important = true;
+						continue;
 					}
-					else
+
+					relay = vessel.GetBestRelay();
+
+					if (relay != null)
 					{
-						this.toolbarButton.Important = false;
+						relay.FindNearestRelay();
 					}
 				}
-				if (this.appLauncherButton != null)
-				{
-					this.appLauncherButton.SetTexture(this.currentAppLauncherTexture);
+
+				activeVesselRelays = RelayDatabase.Instance[FlightGlobals.ActiveVessel];
+				for (int rIdx = 0; rIdx < activeVesselRelays.Count; rIdx++)
+				{
+					relay = activeVesselRelays[rIdx];
+
+					relay.FindNearestRelay();
+				}
+
+				if (this.toolbarButton != null || this.appLauncherButton != null)
+				{
+					log.Append("Checking vessel relay status.\n");
+
+					this.currentConnectionStatus = FlightGlobals.ActiveVessel.GetConnectionStatus();
+
+					log.AppendFormat("currentConnectionStatus: {0}, setting texture to {1}",
+						this.currentConnectionStatus, this.currentConnectionTexture);
+
+					if (this.toolbarButton != null)
+					{
+						this.toolbarButton.TexturePath = this.currentConnectionTexture;
+
+						if (this.currentConnectionStatus == ConnectionStatus.None)
+						{
+							if (!this.toolbarButton.Important) this.toolbarButton.Important = true;
+						}
+						else
+						{
+							if (this.toolbarButton.Important) this.toolbarButton.Important = false;
+						}
+					}
+					if (this.appLauncherButton != null)
+					{
+						this.appLauncherButton.SetTexture(this.currentAppLauncherTexture);
+					}
 				}
 			}
 

--- a/ARMapRenderer.cs
+++ b/ARMapRenderer.cs
@@ -26,8 +26,6 @@
 // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-#define DEBUG
-
 #pragma warning disable 1591
 
 using KSP;
@@ -43,8 +41,15 @@
 		#region Fields
 		private Dictionary<Guid, LineRenderer> vesselLineRenderers;
 
+		// Debug Stuff
+		#pragma warning disable 649
+		private System.Diagnostics.Stopwatch timer;
+		private Tools.DebugLogger log;
+		private long relayStart;
+		private long start;
+		#pragma warning restore 649
+
 		#pragma warning disable 414
-		private bool dumpBool;
 		private Color thisColor;
 		#pragma warning restore 414
 		#endregion
@@ -91,12 +96,12 @@
 			{
 				this.vesselLineRenderers = new Dictionary<Guid, LineRenderer>();
 			}
-		}
-
-		#if DEBUG
-		private System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
-		#endif
-		private Tools.DebugLogger log = Tools.DebugLogger.New(typeof(ARMapRenderer));
+
+			#if DEBUG
+			this.timer = new System.Diagnostics.Stopwatch();
+			this.log = Tools.DebugLogger.New(this);
+			#endif
+		}
 
 		private void OnPreCull()
 		{
@@ -109,7 +114,6 @@
 
 			#if DEBUG
 			timer.Restart();
-			long start;
 			#endif
 
 			try
@@ -134,9 +138,7 @@
 					{
 						Vessel vessel = FlightGlobals.Vessels[i];
 
-						#if DEBUG
 						log.AppendFormat("\nStarting check for vessel {0} at {1}ms", vessel, timer.ElapsedMilliseconds);
-						#endif
 
 						if (vessel == null)
 						{
@@ -163,10 +165,13 @@
 
 						IAntennaRelay vesselRelay = vessel.GetBestRelay();
 
-						#if DEBUG
-						log.AppendFormat("\n\tGot best relay {0} for vessel {1} in {2} ms",
-							vesselRelay, vessel, timer.ElapsedMilliseconds - start);
-						#endif
+						if (vesselRelay == null)
+						{
+							continue;
+						}
+
+						log.AppendFormat("\n\tGot best relay {0} ({3}) for vessel {1} in {2} ms",
+							vesselRelay, vessel, timer.ElapsedMilliseconds - start, vesselRelay.GetType().Name);
 
 						if (vesselRelay != null)
 						{
@@ -176,10 +181,8 @@
 
 							this.SetRelayVertices(vesselRelay);
 
-							#if DEBUG
 							log.AppendFormat("\n\tSet relay vertices for {0} in {1}ms",
 								vessel, timer.ElapsedMilliseconds - start);
-							#endif
 						}
 					}
 				}
@@ -208,12 +211,15 @@
 		#endregion
 
 		#region Utility
-		#if DEBUG
-		private long relayStart;
-		#endif
 		private void SetRelayVertices(IAntennaRelay relay)
 		{
 			log.AppendFormat("\n\t\tDrawing line for relay chain starting at {0}.", relay);
+
+			if (relay.vessel == null)
+			{
+				log.Append("\n\t\tvessel is null, bailing out");
+				return;
+			}
 
 			LineRenderer renderer = this[relay.vessel.id];
 			Vector3d start = ScaledSpace.LocalToScaledSpace(relay.vessel.GetWorldPos3D());
@@ -240,7 +246,9 @@
 
 			int idx = 0;
 
+			#if DEBUG
 			relayStart = timer.ElapsedMilliseconds;
+			#endif
 
 			Vector3d nextPoint;
 

--- a/AntennaRange.csproj
+++ b/AntennaRange.csproj
@@ -80,7 +80,6 @@
     <Compile Include="ARConfiguration.cs" />
     <Compile Include="ARFlightController.cs" />
     <Compile Include="ARMapRenderer.cs" />
-    <Compile Include="VesselCache.cs" />
   </ItemGroup>
   <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
   <ItemGroup>

--- a/AntennaRelay.cs
+++ b/AntennaRelay.cs
@@ -37,8 +37,8 @@
 	/// </summary>
 	public class AntennaRelay
 	{
-		public static readonly System.Diagnostics.Stopwatch searchTimer = new System.Diagnostics.Stopwatch();
-		public const long millisecondsBetweenSearches = 125L;
+		private static readonly System.Diagnostics.Stopwatch searchTimer = new System.Diagnostics.Stopwatch();
+		private const long millisecondsBetweenSearches = 125L;
 
 		// We don't have a Bard, so we'll hide Kerbin here.
 		private static CelestialBody _Kerbin;
@@ -111,8 +111,6 @@
 		{
 			get
 			{
-				//this.FindNearestRelay();
-
 				if (this.KerbinDirect || this.targetRelay == null)
 				{
 					return this.DistanceTo(Kerbin);
@@ -159,7 +157,6 @@
 		/// <returns><c>true</c> if this instance can transmit; otherwise, <c>false</c>.</returns>
 		public virtual bool CanTransmit()
 		{
-			//this.FindNearestRelay();
 			return this.canTransmit;
 		}
 
@@ -167,7 +164,7 @@
 		/// Finds the nearest relay.
 		/// </summary>
 		/// <returns>The nearest relay or null, if no relays in range.</returns>
-		private void FindNearestRelay()
+		public void FindNearestRelay()
 		{
 			if (!FlightGlobals.ready)
 			{
@@ -632,7 +629,9 @@
 			#if DEBUG
 			} catch (Exception ex) {
 				log.AppendFormat("\nCaught {0}: {1}\n{2}", ex.GetType().FullName, ex.ToString(), ex.StackTrace);
+			#if QUIT_ON_EXCEPTION
 				UnityEngine.Application.Quit();
+			#endif
 			} finally {
 			#endif
 			log.Print(false);
@@ -666,6 +665,8 @@
 		{
 			this.moduleRef = module;
 			this.isChecked = false;
+
+			Tools.PostLogMessage("{0}: constructed {1}", this.GetType().Name, this.ToString());
 		}
 	}
 }

--- a/IAntennaRelay.cs
+++ b/IAntennaRelay.cs
@@ -83,6 +83,8 @@
 		/// </summary>
 		bool CanTransmit();
 
+		void FindNearestRelay();
+
 		/// <summary>
 		/// Returns a <see cref="System.String"/> that represents the current <see cref="AntennaRange.IAntennaRelay"/>.
 		/// </summary>

--- a/ModuleLimitedDataTransmitter.cs
+++ b/ModuleLimitedDataTransmitter.cs
@@ -436,6 +436,14 @@
 			return this.relay.CanTransmit();
 		}
 
+		public void FindNearestRelay()
+		{
+			if (this.relay != null)
+			{
+				this.relay.FindNearestRelay();
+			}
+		}
+
 		/// <summary>
 		/// Override ModuleDataTransmitter.TransmitData to check against CanTransmit and fail out when CanTransmit
 		/// returns false.
@@ -444,6 +452,13 @@
 		/// <param name="callback">Callback function</param>
 		public new void TransmitData(List<ScienceData> dataQueue, Callback callback)
 		{
+			this.LogDebug(
+				"TransmitData(List<ScienceData> dataQueue, Callback callback) called.  dataQueue.Count={0}",
+				dataQueue.Count
+			);
+
+			this.FindNearestRelay();
+
 			this.PreTransmit_SetPacketSize();
 			this.PreTransmit_SetPacketResourceCost();
 
@@ -451,7 +466,20 @@
 			{
 				ScreenMessages.PostScreenMessage(this.buildTransmitMessage(), 4f, ScreenMessageStyle.UPPER_LEFT);
 
-				base.TransmitData(dataQueue, callback);
+				this.LogDebug(
+					"CanTransmit in TransmitData, calling base.TransmitData with dataQueue=[{0}] and callback={1}",
+					dataQueue.SPrint(),
+					callback == null ? "null" : callback.ToString()
+				);
+
+				if (callback == null)
+				{
+					base.TransmitData(dataQueue);
+				}
+				else
+				{
+					base.TransmitData(dataQueue, callback);
+				}
 			}
 			else
 			{
@@ -549,6 +577,11 @@
 		/// <param name="dataQueue">List of <see cref="ScienceData"/> to transmit.</param>
 		public new void TransmitData(List<ScienceData> dataQueue)
 		{
+			this.LogDebug(
+				"TransmitData(List<ScienceData> dataQueue) called, dataQueue.Count={0}",
+				dataQueue.Count
+			);
+
 			this.TransmitData(dataQueue, null);
 		}
 
@@ -558,6 +591,8 @@
 		/// </summary>
 		public new void StartTransmission()
 		{
+			this.FindNearestRelay();
+
 			PreTransmit_SetPacketSize ();
 			PreTransmit_SetPacketResourceCost ();
 
@@ -702,12 +737,6 @@
 
 				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;
@@ -729,12 +758,6 @@
 				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;

--- a/ProtoAntennaRelay.cs
+++ b/ProtoAntennaRelay.cs
@@ -54,6 +54,12 @@
 				}
 				else
 				{
+					Tools.PostLogMessage("{0}: Could not fetch vessel!  {1}{2}{3}",
+						this.ToString(),
+						this.protoPart == null ? "\n\tprotoPart=Null" : string.Empty,
+						this.protoPart != null && this.protoPart.pVesselRef == null ? "\n\tthis.protoPart.pVesselRef=Null" : string.Empty,
+						this.protoPart != null && this.protoPart.pVesselRef != null && this.protoPart.pVesselRef.vesselRef == null ? "\n\tthis.protoPart.pVesselRef.vesselRef=Null" : string.Empty
+					);
 					return null;
 				}
 			}
@@ -146,6 +152,8 @@
 		public ProtoAntennaRelay(IAntennaRelay prefabRelay, ProtoPartSnapshot pps) : base(prefabRelay)
 		{
 			this.protoPart = pps;
+
+			Tools.PostLogMessage("{0}: constructed {1}", this.GetType().Name, this.ToString());
 		}
 	}
 }

--- a/RelayDatabase.cs
+++ b/RelayDatabase.cs
@@ -143,6 +143,7 @@
 			}
 			else
 			{
+				var dump = this[vessel];
 				return null;
 			}
 		}
@@ -358,7 +359,7 @@
 								module
 							));
 
-							relay = (module as IAntennaRelay);
+							relay = new ProtoAntennaRelay(module as IAntennaRelay, pps);
 
 							if (relay.maxTransmitDistance > bestRelayRange)
 							{
@@ -367,7 +368,7 @@
 							}
 
 							// ...build a new ProtoAntennaRelay and add it to the table
-							relays.Add(new ProtoAntennaRelay(relay, pps));
+							relays.Add(relay);
 							// ...neglect relay objects after the first in each part.
 							break;
 						}

--- a/RelayExtensions.cs
+++ b/RelayExtensions.cs
@@ -166,45 +166,7 @@
 		/// <param name="vessel">This <see cref="Vessel"/></param>
 		public static IAntennaRelay GetBestRelay(this Vessel vessel)
 		{
-			BestVesselRelayCache relayCache;
-
-			if (RelayDatabase.Instance.TryGetBestVesselRelay(vessel, out relayCache))
-			{
-				if (
-					AntennaRelay.searchTimer.ElapsedMilliseconds - relayCache.timeStamp <
-					AntennaRelay.millisecondsBetweenSearches
-				)
-				{
-					return relayCache.relay;
-				}
-			}
-			else
-			{
-				relayCache = new BestVesselRelayCache();
-				relayCache.vessel = vessel;
-				RelayDatabase.Instance.SetBestVesselRelay(vessel, relayCache);
-			}
-
-			double bestScore = double.PositiveInfinity;
-			double relayScore = double.NaN;
-
-			IList<IAntennaRelay> vesselRelays = RelayDatabase.Instance[vessel];
-			IAntennaRelay relay;
-			for (int rIdx = 0; rIdx < vesselRelays.Count; rIdx++)
-			{
-				relay = vesselRelays[rIdx];
-				relayScore = relay.transmitDistance / relay.maxTransmitDistance;
-
-				if (relayScore < bestScore)
-				{
-					bestScore = relayScore;
-					relayCache.relay = relay;
-				}
-			}
-
-			relayCache.timeStamp = AntennaRelay.searchTimer.ElapsedMilliseconds;
-
-			return relayCache.relay;
+			return RelayDatabase.Instance.GetBestVesselRelay(vessel);
 		}
 	}
 

file:a/VesselCache.cs (deleted)
--- a/VesselCache.cs
+++ /dev/null
@@ -1,16 +1,1 @@
-// AntennaRange © 2015 toadicus
-//
-// This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a
-// copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
-using System;
 
-namespace AntennaRange
-{
-	public class Relay
-	{
-		public Vessel vessel;
-		public IAntennaRelay targetRelay;
-	}
-}
-
-