function varargout = resizeSignals(LSS,testRatio)
% RESIZESIGNALS makes all signals in the input array 5000 samples long.

% Copyright 2020 The MathWorks, Inc.

targetLength = 5000;
signalsOut = {};
labelsOut = {};

signalInfo = [];

for patient_idx = 1:LSS.NumMembers
    
    x = getSignal(LSS,patient_idx);
    
    labelsChan1 = getLabelValues(LSS,patient_idx,'WaveformLabels_Chan1');
    labelsChan2 = getLabelValues(LSS,patient_idx,'WaveformLabels_Chan2');
    y = [labelsChan1.Value'; labelsChan2.Value'] ;
    
    for sig_idx = 1:size(x,1)
        current_sig = x(sig_idx,:);
        current_label = y(sig_idx,:);
        index = 1:size(x,2);
        
        % Ensure column vector
        current_sig = current_sig(:);
        current_label = current_label(:);
                
        % Compute the number of targetLength-sample chunks in the signal
        numSigs = floor(length(current_sig)/targetLength);
        
        if numSigs == 0
            continue;
        end
        
        % Truncate to a multiple of targetLength
        current_sig = current_sig(1:numSigs*targetLength);
        current_label = current_label(1:numSigs*targetLength);
        index = index(1:numSigs*targetLength);
        
        % Create a matrix with as many columns as targetLength signals
        xM = reshape(current_sig,targetLength,numSigs);
        yM = reshape(current_label,targetLength,numSigs);
        index = reshape(index,targetLength,numSigs);
        
        
        % Vertically concatenate into cell arrays
        signalsOut = [signalsOut; mat2cell(xM.',ones(numSigs,1))]; %#ok<AGROW>
        labelsOut = [labelsOut; mat2cell(yM.',ones(numSigs,1))]; %#ok<AGROW>
        sizeInfo = length(signalInfo);
        
        for ii = 1:numSigs
            signalInfo{sizeInfo+ii,1} = struct('patientID',patient_idx,'channelID',...
                sig_idx,'indexID',index(:,ii)); %#ok<AGROW>
        end       
    end
end

% Shuffle the signals
index = randperm(length(signalsOut));
numTestSamples = floor(length(signalsOut)*testRatio);
varargout{1} = signalsOut(index(1:numTestSamples));
varargout{2} = labelsOut(index(1:numTestSamples));
varargout{3} = signalsOut(index(numTestSamples+1:end));
varargout{4} = labelsOut(index(numTestSamples+1:end));
varargout{5} = signalInfo(index(1:numTestSamples));
varargout{6} = signalInfo(index(numTestSamples+1:end));