struct Lights
{
	bool bEnabled;
	bool bSpot;
	vec4 color;
	vec4 specular;
	vec4 pos;
	vec4 ambient;
	vec4 direction;
	float spotCosCutoff;
	float spotBall;
	
	float constantAttenuation;
	float linearAttenuation;
	float quadraticAttenuation;
};

varying vec2 texCoord;
varying vec3 normal;
varying vec3 worldPos;
uniform sampler2D Texture0;
uniform mat4 cameraMatrix;
uniform Lights lights[5];
uniform float fTV;

void main (void)
{
	
	vec4 final_color=vec4(0.0,0.0,0.0,1.0);
	vec4 color1 = texture2D(Texture0, texCoord) + gl_FrontMaterial.diffuse + gl_FrontMaterial.emission;
	vec3 N = normalize(normal);
	
	float fAttMult;
	if(fTV!=0.0)
	{
		final_color.xyz = (color1.xyz) * fTV;
		fAttMult=0.3;
	}
	else
	{
		fAttMult=1.0;		
	}	
	
	for(int i=0; i < 5; i++)
	{
		if(lights[i].bEnabled==false) break;
		
		vec3 newlight=vec3(lights[i].pos);
		vec3 lightDir = newlight - worldPos;		
				
		float shiny=gl_FrontMaterial.shininess;
		float d = length(lightDir);		
		vec3 L = normalize(lightDir);	
		
		float att = 1.0 / ( lights[i].constantAttenuation + (lights[i].linearAttenuation*d) + (lights[i].quadraticAttenuation*d*d) );
		att = att * fAttMult;
		
		if(lights[i].bSpot==true)
		{				
			if (dot(-L, lights[i].direction.xyz) <= lights[i].spotCosCutoff)
			{
				if(d>lights[i].spotBall)
				{
					final_color.xyz += (lights[i].ambient.xyz*lights[i].color.xyz*color1.xyz)*clamp(att*4.0,0.0,0.2);	
					continue;
				}
				att*=5.0;
				shiny=0.0;
			}
		}
		else
		{
			final_color.xyz += (lights[i].ambient.xyz*color1.xyz)*att;
		}
		float lambertTerm = max(dot(N,L),0.0);		
		if(lambertTerm > 0.0)
		{
			final_color.xyz += lights[i].color.xyz * color1.xyz * lambertTerm * att;			
			if(shiny!=0.0)
			{
				vec3 E = normalize(-worldPos);
				vec3 R = reflect(-L, N);			
				float specular= abs(pow( max(dot(R, E), 0.0),gl_FrontMaterial.shininess ));		
				final_color.xyz += lights[i].specular.xyz * gl_FrontMaterial.specular.xyz * (specular * att);
			}
		}
	}
	gl_FragColor = final_color;			
}