From c0fe88a5bbfb0bda329b59e41d80a22d0a00b400 Mon Sep 17 00:00:00 2001
From: Thomas Harte <thomas.harte@gmail.com>
Date: Mon, 9 Jan 2023 13:54:49 -0500
Subject: [PATCH] Apply clock conversion to existing usages of
 do_external_slot.

---
 .../9918/Implementation/ClockConverter.hpp     | 18 ++++++++++++++++++
 Components/9918/Implementation/Fetch.hpp       | 12 +++---------
 2 files changed, 21 insertions(+), 9 deletions(-)

diff --git a/Components/9918/Implementation/ClockConverter.hpp b/Components/9918/Implementation/ClockConverter.hpp
index f6ae33bd5..ce7f50657 100644
--- a/Components/9918/Implementation/ClockConverter.hpp
+++ b/Components/9918/Implementation/ClockConverter.hpp
@@ -182,6 +182,24 @@ template <Personality personality> class ClockConverter {
 			}
 		}
 
+		/*!
+			Converts a position in TMS access cycles back to one at the native
+			clock rate.
+		*/
+		static constexpr int from_tms_access_clock(int source) {
+			switch(personality) {
+				default:
+				return source << 1;
+
+				case Personality::V9938:
+				case Personality::V9958:
+				return source << 3;
+
+				case Personality::MDVDP:
+				return source * 20;
+			}
+		}
+
 		/*!
 			Converts a position in internal cycles to its corresponding position
 			on the TMS pixel clock, i.e. scales to 342 clocks per line.
diff --git a/Components/9918/Implementation/Fetch.hpp b/Components/9918/Implementation/Fetch.hpp
index 03c3d9478..c44ab0822 100644
--- a/Components/9918/Implementation/Fetch.hpp
+++ b/Components/9918/Implementation/Fetch.hpp
@@ -41,19 +41,13 @@
 	for the exceptions.
 */
 
-// TODO: external_slot needs to do a proper conversion back to the internal clock,
-// not assume a multiply by two.
-//
-// (and, for MSX 2 purposes, it would ideally know how many cycles since the last access
-// slot, probably, but I'm not completely sure that's necessary yet)
-
 #define slot(n)	\
 	if(use_end && end == n) return;	\
 	[[fallthrough]];				\
 	case n
 
 #define external_slot(n)	\
-	slot(n): do_external_slot((n)*2);
+	slot(n): do_external_slot(clock_converter_.from_tms_access_clock(n));
 
 #define external_slots_2(n)	\
 	external_slot(n);		\
@@ -286,7 +280,7 @@ template<bool use_end> void Base<personality>::fetch_tms_character(int start, in
 
 		slot(31):
 			sprite_selection_buffer.reset_sprite_collection();
-			do_external_slot(31*2);
+			do_external_slot(clock_converter_.from_tms_access_clock(31));
 		external_slots_2(32);
 		external_slot(34);
 
@@ -437,7 +431,7 @@ template<bool use_end> void Base<personality>::fetch_sms(int start, int end) {
 
 		slot(29):
 			sprite_selection_buffer.reset_sprite_collection();
-			do_external_slot(29*2);
+			do_external_slot(clock_converter_.from_tms_access_clock(29));
 		external_slot(30);
 
 		sprite_y_read(31, 0);