#define MAX_LIGHTS 8

uniform sampler2D decalMap;
uniform int lightEnabled[MAX_LIGHTS];

varying vec3 normal;
varying vec4 ecPos;

void main()
{
	vec3 n, halfV;
	float NdotL, NdotHV;
	float att;
	vec3 aux;
	float dist;
	vec3 lightDir;
	vec4 color = gl_LightModel.ambient * gl_FrontMaterial.ambient;
	vec3 surfaceNormal = normalize(normal);

	n = surfaceNormal;

	//first light0 then others
	if(lightEnabled[0])
	{
		aux = vec3(gl_LightSource[0].position - ecPos);

		dist = length(aux);
		lightDir = normalize(aux);

		NdotL = max(dot(n,lightDir),0.0);

		att = 1.0 / (gl_LightSource[0].constantAttenuation +
				gl_LightSource[0].linearAttenuation * dist +
				gl_LightSource[0].quadraticAttenuation * dist * dist);

		color += att * (gl_FrontMaterial.ambient * gl_LightSource[0].ambient);

		if (NdotL > 0.0)
		{
			color += att * (gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse * NdotL);
			halfV[0] = 0.0;
			halfV[1] = 0.0;
			halfV[2] = 1.0;
			NdotHV = max(dot(n, halfV), 0.0);
			color += att * gl_FrontMaterial.specular * gl_LightSource[0].specular * 
					pow(NdotHV, gl_FrontMaterial.shininess);
		}
	}

	for(int i=1;i<MAX_LIGHTS;i++)
	{
		if(lightEnabled[i])
		{
			aux = vec3(gl_LightSource[i].position - ecPos);	

			dist = length(aux);
			lightDir = normalize(aux);
			NdotL = max(dot(n,lightDir),0.0);				

			att = 1.0 / (gl_LightSource[i].constantAttenuation +
					gl_LightSource[i].linearAttenuation * dist +
					gl_LightSource[i].quadraticAttenuation * dist * dist);
		
			color += att * (gl_FrontMaterial.ambient * gl_LightSource[i].ambient);

			if (NdotL > 0.0)
			{			
				color += att * (gl_FrontMaterial.diffuse * gl_LightSource[i].diffuse * NdotL);
				halfV = normalize(gl_LightSource[i].halfVector.xyz);
				NdotHV = max(dot(n, halfV), 0.0);
				color += att * gl_FrontMaterial.specular * gl_LightSource[i].specular * 
								pow(NdotHV, gl_FrontMaterial.shininess);
			}
		}
	}

	if(gl_FrontMaterial.ambient[0] > 1.0)
		color = min(color,1.5);
	
	gl_FragColor = color * texture2D(decalMap,gl_TexCoord[0].st);
}