#version 400

uniform sampler2D inputTex;
uniform ivec2     dirOffset;
//uniform float     passResolution;

// 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 the two input texels for our computations.	
	ivec2 lfTexel  = intTexCoord / (dirOffset+1);
	ivec2 resTexel = lfTexel + ivec2( dirOffset * texSz / 2 );
	
	// Read the pixel colors
	vec4 lfColor  = texelFetch( inputTex, lfTexel, 0 );	
	vec4 resColor = texelFetch( inputTex, resTexel, 0 )-0.5;

	// Every other pixel uses a different reconstruction, so identify if
	//    we're add an odd or even pixel.  Do this along the direction of
	//    the pass traversal.
	ivec2 tmp   = intTexCoord*dirOffset;
	int   coord = max( tmp.x, tmp.y );
	bool  evenCoord = ( coord % 2 ) == 0;

	// Reconstruct the original values
	vec3 reconstr1   = lfColor.xyz + 0.5*resColor.xyz;
	vec3 reconstr2   = lfColor.xyz - 0.5*resColor.xyz;
	
	// Conditionally output the correct reconstructed result
	result = vec4( evenCoord ? reconstr1 : reconstr2, (lfColor.w > 0 ? 1.0 : 0.0) );
}