function [leftTotal,rightTotal] = audioMatrixEncoder( ...
    left,right,center,surround,resetFlag)
% AUDIOMATRIXENCODER Encode four audio channels (left, right, center,
% surround) to two-channel stereo signal (left total and right total).
%
% To reset the filters, pass extra argument set to true.
%
% This function audioMatrixEncoder is only in support of
% SurroundSoundMatrixEncodingAndDecodingExample. It may change in a future
% release.

%   Copyright 2014-2018 The MathWorks, Inc.

persistent bpFilter hilbertFilter
if isempty(bpFilter)
   % Bandpass filter used to filter surround channel
   bpFilter = dsp.VariableBandwidthIIRFilter( ...
       'FilterOrder',8, ...
       'FilterType','Bandpass', ...
       'CenterFrequency',(100 +7000)/2, ...
       'Bandwidth',7000-100);
   % Hilbert transformer used to process surround channel
   b = firpm(31,[0.0500 0.9500],[1 1],'hilbert');
   hilbertFilter = dsp.FIRFilter('Numerator',b);
end

if (resetFlag)
   reset(bpFilter);
   reset(hilbertFilter);
end

% Band-limit the surround channel and introduce phase shift 
filteredSurround = bpFilter(0.5 * surround);
hilbertSurround =  hilbertFilter(filteredSurround);

% Construct stereo signal
leftTotal = left + 0.5 * center - hilbertSurround;
rightTotal = right + 0.5 * center + hilbertSurround;