
uniform sampler2D textureSampler0;
uniform sampler2D textureSampler1;
uniform sampler2D textureSampler2;
uniform sampler2D textureSampler3;
uniform float time;

varying vec3 pos;

void main() {

	gl_FragColor = texture2D(textureSampler0, gl_TexCoord[0].st);
	vec4 overlayPaletteIndex = texture2D(textureSampler1, gl_TexCoord[0].st);
	vec4 overlayColor;
	float indexToUse = overlayPaletteIndex.x;
	
	if(overlayPaletteIndex.x == overlayPaletteIndex.y && overlayPaletteIndex.x == overlayPaletteIndex.z) {
		
		// Straight from color index to palette.
	
	} else {
		
		if(overlayPaletteIndex.x > overlayPaletteIndex.y && overlayPaletteIndex.x > overlayPaletteIndex.z) {
			
			// Use the red channel (x) in the first quarter of the palette.
			indexToUse = overlayPaletteIndex.x * 0.25;
			
		} else {
			
			if(overlayPaletteIndex.y > overlayPaletteIndex.z) {
			
				// Use the green channel(y) in the second quarter of the palette.
				indexToUse = overlayPaletteIndex.y * 0.25 + 0.25;
			
			} else {
			
				// Use the blue channel (z) in the third quarter of the palette.
				indexToUse = overlayPaletteIndex.z * 0.25 + 0.5;
				
			}
			
		}
		
	}
	
	time = frac(time);

	overlayColor = texture2D(textureSampler2, vec2(indexToUse, time));
	
	gl_FragColor = gl_Color * vec4(gl_FragColor.xyz * (1.0 - overlayPaletteIndex.w) + overlayColor.xyz * overlayPaletteIndex.w, gl_FragColor.w);

}

