uniform int nr_lights;

varying vec3 q_tilde;
varying vec3 inv_T_square_v;
varying vec3 inv_T_square_e_c;
varying vec4 ev_clip;
varying vec3 v;
varying vec4 a;
varying vec4 s;

void main()
{
	float q_tilde_squared_length = dot(q_tilde.xy,q_tilde.xy);
	if (q_tilde_squared_length > 1.0)
		discard;
	float lambda = 1.0/(1.0+q_tilde.z*sqrt(1.0-q_tilde_squared_length));
	vec3 n = inv_T_square_e_c + lambda * inv_T_square_v;

	gl_FragColor = a;
	vec3 l;
	vec4 specular;
	vec4 diffuse;
	vec4 result_color = vec4(0);

	for (int i=0; i<nr_lights; ++i) {
		
		if (i==0) {
			l=normalize(gl_LightSource[0].position.xyz);
			specular=gl_LightSource[0].specular;
			diffuse=gl_LightSource[0].diffuse;
		}
		if (i==1) {
			l=normalize(gl_LightSource[1].position.xyz);
			specular=gl_LightSource[1].specular;
			diffuse=gl_LightSource[1].diffuse;
		}
		if (i==2) {
			l=normalize(gl_LightSource[2].position.xyz);
			specular=gl_LightSource[2].specular;
			diffuse=gl_LightSource[2].diffuse;
		}
		if (i==3) {
			l=normalize(gl_LightSource[3].position.xyz);
			specular=gl_LightSource[3].specular;
			diffuse=gl_LightSource[3].diffuse;
		}

		vec3 h=normalize(v+l);

		float ldotn = dot(n,l);
		if (ldotn > 0.0) {
			result_color += 
				ldotn*diffuse*gl_Color+
				pow(max(dot(n,h), 0.0), gl_FrontMaterial.shininess)*s*specular;
		}
	}

	gl_FragColor = result_color;
}