% irTrim.m This function perform IR trimming

function [ spsFormat ] = irTrim( spsFormat, irPeakAnticipation, irTargetLength, plotSignalEnable )

signalLength        = size( spsFormat, 1 );                                 % length of recorded irs
[ ~, peakIndex ]    = max( abs( spsFormat( :, 1 ) ) );                      % search index of peak value of the first IR

% check selected start/end points
if irPeakAnticipation > peakIndex
    error( [ 'The peak is at ' num2str(peakIndex) ' sample.' ...
      '\nChange IR trimming parameters' ] );
end

if irTargetLength > signalLength
    disp( 'selected range is greater than signal' );
    error( [ 'analyzed range must be between 1 and ' num2str(signalLength) ' samples.' ...
        '\nChange IR trimming parameters' ] );
end

irStart             = peakIndex - irPeakAnticipation;               % start index for IR trim
irStop              = irStart + irTargetLength - 1;                 % stop index for IR trim

if plotSignalEnable
    spsMean         = mean( spsFormat, 2 );
    figure
    plot( spsMean )
    xlim( [ 0 size( spsMean, 1 ) ] )
    hold on
    vlimit          = get( gca, 'ylim' );
    line( [ irStart irStart ], vlimit, 'Color', 'red' );
    line( [ irStop irStop ], vlimit, 'Color', 'red' );
    grid on
    title( 'Signal with trimming window' )

    fprintf('Check selected window...then press any key to continue or Ctrl-C to abort\n\n');
    pause
end

spsFormat           = spsFormat( irStart : irStop, : );                     % trim IR
