
const float n = 5.0;
const float c = -1.0;

uniform sampler2D tex;
uniform float width, height;
uniform float threshold;
uniform float contrast;

void main() {
	float xp = 1.0/width;
	float yp = 1.0/height;
	float hottresh = 1.0;

	vec3 t11 = texture2D(tex, gl_TexCoord[0].xy).rgb;
	vec3 t10 = texture2D(tex, gl_TexCoord[0].xy+vec2(0, -yp)).rgb;
	vec3 t01 = texture2D(tex, gl_TexCoord[0].xy+vec2(-xp, 0)).rgb;
	vec3 t21 = texture2D(tex, gl_TexCoord[0].xy+vec2(xp, 0)).rgb;
	vec3 t12 = texture2D(tex, gl_TexCoord[0].xy+vec2(0, yp)).rgb;

	if (t10.b+t01.b+t21.b+t12.b > threshold) {
		gl_FragColor = vec4(t11, 1.0);
	} else {
		gl_FragColor = vec4(t11*n+t10*c+t01*c+t21*c+t12*c, 1.0);
		//gl_FragColor.rgb *= gl_FragColor.rgb;
		
		//gl_FragColor.rgb *= 2.5;
		
		hottresh = gl_FragColor.r + gl_FragColor.g - gl_FragColor.b*2.5;
		
		if(hottresh>0.0) {
			gl_FragColor.r += 2.5*gl_FragColor.r*hottresh;
			gl_FragColor.g += 1.5*gl_FragColor.g*hottresh;
		}
		
		float bri = gl_FragColor.r+gl_FragColor.g+gl_FragColor.b;
		
		if(bri<3.0) {
			float greylevel = 1.0-bri/3.0;
			float greycol = 1.0-greylevel; // bri/2.0;

			greylevel *= greylevel;
			greylevel *= greylevel;
			greylevel = 1.0-greylevel;
			
			gl_FragColor.r = gl_FragColor.r*greylevel + (1.0-greylevel)*greycol;
			gl_FragColor.g = gl_FragColor.g*greylevel + (1.0-greylevel)*greycol;
			gl_FragColor.b = gl_FragColor.b*greylevel + (1.0-greylevel)*greycol;
		}

		
	}
	
	gl_FragColor.rgb=clamp(gl_FragColor.rgb*(1.0-contrast)+gl_FragColor.rgb*gl_FragColor.rgb*contrast*2.0,0.0,1.0);//*(0.5+1.5*(gl_FragColor.rgb*(1.0-contrast)));
	
}
