function codearith
x = [1 3 2 2 3 1 2 1 1 2 2];
c = code(x, @iid)

function q = iid(s)
q = [0.3 0.5 0.2];

function c=code(x, lcc)
% x : message à coder, lcc :  loi de codage conditionnelle
S=53;  %% valeur maximale : 53
l=0; h=2^S; ret=0; symb=-1; c=[];
for k=1:length(x)
    q=feval(lcc, symb);
    symb=x(k); 
    r=[0, cumsum(q)]; 
    l=l+round(r(symb)*h);
    h=round(h*r(symb+1))-round(h*r(symb)); if h<=1; close(wt), error('S trop petit : h=0'); end %ifo que ca soit >=2 !!
    
    while (l>=2^(S-1)) || (l+h<=2^(S-1))
        if l>=2^(S-1) 
            c=[c, 1]; for j=1:ret, c=[c, 0]; end; ret=0;
            l=2*l-2^S; h=2*h-1;
        else
            c=[c, 0]; for j=1:ret, c=[c, 1]; end; ret=0;
            l=2*l; h=2*h-1;
        end
    end
    while (l>=2^(S-2)) && (l+h<=3*2^(S-2))
        ret=ret+1;
        l=2*l-2^(S-1); h=2*h-1;
    end
end
if l<2^(S-2) % et alors l+h>0.5
    c=[c,0];
    for j=1:(ret+1), c=[c, 1]; end
else % 0.25<l<0.5, l+h>0.75
    c=[c, 1];
    for j=1:(ret+1), c=[c, 0]; end    
end

