#!/usr/bin/perl
#
#NAME
#  trim
#
#SYNOPSIS
#  trim file..
#
#DESCRIPTION
#  This rewrites all the files, with trailing white stuff trimmed.
#
#  The alorithm is to read each file into the @data array,  trim  it,
#  and  write  it  back  to the file.  So the original file itself is
#  overwritten, and all links to it will be affected.
#
#  If there are no changes, we don't write the  data  back,  and  the
#  wtime timestamp won't change.
#
#  By default, we show the names  of  changed  files.   This  can  be
#  suppressed  by  changing  the value of $V to 1, either the default
#  value  assigned  below,  or  by  setting  the  V_trim  environment
#  variable to 1.
#
#OPTIONS
#  None yet.  All command-line args are interpreted as file names.
#
#BUGS
#  We need enough memory to hold the largest file.
#
#  We might also want this program to work as a filter.
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>

$| = 1;
($me = $0) =~ s".*/"";
$V = $ENV{"V_$me"} || $ENV{"D_$me"} || 2;

for $f (@ARGV) {
	$f =~ s/^\.\/+//;	# Simplify, simplify
	@data = ();			# Paranoia.
	unless (open(F,$f)) {
		print STDERR "$me: Can't read \"$f\" ($!)\n" if $V>0;
		next;
	}
	@data = <F>;		# Slurp up the data.
	$trimmed = 0;
	for (@data) {		# Trim each line.
		++$trimmed if (s/[\r\s]+\n$/\n/);
	}
	next unless $trimmed;
	printf("%7d $f\n",$trimmed) if $V>1;
	unless (open(F,">$f")) {
		print STDERR "$me: Can't write \"$f\" ($!)\n";
		next;
	}
	print F @data;
}
