function unsigned = real2unsigned(real, intbits, fracbits)
% unsigned = real2unsigned(real, intbits, fracbits)
%
% Real number -> unsigned binary string
%
% Useful for generating verilog statements (like a case statement
% lookup table).
%
% 2008/05/29  Modified from real2twos (BB)  NOT DEBUGGED!!!!!!!


%----- Check inputs
if (nargin ~= 3)
   fprintf(1, 'Error: real2unsigned: %i input args, not 3\n', nargin);
   unsigned = NaN;
   return;
end

if (imag(real) ~= 0)
   fprintf(1, 'Error: real2unsigned: input value is complex\n');
   unsigned = NaN;
   return;
end


%----- Preliminary calculations
Lsb     = 2^(-fracbits);
Msb     = 2^(intbits-1);

%----- A few checks
% Check that input is not too large
if (real > (2*Msb - Lsb))
   fprintf(1, 'Error: real2unsigned: input %f too large\n', real);
   unsigned = NaN;
   return;
end

% Check that input is not too small
if (real < 0)
   fprintf(1, 'Error: real2unsigned: input %f negative\n', real);
   unsigned = NaN;
   return;
end

%----- Main
%if (real < 0)
%   remainder = real + Msb;
%   unsigned = '1';
%else
%   remainder = real;
%   unsigned = '0';
%end
unsigned = '';
remainder = real;

for k=(intbits-1):-1:(-fracbits)
   temp = 2^k;
   if (remainder >= temp)
      remainder = remainder - temp;
      unsigned = strcat(unsigned, '1');
   else
      unsigned = strcat(unsigned, '0');
   end
end

% Give warning if number can not be fully represented.  The output
% number is truncated, not rounded!
if (remainder ~= 0)
   fprintf(1, 'Warning: real2unsigned: input %f does not fit spec.\n', real);
end

