/*
 * plaid.sl -- Surface shader for tri-color plaid.
 *
 * DESCRIPTION:
 *    A color shader for plaid cloth texture.
 *    For a pattern with three stripe colors, one of which is repeated twice.
 *
 * PARAMETERS:
 *    Ka, Kd - ambient and diffuse reflectivity
 *    w1 - stripe 1's width, major wide stripe
 *    w2 - stripe 2's width, background color
 *    w3 - stripe 3's width, narrow stripe repeated twice
 *    w4 - stripe 4's width, same color as 2.
 *    Should have w1 + 2*w2 + 2*w3 + w4 = 1.0.
 *    col1, col2, col3 - colors for the stripes.
 * AUTHOR: Nancy Kiang, cs184-bf
 *
 */


#define avg(a, b, c, num) (( a + b + c)/num)

surface
plaid( 	float Ka = 0.4, Kd = 0.6;
	float w1 = 0.3, w2 = 0.15, w3 = 0.1, w4=0.2;
       	color col1 = color "rgb" (0.1, 0.0, 0.2); /*dark purple*/
	color col2 = color "rgb" (0.2, 0.0, 0.1); /*maroon*/
	color col3 = color "rgb" (0.1, 0.3, 0.1)  /*dark green*/
     )
{
	point Nf = faceforward(normalize(N), I);
	float ss = mod(s, 1.0);
	float tt = mod(t, 1.0);

	/*Check that user did not choose bad widths.  If so, reset defaults.*/
	if ((w1 + 2*w2 + 2*w3 + w4) != 1.0) {
		w1 = 0.3; 
		w2 = 0.15;
		w3 = 0.1;
		w4=0.2;
	}
		

	float if1 = 0.0;
	if ( ss <= w1 || tt <= w1) if1 = 1.0;

	float if2 = 0.0;
	if (    (ss > w1 && ss <= w1+w2) 
		|| (tt > w1 && tt <= w1+w2)
		|| (ss > w1+w2+w3  &&  ss <= w1+w2+w3+w4) 
		|| (tt > w1+w2+w3  &&  tt <= w1+w2+w3+w4)
		|| (ss > w1 + w2 + 2*w3 + w4)
		|| (tt > w1 + w2 + 2*w3 + w4))
	    if2 = 1.0;

	float if3 = 0.0;
	if (    (ss > w1+w2 && ss <= w1+w2+w3)
		|| (tt > w1+w2 && tt <= w1+w2+w3)
		|| (ss > w1 + w2 + w3 + w4 && ss <= w1 + 2*w2 + w3 + w4)
		|| (tt > w1 + w2 + w3 + w4 && tt <= w1 + 2*w2 + w3 + w4))
	    if3 = 1.0;

	float numcolors = if1 + if2 + if3;

	Oi = Os;
	Ci = Os * avg(if1 * col1, if2 * col2, if3 * col3, numcolors) *
		(Ka*ambient() + Kd*diffuse(Nf));


}