module IEEEFloat where
import Data.Word
import Data.Bits

{--
    IEEEFloat module
	Functions for decoding IEEE-754 floating point numbers, 
	from Integral, Bits types
	TODO:Implement the reverse operation (encoding floats into Integral 
	types)
    Copyright (C) 2009  Rafael G. C. P. Pinto

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
--}


convertToIEEE:: (Integral a,Bits a, RealFloat f)=>Int->Int->a->f
convertToIEEE len_e len_s x=
	case expData of 
		0 -> denormal
		a | a==exceptionExp-> exception
		otherwise -> encodeFloat (normalSig*signal) (fromInteger(expData-expBias)- len_s)
	where
		sigMask=(2^len_s)-1
		expMask=((2^len_e)-1) `shift` len_s
		sigData=toInteger (x .&. sigMask)
		normalSig=sigData+(2^len_s)
		expData=toInteger((x .&. expMask) `shift` (-len_s))
		exceptionExp=(2^len_e)-1 ::Integer
		expBias=(2^(len_e-1))-1 ::Integer
		signal=if (x .&. (2^(len_e+len_s)))==0 then 1 else -1 ::Integer
		denormal=if sigData==0 then 0.0 else encodeFloat (signal*sigData) (fromInteger(1-expBias)-len_s)
		exception=if sigData==0 then (if signal==1 then 1/0 else -1/0) else (0.0/0.0)


word64ToIEEEDouble::Word64->Double
word64ToIEEEDouble=convertToIEEE 11 52

word32ToIEEEFloat::Word32->Float
word32ToIEEEFloat=convertToIEEE 8 23
