// loopit 2006

struct v2f {
	float4 position   : POSITION;
	float2 texcoords0 : TEXCOORD0;
};

struct sHSB
{
	float H;
	float S;
	float B;
};


static const float3 hpw = float3( 0.3086f, 0.6094f, 0.0820f ); //note: human perception
//static const float3 hpw = float3( 0.3f, 0.59f, 0.11f ); //note: ntsc
sHSB rgb2HSB( const float3 in_rgb ) {
	const float u = (2.0f*in_rgb.r - in_rgb.g - in_rgb.b)/3.0f;
	const float v = ( -in_rgb.r + 2.0f* in_rgb.g - in_rgb.b)/3.0f;

	sHSB ret;
	if( abs(u)>0 )
		ret.H = atan2(u,v);
	else
		ret.H = 0.0;
	
	ret.S = sqrt(u*u + v*v);
	ret.B = dot( hpw, in_rgb);

	return ret;
}


float3 HSB2rgb( sHSB hsb ) {
	const float u = hsb.S * sin(hsb.H);
	const float v = hsb.S * cos(hsb.H);

	float3 out_rgb;
	out_rgb.r = hsb.B + u;
	out_rgb.g = hsb.B	+ v;
	out_rgb.b = clamp(hsb.B - u - v, 0, 1);

	return out_rgb;
}


//sHSB ensure_rgb_validity( sHSB in_hsb ) {
//	//TODO: make sure S is inside valid limits... necessary if correction goes beyond borders of
//	//      (happens in both sat-change and regular its-change) - might also want to clamp intensity
//	//      would probably be best to find "closest rgb-valid point in ihs-space" by adjusting intensity also...
//	in_hsb.S = clamp( in_hsb.S, 0, in_hsb.B );
//
//	if(in_hsb.H > M_2PI ) in_hsb.H -= M_2PI;
//	if(in_hsb.H < 0 ) in_hsb.H += M_2PI;
//
//	return ihs;
//}

void main(	in v2f IN,
			in uniform samplerRECT tex0 : TEXUNIT0,
			in uniform float H_adjust,
			in uniform float S_adjust,
			in uniform float B_adjust,
			in uniform float mult_adjust,
			out float4 colOut : COLOR0 )
{
	const float4 img = texRECT( tex0, IN.texcoords0 );
	sHSB hsb = rgb2HSB( img.rgb );

	//note: saturation-correction
	hsb.S *= S_adjust; //note: might become over-saturated - fixed later...

	//note: hue-correction
	hsb.H += H_adjust;

	hsb.H += mult_adjust*hsb.B;

	//ihs = ensure_rgb_validity( ihs );

	float3 rgb = HSB2rgb( hsb );

	//note: photoshop brightness-correction
	//TODO: remove the ifs by always doing double-lerp (second lerp on result from first)
	rgb = lerp( rgb, float3(1,1,1), clamp(B_adjust,0,1) );
	rgb = lerp( float3(0,0,0), rgb, clamp(1+B_adjust,0,1) );

	colOut = float4( rgb, img.a );
	//colOut = img;

	//colOut.rgb = hsb.H / 3.1415;
}
