layout(location = 0, index = 0) out vec4 outcol0;

uniform sampler2D tex0;
uniform vec4 sharpen;
uniform vec4 texelsize;

in vec2 texcoord0_nm;

//remaps interval [a;b] to [0;1]
vec3 remap3( vec3 t, float a, float b ) {
	return clamp( (t - a) / (b - a), 0, 1 );
}

void main()
{
	vec4 sample0 = texture( tex0, texcoord0_nm );

	vec4 sample1 = texture( tex0, texcoord0_nm + vec2(1,0)*texelsize.zw );
	vec4 sample2 = texture( tex0, texcoord0_nm + vec2(-1,0)*texelsize.zw );
	vec4 sample3 = texture( tex0, texcoord0_nm + vec2(0,1)*texelsize.zw );
	vec4 sample4 = texture( tex0, texcoord0_nm + vec2(0,-1)*texelsize.zw );

	vec4 sample5 = texture( tex0, texcoord0_nm + vec2( 1, 1)*texelsize.zw );
	vec4 sample6 = texture( tex0, texcoord0_nm + vec2(-1,-1)*texelsize.zw );
	vec4 sample7 = texture( tex0, texcoord0_nm + vec2(-1, 1)*texelsize.zw );
	vec4 sample8 = texture( tex0, texcoord0_nm + vec2( 1,-1)*texelsize.zw );

	vec3 hz = abs( sample2.rgb - sample1.rgb );
	vec3 vt = abs( sample3.rgb - sample4.rgb );
	vec3 d1 = abs( sample6.rgb - sample5.rgb );
	vec3 d2 = abs( sample8.rgb - sample7.rgb );

	//vec3 its = hz + vt + 0.5*(d1+d2);
	vec3 its = 2.5*min(max(hz,vt), max(d1,d2));

	vec3 out_edge = 5.0 * sharpen.x * remap3( its, sharpen.y, sharpen.z );
	
	//outcol0 = vec4( sample0.rgb - 5*sharpen.x*(hz+vt+0.5*(d1+d2)), 1 );

	outcol0 = vec4( max( out_edge, sample0.rgb ), sample0.a );
	
	outcol0.rgb = mix( clamp(outcol0.rgb,0,1), vec3(out_edge), sharpen.w);
}
