
# version @(#) 1 851025
# Prepare files list for size metrics.
# See the manual entry for details.

# This may be slow and inefficient, but good performance was not a design goal.


# INITIALIZE:

	nlist=''			# filename patterns.
	usage=''			# flag: usage error?
	marker='*%&^$#'			# special marker value.


# PARSE ARGUMENTS:

	set -f				# don't expand filenames.
	set -- `getopt n: "$@"`
	set +f

	if test $? != 0			# error in getopt.
	then
	    usage='bad'
	else
	    while test $# != 0		# still have args.
	    do
		case "$1" in

		-n)	if test "x$nlist" != x		# already have some.
			then
			    nlist="$nlist -o -name $2"	# append with "or".
			else
			    nlist="-name $2"		# save new.
			fi

			shift 2
			;;

		--)	shift; break ;;			# end of args.

		*)	usage='bad'; break ;;		# unknown arg.

		esac
	    done
	fi


# TELL CORRECT USAGE:

	if test "$usage"
	then
	    # this is an interpreted here-document.
	    cat >&2 <<-!
			usage: $0 [-n pattern] [files...]
			-n filenames must match pattern ("or" of all patterns)
			files contain input data in proper format
		!

	    exit 1
	fi


# READ INPUT LINES:

	cat $* |

	while read type file qual
	do
	    if test "x$type" = x  -o  x`expr substr "$type" 1 1` = "x#"
	    then
		continue				# blank or comment.

	    elif test "x$type" != xn  -a  "x$type" != xr  -a  "x$type" != xu
	    then
		echo "$0: invalid type letter \"$type\" in input" >&2
		exit 1

	    elif test "x$file" = x
	    then
		echo "$0: input line missing filename" >&2
		exit 1

# EXPAND FILENAMES:

	    else
		echo "$marker $type $file $qual"	# original data.

		if test "x$nlist" = x			# no patterns.
		then
		    find "$file" -type f -print		# file list.
		else
		    set -f			# don't expand filenames.
		    find "$file" \( $nlist \) -type f -print
		    set +f
		fi
	    fi
	done |						# note pipe.

	# Output is marker lines ("marker type file qual") or filenames.
	# Type fields are known to be one letter long.


# CONDENSE EXPANDED FILENAME LIST:

	awk '

	# Save original data from marked line:

	($1 == "'"$marker"'") {
		type = $2;			# save values.
		file = $3;
		qual = $4;

		for (field = 5; field <= NF; field++)
		    qual = qual " " $field;

		fields = NF;
		next;
	}

	# Save data from filename line:

	{
	    if ((type != "r") || (file == $0) || (fields != 4))	# ordinary.
	    {
		# overwrite old or save new, with concatenation:
		data [$0] = type qual;
	    }
	    else	# filename was expanded and qual is a single word.
	    {
		# tack on to qual the expanded part of file:
		data [$0] = type qual substr ($0, length (file));
	    }
	}
    
	# Print condensed data:

	END {
	    for (file in data)			# split type from qual:
		print substr (data [file], 1, 1), file, \
		      substr (data [file], 2);
	}'
