% E2 = FreeEnergyDistNew(codebook,RS,a) implements the Free Energy Ribosome
% Decoding Algorithm. It compares the subsequence s of length n with L
% codewords defined by the codebook "codebook" and finds the most complimentary
% codeword for the received Sequenxce RS, i.e. the codeword that results in 
% a minimum free energy.
%
% E2     :  is a vecotor of length L that represents the free energy 
%           dissipated on binding with the nuceotide doublet codebook{k}(n) 
%           and codebook{k}(n+1) (i.e. the (n)th and the (n+1)th  sybols of 
%           the (k)th codeword. 


function E2 = FreeEnergyDistNew(codebook,RS,a)


L = length(codebook);
n = length(codebook{1});
E1(1:L) = 0;  % Initialization

% FERD Algorithm in Dawy's paper:
for i = 1:L
    for j = 1:n-1
        if isequal({codebook{i}(j:j+1)},{RS{1}(j:j+1)})
            
            FED = codebook{i}(j:j+1);
            E1(i) = E1(i) + energy(FED);
        else
            E1(i) = E1(i);
        end
    end
end

E_min1 = min(E1);


L = length(codebook);
n = length(codebook{1});
E2(1:L) = 0;  % Initialization

% Maria Algorithm
for i = 1:L
    sigma = 0;
    sigmahat = 0;
    Rho = 0;
    w(1) = a;
    for j = 1:n-1
        if isequal({codebook{i}(j:j+1)},{RS{1}(j:j+1)})
            
            FED = codebook{i}(j:j+1);
            sigma = sigma + 1;
            sigmahat = 0;
            w(j) = Rho + a^(sigma);
            Rho = Rho; 
        else
            sigmahat = sigmahat + 1;
            sigma = 0;
            v = w(1) - (a^(sigmahat+1)-a^(sigmahat));
            if j>=2,
                v = w(j-1) - (a^(sigmahat+1)-a^(sigmahat));
            end
            w(j) = max([0 v]);
            if Rho <= a, 
                Rho = 0;
            else
                Rho = max([0 v]);
            end 
        end
        FED = codebook{i}(j:j+1);
        E2(i) = E2(i) + w(j) * energy(FED);
    end
end




