%% Data Conversion Script
%% Authors: Juan Sanchez, Michiel Sandra
%% Date: 2022.09.19
% This script takes the input binary file from the measurements taken with
% the channel sounder and converts it into a .mat file for further
% processing in MATLAB
% Parameters to configure: Sampling rate, end time, input file name
% Output: .mat file with the same naming as the input file's

%% (Optional) Memory clearing procedure

clc; % Clear terminal
clear; % Clear workspace
close all; % Close all figures

%% Set parameters for data conversion script

sampleRate = 0; % Setting the sampling rate of the channel sounder [Hz]
endTime = 0; % Set an end time to get a subset/whole set of samples [seconds]
fileName = 'randomName'; % Naming for the file WITHOUT the .dat extension

%% Measurement stream extraction from file

fid = fopen([fileName,'.dat'], 'r'); % Open the file and create a file ID to call for reading
measurementStream = fread(fid, inf, 'int16'); % Read binary file with source data int16, output a vector
fclose(fid); % Close file

%% IQ data extraction from measurement stream

I = measurementStream(1:2:end); % Extract I samples
Q = measurementStream(2:2:end); % Extract Q samples

%% Fetching X ms of the signal

waveform = I(1:endTime*sampleRate)+1j*Q(1:endTime*sampleRate); % Get the requested amount of samples
clear I Q % Clear the IQ vectors for memory management reasons

%% (Debug visualization) Spectrogram of received waveform

% figure; % Initialize figure
% nfft = 4096; % Set a default FFT size of 4096 for NR, for debug spectrogram
% spectrogram(waveform,ones(nfft,1),0,nfft,'centered',sampleRate,'yaxis','MinThreshold',-130); % Plot spectrogram of the received data subset
% title('Spectrogram of the Received Waveform'); % Set title of the figure

%% Save waveform and sampling rate into .mat file

save([fileName,'.mat'],'waveform','sampleRate'); % Save a .mat version of the subset of samples into an array for further processing
