#! /usr/local/bin/sizzle -s
!#

; html-pp.scm
;
; This fine tool can be used to preprocess text files (I mainly use it
; to generate web pages.  Usage is simple.  Just pass the name of the
; file to preprocess on the commandline and the processed output will
; be written to stdout.  If no file name is given, standard input is
; used to read the data.
;
; Syntax of the source files:
; ===========================
;
; Normal text in source files are simply written to standard output.
;
; Preprocessing is triggered by using the character `%' in the input
; file. The Scheme expression immediately following this character is
; read and evaluated, the result of evaluation is then written to
; standard output, if it is a string, otherwise it is only evaluated
; for side effects.
;
; Note that any whitespace following a Scheme expression is discarded
; and thus does not appear in the output.
;
; See the example source file `boo.scmtml' for how to use this script.


;;; File handling ====================================================

;; Process all expressions available on port IN-PORT.
(define (handle-file in-port)
  (let loop ((ch (read-char in-port)))
    (cond ((eof-object? ch)
	   #f)
	  ((char=? ch #\%)
	   (let* ((expr (read in-port))
		  (res (eval expr)))
	     (if (string? res)
		 (display res)))
	   (loop (read-char in-port)))
	  (else
	   (display ch)
	   (loop (read-char in-port))))))

;; Process all files whose filenames are on the list FILES.  Use STDIN
;; if the given list is empty.
(define (handle-files files)
  (if (pair? files)
      (for-each (lambda (file)
		  (call-with-input-file file handle-file))
		files)
      (handle-file (current-input-port))))

(let ((cmdline (command-line)))
  (handle-files (if (pair? cmdline) (cdr cmdline) '())))
