#! perl -w
use RISCOS;
use File::Copy;

# Swap the files in the perl library from Name/pm to pm.Name

die "$0 <from> <to>" unless( @ARGV == 2 );

$from = shift;
$to = shift;

sub ensuredir ($) {
    my ($path);
    foreach (split /\./, $_[0])
    {
	if( defined $path )
	{
	    $path .= ".$_";
	}
	else
	{
	    $path = $_
	}
	mkdir $path, 0777 or warn $! unless -d $path;
    }
}

@ext = qw(pm pl al ix);

# Sort makes sure we do things in the right order, moving file *.pm out of the
# way before creating directory *.pm
foreach $file ( sort { $b cmp $a } ( <$from..*> ) )
{
    $dest = $file;
    $dest =~ s/^\Q$from\E/$to/;

    unless( -d $file )
    {
	foreach $ext (@ext)
	{
	    ($base, $leaf) = $dest =~ m|^(.*)\.(.*)/$ext$|;
	    ($base, $leaf) = $dest =~ m|^(.*)\.(.*)\.$ext$|
	       unless defined $leaf;
	       # See autosplit - this is a UnixLib bug workaround

	    if( defined $leaf )
	    {
	      $dir = "$base.$ext";
	      $dest = "$base.$ext.$leaf";

	      last;
	    }
	}
	($dir) = $dest =~ /(.*)\./ unless defined $leaf;
	warn "No suffix on '$file'\n" unless defined $leaf;
	
	ensuredir( $dir );
	printf "%s - %s\n", $file, $dest;
#        printf "%s -> %s\n", RISCOS::Filespec::riscosify($file),
#				RISCOS::Filespec::riscosify ($dest);
	copy $file, "$dest" or warn $!;
    }
}
