//
// LiDIA - a library for computational number theory
//   Copyright (c) 1994, 1995 by the LiDIA Group
//
// File        : nearest.c 
// Author      : Thomas Papanikolaou (TP)
// Last change : TP, Feb 7 1995, initial version
//

#include <LiDIA/bigint.h>

void
nearest(bigint & z, const bigint & u, const bigint & v)
{
  if (v.is_zero())
    lidia_error_handler("bigint", "nearest()::division by zero.");

  bigint tmp, tmp_u(u), tmp_v(v);

  if (tmp_v.is_lt_zero())
    {
      tmp_v.negate();
      tmp_u.negate();
    }

  div_rem(z, tmp, tmp_u, tmp_v);
  tmp.multiply_by_2();
  if (tmp.abs_compare(tmp_v) >= 0)
  {
    if (tmp_u.is_ge_zero())
      inc(z);
    else
      dec(z);
  }
}
