#include "FixedInt.h"

FixedInt::FixedInt ()
{
  value=0;
}

FixedInt::FixedInt (const FixedInt & rhs)
{
  *this=rhs;
}

FixedInt::~FixedInt ()
{
}

FixedInt::FixedInt (int v)
{
  value = v << 8;
}

FixedInt::FixedInt (double v)
{
  value = (int32_t)(v * (1 << 8));
}

//returns the raw value underneath.
int FixedInt::rawValue() const
{
  return value;
}

int FixedInt::toInt() const
{
  return value >> 8;
}

FixedInt FixedInt::operator + (const FixedInt & rhs)
{
  FixedInt result = *this;
  result+=rhs;
  return result;
}

FixedInt FixedInt::operator * (const FixedInt & rhs)
{
  FixedInt result = *this;
  result*=rhs;
  return result;
}

FixedInt FixedInt::operator - (const FixedInt & rhs)
{
  FixedInt result = *this;
  result-=rhs;
  return result;
}

FixedInt FixedInt::operator / (const FixedInt & rhs)
{
  FixedInt result = *this;
  result/=rhs;
  return result;
}

FixedInt FixedInt::operator % (const FixedInt & rhs)
{
  FixedInt result = *this;
  result%=rhs;
  return result;
}

FixedInt & FixedInt::operator = (const FixedInt & rhs)
{
  if (this == &rhs)
      return *this;

  value = rhs.value;
  return *this;
}

void FixedInt::operator += (const FixedInt & rhs)
{
  value = value + rhs.value;
}

void FixedInt::operator *= (const FixedInt & rhs)
{
  value = ((value * rhs.value) >>8);
}

void FixedInt::operator -= (const FixedInt & rhs)
{
  value = value - rhs.value;
}

void FixedInt::operator /= (const FixedInt & rhs)
{
  value = (value << 8) / rhs.value;
}

void FixedInt::operator %= (const FixedInt & rhs)
{
  value = value % rhs.value;
}

float FixedInt::toFloat() const
{
  return (((float)value) / (1.0*(1<<8)));
}

bool FixedInt::operator == (const FixedInt & rhs)
{
  return value == rhs.value;
}

ostream & operator<< (ostream & os, const FixedInt& rhs)
{
  os << rhs.toFloat();
  return os;
}


bool FixedInt::operator == (const int & rhs)
{
  int temp=rhs << 8;
  return (value==temp);
}

bool FixedInt::operator > (const int & rhs)
{
  int temp=rhs << 8;
  return (value>temp);
}

bool FixedInt::operator < (const int & rhs)
{
  int temp=rhs << 8;
  return (value<temp);
}

bool FixedInt::operator >= (const int & rhs)
{
  return ((*this>rhs)||(*this==rhs));
}

bool FixedInt::operator <= (const int & rhs)
{
  return ((*this<rhs)||(*this==rhs));
}

uint8_t FixedInt::toAngle()
{
  return uint8_t(toInt()%256);
}

//returns the square root using intSqrt.

//runnig intSqrt on the underlying value gives us 2^4 ans, so we need to multiply it by 2^4 again to get the answer in terms of FixedInt.
void FixedInt::sqrt()
{
  int underside=intSqrt(value);

  value=underside * 16;
}

const FixedInt fixSqrt(FixedInt t)
{
  FixedInt t2 = t;
  t2.sqrt();
  return t2;
}
