#!/usr/bin/perl -w

## require("/home/mario/public_html/x/sh-lib.pl");

($PATTERN, $REPLACEMENT, @files) = @ARGV;

if ($PATTERN && $REPLACEMENT && @files) {


if ($#files < 0) {
   @files = ("-");
}
elsif (!$files[0] eq "-") {
   print "fr: replacing `$PATTERN' with `$REPLACEMENT'\n";
}


foreach $file (@files) {

  if ( (! ($file eq "-")) && (! -f $file || ! -r $file) ) {
     next;
  }

  open READ, "$file";
  @text = (<READ>);
  close READ;

  $text = '';
  foreach $line (@text) {
    $text .= $line;
  }

  @numfound = ($text =~ /($PATTERN)/igs);
  $numfound = $#numfound + 1;
  if ($numfound >= 1) {

    $text =~ s/$PATTERN/$REPLACEMENT/igs;

    if (! ($file eq "-")) {
       print "$numfound replacing in $file\n";
    }

    open WRITE, ">$file";
    print WRITE $text;
    close WRITE;

  }
}

}
else {
  print "\nfr PATTERN REPLACEMENT files...\n\nwill replace any occourences of ".
        "PATTERN with REPLACEMENT in given files\n(use `find` in place of ".
        "\"files...\")\n\n";
}
