#!/bin/sh

set -e

# http://www.iq0.com/duffgram/com.html implementation
# (consulted source to see what -n did)

arv0="$0"; shell=sh

usage(){
	printf 'Usage: %s (-n) (file...)\n' "$argv0" >&2
	exit 64	# sysexits(3) EX_USAGE
}

for arg in "$@"
do
	printf '%s\n' "$arg" \
		| grep '^-' >/dev/null 2>&1 \
			|| break
	shift
	printf '%s\n' "$arg" \
		| grep 'n' >/dev/null 2>&1 \
			&& shell=cat \
			|| true
	printf '%s\n' "$arg" \
		| grep '[^-n]' >/dev/null 2>&1 \
			&& usage \
			|| true
	printf '%s\n' "$arg" \
		| grep -- '-.*-' >/dev/null 2>&1 \
			&& break \
			|| true
done

test -n "$1" \
	|| set -- "$(cat .comfile 2>/dev/null)" \
	&& test -n "$1" \
	|| usage

>.comfile

while	test -n "$1"
do	
	c="$(<"$1" grep '/\*%' 2>/dev/null | head -n 1)"
	test -z "$c" \
		&& printf '%s: no command\n' "$arv0" >&2 \
		&& exit 65 \
		|| true	#^- sysexits(3) EX_DATAERR

	printf '%s\n' "$c" \
		| sed	-e 's,.*/\*%[space]*,,' \
		| awk \
			-v name="$1" \
			-v stem="$(printf '%s\n' "$1" | sed 's,\.[^.]*$,,')" '
{
	for(i = 0; i < length($0) - 1; ++i){
		if(substr($0, i, 2) == "##" || substr($0, i, 2) == "%%")
			printf("%s", substr($0, i++, 1))
		else if(substr($0, i, 1) == "#")
			printf("%s", stem)
		else if(substr($0, i, 1) == "%")
			printf("%s", name)
		else
			printf("%s", substr($0, i, 1))
	}
	printf("%s\n", substr($0, i, 2))
}
	'	| $shell
	printf '%s\n' "$1" >>.comfile
	shift
done
