#   RenameScripts.pl
#   ---------
#   This script renames book scripts to their approprate names.
#   It reads the comment header at the beginning of the script
#   and looks for:
#       Example 8.2:
#   Then proceeds to name the file Example_8_2.pl.
#   This is used to convert script names to their Example number.
#   This was used for the book:
#       Win32 Perl Scripting: Administrator's Handbook
#
#   2000.08.14 roth
#
print "From the book 'Win32 Perl Scripting: The Administrator's Handbook' by Dave Roth\n\n";

$Dir = "." unless( $Dir = shift @ARGV );
ProcessDir( $Dir );



sub ProcessDir
{
    my( $Dir ) = @_;
    my @Dirs;

    if( opendir( DIR, $Dir ) )
    {
        while( my $File = readdir( DIR ) )
        {
            my $Path = "$Dir/$File";

            next if( "." eq $File || ".." eq $File );

            if( -d $Path )
            {
                push( @Dirs, $Path );
            }
            else
            {
                ProcessFile( $Dir, $File );
            }
        }
        closedir( DIR );

        foreach my $Path ( sort( @Dirs ) )
        {
            ProcessDir( $Path );
        }
    }
}

sub ProcessFile
{
    my( $Dir, $File ) = @_;
    $Path = "$Dir/$File";

    return unless( $Path =~ /\.pl$/i );

    if( open( FILE, "< $Path" ) )
    {
        my $Example;
        my $SubExample;

        print "$Path ";

        while( my $Line = <FILE> )
        {

            if( ( $Example ) = ( $Line =~ /^#\s*Example\s+(.*)\s*$/i ) )
            {
                print "($Example) ";
                last;
            }
        }
        close( FILE );

        if( "" ne $Example )
        {
            my $NewName;

            ( $Example, $SubExample ) = ( $Example =~ /(\d+)\.(\d+)/ );

            $NewName = sprintf( "Example_%d_%d.pl", $Example, $SubExample );
            if( lc( $NewName ) ne lc( $File ) )
            {
                print "=> $NewName";
                rename( $Path, "$Dir/$NewName" );
            }
        }
        print "\n";
    }
}
