#version 130

uniform mat4 influences; // One column=influences of others colors on one particular color

uniform vec4 gradiantsColors[16];
uniform float gradiantsValues[16];

uniform vec2 screenSize;

uniform sampler2D tex;

void main()
{
    vec4 sumVals=texture(tex,gl_FragCoord.xy/screenSize)*256;
    vec4 vals=vec4(0,0,0,0);

    for(int i=0;i<4;++i)
    {
        vec4 oth=sumVals*influences[i];
        vals[i]=max(0,sumVals[i]-max(max(oth[0],oth[1]),max(oth[2],oth[3])));
    }

    float sum=vals[0]+vals[1]+vals[2]+vals[3];
    if(sum==0) discard;
    vals/=sum;
    sum/=sum+1;
    mat4 colors;
    for(int i=0;i<4;++i)
    {
        if(sum<gradiantsValues[i*4]) colors[i]=vec4(0,0,0,0);
        else
        {
            int pos=0;
            if(sum>=gradiantsValues[i*4+1]) pos=1;
            if(sum>=gradiantsValues[i*4+2]) pos=2;
            if(sum>=gradiantsValues[i*4+3]) colors[i]=gradiantsColors[i*4+3];
            else
            {
                float fpos=(sum-gradiantsValues[i*4+pos])/(gradiantsValues[i*4+pos+1]-gradiantsValues[i*4+pos]);
                colors[i]=mix(gradiantsColors[i*4+pos],gradiantsColors[i*4+pos+1],fpos);
            }
        }
    }
    gl_FragColor=vals[0]*colors[0]+vals[1]*colors[1]+vals[2]*colors[2]+vals[3]*colors[3];
}