uniform sampler2D s_tex0; // for WiiU - changed 'tex' to 's_tex0'
uniform vec4 u_blendcolor;
uniform vec2 u_textureSize;
uniform float time;

varying vec2 v_texcoord;
varying vec2 v_omega;

#define round(x) floor( (x) + 0.5 )

const float base_brightness = 0.85;
const vec2 sine_comp = vec2(0.15, 0.05);

void main()
{
    vec2 texelSize = 1.0 / u_textureSize;
    vec2 texCoord = v_texcoord.xy;

    //scanline stuff
    vec4 c11 = texture2D(s_tex0, v_texcoord.xy);
    vec4 scanline = c11 * (base_brightness + 0.15 * mod(time, 0.15) + dot(sine_comp * sin(v_texcoord.xy * v_omega), vec2(1.0)));

    vec2 range = vec2(abs(dFdx(texCoord.x)), abs(dFdy(texCoord.y)));
    range = range * 0.999;

    float left   = texCoord.x - range.x;
    float top    = texCoord.y + range.y;
    float right  = texCoord.x + range.x;
    float bottom = texCoord.y - range.y;

    vec4 topLeftColor     = texture2D(s_tex0, vec2(left, top));
    vec4 bottomRightColor = texture2D(s_tex0, vec2(right, bottom));
    vec4 bottomLeftColor  = texture2D(s_tex0, vec2(left, bottom));
    vec4 topRightColor    = texture2D(s_tex0, vec2(right, top));

    vec2 border = clamp(
        round(texCoord / texelSize) * texelSize,
        vec2(left, bottom),
        vec2(right, top)
    );

    float totalArea = 4.0 * range.x * range.y;

    vec4 averageColor;
    averageColor  = ((border.x - left)  * (top - border.y)    / totalArea) * topLeftColor;
    averageColor += ((right - border.x) * (border.y - bottom) / totalArea) * bottomRightColor;
    averageColor += ((border.x - left)  * (border.y - bottom) / totalArea) * bottomLeftColor;
    averageColor += ((right - border.x) * (top - border.y)    / totalArea) * topRightColor;

    gl_FragColor = clamp((averageColor * scanline), 0.0, 1.0) * 0.97 + 0.03 * mod(time, 0.11) * 9.0909091;
}