#! /usr/bin/perl -w

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

use utf8;
use encoding 'utf8';
use open ':utf8'; # input and output default layer will be UTF-8
use POSIX;
if ($#ARGV!=2) {die "Usage: $0 [s|y] RE REPLACEMENT"}
my $sy=shift;
my $re=shift;
my $subs=shift;
my $doit;
if ($sy eq "s") {
	$doit="\$d=~s/$re/$subs/gomi;";
} elsif ($sy eq "y") {
	$doit="\$d=~y/$re/$subs/;";
} else {die "Usage: $0 [s|y] RE REPLACEMENT"}

sub filter_re($) {
  my $fn=shift;
  print PIPE "$fn\n";
}

sub recursive_plus {
  my $dir=shift;
  my $func= shift;
  my $i;
  my $j;
  my @a;
  &$func ("$dir") unless ($dir eq "." or $dir eq "./");
  opendir D, $dir;
  @a=readdir D;
  @a=grep {
    ($_ ne ".") && ($_ ne "..") && ($_ ne "+")
  } @a;
  @a=sort @a;
  foreach $i (@a) {
	$j=$dir."/".$i;
	$j=~s/\/\//\//; # remove repeated //
	$j=~s/^\.\///; # remove leading ./
	$j=~s/\/$//; # remove tailing /
	if (-d $j) {recursive_plus("$j",$func);}
	else {&$func ("$j");}
  }
  closedir D;
}
sub cd_th {
  my $pwd=getcwd();
  do {
    if (-d "+") {return $pwd;}
    chdir("..");
    $pwd=getcwd();
  }until ($pwd eq "/");
  return 0;
}

my $prefix;
$prefix=cd_th() or die "Could not found Thwab control + directory";
printf "@<%s>\n",$prefix;
open PIPE, "|perl -w -CSDA -Mutf8 -ne \'\
chomp;\$fn=\$_; \$f=\$fn.\".tmp\";\
if (not -f \"\$fn\") {next}\
\@st=stat(\$fn); \$s=\$st[7];\
rename \$fn, \$f or die \"could not rename [\$fn]\\n\";\
open F,\$f; sysread F, \$d, \$s; close F;\
$doit\
open F,\">\".\$fn  or die \"could not open [\$fn]\\n\";\
syswrite(F,\$d,length(\$d))  or die \"could not write to [\$fn], original is backup as [\$f]\\n\";\
close F; unlink \"\$f\";\
\'";

&recursive_plus (".", \&filter_re);
close PIPE;
