#!/bin/sh
: ; exec klone $0 "$@"
; The above line finds the klone executable in the $PATH
;;Skeleton of a typical klone script

(setq args (getopts "USAGE: %0 [options] [file]
Ouputs contents of file on stdout (or filters input if no file),
quoting non-legal html URL chars in the %xx form
"
    ("-p" () quote-for-pre "quote for inclusion in <PRE></PRE> tags")
))

(defun main (&aux
    (fd (if args (open (0 args)) *standard-input*))
    (s (String fd))
  )
  (if quote-for-pre
    (write-string (html:quote-for-pre s))
    (write-string (html:quote-values s))
))

(defun html:quote-values (string &aux
    (res (copy ""))
    (re-html-tq (regcomp "^([,.=+\n/0-9a-zA-Z_-]*)([^,.=+\n/0-9a-zA-Z_-])"))
    (offset 0)
  )
  (while (regexec re-html-tq string offset)
    (nconc res (regsub re-html-tq 1))
    (with (cval (get (regsub re-html-tq 2) 0))
      (put res -1 #\%)
      (put res -1 (get (itox (/ cval 16)) 2))
      (put res -1 (get (itox (mod cval 16)) 2))
    )
    (setq offset #[re-html-tq 2 1])
  )
  (nconc res (subseq string offset))
  res
)

(defun html:quote-for-pre (string &aux
    (res (copy ""))
    (re-html-tq (regcomp "^([^<>]*)([<>])"))
    (offset 0)
  )
  (while (regexec re-html-tq string offset)
    (nconc res (regsub re-html-tq 1))
    (if (= ">" (regsub re-html-tq 2))
      (nconc res "&gt;")
      (nconc res "&lt;")
    )
    (setq offset #[re-html-tq 2 1])
  )
  (nconc res (subseq string offset))
  res
)

(main)

;;; EMACS MODES
;;; Local Variables: ***
;;; mode:lisp ***
;;; End: ***

