
;; (digit-to-char 1)
(defun digit-to-char (d)
  (assert (<= d 15))
  (assert (>= d  0))
  (cond
   ((<= d 9)
    (+ d ?0))
   ((<= d 15)
    (+ (- d 10) ?a))
   (t
    (error "Should never happen"))))

;; (char-to-digit ?3)
;; (char-to-digit ?a)
(defun char-to-digit (ch)
  (cond
   ((and (>= ch ?0) (<= ch ?9))
    (- ch ?0))
   ((and (>= ch ?a) (<= ch ?f))
    (+ 10 (- ch ?a)))
   (t
    (error "Should never happen"))))

;; (to-hex 32)
(defun to-hex-byte (i)
  (assert (<= i 255))
  (assert (>= i 0))
  (let ((d1 (/ i 16))
        (d2 (% i 16)))
    (format "0x%c%c" (digit-to-char d1) (digit-to-char d2))))

;; (from-hex "0xcc")
;; (from-hex "0x20")
(defun from-hex-byte (h)
  (assert (stringp h))
  (setq h (downcase h))
  (assert (= (length h) 4))
  (assert (string-match "^0x" h))
  (+ (* 16 (char-to-digit (aref h 2))) (char-to-digit (aref h 3))))

;; (setq hex-triple "#88cc88")
;; (hex-colour-code-to-255-255-255 "#88cc88")
;; (hex2dec "#ff00ff")
(defun hex2dec (hex-triple)
  (interactive "sEnter Hex Triple: (e.g. #ff8800) ")
  (assert (stringp hex-triple))
  (setq hex-triple (downcase hex-triple))
  (assert (string-match "^#" hex-triple))
  (assert (= 7 (length hex-triple)))
  (let ((sr (concat "0x" (substring hex-triple 1 3)))
        (sg (concat "0x" (substring hex-triple 3 5)))
        (sb (concat "0x" (substring hex-triple 5 7))))

    (message "(%d %d %d)" (from-hex-byte sr) (from-hex-byte sg) (from-hex-byte sb))
    (list (from-hex-byte sr) (from-hex-byte sg) (from-hex-byte sb))))

;; (dec2hex)
(defun dec2hex (&optional r g b)
  (interactive)
  (let (result)
    (if (not r)
        (setq r (read (read-from-minibuffer "Red (0-255): "))))
    (if (not g)
        (setq g (read (read-from-minibuffer "Green (0-255): "))))
    (if (not b)
        (setq b (read (read-from-minibuffer "Blue (0-255): "))))
    (if (floatp r)
        (setq r (floor r)))
    (assert (numberp r))
    (assert (>= r 0))
    (assert (<= r 255))
    (if (floatp g)
        (setq g (floor g)))
    (assert (numberp g))
    (assert (>= g 0))
    (assert (<= g 255))
    (if (floatp b)
        (setq b (floor b)))
    (assert (numberp b))
    (assert (>= b 0))
    (assert (<= b 255))
    (setq result (format "#%s%s%s"
                         (substring (to-hex-byte r) 2)
                         (substring (to-hex-byte g) 2)
                         (substring (to-hex-byte b) 2)))
    (message "result=%s" result)
    result
    ))

;;(set-face-background 'default (dec2hex 255 255 255))
;;(set-face-background 'default "#f0f0f0")

(provide 'd-hex)
;;; d-hex.el ends here
