% Matlab file fl.m
% function flx = fl( x )
% Purpose: compute the floating point representation of x
% Input:   x -- number to be converted  
% Output:  floating point representation of x
% Global variables required:
%    fp_t -- number of decimal digits to retain
%    fp_U    -- Largest exponent allowed
%    fp_L    -- Smallest exponent allowed
%    fp_method -- = 'R' indicates truncated arithmetic, = 'T' indicates rounded arithmetic

function flx = fl( x )

% declare global variables
global fp_t fp_U fp_L fp_method

if x == 0
   % if x = 0 then fl( x ) = 0
   flx = 0;
else
   % compute mantissa so that x = +- mantissa * 10^exponent
   % where 0.1 <= mantissa < 1
   exponent = 0;
   mantissa = abs( x );
   
   while mantissa >= 1
      mantissa = mantissa/10;
      exponent = exponent+1;
   end
   while mantissa < .1
   	mantissa = mantissa * 10;
   	exponent = exponent-1;
	end
   
   % Round or truncate, as indicated by fp_method
   if fp_method == 'R'
      mantissa = round( mantissa*(10^fp_t) ) / (10^fp_t);
   elseif fp_method == 'T'
      mantissa = floor( mantissa*(10^fp_t) ) / (10^fp_t);
   end
   
   if mantissa == 1
      mantissa = mantissa/10;
      exponent = exponent+1;
   end
   
   if exponent > fp_U
      disp( 'WARNING overflow' )
   elseif exponent < fp_L
      disp( 'WARNING underflow' )
   end
   
	flx = sign(x) * mantissa * 10^exponent;
end