function [M, J] = mutual_information(x, y, prec)
%% Funkce po vypocet MI, soucast mutual_information toolbox
% [M, J] = mutual_information(x, y)
% 
% This function calculates the mutual information between two column
% vectors.
% 
% x     - input column vector
% y     - input column vector
% prec  - precision of calculation; if prec = -1 then the precision will be
%         maximal (default: depending on the length of vector)
% M     - output mutual information
% J     - joint entropy

%% Paths and variables
if((nargin < 3) || isempty(prec))
    if(length(y) < 64)
        prec = 32;
    elseif(length(y) < 128)
        prec = 64;
    else
        prec = 256;
    end
end

%% Check the same lengths of vectors
if(length(x) ~= length(y))
    error('Vectors must have the same lengths.');
end

%% Quantize the input sequences
if(prec > 0)
    y = quantiz(y,min(y):range(y)/prec:max(y));
    x = quantiz(x,min(x):range(x)/prec:max(x));

    y(y == 0) = 1;
    x(x == 0) = 1;
end

%% Calculate the entropies
H1 = entropy(x, -1);
H2 = entropy(y, -1);

%% Calculate joint entropy
p12 = joint_probabilities([x y], -1);

J = -sum(p12.*log2(p12));

%% Calculate the mutual information
M = H1 + H2 - J;