/*=========================================================================

  Copyright (c) Kitware, Inc.
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/VolViewCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

// .NAME vtkITKImageToImageRegionFilter - 

#ifndef __vtkITKImageToImageRegionFilter_h
#define __vtkITKImageToImageRegionFilter_h


#include "vtkITKImageToImageFilter.h"
#include "vtkImageClip.h"

class VTK_EXPORT vtkITKImageToImageRegionFilter : public vtkITKImageToImageFilter
{
public:
  static vtkITKImageToImageFilter *New()
    {
    return new vtkITKImageToImageRegionFilter;
    };
  
  vtkTypeMacro(vtkITKImageToImageRegionFilter, vtkITKImageToImageFilter);

  // Description:
  // Set the Input of the filter.
  virtual void SetInput(vtkImageData *input)
    {
    this->ImageClip->SetInput(input);
    this->ImageClip->ResetOutputWholeExtent();
    };

  // Description:
  // Return the input to the filter
  virtual vtkDataObject* GetInput()
    {
    return (vtkDataObject::SafeDownCast( this->vtkCast->GetInput() ));
    };

  virtual void SetROIExtent( int extent[6] )
    {
    this->ImageClip->SetOutputWholeExtent(extent);
    }

  virtual void SetROIBounds( double bounds[6] )
    {
    vtkImageData *image = vtkImageData::SafeDownCast(this->ImageClip->GetInput());
    if (image)
      {
      double inputVolumeOrigin[3], inputVolumeSpacing[3];
      int inputVolumeDimensions[3], idx[6];
      image->GetOrigin(inputVolumeOrigin);
      image->GetSpacing(inputVolumeSpacing);
      image->GetDimensions(inputVolumeDimensions);
    
      // convert bounds into indices that represent VTK extents
      for ( unsigned int j = 0; j < 6; ++j )
        {
        idx[j] = (int)( (bounds[j]-inputVolumeOrigin[j/2])/
                                 inputVolumeSpacing[j/2] + 0.5);

        // Truncate them if they go out of bounds
        if (idx[j] < 0) 
          {
          idx[j] = 0;
          }
        if (idx[j] >= inputVolumeDimensions[j/2])
          {
          idx[j] = inputVolumeDimensions[j/2] -1;
          }
        }

      this->SetROIExtent(idx);
      }
    }

 protected:

  vtkITKImageToImageRegionFilter()
    {
    // Need an import, export, and a ITK pipeline
    this->ImageClip = vtkImageClip::New();
    this->vtkCast->SetInput( this->ImageClip->GetOutput() );
    }

  ~vtkITKImageToImageRegionFilter()
    {
    this->ImageClip->Delete();
    }

  vtkImageClip * ImageClip;
  
private:
  vtkITKImageToImageRegionFilter(const vtkITKImageToImageRegionFilter&);  // Not implemented.
  void operator=(const vtkITKImageToImageRegionFilter&);  // Not implemented.
};

#endif

