#include "subimage.h"

subimage::subimage()
{
  image = NULL;
}

subimage::subimage( const subimage &in)
{
  image = in.image;
  up = in.up;
  low = in.low;
  left = in.left;
  right = in.right;
  sizex = in.sizex;
  sizey = in.sizey;
}

subimage::~subimage()
{
}


int subimage::init(double *data, int u, int l, int f,
                   int r, int x, int y)
{
  image = data;
  up = u;
  low = l;
  left = f;
  right = r;
  sizex = x;
  sizey = y;
  return 0;
}

double subimage::getpixel(int x, int y)
{

#ifndef __NO_IMAGE_BOUNDRY_CHECK__
  if(image == NULL)
    return 0;
#endif

  int ix = x+up;
  int iy = y+left;
#ifndef __NO_IMAGE_BOUNDRY_CHECK__
  if(ix < low && iy < right)
    {
#endif
      int s = ix*sizey+iy;
#ifndef __NO_IMAGE_BOUNDRY_CHECK__
      if( s >= sizex*sizey )
        {
          std::cout << "ERROR subimage size: "
                    << x << ", " << y << "\n"
                    << up << ", " << low << "\n"
                    << left << ", " << right << "\n";
        }
#endif
      return image[s];
#ifndef __NO_IMAGE_BOUNDRY_CHECK__
    }
#endif
  return 0;
}

int subimage::setpixel(double value, int x, int y)
{
#ifndef __NO_IMAGE_BOUNDRY_CHECK__
  if(image == NULL)
    return 0;
#endif
  int ix = x+up;
  int iy = y+left;
#ifndef __NO_IMAGE_BOUNDRY_CHECK__
  if(ix < low && iy < right)
#endif
    image[ix*sizey+iy] = value;
  return 0;
}

#ifndef _NOMAGICK_
int subimage::getimage(Magick::Image &im1)
{
  if(image == NULL)
    return -1;
  Magick::Geometry geo;
  int sx, sy;
  sx = low-up;
  sy = right-left;
#ifdef __DEBUG__
  std::cout << "subimage size " << sx << " " << sy << "\n";
#endif
  geo.width(sy);
  geo.height(sx);
  Magick::Image im(geo, Magick::Color("black"));
  //im.modifyImage();
  //im.size(geo);
  //im.type(Magick::GrayscaleType);
  //Magick::PixelPacket *pixel_cache = im.getPixels(0,0, sy, sx);
#ifdef __DEBUG__
  std::cout << "geometry set\n";
#endif
  Magick::ColorGray gray(0.5);
  for(int i = 0; i < low-up; i++)
    {
      for(int j = 0; j < right-left; j++)
	{
          //std::cout << "jfds\n";
	  //gray.isValid(true);
	  try
	    {
              gray.shade(fabs(getpixel(i, j)));
              //*(pixel_cache+j*sx+i) = gray;
	      im.pixelColor(j, i, gray);
	    }
	  catch( Magick::Exception &error_ )
	    {
	      std::cout << "Caught exception: " << error_.what() << std::endl;
	      std::cout << "\t" << "(" << i << "," << j << ") "
			<< getpixel(i, j) << " " << gray.shade() << "\n";
	    }
	}
    }
  //im.syncPixels();
  //im.write("subimage.tif");
  im1 = im;
#ifdef __DEBUG__
  std::cout << "image copied\n";
#endif
  return 0;
}
#endif

int subimage::getsizex()
{
  return low-up;
}

int subimage::getsizey()
{
  return right-left;
}
