// cl_LF_shortenrelative().

// General includes.
#include "cl_sysdep.h"

// Specification.
#include "cl_LF.h"


// Implementation.

#include "cln/abort.h"

#undef MAYBE_INLINE2
#define MAYBE_INLINE2 inline
#include "cl_LF_precision.cc"
#undef MAYBE_INLINE
#define MAYBE_INLINE inline
#include "cl_LF_exponent.cc"

namespace cln {

const cl_LF cl_LF_shortenrelative (const cl_LF& x, const cl_LF& y)
{
	// Methode:
	// x = 0.0 -> Precision egal, return x.
	// ex := float_exponent(x), ey := float_exponent(y).
	// dx := float_digits(x), dy := float_digits(y).
	// 1 ulp(x) = 2^(ex-dx), 1 ulp(y) = 2^(ey-dy).
	// Falls ex-dx < ey-dy, x von Precision dx auf dy-ey+ex verkürzen.
	var sintL ey = float_exponent(y);
	var sintL dy = float_precision(y);
	if (dy==0) // zerop(y) ?
		cl_abort();
	var sintL ex = float_exponent(x);
	var sintL dx = float_precision(x);
	if (dx==0) // zerop(x) ?
		return x;
	var sintL d = ex - ey;
	if (ex>=0 && ey<0 && d<0) // d overflow?
		return x;
	if (ex<0 && ey>=0 && d>=0) // d underflow?
		return LF_to_LF(x,LF_minlen);
	if (d >= dx - dy)
		return x;
	var uintL new_dx = dy + d;
	var uintL len = ceiling(new_dx,intDsize);
	if (len < LF_minlen)
		len = LF_minlen;
	if (intDsize*len < (uintL)dx)
		return shorten(x,len);
	else
		return x;
}

}  // namespace cln
