#!/bin/ksh
# @(#) filt.ksh 1.0 92/10/08
# 92/10/08 john h. dubois iii (john@armory.com)

# Use ksh because sh "type" doesn't exit nonzero if it fails
# & ksh has continue <n>

name=${0##*/}
filter=$1
shift
if [ $# -eq 0 ]; then
    echo \
"$name: filter files.
Usage: $name filter file ...
Each file is passed to filter as its standard input.
Output is written to file+.  If the exit value of filter is zero,
the original file is moved file- and the output is moved to file+."
    exit 0
fi

# testex $foo will test executability of the first component of foo
# without having to do a set -- $foo which would lose positional parameters
testex() {
    type $1 > /dev/null
    return $?
}

if testex $filter; then :; else
    echo "$filter: cannot execute." 1>&2
    exit 1
fi

for file; do
    for newfile in "$file+" "$file-"; do
	if [ -f "$newfile" ]; then
	    echo "$newfile already exists.  $file not processed." 1>&2
	    continue 2
	fi
    done
    if [ ! -r "$file" ]; then
	echo "$file: cannot read." 1>&2
	continue
    fi
    if $filter < "$file" > "$file+"; then
	mv $file $file-
	mv $file+ $file
	echo "$file succesfully filtered by $filter."
    else
	echo "$filter exited nonzero on file $file; $file not touched."
    fi
done
