%*************************************************************************************************
% oa_multichannel_conv.m                                                     Lorenzo Chiesi 2013 *
%                                                                                                *
%                                                                                                *
%*************************************************************************************************
%
% outData = oa_multichannel_conv(inData,h);
%
% inData Input signal matrix with dimension [Mic x Nin]
% h fir matrix with dimension [Mic x VirtualMic x N]
% !! inData and h MUST have the same first dimension (Mic)!!
%
% outData return signal convolution with dimension [VirtualMic x (Nin+N-1)]

function outData = oa_multichannel_conv(inData,h )

    M = size(h,1); 
    V = size(h,2); 
    N = size(h,3);
    Nin = size(inData,2);
    
    BlocksNum = ceil(Nin/N);
    BlockId = 1;
    
    outData = zeros(V,BlocksNum*N+N);
    
    overlapBlock = zeros(V,N);
    fd_convBlock = zeros(1,V,N);
    
    %Prepare frequency domain FIR coeff
    H = fft(h,2*N,3);
    
    oldCompletedPercentage = -1;
    
    fprintf('\nConvolving audio: ')
    varStr = '0%%';
    varStrLen = length(varStr);
    fprintf('%s',varStr)
    
    %Process the data block by block 
    while(BlockId <= BlocksNum)
        
        CompletedPercentage = round(BlockId/BlocksNum*100);
        if oldCompletedPercentage ~= CompletedPercentage
            for i=1:varStrLen
                fprintf('\b')
            end
            varStr = sprintf('%d%%',CompletedPercentage);
            varStrLen = length(varStr);
            fprintf('%s',varStr)
        end
        oldCompletedPercentage = CompletedPercentage;
            
        inBlock = inData(:, (BlockId-1)*N+1 : min(BlockId*N,Nin) );
        %inBlock size [Mic x N]
        
        %%%%%%%%%%%%%%%%%%%%%%%%%
        %Block process
        
        fd_inBlock = fft(inBlock,2*N,2);
  
        for k = 1:1:2*N
            fd_convBlock(1,:,k) =  reshape(fd_inBlock(:,k),1,M) * squeeze(H(:,:,k));
        end
        
        convBlock = ifft(reshape(fd_convBlock,V,2*N),2*N,2);
        
        outBlock = overlapBlock + convBlock(:,1:N);
        
        overlapBlock = [ convBlock(:,N+1:2*N-1) , zeros(V,1) ];
        
        %%%%%%%%%%%%%%%%%%%%%%%%%
        
        
        outData(:,(BlockId-1)*N+1:BlockId*N) = outBlock;
        BlockId = BlockId+1;
    end
    
    %Store last overlapBlock
    outData(:,(BlockId-1)*N+1:BlockId*N) = overlapBlock;
    
    %Crop outData
    outData = outData(:,1:Nin+N-1);
        
   
    fprintf('\n')
        
end
