#!/usr/bin/perl -w

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";
	}
}

