function mrev = reverse(m, r, n) 
% digit reverser, n digits base r 
% ..gives integer m if read backwards base r

a=0; 
while (r^a <= m )
  a=a+1;     %find how many digits 
end 
if( a > n ) 
 fprintf(' overflow in reverse function')
end 
offset = n-a; %leftmost zeros will become rightmost zeros when reversed 
a = a-1;      %count digits 0th to a-th, to agree with their exponents 

m_left = m; 
for k=a:-1:0, 
 d(k+1) = floor(m_left/(r^k));
 m_left = m_left - d(k+1)*r^k; 
end 

mrev=0; 
int = 0;
for k=0:a, 
 kk   = a - k; 
 int  = int + d(k+1)*r^k; 
 mrev = mrev + d(kk+1)*r^(k+offset);  
end 

%d
%if(int ~= m) 
% fprintf(' answer doesn''t check in drev \n')
%end 

end 
