function [bits,errors,ber,errorIndice] = calc_ber(data_in,data_ref,options)

arguments(Input)
    data_in;
    data_ref;
    options.skip_front = 0;
    options.skip_end = 0;
    options.returnErrorLocation = 0;
end
options.skip_end = abs(options.skip_end);
options.skip_front = abs(options.skip_front);

bits = 0;
errors= 0;
ber= 0;
errorIndice= [];

% trim sequence to given start; stop. trim reference if signal is shorter
[data_in,data_ref]=trimseq(data_in,data_ref,options.skip_front,options.skip_end);

if length(data_ref) == length(data_in)

    bits = 0;
    bits = bits+numel(data_in(:,options.skip_front+1:end));

    try
        if options.returnErrorLocation == 0
            errors = sum( data_in ~= data_ref,"all" );
        else
            errorIndice = sum(data_in ~= data_ref,1);
            errors = sum(errorIndice ,"all" );
            [~,errorIndice] = find(errorIndice==1);
        end

    catch
        warning('BER calculation not optimal: Arrays have incompatible sizes for this operation.')
        errors = NaN;
    end

    % Determine BER
    ber = sum(errors)/sum(bits);

else
    error('Sequence length does not match');
end

    function [data_,reference_]=trimseq(data,reference,skipstart,skip_end)

        data_  =  logical(data(skipstart+1:end-skip_end,:))';

        delta_bits = length(reference) - length(data);

%         skip_end = max(skip_end,delta_bits);
        skip_end = delta_bits + skip_end;

        reference_ = logical(reference(skipstart+1:end-skip_end,:))';

    end

end