function spectrogram_analysis(signal, fs_Hz, freq_range_to_show_Hz, title_str)
% Function to explore a time signal in the time and spectro-temporal domain
%
% 2018 Matlab Course at the CBU
%
% F. Guérit and A. Archer-Boyd


%% Calculate time axis

len_sig_samp = length(signal); % Duration of signal in samples
len_sig_sec = len_sig_samp / fs_Hz; % Duration of signal in seconds
time_signal_sec = 0:1/fs_Hz:(len_sig_sec - 1/fs_Hz); % time value in seconds for each sample of the signal

%% Plot time signal

figure

subplot(2, 1, 1)
plot(time_signal_sec, signal, 'linewidth', 1)

% Make the plot pretty and informative
xlim([0 len_sig_sec])
ylim([-1 1])
box on
title(['Time domain: ' title_str])
xlabel('Time (sec)')

% The following is needed to align this plot with spectrogram plot
c = colorbar;
c.Visible = 'off';

%% Plot spectrogram

subplot(2, 1, 2)

% You can modify the following value to improve the analysis
n_samples_window = 512;

% Derived parameters that should work ok with the size of the window
n_overlap = round(n_samples_window/2);
n_fft = n_samples_window;

spectrogram(signal, n_samples_window, n_overlap, n_fft, fs_Hz, 'yaxis')

% Make the plot pretty and informative
xlim([0 len_sig_sec])
title(['Spectrogram: ' title_str])
xlabel('Time (sec)')
ylabel('Frequency (kHz)')
