% decoding function to reconstruct the input sequence
function [decod] =a_decode(N,sym,c_count,code_b,lseq)
%
msb=N; % position of the msb 
msbm1=N-1; % position of the second msb
total=c_count(end); % length of the sequence
tag=bi2de(code_b(end-N+1:end)); % most significant N bits
l=0; % initial lower limit
u=2^N-1; % initial upper limit
decod=[]; % symbol accumulator
ps=1;
for pp=1:lseq
  tem=floor(((tag-l+1)*total-1)/(u-l+1));
  k=1;
  while (tem >= c_count(k)); % symbol decode
    k=k+1;
  end
  x=sym(k-1); % decoded symbol
  decod=[decod sym(k-1)]; % accumulate the symbols
  temp=l;
  l=l+floor((u-l+1)*c_count(k-1)/total);
  u=temp+floor((u-temp+1)*c_count(k)/total)-1;
  lb=de2bi(l,N);
  ub=de2bi(u,N);
  while (lb(msb) == ub(msb) | (lb(msbm1) == 1 & ub(msbm1) == 0))
    if (lb(msb) == ub(msb))
      %b=ub(msb);
      tb=de2bi(tag,N);
      lb=circshift(lb,[0,1]);lb(1)=0;
      ub=circshift(ub,[0,1]);ub(1)=1;
      tb=circshift(tb,[0,1]);tb(1)=code_b(end-N+1-ps);
% left shift the tag by 1 bit and read the next bit
% into the lsb from the binary code
      ps=ps+1;
      l=bi2de(lb);
      u=bi2de(ub);
      tag=bi2de(tb);
    end % if end
    if (lb(msbm1) == 1 & ub(msbm1) == 0)
      lb(msbm1)=0; % complement second msb of lb
      ub(msbm1)=1; % complement second msb of ub
      lb=circshift(lb,[0,1]);lb(1)=0;
      ub=circshift(ub,[0,1]);ub(1)=1;
      l=bi2de(lb);
      u=bi2de(ub);
      tb=de2bi(tag,N);
      tb=circshift(tb,[0,1]);tb(1)=code_b(end-N+1-ps);
      ps=ps+1;
      tb(msb)=~tb(msb);
      tag=bi2de(tb);
    end % 2nd if end
  end % while end
end % for end

