#version 400

uniform sampler2DMS  theRenderTex;
uniform sampler2D    alphaTex;
uniform int          numSamples; 

in vec2 fragTexCoord;
out vec4 result;


// This is the actual code that is executed.
void main( void )
{
	ivec2 iTexCoord = ivec2(textureSize(theRenderTex) * vec2(fragTexCoord.x, 1-fragTexCoord.y));
	vec2 fTexCoord  = vec2(fragTexCoord.x, 1-fragTexCoord.y);
	
	float alpha = texture( alphaTex, fTexCoord ).x;
	
	if (alpha >= 1.0f)
		discard;
	
	float R = 0;
	for(int i = 0; i < numSamples; i++)
	{
		vec4 sampleColor = texelFetch(theRenderTex, iTexCoord, i);
		result += vec4( sampleColor.xyz, 1.0 );
		R      += sampleColor.w;
	}
	//R /= numSamples;

	//result = result / float( numSamples );
	result = (1.0-alpha) * result / R;
}