#include "ClampRangeImageFilter.h"

#include <iostream>

template<class TRImage>
ClampRangeImageFilter<TRImage>
::ClampRangeImageFilter()
{
	// Create internal filter
	m_RangeFilter = RangeFilterType::New();

	// Initialize bounds
	SetLowerBound(-1e16);
	SetUpperBound(1e16);
}


template<class TRImage>
ClampRangeImageFilter<TRImage>
::~ClampRangeImageFilter()
{
}


//----------------------------------------------------------------------------
template<class TRImage>
void
ClampRangeImageFilter<TRImage>
::SetLowerBound(BoundValueType value)
{
	if ( m_LowerBound == value )
		return;

	m_LowerBound = value;
	m_RangeFilter->SetLowerBound(m_LowerBound);
	this->Modified();
}


//----------------------------------------------------------------------------
template<class TRImage>
typename ClampRangeImageFilter<TRImage>::BoundValueType
ClampRangeImageFilter<TRImage>
::GetLowerBound()
{
	return m_LowerBound;
}


//----------------------------------------------------------------------------
template<class TRImage>
void
ClampRangeImageFilter<TRImage>
::SetUpperBound(BoundValueType value)
{
	if ( m_UpperBound == value )
		return;

	m_UpperBound = value;
	m_RangeFilter->SetUpperBound(m_UpperBound);
	this->Modified();
}


//----------------------------------------------------------------------------
template<class TRImage>
typename ClampRangeImageFilter<TRImage>::BoundValueType
ClampRangeImageFilter<TRImage>
::GetUpperBound()
{
	return m_UpperBound;
}


//----------------------------------------------------------------------------
template<class TRImage>
void
ClampRangeImageFilter<TRImage>
::DoFiltering()
{
	// Filter range image if requested
	if ( (this->GetFilterMode()&Superclass::RANGE) == Superclass::RANGE )
	{
		m_RangeFilter->SetValidFlag(InputImageType::VALID);
		m_RangeFilter->SetInput(this->GetInput()->GetRangeImage());
		m_RangeFilter->SetMaskImageInput(this->GetInput()->GetFlagImage());
		m_RangeFilter->GetOutput()->SetRequestedRegion(this->GetOutput()->GetRequestedRegion());
		try
		{
			m_RangeFilter->Update();
		}
		catch ( itk::ExceptionObject &e )
		{
			std::cerr << e << std::endl;
		}

		// Set the output
		this->GetOutput()->SetRangeImage(m_RangeFilter->GetOutput());
		this->GetOutput()->SetFlagImage(m_RangeFilter->GetMaskOutput());
		//this->GetOutput()->GetRangeImage()->DisconnectPipeline();
		//this->GetOutput()->GetFlagImage()->DisconnectPipeline();
	}

	// Filtering for RGBs NOT supported
	if ( (this->GetFilterMode()&Superclass::RGB) == Superclass::RGB )
	{
		itkExceptionMacro(<<"Filtering of gray scale values not supported!");
	}

	// Filtering for world coord images NOT supported
	if ( (this->GetFilterMode()&Superclass::WORLDCOORD) == Superclass::WORLDCOORD ) 
	{
		itkExceptionMacro(<<"Filtering of world coords not supported!");
	}
}
