% encoding function to generate the binary code
function [code_b,N] = a_encode(seq,sym,c_count)
total=c_count(end); % total count
N=round(log2(4*total)); % word length 
msb=N; % position of the msb 
msbm1=N-1; % position of the second msb
l=0; % initial lower limit of the interval
u=2^N-1; % initial upper limit of the interval
flag=0; % flag 
cod=[]; % initialize code accumulator
for k=1:length(seq) % one loop for each symbol  
  temp=l;
  num=seq(k); % read the new number
  index=find( sym == num); % find the index of the symbol
  l=l+floor((u-l+1)*c_count(index)/total); % lower limit 
  u=temp+floor((u-temp+1)*c_count(index+1)/total)-1; % upper limit 
  lb=de2bi(l,N); % convert l to binary 
  ub=de2bi(u,N); % convert u to binary
  while (lb(msb) == ub(msb) | (lb(msbm1) == 1 & ub(msbm1) == 0))
% loop if lb(msb) = ub(msb) or lb(msbm1) == 1 & ub(msbm1) == 0   
    if (lb(msb) == ub(msb)) % if msbs of l and u are equal
      b=ub(msb); % msb of ub is the code bit 
      cod=[cod b]; % accumulate the code
      lb=circshift(lb,[0,1]);lb(1)=0; 
% left shift lb by one position and then set lsb to 0
      ub=circshift(ub,[0,1]);ub(1)=1;
% left shift ub by one position and then set lsb to 1
      l=bi2de(lb); % convert lb to decimal
      u=bi2de(ub); % convert ub to decimal
      while flag > 0
        cod=[cod ~b]; 
% code bit is the complement of the last code bit
        flag=flag - 1; % decrement the flag
      end
    end % if
  %%%%%%% if  lb(msbm1) == 1 & ub(msbm1) == 0 holds
    if (lb(msbm1) == 1 & ub(msbm1) == 0)
      lb(msbm1)=0; % complement lb(msbm1)
      ub(msbm1)=1; % complement ub(msbm1
      lb=circshift(lb,[0,1]);lb(1)=0;
      ub=circshift(ub,[0,1]);ub(1)=1;
      l=bi2de(lb);
      u=bi2de(ub);
      flag=flag + 1; % increment the flag
    end 
  end % while
end % for
if flag == 0 % appending the tag to the code
  code_b= [cod lb(N:-1:1)];
else
  code_b= [cod lb(N) ones(1,flag) lb(N-1:-1:1)];
end
code_b=code_b(length(code_b):-1:1);



            
            
