#!/usr/bin/perl
require 'getopts.pl';
&Getopts('vi:');

$SUFFIX = $opt_i;
$CHANGED=0;

foreach $file (@ARGV) {
  next unless -f $file;
  next if -l $file;
  @BC{This_In, This_Out} = (0, 0) if $opt_v;
  my $THIS_CHANGED = 0;
  unless (open IN, "< $file") {
    warn "Couldn't open file `$file' for reading: $!; skipping.\n";
    next;
  }
  if ($SUFFIX) {
    unless (rename $file, "$file$SUFFIX") {
      warn "Couldn't backup file `$file' to `$file$SUFFIX': $!; skipping.\n";
      next;
    }
    unless (open OUT, "> $file") {
      warn "Couldn't open file `$file' for writing: $!; skipping.\n";
      unless (rename $file, "$file$SUFFIX") {
	warn "Couldn't put original file back into `$file' ($!); it is in `$file$SUFFIX'\n";
      }
      next;
    }
  } else {
    unless (unlink $file) {
      warn "Couldn't remove file `$file': $!; skipping.\n";
      next;
    }
    unless (open OUT, "> $file") {
      warn "Couldn't open file `$file' for writing: $!; skipping.\n";
    }
  }

  $/ = '';
  $header = <IN>;
  $BC{This_In} = length($header) if $opt_v;
  $header =~ s/^Received:\s+.*\n(\s+.*\n)*//mg;
  $BC{This_Out} = length($header) if $opt_v;
  $THIS_CHANGED++  if $opt_v && $BC{This_In} != $BC{This_Out};
  
  print OUT $header;

  $/ = "\n";
  while (<IN>) {
    if ($opt_v) {
      my $len = length;
      foreach $k (qw(This_In This_Out)) {
	$BC{$k} += $len;
      }
    }
    print OUT;
  }
  if ($opt_v) {
    if ($THIS_CHANGED) {
      $BC{Changed_In} += $BC{This_In};
      $BC{Changed_Out} += $BC{This_Out};
      $CHANGED++;
    }
    $BC{Total_In} += $BC{This_In};
    $BC{Total_Out} += $BC{This_Out};
  }

  if ($opt_v && ++$NUMFILES % 100 == 0 || $NUMFILES == @ARGV) {
    print STDERR "$CHANGED/$NUMFILES files processed.\n";
  }
}

if ($opt_v) {
  my $compressed = sprintf("%2.2f", 100*(1 - $BC{Total_Out}/$BC{Total_In}));
  print STDERR "In: $BC{Total_In}.  Out: $BC{Total_Out}.  Compression: $compressed%\n";
  if ($BC{Changed_In}) {
    my $chcomp = sprintf("%2.2f", 100*(1 - $BC{Changed_Out}/$BC{Changed_In}));
    print STDERR "Changed files: $CHANGED.  In: $BC{Changed_In}.  Out: $BC{Changed_Out}.  Compression: $chcomp%\n";
  } else {
    print STDERR "No changes.\n";
  }
}
