% This script tests calling the MATLAB processing functions
% It works in Native mode or on a target

%GSYS = load_awd('Example - Process Files.awd'); % Will load directly from Disk

% If the system is open in Designer, get it directly.  This is faster
% than load_awd().
GSYS = get_gsys('WaveFileSink_Source-Process Files.awd');

SYS = GSYS.SYS;

lv.TOP_BLOCKSIZE = 32;


SYS.targetSpecificInfo.RT = 0; % 0 for non-real time build
% Non-real time build does 2 things:
% This forces the input and output buffers to not be double buffered
% And you no longer have to match the fundamental block size of the system


% ==============================================
% Make a chirp signal
% ==============================================
blockSize = SYS.inputPin{1}.type.blockSize;
numChannels = SYS.inputPin{1}.type.numChannels;
SR = SYS.inputPin{1}.type.sampleRate;

% Generate the input data
NUM_BLOCKS = 100; % chirp signal is 100 blocks long

L = NUM_BLOCKS * blockSize; % 256 * 100

n = 0:(L-1);
n = n(:);
T = n/SR;

% Starting and ending frequencies of the chirp, in Hz.
f0 = 20;
f1 = 5000;
X = chirp(T,f0,max(T),f1,'logarithmic', -90);
X = repmat(X, 1, numChannels); % duplicate to make stereo

% Build the system.  On PC or on the target
SYS=build(SYS);

% ==============================================
% Make a chirp signal
% ==============================================

if (0) % 0 or 1
    % Process everything in one call if 1
    WIRE_IN = {X}; % X is input data.  Turn into system input wire
    [SYS, WIRE_OUT] = process(SYS, WIRE_IN, NUM_BLOCKS); % call process function, tell how many blocks, and give input data
    Y = WIRE_OUT{1};
else
    % Process block-by-block if 0
    Y = [];
    for i = 1:NUM_BLOCKS % loop over all the blocks
        if (i == 10) % if we're at block number 10, change the master gain to -12
            % Make a tuning change
            SYS.ScalerN1.masterGain = -12;
        end
        startIndex = (i - 1) * blockSize + 1; % Start index of data
        endIndex = startIndex + blockSize - 1; % End index of data
        WIRE_IN = {X(startIndex:endIndex, :)}; % Get data out of the input array from the correct indexes (get both channels)
        [SYS, WIRE_OUT] = process(SYS, WIRE_IN, 1); % Process 1 block, and get SYS object back, get wire output
        fprintf(1, 'Processing block %d of %d\n', i, NUM_BLOCKS); % 100 blocks, 1 block at a time
        if (isempty(Y)) % Accumulate all the wire output into Y, 1 block at a time
            Y = WIRE_OUT{1};
        else
            Y = [Y; WIRE_OUT{1}];
        end
    end
end

% Plot data
figure;
subplot(211);
plot(X);
title('Input Plot'); 
subplot(212);
plot(Y);
title('Output Plot');