ms: flexible template for value_type buffer sum

Manual attempts to get the number of complex and single samples right
turned out to be a bit error prone at times...

Change-Id: I3c9953073555e3a7f70b78b0946dfdf949175a82
diff --git a/Transceiver52M/ms/ms.h b/Transceiver52M/ms/ms.h
index 8ca9b02..ad2d056 100644
--- a/Transceiver52M/ms/ms.h
+++ b/Transceiver52M/ms/ms.h
@@ -84,16 +84,19 @@
 template <typename T>
 struct is_complex : std::false_type {
 	using baset = T;
+	static const unsigned int len_mul = 1;
 };
 
 template <typename T>
 struct is_complex<std::complex<T>> : std::true_type {
 	using baset = typename std::complex<T>::value_type;
+	static const unsigned int len_mul = 2;
 };
 
 template <typename T>
 struct is_complex<Complex<T>> : std::true_type {
 	using baset = typename Complex<T>::value_type;
+	static const unsigned int len_mul = 2;
 };
 
 } // namespace cvt_internal
@@ -106,6 +109,19 @@
 	return cvt_internal::convert_and_scale_i((vd *)dst, (vs *)src, src_len, scale);
 }
 
+template <typename array_t>
+float normed_abs_sum(array_t *src, int len)
+{
+	using vd = typename cvt_internal::is_complex<array_t>::baset;
+	auto len_mul = cvt_internal::is_complex<array_t>::len_mul;
+	auto ptr = reinterpret_cast<const vd *>(src);
+	float sum = 0;
+	for (unsigned int i = 0; i < len * len_mul; i++)
+		sum += std::abs(ptr[i]);
+	sum /= len * len_mul;
+	return sum;
+}
+
 struct one_burst {
 	one_burst()
 	{
diff --git a/Transceiver52M/ms/ms_rx_lower.cpp b/Transceiver52M/ms/ms_rx_lower.cpp
index 26ee131..1872c6c 100644
--- a/Transceiver52M/ms/ms_rx_lower.cpp
+++ b/Transceiver52M/ms/ms_rx_lower.cpp
@@ -101,11 +101,7 @@
 	const unsigned int rx_max_cutoff = (rxFullScale * 2) / 3;
 	static int gain_check = 0;
 	static float runmean = 0;
-	float sum = 0;
-	for (auto i : brst.burst)
-		sum += abs(i.real()) + abs(i.imag());
-	sum /= ONE_TS_BURST_LEN * 2;
-
+	float sum = normed_abs_sum(&brst.burst[0], ONE_TS_BURST_LEN);
 	runmean = gain_check ? (runmean * (gain_check + 2) - 1 + sum) / (gain_check + 2) : sum;
 
 	if (gain_check == avgburst_num - 1) {
@@ -231,12 +227,8 @@
 		sch_pos = 0;
 		rcv_done = true;
 		auto sch_search_fun = [this] {
-			auto ptr = reinterpret_cast<const int16_t *>(first_sch_buf);
 			const auto target_val = rxFullScale / 8;
-			float sum = 0;
-			for (unsigned int i = 0; i < SCH_LEN_SPS * 2; i++)
-				sum += std::abs(ptr[i]);
-			sum /= SCH_LEN_SPS * 2;
+			float sum = normed_abs_sum(first_sch_buf, SCH_LEN_SPS);
 
 			//FIXME: arbitrary value, gain cutoff
 			if (sum > target_val || rxgain >= 60) // enough ?