% This script file loads an impulse response stored in a WAV file, formats
% the coefficients, and then sends to Audio Weaver.  Make sure that you
% have the file whose name is given by the designerFile variable open in Designer.

designerFile = 'LongFIRExample.awd';
reverbImpulseRespWav = 'CathedralRoom.wav';
% reverbImpulseRespWav = 'BatteryBenson.wav';
% Get the location of this .m file on disk
str = mfilename('fullpath');

ind = find(str == filesep);
dirStr = str(1:ind(end)-1);

LR = audioread(fullfile(dirStr, reverbImpulseRespWav));

GSYS = get_gsys(fullfile(dirStr, designerFile));

% Get the lengths of the individual filters
L1 = GSYS.SYS.FIR1.L;
L2 = GSYS.SYS.FIR2.L;

% make sure that the size of L3 is an integer multiple of L1 + L2
wavLengthInfo =  size(LR);
wavLength = wavLengthInfo(1) - (L1 + L2);
L3Length = floor(wavLength/(L1 + L2)) * (L1 + L2);
% L3PadLength is number of zeroes to add so that L3 is an integer 
% multiple of (L1 + L2).  
L3PadLength = L1 + L2 - wavLength + L3Length;

% Zero pad or truncate the impulse response
% LR = truncate(LR, L_total);

L = LR(:, 1);
R = LR(:, 2);

% Pick which impulse response to use
fprintf(1,'Using the left channel of %s.\n', reverbImpulseRespWav);
h = L;
zeroes = zeros(L3PadLength, 1);
fprintf(1,'Padding the impulse response %s by %d bytes.\n', reverbImpulseRespWav, L3PadLength);
h = [h; zeroes];

% Scale the impulse response.  Keep the peak frequency response value at 
% 0 dB
p2 = ceil(log2(length(h)));
FFT_L = 2^p2;

H = desym(fft(truncate(h, FFT_L)));
Hmax = max(abs(H));

h = h / Hmax;
fprintf(1, 'Impulse response scaled by %.1f dB\n', db20(1/Hmax));

% Split into individual filters
h1 = h(1:L1);
h2 = h(L1+1:L1+L2);
h3 = h(L1+L2+1:end);

% Update the coefficients
GSYS.SYS.FIR1.coeffs = h1;
GSYS.SYS.FIR2.coeffs = h2;
% the argument FIR3.L in the awd file needs to be set manually for each 
% impulse response WAV file.  This try-catch code shows an error message 
% if the size is not correct.
length3 = L3Length + L1 + L2;
GSYS.SYS.FIR3.L = length3;
try
GSYS.SYS.FIR3.coeffs = h3;
catch 

    warning('Make sure the that "L" argument of FIR3 is %d\n', length3);
    return
end
% Now send the updated system to Designer
set_gsys(GSYS);
disp('Filter coefficients uploaded.');