varying vec4 ambientGlobal, coordinates;
varying vec3 normal;

uniform int lightNumber;
uniform sampler2D texture;

vec3 getColor(vec3 viewVec, vec3 n, vec4 texel, gl_LightSourceParameters lightsource) {
	vec4 color;
	vec3 lightVec;
	float NdotL,RdotV, att, dist;
	
	lightVec = vec3(lightsource.position - coordinates);
	dist = length(lightVec);
	
	lightVec = normalize(lightVec);
	
	NdotL = max(dot(n,lightVec),0.0);
	att = 1.0 / (lightsource.constantAttenuation +
			lightsource.linearAttenuation * dist +
			lightsource.quadraticAttenuation * dist * dist);
			
	color = att * texel * (
		gl_FrontMaterial.diffuse * lightsource.diffuse * NdotL +
		gl_FrontMaterial.ambient * lightsource.ambient);
	
	if (NdotL > 0.0) {
		RdotV = max(dot(reflect(-lightVec, n),viewVec),0.0);
		color += att * gl_FrontMaterial.specular * lightsource.specular * 
						pow(RdotV,gl_FrontMaterial.shininess);
	}
	
	return vec3(color);
}

void main()
{
	vec3 n;
	vec4 color, texel;
	vec3 viewVec;
	
	n = normalize(normal);
	color = ambientGlobal*gl_FrontMaterial.ambient;
	color.a = gl_FrontMaterial.diffuse.a;
	texel = texture2D(texture,gl_TexCoord[0].st);
	if (texel.a <= 0.0) {
		texel = vec4(1.0, 1.0, 1.0, 1.0);
	}
	viewVec = normalize(vec3(-coordinates));
	
	if (lightNumber == -1) {
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[0]),0);
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[1]),0);
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[2]),0);
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[3]),0);
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[4]),0);
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[5]),0);
	}	
	if (lightNumber == 0) {
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[0]),0);
	}
	if (lightNumber == 1) {
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[1]),0);
	}
	if (lightNumber == 2) {
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[2]),0);
	}
	if (lightNumber == 3) {
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[3]),0);
	}
	if (lightNumber == 4) {
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[4]),0);
	}
	if (lightNumber == 5) {
		color += vec4(getColor(viewVec, n, texel, gl_LightSource[5]),0);
	}
	
	gl_FragColor = color;
}
