%*********************************************************************************
%*               LOAD IMPULSE RESPONSE MATRIX FROM WAV FILE                      *
%*          by Lorenzo Chiesi 2009 - lorenzo.chiesi(at)gmail.com                 *
%*********************************************************************************
%
%[ir_matrix,fs] = load_ir(ir_file, ir_position, mic, delay, N)
%
% Input:  ir_file     : WAV file to open
%         ir_position : Number of IR recording position
%         mic         : Number of microphone channel
%         delay       : Number of sample to skip before each IR
%         N           : Desidered IR length
%
% Output: ir_matrix  : Matrix of impulse response (IRPosition x Mic x N)
%         fs         : Sampling frequency
%

function [ir_matrix,fs] = load_ir(ir_file, ir_position, mic, delay, N )


display(sprintf('Loading IR from file "%s"...',ir_file))


%Load multichannel wav file
[wav, fs] = audioread(ir_file);          


%Check parameters

ir_sample = floor(size(wav,1) / ir_position);   %Lenght of each single IR
if not(ir_sample == floor(ir_sample))
    error('Errore: Il numero di campioni nel file non corrisponde!')
end

if not(size(wav,2) == mic)
    error('Errore: Il numero di microfoni nel file non corrisponde!')
end

if exist('delay','var')
    if (delay >= ir_sample)
        error('Errore: "delay" troppo elevato!')
    end
else
    delay = 0;
end

if ((not(exist('N','var'))) || (N == 0))
    N = ir_sample;
end



display(sprintf('Rearranging IR''s matrix...'))


%Preallocate matrix memory
ir_matrix = zeros(ir_position,mic,N, 'double' );                 

%Rearrange IR's in matrix
N_wav = min(N,ir_sample-delay);
ptr = delay;
   
for pos_i = 1:ir_position
   
        ir_matrix(pos_i,:,1:N_wav) = wav( ptr+1:ptr+N_wav , : )' ;

    ptr = ptr + ir_sample;
end

end

