function [codem] = fhuffman(s,p)
%function [codem] = fhuffman(s,p)
%This algoritm creates a Huffman code from s (a cell of strings) and a
%p (vector of floats) which is synchronized with s. meaning p(1) is the
%probability of symbol s(1).
%This algorithm uses string comparison, therefore the condition for vector
%s is that all characters should be SINGLE CHARACTER and different from 
%each other.
%The outpus is a cell with two columns, first has the symbols and the
%second column has the codeword
%Example fhuffman({'a';'b';'c';'d';'e'},[.25;.25;.2;.15;.15])

%length of the diccionary
len = length(s);

%CodeMatrix. First column is initialized to the symbols in s,
%second column is emptied will be used to store the Huffman code as a
%binary string (string of 0's and 1's)
codem=cell(len,2);
codem(:,1)=cellstr(s);
codem(:,2)={''};

%We will modify the p vector, so we create a copy to work with it
pwork = p;
%We will modify the s vector, so we create a copy to work with it
swork = s;

%Find first two symbols with the smallest probability
%take that value from the vector, and repeat
%until we have counted all probabilities.
for i=1:len-1
    %first minimum symbol
    [pmin1,ind0]=min(pwork);
    pwork(ind0)=2; %Replace with an impossible probability
    %second minimum symbol
    [pmin2,ind1]=min(pwork);
    pwork(ind1)=2; %Replace with an impossible probability

    %Add probabilities
    pnew = pmin1+pmin2;

    %update pwork adding at the end of the vector the new
    %supersymbol and the new probability
    lsw = length(swork);
    pwork(lsw+1,1)=pnew;

    %Assign bits to the selected symbols.
    for j=1:len
        if double(findstr(char(swork(ind0)),char(s(j)))) >=1
            %disp(['Assign 0 to ',s(j)])
            codem(j,2)={['0',char(codem(j,2))]};
        end

        if double(findstr(char(swork(ind1)),char(s(j)))) >=1
            %disp(['Assign 1 to ',s(j)])
            codem(j,2)={['1',char(codem(j,2))]};
        end
    end

    %Create new super symbol
    ssym = {[char(swork(ind0)),char(swork(ind1))]};

    swork(lsw+1,1)=ssym;
   
end
