varying vec2 TexCoordOut;
uniform sampler2D SamplerY;
uniform sampler2D SamplerU;
uniform sampler2D SamplerV;
uniform sampler2D SamplerW;
uniform int WaterMark;

float crCalculateBlend(float a1, float a2, float c1, float c2)
{
    return (c1 * a1 * (1.0 - a2) + c2 * a2) / (a1 + a2 - a1 * a2);
}

void main() {
    float y, u, v, r, g, b;
    y = texture2D(SamplerY, TexCoordOut).r;
    u = texture2D(SamplerU, TexCoordOut).r;
    v = texture2D(SamplerV, TexCoordOut).r;
	
    u = u - 0.5;
    v = v - 0.5;
    r = y + 1.403 * v;
    g = y - 0.344 * u - 0.714 * v;
    b = y + 1.770 * u;

    if ( WaterMark > 0 ) {
        float wr, wg, wb, wa;
        wr = texture2D(SamplerW, TexCoordOut).r;
        wg = texture2D(SamplerW, TexCoordOut).g;
        wb = texture2D(SamplerW, TexCoordOut).b;
        wa = texture2D(SamplerW, TexCoordOut).a;
        
        float fAlpBlend = 1.0 + wa - 1.0 * wa;
        float fRedBlend = crCalculateBlend(1.0, wa, r, wr);
        float fGreenBlend = crCalculateBlend(1.0, wa, g, wg);
        float fBlueBlend = crCalculateBlend(1.0, wa, b, wb);
        
        gl_FragColor = vec4(fRedBlend, fGreenBlend, fBlueBlend, fAlpBlend);
    } else {
        gl_FragColor = vec4(r , g , b , 1.0 );
    }
}
