varying vec2 		texcoord;
uniform sampler2D 	tex;
uniform sampler2D 	lum;
uniform vec4		params;
uniform float 		lumAvg;
uniform float 		W;// = 20.0;//11.2; // linear white

void main()
{
	//float fWhiteCutoff=0.9;

	vec4 outcolor=texture2D(tex, texcoord);
	float lumColor=texture2D(lum, texcoord).r;

	//float lum=dot(vec3(0.27, 0.67, 0.06),color.rgb);
	
	// saturate(color.xyz - params.xyz) * params.w;
	//float grey=clamp(dot(vec3(0.27, 0.67, 0.06),color.rgb),0.0,1.0);
	
	// Determine what the pixel's value will be after tone mapping occurs
	//vec4 outcolor;
	outcolor.rgb *= /*lumAvg*/0.5 / ( lumColor + 0.001f );//color.rgb * (1.0/(lumColor + 0.001));
	outcolor.rgb *= ( 1.0f + ( outcolor.rgb / ( W * W ) ) );
 
	// Subtract out dark pixels
	/*outcolor.rgb -= params.xyz;

	// Clamp to 0
	outcolor = max(outcolor, 0.0);

	// Map the resulting value into the 0 to 1 range. Higher values for
	// BRIGHT_PASS_OFFSET will isolate lights from illuminated scene 
	// objects.
	outcolor.rgb /= (vec3(params.w)+outcolor.rgb); 
	//float grey=clamp(dot(vec3(0.27, 0.67, 0.06),outcolor.rgb),0.0,1.0);
	
	gl_FragColor.xyz = outcolor.rgb;//mix(outcolor.rgb,grey,0.5);//max(color.rgb,outcolor.rgb);//outcolor.rgb;//max(color.rgb,outcolor.rgb);
	//vec3 final=(color.xyz - params.xyz) * params.w;
	//gl_FragColor.xyz = clamp(final.xyz,0.0,1.0);*/
	
	/*vec4 color=texture2D(tex, texcoord);
	vec3 outcolor;*/
	
	// computes color lum
	float lum=dot(vec3(0.27, 0.67, 0.06),outcolor.rgb);

	// remove color below white point
	if(lum<params.x)
		outcolor.rgb=vec3(0.0,0.0,0.0);
	else
		outcolor.rgb = outcolor.rgb/(vec3(params.w)+outcolor.rgb); // scale color upon white point (params.w=OFFSET)

	/* PROVA 
	vec3 color=texture2D(tex, texcoord).rgb;
	float lum2=max(lum-vec3(params.x),0.0);	// cut off below white point
	finalColor=color.rgb*(lum2/lum);		// scales upon white point
	/*********/
	gl_FragColor.xyz=outcolor.xyz;
}
