#version 330

#include "commonMLDX.h"
#include "alpha.h"
#include "inputColorHelper.h"

uniform sampler2DRect inputTex;
uniform sampler2DRect inputTexMask;
uniform vec4 endColor;
uniform float endOpacity;

in vec2 fsTexture;
in vec2 fsTextureMask;
out vec4 outColor;

void main()
{
    float isOddLine;
    float isOddUV;
    vec2 tc00;
    vec2 tc10;
    vec2 tc20;
    vec4 c00;
    vec4 c10;
    vec4 c20;
    vec4 avg;

    tc10=fsTexture.xy;

#ifdef IS_ODD
    isOddLine=1.0 - floor(fract(tc10.y * 0.5) * 2.0);
#else
    isOddLine=floor(fract(tc10.y * 0.5) * 2.0);
#endif
    isOddUV = floor(fract(tc10.x * 0.5) * 2.0);

    //above and below lines start with same coordinates
    tc00=tc10;
    tc20=tc10;
    //for above line, subtract 1
    tc00.y-=isOddLine;
    //for below line, add 1
    tc20.y+=isOddLine;

#ifdef ARGB
    c00 = texture(inputTex, tc00).argb;
    c10 = texture(inputTex, tc10).argb;
    c20 = texture(inputTex, tc20).argb;
#endif

#ifdef ABGR
    c00 = texture(inputTex, tc00).abgr;
    c10 = texture(inputTex, tc10).abgr;
    c20 = texture(inputTex, tc20).abgr;
#endif

#ifdef BGRA
    c00 = texture(inputTex, tc00).bgra;
    c10 = texture(inputTex, tc10).bgra;
    c20 = texture(inputTex, tc20).bgra;
#endif

#ifdef RGBA
    c00 = texture(inputTex, tc00).rgba;
    c10 = texture(inputTex, tc10).rgba;
    c20 = texture(inputTex, tc20).rgba;
#endif

    float gray0 = dot(c00.rgb, vec3(0.299, 0.587, 0.114));
    float gray1 = dot(c10.rgb, vec3(0.299, 0.587, 0.114));
    float gray2 = dot(c20.rgb, vec3(0.299, 0.587, 0.114));

    avg=(c00+c20)*0.5;

    if(gray1>=gray0)
    {
        if(gray1>gray2)
            c10=avg;
    }
    else
    {
        if(gray1<gray2)
            c10=avg;
    }

    outColor=c10;

    outColor=processColorProfile(outColor);

#ifdef USE_MASK
    multiplyOpacity(outColor, texture(inputTexMask, fsTextureMask).a);
#endif

#ifdef USE_END_COLOR
    mixColor(outColor, endColor, outColor, endOpacity);
#endif

}
