% GenerateSpsFormat_ricohTheta.m Generation of SPS format from RicohTheta recordings.
% This script takes 4 channels recording as input (both .mat 
% and .wav are accepted), convolves it with SPS matrix and stores the 
% results in a .mat or .wav file.
%
% INPUT
% - Noise file from RicohTheta (.wav)
% - SPS matrix filter (.mat)
%
% OUTPUT
% - SPS format (.mat / .wav)
%
% Author: Daniel Pinardi.
% University of Parma, 2017.
% Last review: 01/2020, Daniel Pinardi

clear all
close all
clc

addpath( './lib' )
a_configureFileNamesAndDirectories


%% SAVE ALSO WAV FILE: POSSIBLE VALUES '0 -> disable' , '1 -> enable'
saveWavEnable               = 0;


%% LOAD DATA FROM FILES         ONLY one between .mat and .wav needed !
disp( [ 'NOISE - Loading file: ' recordedFileName ] );
[ fileToProcess, fs ]   = audioread( recordedNoiseFile );
outputWavFileName       = encodedNoiseWavFileName;
outputMatFileName       = encodedNoiseMatFileName;
if ~isdir( encodedNoiseFolder )
    mkdir( encodedNoiseFolder )
end 

% filter matrix for SPS beamforming
load( './resources/ambix2sps_cardiod_ricohThetaV.mat' );
encodedFormat               = fileToProcess .* ambix2sps;
virtualMicNumber            = size ( ambix2sps, 2 );


%% Exporting results in a .mat file
disp( [ 'Saving ' num2str( virtualMicNumber) ' channels SPS in MAT files: ' outputMatFileName ] );
save( outputMatFileName, 'encodedFormat', 'fs', '-v7.3', '-nocompression' );


%% Normalize and save 32ch .wav file
if saveWavEnable
    maxAbsValue                 = max( max( abs( encodedFormat ) ) );               % searc for absolute max value
    encodedFormat               = encodedFormat ./ maxAbsValue;                     % normalize IRs between -1 and +1
    disp( [ 'Saving ' num2str( virtualMicNumber ) ' channels SPS in WAV files: ' outputWavFileName ] );
    audiowrite( outputWavFileName, encodedFormat, fs, 'BitsPerSample', 32 );
end

rmpath( './lib' )
fprintf( '\nEnded correctly.\n\n' );
