/*
 * Implementation of class CoeffInformation
 *
 * $Date$
 * $Revision$
 *
 */

#include "WImage/CoeffInformation.hh"
#include <cmath>
#ifndef _WIN32_WCE
#include <fstream>
#include <iostream>
#include <iomanip>
#endif

#if !(defined __WATCOMC__ && __WATCOMC__ < 1230)
using namespace std;
#endif

CoeffInformation::CoeffInformation (coeff val, int y, int x, 
                                    int abs, long id, coeff misc)
{
  set (val, y, x, abs, id, misc);
}

void
CoeffInformation::set (coeff val, int y, int x, int abs, long id, coeff misc)
{
  m_value = val;
  m_yposition = y;
  m_xposition = x;
  m_xyposition = abs;
  m_id = id;
  m_misc = misc;
}

void
CoeffInformation::set (const CoeffInformation &c)
{
  m_value = c.val ();
  m_yposition = c.ypos ();
  m_xposition = c.xpos ();
  m_xyposition = c.xypos ();
  m_id = c.id ();
}

void
CoeffInformation::set (const Image &img, int ypos, int xpos)
{
  m_yposition = ypos;
  m_xposition = xpos;
  m_value = img.at (ypos, xpos);
  m_xyposition = img.abs (ypos, xpos);
}

int
CoeffInformation::svcmp (const CoeffInformation &c) const
{ 
  coeff tmp = m_value - c.val ();
  if (fabs (tmp) < COEFF_EPSILON)
    {
      return 0;
    }
  return tmp > 0.0? 1: -1;
}


int
CoeffInformation::avcmp (const CoeffInformation &c) const
{ 
  coeff tmp = fabs (m_value) - fabs (c.val ());
  if (fabs (tmp) < COEFF_EPSILON)
    {
      return 0;
    }
  return tmp > 0.0? 1: -1;
}

int
CoeffInformation::socmp (const CoeffInformation &c) const
{ 
  int rval = svcmp (c);
  
  if (rval != 0)
    {
      return rval;
    }
  return pcmp (c);
}


int
CoeffInformation::aocmp (const CoeffInformation &c) const
{ 
  int rval = avcmp (c);
  
  if (rval != 0)
    {
      return rval;
    }
  return pcmp (c);
}

int
CoeffInformation::pcmp (const CoeffInformation &c) const
{ 
  if (m_yposition > c.ypos ())
    {
      return 2;
    }
  if (m_yposition < c.ypos ())
    {
      return -2;
    }
  if (m_xposition > c.xpos ())
    {
      return 3;
    }
  if (m_xposition < c.xpos ())
    {
      return -3;
    }
  
  return 0;
}

bool
CoeffInformation::equals (const CoeffInformation &c) const
{ 
  return socmp (c) == 0;
}

#ifndef _WIN32_WCE
void 
CoeffInformation::dump (const char *delim, const char *file) const
{
  ostream *stream;
  if (file[0] == '\0')
    {
      stream = &cout;
    }
  else
    {
      stream = NEW (ofstream (file, ios_base::app));
      if (stream->fail ())
        {
          throw ios_base::failure ("Error opening file for writing.");
        }
    }
  stream->setf (ios::fixed, ios::floatfield);
  *stream << "(" << m_yposition << ", " << m_xposition 
          << ": " << std::setprecision (2) << std::setw (4)
          << m_value << ")" << delim;
  stream->setf (FMT0, ios::floatfield);
  if (stream != &cout)
    {
      DELETE (stream);
    }
}
#endif
