#include "kk_color_space.h"

static float hue_to_rgb(float m1, float m2, float h)
{
	h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h);
	if (h * 6 < 1)
	{
		return (m1 + (m2 - m1) * h * 6);
	}
	else if (h * 2 < 1)
	{
		return m2;
	}
	else if (h * 3 < 2)
	{
		return m1 + (m2 - m1) * (0.66666 - h) * 6;
	}
	else
	{
		return m1;
	}
}

void hsl_to_rgb(float h,float s,float l,unsigned char* r,unsigned char * g,unsigned char * b)
{
	float m1, m2;

	m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s;
	m1 = l * 2 - m2;
	*r = 255 * hue_to_rgb(m1, m2, h + 0.33333);
	*g = 255 * hue_to_rgb(m1, m2, h);
	*b = 255 * hue_to_rgb(m1, m2, h - 0.33333);
}
void rgb_to_hsl(unsigned char r, unsigned char g, unsigned char b,unsigned short* H,unsigned char*S,unsigned char* L)
{
	float min = 0, max = 0, delta = 0;
	float h = 0, s = 0, l = 0, R = 0, G = 0, B = 0;
	R = r / 255.0;
	G = g / 255.0;
	B = b / 255.0;

	min = R < G ? R : G;
	min = B < min ? B : min;

	max = R > G ? R : G;
	max = B > max ? B : max;

	delta = max - min;
	l = (min + max) / 2.0;

	s = 0;
	if (l > 0 && l < 1)
	{
		s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
	}

	h = 0;
	if (delta > 0)
	{
		if (max == R && max != G)
		{
			h += (G - B) / delta;
		}
		else if (max == G && max != B)
		{
			h += (2 + (B - R) / delta);
		}
		else if (max == B && max != R)
		{
			h += (4 + (R - G) / delta);
		}

		{
			h /= 6.0;
		}
	}

	*H = (unsigned char)h;
	*S = (unsigned char)s;
	*L = (unsigned char)l;
}


