/*------------------------------------------------------------------------------
						PRE_SHARPEN
------------------------------------------------------------------------------*/

float4 SharpenPass( float2 tex ) 
{
	float AverageBlur2 = 0;
	float CoefficientsBlur2 = 0;
	float CoefficientsOriginal = 0;
	float SharpenEdge2 = 0;
	float SharpenContour2 = 0;
	if ( AverageBlur < 1 || AverageBlur > 9) AverageBlur2 = 0.2;
	else AverageBlur2 = AverageBlur * 0.05;
	if ( CoefficientsBlur < 1 || CoefficientsBlur > 9) 
	{
		CoefficientsBlur2 = 2;
		CoefficientsOriginal = 3;
	}
	else 
	{
		CoefficientsBlur2 = CoefficientsBlur * 0.33;
		CoefficientsOriginal = CoefficientsBlur2 + 1;
	}
	if ( SharpenEdge < 1 || SharpenEdge > 9) SharpenEdge2 = 0.2;
	else SharpenEdge2 = SharpenEdge * 0.05;
	if ( SharpenContour < 1 || SharpenContour > 9) SharpenContour2 = 0.0125;
	else SharpenContour2 = SharpenContour * 0.0125;
	// Recover the original pixels
	float4 Original = tex2D(s0, tex);
	// Gaussian filter
	//   [ 1, 2 , 1 ]
	//   [ 2, 4 , 2 ]
	//   [ 1, 2 , 1 ]
	float4 c1 = tex2D(s0, tex + float2(-dx,-dy));
	float4 c2 = tex2D(s0, tex + float2(0,-dy));
	float4 c3 = tex2D(s0, tex + float2(dx,-dy));
	float4 c4 = tex2D(s0, tex + float2(-dx,0));
	float4 c5 = tex2D(s0, tex + float2(dx,0));
	float4 c6 = tex2D(s0, tex + float2(-dx,dy));
	float4 c7 = tex2D(s0, tex + float2(0,dy));
	float4 c8 = tex2D(s0, tex + float2(dx,dy));
	//Normalize the values. Formula: 1 / (1+2+1+2+4+2+1+2+1) = 1 / 16 = .0625
	float4 blur = (c1+c3+c6+c8 + 2*(c2+c4+c5+c7)+ 4*Original)*0.0625;
	//Subtracting the blurred image from the original image
	float4 Corrected = CoefficientsOriginal*Original - CoefficientsBlur2*blur;
	//For higher precision in the calculation of contour, requires slightly more processing power
	//   [ c1, c2 , c3 ]
	//   [ c4, ori , c5 ]
	//   [ c6, c7 , c8 ]
	if (highQualitySharpen == true)
	{
		c1 = tex2D(s0, tex + float2(-px,-py));
		c2 = tex2D(s0, tex + float2(0,-py));
		c3 = tex2D(s0, tex + float2(px,-py));
		c4 = tex2D(s0, tex + float2(-px,0));
		c5 = tex2D(s0, tex + float2(px,0));
		c6 = tex2D(s0, tex + float2(-px,py));
		c7 = tex2D(s0, tex + float2(0,py));
		c8 = tex2D(s0, tex + float2(px,py));
	}
	else {}
	// Horizontal gradient
	//   [ -1, 0 ,1 ]
	//   [ -2, 0, 2 ]
	//   [ -1, 0 ,1 ]
	float delta1 = (c3 + 2*c5 + c8)-(c1 + 2*c4 + c6);
	// Vertical gradient
	//   [ -1,- 2,-1 ]
	//   [  0,  0, 0 ]
	//   [  1,  2, 1 ]
	float delta2 = (c6 + 2*c7 + c8)-(c1 + 2*c2 + c3);
	// Calculate and sharpen the blurry edges
	if (sqrt( mul(delta1,delta1) + mul(delta2,delta2)) > SharpenEdge2) 
		{
			// Contour sharpening
			return Original * CoefficientsBlur2 - (c1 + c2 + c3 + c4 + c5 + c6 + c7 + c8 ) * SharpenContour2;
		}
	else 
		{
			// Return corrected image
			return Corrected;
		}
}