namespace X3DTK {

template<class T>
T *Memory<T>::access(Image *I, unsigned short x, unsigned short y)
{
  return (reinterpret_cast<T *>(I->getData()) + (I->getWidth()*y + x));
}

template<class IT, class OT>
void ImageConverter<IT, OT>::make(unsigned char *out, unsigned char *in, unsigned int length)
{
  IT *iPtr = reinterpret_cast<IT *>(in);
  OT *oPtr = reinterpret_cast<OT *>(out);
  
  for (unsigned int i = 0; i < length; ++i)
  {
    double r;
    IT v = *iPtr;

    if (std::numeric_limits<IT>::is_integer)
    {
      r = static_cast<double>(v)/static_cast<double>(std::numeric_limits<IT>::max());
      //if (std::numeric_limits<IT>::is_signed)
      //  r = 0.5*r + 0.5;
    }
    else
    {
      r = v;  
      if (r > 1.0)
        r = 1.0;
      if (r < 0.0)
        r = 0.0;
    }  

    if (std::numeric_limits<OT>::is_integer)
    {
      //if (std::numeric_limits<OT>::is_signed)
      //  r = 2.0*r - 1.0;
      *oPtr = static_cast<OT>(static_cast<double>(std::numeric_limits<OT>::max())*r);    
    }
    else
      *oPtr = static_cast<OT>(r);
    
    ++iPtr;
    ++oPtr;
  }
}

}

