#version 330 core

uniform sampler2D iChannel0; // key state input
uniform sampler2D iChannel1; // previous state
uniform int iFrame;
out vec4 FragColor;

#define keystate(k,n) ( texelFetch(iChannel0,ivec2(k,n),0) )

void mainImage(out vec4 t, vec2 uv) {
#if __VERSION__ < 300
    t = vec4(0);
#else
    int i = int(uv.x);
    int j = int(uv.y);
    if ( iFrame == 0 ) {
        t = vec4(0);
    } else {
        t = texelFetch(iChannel1,ivec2(i,j),0);
    }
    if (i == 0) {
        float w1 = keystate(j,2).x;
        if (w1 != t.w) {
            t.w = w1;
            t.x++;
        }
    }
#endif
}

void main() {
    vec2 uv = gl_FragCoord.xy; 
    vec4 t;
    mainImage(t, uv);
    FragColor = t;
}
