#!/usr/bin/perl
# fix-file-names - change file names to safe names, e.g. space to _ etc.
# 2009-2021 Vlado Keselj vlado@dnlp.ca http://vlado.ca last update:2021-04-06
# Usage: fix-file-names f1 f2 ...

for my $fnold (@ARGV) {
  my $fnnew = &fix_filename($fnold);

    if ($fnnew eq $fnold) { print "$fnnew \t\tthe same file name kept!\n" }
    else {
	if (-e $fnnew) { die "$fnnew already exists!" }
	print "$fnold \t-> $fnnew\n";
	rename($fnold,$fnnew) or die;
    }
}

sub fix_filename {
  local $_ = shift; s/^-/F-/; s/%20/ /g; s/ +- +/-/g;
  s/''+/--/g; s/'/-/g; s/[[(<{]/_-/g; s/[])>}]/-_/g;
  s/[,:;]\s*/--/g; s/&/and/g; s/ /_/g;
  s/__+/_/g; s/---+/--/g;
  s/\xE2\x80\x99/-/g; # Single right quote
  s/[^\w.-]/"0x".uc unpack("H2",$&)/ge;
  return $_;
}

# 2021-04-06 treating %20 as a space
# 2020-12-06
# - =HH encoding is replaced with 0xHH since '=' is a special character in
#   shell (bash)
