#extension GL_ARB_texture_rectangle : enable

varying vec2 texcoord;
uniform sampler2DRect tex0;
uniform sampler2DRect tex_noise;
uniform sampler2DRect tex1;

uniform float fade;

uniform float rgboffset;
uniform float noisepos;
uniform float noiseamount;

uniform float rausch;
uniform float time;

uniform float red;
uniform float green;
uniform float blue;
uniform float blur;
uniform float contrast;
uniform int fademode;

	float rand(vec2 co)
	{
		return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453*time);
	}
	
	
	vec4 getBlurredPixel(sampler2DRect tex,vec2 pos, float bluramount)
	{
		vec4 finalColor=vec4(0,0,0,0);
		float i=0.0;
		float count=0.0;
		for(i=0.0;i<bluramount;i+=4.0)
		{
		count+=1.0;
			finalColor+=texture2DRect(tex, vec2(pos.s,pos.t-i));
			finalColor+=texture2DRect(tex, vec2(pos.s-i,pos.t));
			finalColor+=texture2DRect(tex, vec2(pos.s-i,pos.t-i));
			
			finalColor+=texture2DRect(tex, vec2(pos.s,pos.t+i));
			finalColor+=texture2DRect(tex, vec2(pos.s+i,pos.t));
			finalColor+=texture2DRect(tex, vec2(pos.s+i,pos.t+i));

			finalColor+=texture2DRect(tex, vec2(pos.s+i,pos.t-i));
			finalColor+=texture2DRect(tex, vec2(pos.s-i,pos.t+i));
		}

		finalColor/=count*8.0;
		return finalColor; 
	}
	
	
	vec4 getPixel(vec2 pos)
	{
		
		vec4 fc=texture2DRect(tex0, pos);
		
		if(blur!=0.0)
			fc=getBlurredPixel(tex0,pos,blur);
	
		
		if(fade!=0.0)
		{
			vec4 finalColor2=texture2DRect(tex1, pos);
			if(blur!=0.0)
				finalColor2=getBlurredPixel(tex1,pos,blur);

			if(fademode==2)
			{
				if(blur<fade*20.0 || blur <(1.0-fade)*20.0)
				{
					fc=getBlurredPixel(tex0,pos,fade*20.0);
					finalColor2=getBlurredPixel(tex1,pos,(1.0-fade)*20.0);
				}
			}
			fc = finalColor2 * fade + fc * (1.0 - fade);
		}
		
		return fc;
		
	}
	
	// ------------------------------------------------------------------

void main (void)
{

	vec2 mytexcoord=texcoord;

	
	if(noiseamount>0.0)
	{
		vec4 noiseColor=texture2DRect(tex_noise, vec2(noisepos*190.0,texcoord.t));
		mytexcoord.s=mytexcoord.s+(noiseColor.r-0.5)*350.0*noiseamount;
	}

vec4 finalColor=getPixel( mytexcoord);
vec4 finalColor2;



	// rgb 
		
	if(rgboffset>0.0)
	{
		float off=20.0*rgboffset;
		vec4 col; 
		col= getPixel(vec2(mytexcoord.s-off,mytexcoord.t));
		finalColor.r=col.r;
	
		col= getPixel(mytexcoord);
		finalColor.g=col.g;
	
		col= getPixel(vec2(mytexcoord.s+off,mytexcoord.t));
		finalColor.b=col.b;
	}






	if(rausch>0.0)
	finalColor+=(rand(mytexcoord)-0.5)*rausch;

	if(red!=0.0)finalColor.r*=red;
	if(blue!=0.0)finalColor.b*=blue;
	if(green!=0.0)finalColor.g*=green;

	if(contrast!=0.0)
	{
		finalColor=smoothstep(contrast,1.0,finalColor);
		finalColor.a=1.0;
	}


		gl_FragColor =finalColor;
	
	 
}
