
#include "rgb_hsv.h"
#ifndef WIN32
#include <sys/param.h>
#else /* WIN32 */
#define MAX(a,b) max(a,b)
#define MIN(a,b) min(a,b)
#endif /* WIN32 */

void CFC_API rgb_to_hsv( float *r, float *g, float *b, float *h, float *s, float *v)
{
    float r1, r2;
    float b_rel, c_min, c_max, g_rel, r_rel;

    r1 = *r;
    r2 = MAX(*b, *g);
    c_max = MAX(r1, r2);

    r1 = *r;
    r2 = MIN(*b, *g);
    c_min = MIN(r1, r2);

    if (c_max == c_min) {
        *h = (float)0.;
        *s = (float)0.;
        *v = *r;
    } else {
        *v = c_max;
        *s = (c_max - c_min) / c_max;
        r_rel = (c_max - *r) / (c_max - c_min);
        g_rel = (c_max - *g) / (c_max - c_min);
        b_rel = (c_max - *b) / (c_max - c_min);
        if (*r == c_max) {
            if (*g == c_min)
                *h = b_rel + (float)5.;
            else
                *h = (float)1. - g_rel;
        } else if (*g == c_max) {
            if (*b == c_min)
                *h = r_rel + (float)1.;
            else
                *h = (float)3. - b_rel;
        } else {
            if (*r == c_min)
                *h = g_rel + (float)3.;
            else
                *h = (float)5. - r_rel;
        }
        *h *= (float)60.;
    }
}

void CFC_API hsv_to_rgb( float *h, float *s, float *v, float *r, float *g, float *b)
{
    float x;

    x = (float)(((int)*h) % 360);

    if (x < (float)60.) {
        *r = (float)1.;
        *g = x / (float)60.;
        *b = (float)0.;
    } else if (x < (float)120.) {
        *r = ((float)120. - x) / (float)60.;
        *g = (float)1.;
        *b = (float)0.;
    } else if (x < (float)180.) {
        *r = (float)0.;
        *g = (float)1.;
        *b = (x - (float)120.) / (float)60.;
    } else if (x < (float)240.) {
        *r = (float)0.;
        *g = ((float)240. - x) / (float)60.;
        *b = (float)1.;
    } else if (x < (float)300.) {
        *r = (x - (float)240.) / (float)60.;
        *g = (float)0.;
        *b = (float)1.;
    } else {
        *r = (float)1.;
        *g = (float)0.;
        *b = ((float)360. - x) / (float)60.;
    }
    *b = *v * ((float)1. - *s + *s * *b);
    *g = *v * ((float)1. - *s + *s * *g);
    *r = *v * ((float)1. - *s + *s * *r);
}

