#!/usr/bin/perl -w
#
# chomp: Trim trailing whitespace from a list of files.
#
# Usage: chomp file1 file2 file3...
#
# NOTE:  Files are modified in-place.  No backups are created.
#
# Files are, of course, not updated if they lack trailing whitespace.
#
#

use strict;

my ($argv_fn);
my $bytes_saved = 0;

while ($argv_fn = shift @ARGV) {
	&chomp_file($argv_fn);
}
printf "%u bytes chomped.\n", $bytes_saved;
exit(0);


sub chomp_file {
	my ($fn) = @_;
	my ($s, $i);
	my $chomped = 0;

	# read entire data file into memory
	open (F, $fn) or die "cannot open $fn: $!\n";
	my @data = <F>;
	close (F);

	# trim trailing whitespace
	foreach $i (0 .. $#data) {
		$s = $data[$i];
		if ($s =~ /\s$/) {
			while (($s) && ($s =~ /\s$/)) {
				chop $s;
				$bytes_saved++;
			}
			$s .= "\n";
			$bytes_saved--;
			if ($s ne $data[$i]) {
				$chomped = 1;
				$data[$i] = $s;
			}
		}
	}

	# dump data back to disk
	if ($chomped) {
		open (F, ">$fn") or die "cannot overwrite $fn: $!\n";
		print F @data;
		close (F);

		print "$fn modified.\n";
	}
}

