% GSYS = load_awd('Example1.awd');
% awe_init;
% global AWE_INFO;
% AWE_INFO.displayControl.showHidden = 1;
% [whiteNoise, Fs] = audioread('audiocheck.net_whitenoisegaussian.wav');


% Create a subsystem with a single second_order_filter module.
blockSize = 64;
SR = 44100;
SYS = matlab_target_system('test', 'Process.m example system');
add_pin(SYS, 'input', 'in', 'Audio input', new_pin_type(1, blockSize, SR));
add_pin(SYS, 'output', 'out', 'Audio output', new_pin_type(1, blockSize, SR));
add_module(SYS, second_order_filter_module('sof'));
connect(SYS, '', 'sof');
connect(SYS, 'sof', '');

SYS.sof.filterType = 12;
SYS.sof.freq = 2000;
SYS.sof.Q = 1;
SYS.sof.gain = 12;

global AWE_INFO;
AWE_INFO.buildControl.matchDataType=0;
SYS=build(SYS);

duration = 0.25;
L = SR*duration;
numBlocks = ceil(L/blockSize);
L = numBlocks*blockSize;
n = 0:(L-1);
n = n(:);
T = n/SR;
x = chirp(T, 0, duration, SR/4);

WIRE_IN = {x};
[SYS, WIRE_OUT] = process(SYS, WIRE_IN, numBlocks);
y = WIRE_OUT{1};
  
subplot(211);
plot(x);
set(gca, 'YLim', [-5 5]);
title('Input data - one big block');

subplot(212);
plot(y);
set(gca, 'YLim', [-5 5]);
title('Output data - one big block');

% Here's the modification. Pretty clunky but you get the idea
clear SYS;
SYS = matlab_target_system('test', 'Process.m example system');
add_pin(SYS, 'input', 'in', 'Audio input', new_pin_type(1, blockSize, SR));
add_pin(SYS, 'output', 'out', 'Audio output', new_pin_type(1, blockSize, SR));
add_module(SYS, second_order_filter_module('sof'));
connect(SYS, '', 'sof');
connect(SYS, 'sof', '');

SYS.sof.filterType = 12;
SYS.sof.freq = 2000;
SYS.sof.Q = 1;
SYS.sof.gain = 12;

SYS=build(SYS);
% end of modification

%Process things on a frame-by-frame basis instead. Theoreticall
totalOutput = zeros(size(x));
for i = 0:numBlocks-1
    startIndex = 1 + i*blockSize;
    stopIndex = (i+1)*blockSize;
    WIRE_IN = {x(startIndex:stopIndex)};
    [SYS, WIRE_OUT] = process(SYS, WIRE_IN, 1);
    totalOutput(startIndex:stopIndex) = WIRE_OUT{1};
end

figure;
subplot(211);
plot(x);
set(gca, 'YLim', [-5 5]);
title('Input data - frame based approach');

subplot(212);
plot(totalOutput);
set(gca, 'YLim', [-5 5]);
title('Output data - frame based approach');

figure;
plot(totalOutput - y);
title('Difference between frame based and total signal approach');