% syncAudioVideo.m This function perform auto sync between EigenMike and
% audio recorded by camera

function [ delay ] = syncRef( signal, reference )

    % extract first signal for computing delay
    signal                  = signal( :, 1 );
    reference               = reference( :, 1 ); 

    % define signal length
    signalLength            = length( signal );
    referenceLength         = length( reference );
    minLength               = min( signalLength, referenceLength );
    
    % compute transfer function
    tf                      = tfestimate( signal( 1 : minLength ), reference( 1 : minLength ), rectwin( minLength ), [], minLength );
    tf                      = [ 0; tf( 2 : end - 1 ); 0; flipud( conj( tf( 2 : end - 1 ) ) ) ];
    tfIR                    = ifft( tf );
    [ ~, delay ]            = max( abs( tfIR ) );
    tfLength                = size( tfIR, 1 );

    if delay > tfLength/2
        delay               = delay - tfLength;
    end
    
end
        