/* fixed point integer minilib
   Copyright (C) 2016 Tibor 'Igor2' Palinkas
   This file is licensed under Creative Commons CC0 version 1.0, see
   https://creativecommons.org/publicdomain/zero/1.0/
   Source code: svn://svn.repo.hu/genfip/trunk
*/

FIP_FUNC FIP(_t) FIP(_add)(FIP(_t) a, FIP(_t) b)
{
	FIP(_t) res;

	res.f = a.f + b.f;
	res.i = a.i + b.i;
	if ((res.f < a.f) || (res.f < b.f))
		res.i++;
	return res;
}

FIP_FUNC FIP(_t) FIP(_sub)(FIP(_t) a, FIP(_t) b)
{
	int carry = 0;
	FIP(_t) res;

	if (b.f > a.f)
		carry = 1;

	res.i = a.i - b.i - carry;
	res.f = a.f - b.f;
	return res;
}

FIP_FUNC FIP(_t) FIP(_neg)(FIP(_t) a)
{
	FIP(_t) res;

	if (a.f == 0) {
		res.i = -a.i;
		res.f = 0;
		return res;
	}

	res.i = -a.i - 1;
	res.f = FIP_FRAC_MAX - a.f + 1;
	return res;
}

FIP_FUNC double FIP(_to_double)(FIP(_t) a)
{
	return (double)a.i + (double)a.f / (double)(FIP_FRAC_MAX+1.0);
}

FIP_FUNC FIP(_t) FIP(_from_double)(double a)
{
	FIP(_t) res;
	double af = floor(a);

	res.i = af;
	res.f = (a - af) * ((double)FIP_FRAC_MAX+1.0);
	return res;
}

typedef int FIP(mul_t);
FIP_FUNC FIP(_t) FIP(_mul)(FIP(_t) a, FIP(_t) b)
{
	FIP(_t) res;
	FIP(mul_t) mi = 0, mf = 0, tmp;
	mi = a.i * b.i;

	tmp = a.i * b.f;
	mi += tmp / (FIP_FRAC_MAX+1);
	mf += tmp % (FIP_FRAC_MAX+1);

	tmp = b.i * a.f;
	mi += tmp / (FIP_FRAC_MAX+1);
	mf += tmp % (FIP_FRAC_MAX+1);

	tmp = b.f * a.f;
	mf += tmp / (FIP_FRAC_MAX+1);

	res.i = mi;
	res.f = mf;
	return res;
}

