#version 330 core

in vec2 texCoord;
out vec4 fragColor;

uniform sampler2D texture0; 
uniform sampler2D texture1; // fft

uniform float intensity = 1.0;
uniform float zoom = 8.0;

uniform vec3 iResolution;

uniform vec4 color = vec4(1);

uniform float fftHistory = 16.0;

uniform float threshold = 1.0;

void main()
{

    // Horizontal bars

    float mval = 0.0;
    float mvalDecay = 0.0;
    float mavg = 0.0;
    float mcur = texture2D(texture1, vec2(texCoord.x, 1.0)).r;

    /*for (int i = 0; i < fftHistory; i++) {
        float percent = i/fftHistory;
        vec2 coordHistory = vec2(texCoord.x, percent);

        mavg += texture2D(texture1, coordHistory).r;

        mval = max(texture2D(texture1, coordHistory).r, mval);
        mvalDecay = max(texture2D(texture1, coordHistory).r*smoothstep(0.0,1.0,percent), mvalDecay);
    }
    mavg /= fftHistory;

    if (texCoord.y <= mval) {
        fragColor = vec4(vec3(mvalDecay),1.0);
    }*/

    float prec = 0.003;
/*
    if (texCoord.y > mvalDecay-prec && texCoord.y < mvalDecay+prec) {
        fragColor = vec4(1,1,0,1);
    }

    if (texCoord.y > mval-prec && texCoord.y < mval+prec) {
        fragColor = vec4(1,0,0,1);
    }

    if (texCoord.y > mavg-prec && texCoord.y < mavg+prec) {
        fragColor = vec4(1,0,1,1);
    }

    if (texCoord.y > mcur-prec && texCoord.y < mcur+prec) {
        fragColor = vec4(0.5,1,1,1);
    }

    if (1.0-texCoord.y > 1.0-mcur-prec && 1.0-texCoord.y < 1.0-mcur+prec) {
        fragColor = vec4(0.5,1,1,1);
    }
*/
    if (fragColor.r <= threshold) {
        //circle visualization

        vec2 coord = (texCoord.yx-vec2(.5,.5))/vec2(iResolution.z,1.0)/zoom;

        //float tcur = texture2D(texture0, texCoord).r;

        float r = length(coord);


        float c = 0.0;
        for (int i = 0; i < fftHistory; i++) {
            float percent = i/fftHistory;
            c = mix(0.0, 1.0, (texture2D(texture1, vec2(r,percent)).r)*intensity*(percent));
        }

        fragColor = mix(vec4(0),vec4(1.0),vec4(vec3(c-r),c*1.0))*color;
    } else {
    discard;
    }
}
