#version 400

uniform sampler2D inputTex;
uniform ivec2     dirOffset;

// Are we drawing over the whole image, or a lower resolution part?
uniform float passScale;

in vec2 texelPos;

out vec4 result;

// This is the actual code that is executed.
void main( void )
{	
	// We're dealing with integer tex coords here, so convert to int now.
	//    Waiting till later almost guarantees the indices will be off by one.
	ivec2 texSz       = ivec2( passScale * textureSize( inputTex, 0 ) );
	ivec2 intTexCoord = ivec2( texelPos * texSz );

	// Compute which side we're on...  Lower frequency image or residual
	//    Should be 0.5 in only one of 2 components.  Should be 0 for
	//    half the quad, and 0.5 for the other half.
	vec2 sub;
	sub.x = (dirOffset.x > 0 && texelPos.x > 0.5) ? 0.5f : 0.0f;
	sub.y = (dirOffset.y > 0 && texelPos.y > 0.5) ? 0.5f : 0.0f;
	
	// Determine are we on the low frequency side or the residual side?
	bool isResidual = (sub.x+sub.y) > 0;

	// If we're in the residual half, we need to find the corresponding location
	//    on the non-residual half. 
	intTexCoord = isResidual ? intTexCoord - (dirOffset * texSz / 2) :
	                           intTexCoord;

	// Find the texture coordiantes
	ivec2 pixID1 = (dirOffset+1)*intTexCoord;
	ivec2 pixID2 = (dirOffset+1)*intTexCoord + dirOffset; 
	
	// Read the pixel colors
	vec4 texel1 = texelFetch( inputTex, pixID1, 0 );	
	vec4 texel2 = texelFetch( inputTex, pixID2, 0 );
	
	float inputWasResidual = texel1.w;	
	
	// Compute the residual.  The ordering of texture is reversed on the
	//    two sides of our image.
	vec4 texResidual = texel1-texel2;
	
	// Compute the lower frequency result
	vec4 texLowFreq  = texel1 - 0.5 * texResidual;
	
	// Conditionally output the low frequency / residual depending
	//    on which side of the image we're on!  
	// If displaying a residual (could be +/- near zero), move it up
	//    so we're displaying a number near 0.5
	result = isResidual ? vec4( 0.5+texResidual.xyz, 0.0 ) : 
	                      vec4( texLowFreq.xyz,      inputWasResidual ) ;
}