#!/usr/bin/perl
# Author: Vlado Keselj 2009-19  last update: 2019-04-22
# Change file names to safe names (e.g., space to _)
# Usage: fix-file-names.pl 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/ +- +/-/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.-])/"=".uc unpack("H2",$1)/ge;
  return $_;
}
