varying vec3 eyeVec;
varying vec2 texCoord;
varying vec3 lightVec[]; 
varying vec3 spotDirVec[];

uniform sampler2D colorMap;
uniform sampler2D normalMap;

uniform float spotCount;

const float spotExponent = 4.0;
const float spotAngle = 0.7053981625;
const vec4 spotColor = vec4(1.0,1.0,1.0,1.0);
const float linear_att = 0.1;

void main (void)
{
   vec3 vVec = normalize(eyeVec);
   vec4 base = texture2D(colorMap, texCoord);
   vec3 bump = normalize(texture2D(normalMap, texCoord).xyz * 2.0 - 1.0);
   vec4 vDiffuse = vec4(0.0);
   vec4 vSpecular = vec4(0.0);
   float d = length(lightVec[0]);
   vec3 lVec = normalize(lightVec[0]);
   vec4 vAmbient = gl_FrontMaterial.ambient;
   
   float spotDot = dot(-lVec, spotDirVec[0]);
   
   float att;
   float diffuse;
   float specular;
   if(spotDot > cos(spotAngle)) {
   	  d = length(lightVec[0]);
   	  att = 1.0 / (linear_att * d);
      att *= pow(spotDot, spotExponent);
      diffuse = max( dot(lVec, bump), 0.0 );      
      vDiffuse += spotColor * gl_FrontMaterial.diffuse * diffuse * att;    
      specular = pow(clamp(dot(reflect(-lVec, bump), vVec), 0.0, 1.0), gl_FrontMaterial.shininess );  
      vSpecular += spotColor * gl_FrontMaterial.specular * specular * att;
   }
   
   if(spotCount >= 2.0) {
	   lVec = normalize(lightVec[1]);
	   spotDot = dot(-lVec, spotDirVec[1]);
	   if(spotDot > cos(spotAngle)) {
	      d = length(lightVec[1]);
   	  	  att = 1.0 / (linear_att * d);
      	  att *= pow(spotDot, spotExponent);
	      diffuse = max( dot(lVec, bump), 0.0 );
	      vDiffuse += spotColor * gl_FrontMaterial.diffuse * diffuse * att;
	      specular = pow(clamp(dot(reflect(-lVec, bump), vVec), 0.0, 1.0), gl_FrontMaterial.shininess );
	      vSpecular += spotColor * gl_FrontMaterial.specular * specular * att;
	   }
   }
   
   if(spotCount >= 3.0) {
	   lVec = normalize(lightVec[2]);
	   spotDot = dot(-lVec, spotDirVec[2]);
	   if(spotDot > cos(spotAngle)) {
	      d = length(lightVec[2]);
   	  	  att = 1.0 / (linear_att * d);
          att *= pow(spotDot, spotExponent);
	      diffuse = max( dot(lVec, bump), 0.0 );
	      vDiffuse += spotColor * gl_FrontMaterial.diffuse * diffuse * att;
	      specular = pow(clamp(dot(reflect(-lVec, bump), vVec), 0.0, 1.0), gl_FrontMaterial.shininess );
	      vSpecular += spotColor * gl_FrontMaterial.specular * specular * att;
	   }
   }
   
   gl_FragColor = (vAmbient*base + vDiffuse*base + vSpecular);
}