#!/bin/sh

# colors.sh -- Compute RGB color codes of easily discernible colors.
#
# Copyright (C) 2007 Nicolas François
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This shell script contains 2 functions:
# hsv_to_rgb
#   Internal function
#
# get_color(number, index)
#   Can be used to generate color codes for up to number colors.
#   You should call get_color() with the same number of colors,
#   incrementing index after each call.
#

hsv_to_rgb()
{
    h=$(($1 % 360))
    i=$((h * 6 / 360))

    case $i in
        0)
            r=255
            g=$(( h * 255 * 6 / 360 ))
            b=0
            ;;
        1)
            r=$(( 2 * 255 - h * 255 * 6 / 360 ))
            g=255
            b=0
            ;;
        2)
            r=0
            g=255
            b=$(( h * 255 * 6 / 360 - 2 * 255 ))
            ;;
        3)
            r=0
            g=$(( 4 * 255 - h * 255 * 6 / 360 ))
            b=255
            ;;
        4)
            r=$(( h * 255 * 6 / 360 - 4 * 255 ))
            g=0
            b=255
            ;;
        5)
            r=255
            g=0
            b=$(( 6 * 255 - h * 255 * 6 / 360 ))
            ;;
    esac

    printf "%02x%02x%02x" $r $g $b
}

get_color()
{
# number of colors
    n=$1
# index of the color
    i=$2

    case $(( i % 2 )) in
        0)
            hsv_to_rgb $(( (i/2)*180/((n+1)/2) ))
            ;;
        1)
            hsv_to_rgb $(( ((i-1)/2)*180/((n+1)/2) + 180 ))
            ;;
    esac
}
