function [ImOut,Sint]=RGB_spectrogram(x,FFTSizes,ImSize,fs,fMax,Levels)

%  RGB_spectrogram(x,FFTSizes,ImSize,fs,fMax,Levels)
%
% Inputs
%   x - Time series
%   FFTSize - a 3 element vector with the 3 FFT sizes to be used
%   ImSize - dimensions of the output image
%   fs - sample rate
%   fMax - maximum frequency of the analysis
%   Levels - two element vector defining the colour range of the spctrograms, [Lmin Lmax] in dB
%
% Outputs (all on a dB scale)
%   ImOut - RBG image in uint8 format values between 0 and 256, read to be written using imwrite
%   Sint - Same as ImOut but unrounded, still limited by Levels

%% Computing the spectrograms
X={};
f={};
t={};
% Compute the spectrograms for the 3 different resolutions and store the outputs in Cell arrays
for k=1:3
    [S,frq,tm]=spectrogram(x,FFTSizes(k),[],[],fs);
    S=20*log10(abs(S)/sqrt(sum(hanning(FFTSizes(k)).^2)));      % Convert to a dB scale.  Divisor is so noise appears at the same level
                                                                % for each of the FFT sizes
    S(S<Levels(1))=Levels(1);                                   % Clipping the lowest value to Levels(1)
    S(S>Levels(2))=Levels(2);                                   % Clipping the highest value to Levels(2)
    %subplot(2,2,k),pcolor(tm,frq,S),shading flat,colorbar
    % Store spectrograms and time/frequency vectors in cell arrays
    X{k}=S;                                                 
    t{k}=tm;
    f{k}=frq;
end

%% Interpolate spectrograms so they are the right size for the image
FrqInt=linspace(0,fMax,ImSize(1));          % Frequencies for the points in the interpolated image
TmInt=linspace(0,length(x)/fs,ImSize(2));   % Times for the points in the interpolated image

Sint=zeros(ImSize(1),ImSize(2),3);          % Empty 3D structure to put RGB image in

% Interpolating the spectrograms and putting them in Sint
for k=1:3
    Sint(:,:,k)=interp2(t{k}',f{k},X{k},TmInt',FrqInt);
end

% Scaling the data and converting format, so Level(1) is zero and Level(2) is 255S
ImOut=uint8(255*(Sint-Levels(1))/(Levels(2)-Levels(1)));
ImOut=rescale(ImOut, 0, 1);
