#!Perl

# fixnames droplet: this droplet converts the names of files
#	                from DOS to mac and unix friendly formats
#
# USE:				Save source as Droplet. Drop file or folder
#					of html and images on it.
#
# WARNING:			This code is not guaranteed, always backup
#                   your work before using it.
# Bill Humphries, June 1996

$DIRSEP = ':';	# change to the directory separator char for your OS

@args = @ARGV;

&process(@args);

&MacPerl'Quit(2);

sub process {

	local (@list) = @_;

#	print join("\n",@list),"\n";

	foreach $f (@list)
	{

		if (-d $f) # test to see if the file is a directory
		{
			$oldname = $f;
			($newname = $oldname) =~ tr/A-Z/a-z/;
			print "$f is a directory: renaming to $newname.\n";
			rename($oldname,$newname);	
			opendir(NEXT,$f);
			@newlist = readdir(NEXT);
			foreach $newfile (@newlist)
			{
			
				$newfile = $f.$DIRSEP.$newfile;	# prepend the pathname to the file

			}
			&process(@newlist);
		}
		else
		{
			$oldname = $f;
			($newname = $oldname) =~ tr/A-Z/a-z/;
			$newname =~ s/\.htm$/\.html/;
			print "$f is a file: renaming to $newname.\n";
			rename($oldname,$newname);
#			if this is an .html file, fix all the links
			$newname =~ /html$/ && &fix_file($newname);

		}

	}

}

sub fix_file {

	local ($the_file) = @_;

	open(FILE,"$the_file") || die "Cannot open $the_file\n";
#	print "opening $the_file\n";

	# make perl read whole documents at one go

	undef ($/);

	# read in the file

	$source = <FILE>;	
	close(FILE);

	# make the replacements for local images and links

	$source =~ s/(src|SRC) *= *"[a-zA-Z0-9\-\_\/\.\#]+"/\L$&\E/ig;
 	$source =~ s/(href|HREF) *= *"[a-zA-Z0-9\-\_\/\.\#]+"/\L$&\E/ig;
 	$source =~ s/(name|NAME) *= *"[a-zA-Z0-9\-\_\/\.\#]+"/\L$&\E/ig;

	# convert .htm to .html

	$source =~ s|\.htm\"|\.html\"|ig;
	$source =~ s/\.htm\#/\.html\#/ig;

 	# write out the changes
	open(NEW,">$the_file");

 	print NEW $source;

 	close(NEW);
		
}
