#version 150
#extension GL_ARB_explicit_attrib_location : enable

uniform sampler2D Color;
uniform sampler2D Tex0; //Grade map

out vec4 outColor;
in vec2 UV;

layout (std140) uniform ColorGrading
{
vec4 shadows;
vec4 midtones;
vec4 highlights;
};

void main()
{
	vec4 sample = texture2D(Color, UV);

	float factor = max(sample.x, max(sample.y, sample.z));
	vec4 shadowsF = shadows;
	
	vec4 finalColor;

	if(factor < 0.1)	//shadowsF
	{
		if(factor > 0.01)
		{
			factor = (factor + 0.09)*10;
			
			shadowsF.w = shadowsF.x; //.w is value backup
			shadowsF.x = ((1 - shadowsF.w) / 2) * factor;
			shadowsF.x += shadowsF.w;	//Adding backup
			
			shadowsF.w = shadowsF.y; //.w is value backup
			shadowsF.y = ((1 - shadowsF.w) / 2) * factor;
			shadowsF.y += shadowsF.w;	//Adding backup
			
			shadowsF.w = shadowsF.z; //.w is value backup
			shadowsF.z = ((1 - shadowsF.w) / 2) * factor;
			shadowsF.z += shadowsF.w;	//Adding backup
		}
		finalColor = vec4(sample.x * shadowsF.x, sample.y * shadowsF.y, sample.z * shadowsF.z, sample.z);	
	}
	else finalColor = sample;

	//Midtones
	factor = (finalColor.x + finalColor.y + finalColor.z)/3;
	vec4 midtonesF = midtones;
	
	if(factor >= 0.1 && factor <= 0.5)	//Middle-tones
	{
		if(factor > 0.3)
		{
			factor = (factor - 0.31)*10;
			
			midtonesF.w = midtonesF.x; //.w is value backup
			midtonesF.x = ((1 - midtonesF.w) / 2) * factor;
			midtonesF.x += midtonesF.w;	//Adding backup
			
			midtonesF.w = midtonesF.y; //.w is value backup
			midtonesF.y = ((1 - midtonesF.w) / 2) * factor;
			midtonesF.y += midtonesF.w;	//Adding backup
			
			midtonesF.w = midtonesF.z; //.w is value backup
			midtonesF.z = ((1 - midtonesF.w) / 2) * factor;
			midtonesF.z += midtonesF.w;	//Adding backup
		}
		else if(factor <= 0.3)
		{
			factor = (factor - 0.1)*10;
			
			midtonesF.w = midtonesF.x;
			midtonesF.x = (1 - midtonesF.w) - (factor * ((1 - midtonesF.w) / 2));
			midtonesF.x += midtonesF.w;
			
			midtonesF.w = midtonesF.y;
			midtonesF.y = (1 - midtonesF.w) - (factor * ((1 - midtonesF.w) / 2));
			midtonesF.y += midtonesF.w;
			
			midtonesF.w = midtonesF.z;
			midtonesF.z = (1 - midtonesF.w) - (factor * ((1 - midtonesF.w) / 2));
			midtonesF.z += midtonesF.w;
		}
		
		finalColor *= midtonesF;
	}		

	factor = (finalColor.x + finalColor.y + finalColor.z)/3;
	vec4 highlightsF = highlights;
	
	if(factor > 0.5)	//Hightlights
	{
		if(factor <= 0.8)
		{
			factor = (factor - 0.51)*10;
			
			highlightsF.w = highlightsF.x;
			highlightsF.x = (1 - highlightsF.w) - (factor * ((1 - highlightsF.w) / 2));
			highlightsF.x += highlightsF.w;
			
			highlightsF.w = highlightsF.y;
			highlightsF.y = (1 - highlightsF.w) - (factor * ((1 - highlightsF.w) / 2));
			highlightsF.y += highlightsF.w;
			
			highlightsF.w = highlightsF.z;
			highlightsF.z = (1 - highlightsF.w) - (factor * ((1 - highlightsF.w) / 2));
			highlightsF.z += highlightsF.w;
		}
	
		finalColor *= highlightsF;
	}

	finalColor.a = sample.a;
	outColor = finalColor;
}