#!/usr/bin/env zsh
# Convert 16-bit RGB values to hexadecimal
# For example, xmag shows color in this format.
#
# Usage (outputs #00cb02):
#
#     rgb2hex 0 cbcb 202

while getopts h opt; do
    case $opt in
    h) awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
       exit ;;
    esac
done
shift $(( OPTIND - 1 ))

r="${1:?Missing red}"
g="${2:?Missing green}"
b="${3:?Missing blue}"

# TODO POSIX printf doesn't handle the 16# prefix. Another way?

printf '%d / 256
%d / 256
%d / 256
' "16#${r}" "16#${g}" "16#${b}" | bc | xe -N3 printf '#%02x%02x%02x\n'
